Index: /tags/SHM-9.0/COPYING
===================================================================
--- /tags/SHM-9.0/COPYING	(revision 1088)
+++ /tags/SHM-9.0/COPYING	(revision 1088)
@@ -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: /tags/SHM-9.0/SHM.xcodeproj/project.pbxproj
===================================================================
--- /tags/SHM-9.0/SHM.xcodeproj/project.pbxproj	(revision 1088)
+++ /tags/SHM-9.0/SHM.xcodeproj/project.pbxproj	(revision 1088)
@@ -0,0 +1,1414 @@
+// !$*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 */; };
+		6B635E7416E5EAA10057B313 /* TAppEncLayerCfg.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 6B635E7316E5EAA10057B313 /* TAppEncLayerCfg.cpp */; };
+		6B635E7716E5EAB60057B313 /* TComUpsampleFilter.h in Headers */ = {isa = PBXBuildFile; fileRef = 6B635E7516E5EAB60057B313 /* TComUpsampleFilter.h */; };
+		6B635E7816E5EAB60057B313 /* TComUpsampleFilter.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 6B635E7616E5EAB60057B313 /* TComUpsampleFilter.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 */; };
+		C3D5A69A190AD6DA005E0EBE /* TCom3DAsymLUT.cpp in Sources */ = {isa = PBXBuildFile; fileRef = C3D5A698190AD6DA005E0EBE /* TCom3DAsymLUT.cpp */; };
+		C3D5A69B190AD6DA005E0EBE /* TCom3DAsymLUT.h in Headers */ = {isa = PBXBuildFile; fileRef = C3D5A699190AD6DA005E0EBE /* TCom3DAsymLUT.h */; };
+		C3D5A69E190AD6F8005E0EBE /* TEnc3DAsymLUT.cpp in Sources */ = {isa = PBXBuildFile; fileRef = C3D5A69C190AD6F8005E0EBE /* TEnc3DAsymLUT.cpp */; };
+		C3D5A69F190AD6F8005E0EBE /* TEnc3DAsymLUT.h in Headers */ = {isa = PBXBuildFile; fileRef = C3D5A69D190AD6F8005E0EBE /* TEnc3DAsymLUT.h */; };
+		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>"; };
+		6B635E7216E5EAA10057B313 /* TAppEncLayerCfg.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TAppEncLayerCfg.h; path = source/App/TAppEncoder/TAppEncLayerCfg.h; sourceTree = "<group>"; };
+		6B635E7316E5EAA10057B313 /* TAppEncLayerCfg.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TAppEncLayerCfg.cpp; path = source/App/TAppEncoder/TAppEncLayerCfg.cpp; sourceTree = "<group>"; };
+		6B635E7516E5EAB60057B313 /* TComUpsampleFilter.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TComUpsampleFilter.h; path = source/Lib/TLibCommon/TComUpsampleFilter.h; sourceTree = "<group>"; };
+		6B635E7616E5EAB60057B313 /* TComUpsampleFilter.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TComUpsampleFilter.cpp; path = source/Lib/TLibCommon/TComUpsampleFilter.cpp; 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>"; };
+		C3D5A698190AD6DA005E0EBE /* TCom3DAsymLUT.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TCom3DAsymLUT.cpp; path = source/Lib/TLibCommon/TCom3DAsymLUT.cpp; sourceTree = "<group>"; };
+		C3D5A699190AD6DA005E0EBE /* TCom3DAsymLUT.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TCom3DAsymLUT.h; path = source/Lib/TLibCommon/TCom3DAsymLUT.h; sourceTree = "<group>"; };
+		C3D5A69C190AD6F8005E0EBE /* TEnc3DAsymLUT.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TEnc3DAsymLUT.cpp; path = source/Lib/TLibEncoder/TEnc3DAsymLUT.cpp; sourceTree = "<group>"; };
+		C3D5A69D190AD6F8005E0EBE /* TEnc3DAsymLUT.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TEnc3DAsymLUT.h; path = source/Lib/TLibEncoder/TEnc3DAsymLUT.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 = (
+				C3D5A698190AD6DA005E0EBE /* TCom3DAsymLUT.cpp */,
+				C3D5A699190AD6DA005E0EBE /* TCom3DAsymLUT.h */,
+				6B635E7516E5EAB60057B313 /* TComUpsampleFilter.h */,
+				6B635E7616E5EAB60057B313 /* TComUpsampleFilter.cpp */,
+				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 = (
+				C3D5A69C190AD6F8005E0EBE /* TEnc3DAsymLUT.cpp */,
+				C3D5A69D190AD6F8005E0EBE /* TEnc3DAsymLUT.h */,
+				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 = (
+				6B635E7216E5EAA10057B313 /* TAppEncLayerCfg.h */,
+				6B635E7316E5EAA10057B313 /* TAppEncLayerCfg.cpp */,
+				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 */,
+				C3D5A69B190AD6DA005E0EBE /* TCom3DAsymLUT.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 */,
+				C3D5A69F190AD6F8005E0EBE /* TEnc3DAsymLUT.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 */,
+				6B635E7716E5EAB60057B313 /* TComUpsampleFilter.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 "SHM" */;
+			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 = (
+				C3D5A69E190AD6F8005E0EBE /* TEnc3DAsymLUT.cpp in Sources */,
+				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 */,
+				C3D5A69A190AD6DA005E0EBE /* TCom3DAsymLUT.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 */,
+				6B635E7816E5EAB60057B313 /* TComUpsampleFilter.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 */,
+				6B635E7416E5EAA10057B313 /* TAppEncLayerCfg.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 = macosx10.8;
+			};
+			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 = macosx10.8;
+			};
+			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 = "";
+				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 = "";
+				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 "SHM" */ = {
+			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: /tags/SHM-9.0/build/HM_vc10.sln
===================================================================
--- /tags/SHM-9.0/build/HM_vc10.sln	(revision 1088)
+++ /tags/SHM-9.0/build/HM_vc10.sln	(revision 1088)
@@ -0,0 +1,116 @@
+﻿
+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}") = "TAppDownConvert", "vc10\TAppDownConvert\TAppDownConvert.vcxproj", "{FB952E1B-681F-4461-9C8B-4F1F8B70E58B}"
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TAppDecoderAnalyser", "vc10\TAppDecoderAnalyser_vc10.vcxproj", "{6BB4C8D8-449D-4CC1-A5E1-E98AAF94012F}"
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TLibDecoderAnalyser", "vc10\TLibDecoderAnalyser_vc10.vcxproj", "{68C1251A-55D8-47C9-9052-62F785BD437A}"
+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
+		{FB952E1B-681F-4461-9C8B-4F1F8B70E58B}.Debug|Win32.ActiveCfg = Debug|Win32
+		{FB952E1B-681F-4461-9C8B-4F1F8B70E58B}.Debug|Win32.Build.0 = Debug|Win32
+		{FB952E1B-681F-4461-9C8B-4F1F8B70E58B}.Debug|x64.ActiveCfg = Debug|x64
+		{FB952E1B-681F-4461-9C8B-4F1F8B70E58B}.Debug|x64.Build.0 = Debug|x64
+		{FB952E1B-681F-4461-9C8B-4F1F8B70E58B}.Release|Win32.ActiveCfg = Release|Win32
+		{FB952E1B-681F-4461-9C8B-4F1F8B70E58B}.Release|Win32.Build.0 = Release|Win32
+		{FB952E1B-681F-4461-9C8B-4F1F8B70E58B}.Release|x64.ActiveCfg = Release|x64
+		{FB952E1B-681F-4461-9C8B-4F1F8B70E58B}.Release|x64.Build.0 = Release|x64
+		{6BB4C8D8-449D-4CC1-A5E1-E98AAF94012F}.Debug|Win32.ActiveCfg = Debug|Win32
+		{6BB4C8D8-449D-4CC1-A5E1-E98AAF94012F}.Debug|Win32.Build.0 = Debug|Win32
+		{6BB4C8D8-449D-4CC1-A5E1-E98AAF94012F}.Debug|x64.ActiveCfg = Debug|x64
+		{6BB4C8D8-449D-4CC1-A5E1-E98AAF94012F}.Debug|x64.Build.0 = Debug|x64
+		{6BB4C8D8-449D-4CC1-A5E1-E98AAF94012F}.Release|Win32.ActiveCfg = Release|Win32
+		{6BB4C8D8-449D-4CC1-A5E1-E98AAF94012F}.Release|Win32.Build.0 = Release|Win32
+		{6BB4C8D8-449D-4CC1-A5E1-E98AAF94012F}.Release|x64.ActiveCfg = Release|x64
+		{6BB4C8D8-449D-4CC1-A5E1-E98AAF94012F}.Release|x64.Build.0 = Release|x64
+		{68C1251A-55D8-47C9-9052-62F785BD437A}.Debug|Win32.ActiveCfg = Debug|Win32
+		{68C1251A-55D8-47C9-9052-62F785BD437A}.Debug|Win32.Build.0 = Debug|Win32
+		{68C1251A-55D8-47C9-9052-62F785BD437A}.Debug|x64.ActiveCfg = Debug|x64
+		{68C1251A-55D8-47C9-9052-62F785BD437A}.Debug|x64.Build.0 = Debug|x64
+		{68C1251A-55D8-47C9-9052-62F785BD437A}.Release|Win32.ActiveCfg = Release|Win32
+		{68C1251A-55D8-47C9-9052-62F785BD437A}.Release|Win32.Build.0 = Release|Win32
+		{68C1251A-55D8-47C9-9052-62F785BD437A}.Release|x64.ActiveCfg = Release|x64
+		{68C1251A-55D8-47C9-9052-62F785BD437A}.Release|x64.Build.0 = Release|x64
+	EndGlobalSection
+	GlobalSection(SolutionProperties) = preSolution
+		HideSolutionNode = FALSE
+	EndGlobalSection
+EndGlobal
Index: /tags/SHM-9.0/build/HM_vc8.sln
===================================================================
--- /tags/SHM-9.0/build/HM_vc8.sln	(revision 1088)
+++ /tags/SHM-9.0/build/HM_vc8.sln	(revision 1088)
@@ -0,0 +1,98 @@
+﻿
+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}
+	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
+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
+	EndGlobalSection
+	GlobalSection(SolutionProperties) = preSolution
+		HideSolutionNode = FALSE
+	EndGlobalSection
+EndGlobal
Index: /tags/SHM-9.0/build/HM_vc9.sln
===================================================================
--- /tags/SHM-9.0/build/HM_vc9.sln	(revision 1088)
+++ /tags/SHM-9.0/build/HM_vc9.sln	(revision 1088)
@@ -0,0 +1,98 @@
+﻿
+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}
+	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
+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
+	EndGlobalSection
+	GlobalSection(SolutionProperties) = preSolution
+		HideSolutionNode = FALSE
+	EndGlobalSection
+EndGlobal
Index: /tags/SHM-9.0/build/linux/app/TAppDecoder/makefile
===================================================================
--- /tags/SHM-9.0/build/linux/app/TAppDecoder/makefile	(revision 1088)
+++ /tags/SHM-9.0/build/linux/app/TAppDecoder/makefile	(revision 1088)
@@ -0,0 +1,64 @@
+# 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	=
+
+ifeq ($(HIGHBITDEPTH), 1)
+HBD=HighBitDepth
+else
+HBD=
+endif
+
+# intermediate directory for object files
+OBJ_DIR				= ./objects$(HBD)
+
+# set executable name
+PRJ_NAME			= TAppDecoder$(HBD)
+
+# 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		= -lTLibDecoder$(HBD)d -lTLibCommon$(HBD)d -lTLibVideoIO$(HBD)d -lTAppCommon$(HBD)d
+DYN_DEBUG_PREREQS		= $(LIB_DIR)/libTLibDecoder$(HBD)d.a $(LIB_DIR)/libTLibCommon$(HBD)d.a $(LIB_DIR)/libTLibVideoIO$(HBD)d.a $(LIB_DIR)/libTAppCommon$(HBD)d.a
+STAT_DEBUG_LIBS		= -lTLibDecoder$(HBD)Staticd -lTLibCommon$(HBD)Staticd -lTLibVideoIO$(HBD)Staticd -lTAppCommon$(HBD)Staticd
+STAT_DEBUG_PREREQS		= $(LIB_DIR)/libTLibDecoder$(HBD)Staticd.a $(LIB_DIR)/libTLibCommon$(HBD)Staticd.a $(LIB_DIR)/libTLibVideoIO$(HBD)Staticd.a $(LIB_DIR)/libTAppCommon$(HBD)Staticd.a
+
+DYN_RELEASE_LIBS	= -lTLibDecoder$(HBD) -lTLibCommon$(HBD) -lTLibVideoIO$(HBD) -lTAppCommon$(HBD)
+DYN_RELEASE_PREREQS	= $(LIB_DIR)/libTLibDecoder$(HBD).a $(LIB_DIR)/libTLibCommon$(HBD).a $(LIB_DIR)/libTLibVideoIO$(HBD).a $(LIB_DIR)/libTAppCommon$(HBD).a
+STAT_RELEASE_LIBS	= -lTLibDecoder$(HBD)Static -lTLibCommon$(HBD)Static -lTLibVideoIO$(HBD)Static -lTAppCommon$(HBD)Static
+STAT_RELEASE_PREREQS	= $(LIB_DIR)/libTLibDecoder$(HBD)Static.a $(LIB_DIR)/libTLibCommon$(HBD)Static.a $(LIB_DIR)/libTLibVideoIO$(HBD)Static.a $(LIB_DIR)/libTAppCommon$(HBD)Static.a
+
+
+# name of the base makefile
+MAKE_FILE_NAME		= ../../common/makefile.base
+
+# include the base makefile
+include $(MAKE_FILE_NAME)
Index: /tags/SHM-9.0/build/linux/app/TAppDecoderAnalyser/makefile
===================================================================
--- /tags/SHM-9.0/build/linux/app/TAppDecoderAnalyser/makefile	(revision 1088)
+++ /tags/SHM-9.0/build/linux/app/TAppDecoderAnalyser/makefile	(revision 1088)
@@ -0,0 +1,64 @@
+# 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	=
+
+ifeq ($(HIGHBITDEPTH), 1)
+HBD=HighBitDepth
+else
+HBD=
+endif
+
+# intermediate directory for object files
+OBJ_DIR				= ./objects$(HBD)
+
+# set executable name
+PRJ_NAME			= TAppDecoderAnalyser$(HBD)
+
+# defines to set
+DEFS				= -DMSYS_LINUX -D_LARGEFILE64_SOURCE -D_FILE_OFFSET_BITS=64 -DMSYS_UNIX_LARGEFILE -DRExt__DECODER_DEBUG_BIT_STATISTICS=1
+
+# 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		= -lTLibDecoderAnalyser$(HBD)d -lTLibCommon$(HBD)d -lTLibVideoIO$(HBD)d -lTAppCommon$(HBD)d
+DYN_DEBUG_PREREQS		= $(LIB_DIR)/libTLibDecoderAnalyser$(HBD)d.a $(LIB_DIR)/libTLibCommon$(HBD)d.a $(LIB_DIR)/libTLibVideoIO$(HBD)d.a $(LIB_DIR)/libTAppCommon$(HBD)d.a
+STAT_DEBUG_LIBS		= -lTLibDecoderAnalyser$(HBD)Staticd -lTLibCommon$(HBD)Staticd -lTLibVideoIO$(HBD)Staticd -lTAppCommon$(HBD)Staticd
+STAT_DEBUG_PREREQS		= $(LIB_DIR)/libTLibDecoderAnalyser$(HBD)Staticd.a $(LIB_DIR)/libTLibCommon$(HBD)Staticd.a $(LIB_DIR)/libTLibVideoIO$(HBD)Staticd.a $(LIB_DIR)/libTAppCommon$(HBD)Staticd.a
+
+DYN_RELEASE_LIBS	= -lTLibDecoderAnalyser$(HBD) -lTLibCommon$(HBD) -lTLibVideoIO$(HBD) -lTAppCommon$(HBD)
+DYN_RELEASE_PREREQS	= $(LIB_DIR)/libTLibDecoderAnalyser$(HBD).a $(LIB_DIR)/libTLibCommon$(HBD).a $(LIB_DIR)/libTLibVideoIO$(HBD).a $(LIB_DIR)/libTAppCommon$(HBD).a
+STAT_RELEASE_LIBS	= -lTLibDecoderAnalyser$(HBD)Static -lTLibCommon$(HBD)Static -lTLibVideoIO$(HBD)Static -lTAppCommon$(HBD)Static
+STAT_RELEASE_PREREQS	= $(LIB_DIR)/libTLibDecoderAnalyser$(HBD)Static.a $(LIB_DIR)/libTLibCommon$(HBD)Static.a $(LIB_DIR)/libTLibVideoIO$(HBD)Static.a $(LIB_DIR)/libTAppCommon$(HBD)Static.a
+
+
+# name of the base makefile
+MAKE_FILE_NAME		= ../../common/makefile.base
+
+# include the base makefile
+include $(MAKE_FILE_NAME)
Index: /tags/SHM-9.0/build/linux/app/TAppDownConvert/makefile
===================================================================
--- /tags/SHM-9.0/build/linux/app/TAppDownConvert/makefile	(revision 1088)
+++ /tags/SHM-9.0/build/linux/app/TAppDownConvert/makefile	(revision 1088)
@@ -0,0 +1,57 @@
+# the SOURCE definiton lets you move your makefile to another position
+CONFIG 				= CONSOLE
+
+# set directories to your wanted values
+SRC_DIR				= ../../../../source/App/TAppDownConvert
+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			= TAppDownConvert
+
+# defines to set
+DEFS				= -DMSYS_LINUX -D_LARGEFILE64_SOURCE -D_FILE_OFFSET_BITS=64 -DMSYS_UNIX_LARGEFILE
+
+# set objects
+OBJS          		= 	\
+					$(OBJ_DIR)/TAppDownConvert.o \
+					$(OBJ_DIR)/DownConvert.o \
+					
+
+# set libs to link with
+LIBS				= -ldl
+
+DEBUG_LIBS			=
+RELEASE_LIBS		=
+
+STAT_LIBS			= -lpthread
+DYN_LIBS			=
+
+
+DYN_DEBUG_LIBS		= 
+DYN_DEBUG_PREREQS	= 
+STAT_DEBUG_LIBS		= 
+STAT_DEBUG_PREREQS	= 
+
+DYN_RELEASE_LIBS	= 
+DYN_RELEASE_PREREQS	= 
+STAT_RELEASE_LIBS	= 
+STAT_RELEASE_PREREQS= 
+
+
+# name of the base makefile
+MAKE_FILE_NAME		= ../../common/makefile.base
+
+# include the base makefile
+include $(MAKE_FILE_NAME)
Index: /tags/SHM-9.0/build/linux/app/TAppEncoder/makefile
===================================================================
--- /tags/SHM-9.0/build/linux/app/TAppEncoder/makefile	(revision 1088)
+++ /tags/SHM-9.0/build/linux/app/TAppEncoder/makefile	(revision 1088)
@@ -0,0 +1,65 @@
+# 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	=
+
+ifeq ($(HIGHBITDEPTH), 1)
+HBD=HighBitDepth
+else
+HBD=
+endif
+
+# intermediate directory for object files
+OBJ_DIR				= ./objects$(HBD)
+
+# set executable name
+PRJ_NAME			= TAppEncoder$(HBD)
+
+# 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)/TAppEncLayerCfg.o \
+					$(OBJ_DIR)/TAppEncTop.o \
+
+# set libs to link with
+LIBS				= -ldl
+
+DEBUG_LIBS			=
+RELEASE_LIBS		=
+
+STAT_LIBS			= -lpthread
+DYN_LIBS			=
+
+
+DYN_DEBUG_LIBS		= -lTLibEncoder$(HBD)d -lTLibCommon$(HBD)d -lTLibVideoIO$(HBD)d -lTAppCommon$(HBD)d
+DYN_DEBUG_PREREQS		= $(LIB_DIR)/libTLibEncoder$(HBD)d.a $(LIB_DIR)/libTLibCommon$(HBD)d.a $(LIB_DIR)/libTLibVideoIO$(HBD)d.a $(LIB_DIR)/libTAppCommon$(HBD)d.a
+STAT_DEBUG_LIBS		= -lTLibEncoder$(HBD)Staticd -lTLibCommon$(HBD)Staticd -lTLibVideoIO$(HBD)Staticd -lTAppCommon$(HBD)Staticd
+STAT_DEBUG_PREREQS		= $(LIB_DIR)/libTLibEncoder$(HBD)Staticd.a $(LIB_DIR)/libTLibCommon$(HBD)Staticd.a $(LIB_DIR)/libTLibVideoIO$(HBD)Staticd.a $(LIB_DIR)/libTAppCommon$(HBD)Staticd.a
+
+DYN_RELEASE_LIBS	= -lTLibEncoder$(HBD) -lTLibCommon$(HBD) -lTLibVideoIO$(HBD) -lTAppCommon$(HBD)
+DYN_RELEASE_PREREQS	= $(LIB_DIR)/libTLibEncoder$(HBD).a $(LIB_DIR)/libTLibCommon$(HBD).a $(LIB_DIR)/libTLibVideoIO$(HBD).a $(LIB_DIR)/libTAppCommon$(HBD).a
+STAT_RELEASE_LIBS	= -lTLibEncoder$(HBD)Static -lTLibCommon$(HBD)Static -lTLibVideoIO$(HBD)Static -lTAppCommon$(HBD)Static
+STAT_RELEASE_PREREQS	= $(LIB_DIR)/libTLibEncoder$(HBD)Static.a $(LIB_DIR)/libTLibCommon$(HBD)Static.a $(LIB_DIR)/libTLibVideoIO$(HBD)Static.a $(LIB_DIR)/libTAppCommon$(HBD)Static.a
+
+
+# name of the base makefile
+MAKE_FILE_NAME		= ../../common/makefile.base
+
+# include the base makefile
+include $(MAKE_FILE_NAME)
Index: /tags/SHM-9.0/build/linux/common/makefile.base
===================================================================
--- /tags/SHM-9.0/build/linux/common/makefile.base	(revision 1088)
+++ /tags/SHM-9.0/build/linux/common/makefile.base	(revision 1088)
@@ -0,0 +1,490 @@
+#########################################################
+# check CONFIG parameter
+#########################################################
+
+ifneq ($(CONFIG), LIBRARY)
+ifneq ($(CONFIG), CONSOLE)
+CONFIG_ERR = TRUE
+endif
+endif
+
+#########################################################
+# executables used
+#########################################################
+
+CPP     = g++
+CC      = gcc
+AR    	= ar
+LD    	= $(CPP)
+ASM		= nasm
+
+#########################################################
+# output file names and version information
+#########################################################
+
+ifeq ($(CONFIG), LIBRARY)
+# the libraries that can be created
+STAT_DEBUG_OUT    	= $(LIB_DIR)/lib$(PRJ_NAME)Staticd.a
+STAT_RELEASE_OUT  	= $(LIB_DIR)/lib$(PRJ_NAME)Static.a
+DYN_DEBUG_OUT     	= $(LIB_DIR)/lib$(PRJ_NAME)d.so
+DYN_RELEASE_OUT   	= $(LIB_DIR)/lib$(PRJ_NAME).so
+#
+else 
+ifeq ($(CONFIG), CONSOLE)
+# the executables that can be created
+STAT_DEBUG_OUT    = $(BIN_DIR)/$(PRJ_NAME)Staticd
+STAT_RELEASE_OUT  = $(BIN_DIR)/$(PRJ_NAME)Static
+DYN_DEBUG_OUT     = $(BIN_DIR)/$(PRJ_NAME)d
+DYN_RELEASE_OUT   = $(BIN_DIR)/$(PRJ_NAME)
+#
+endif
+endif
+
+
+#########################################################
+# c compiler flags
+#########################################################
+
+# default cpp flags for all configurations
+#CPPFLAGS          = -Wall -fPIC $(DEFS) -I$(CURDIR)/$(INC_DIR) $(USER_INC_DIRS)
+CPPFLAGS          = -fPIC $(DEFS) -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
+##########
+
+ifeq ($(HIGHBITDEPTH), 1)
+CPPFLAGS+="-DRExt__HIGH_BIT_DEPTH_SUPPORT=1"
+endif
+
+#
+# debug cpp flags
+DEBUG_CPPFLAGS    = -g  -D_DEBUG
+#
+# release cpp
+RELEASE_CPPFLAGS  =  -O3 -Wuninitialized
+
+
+#########################################################
+# assembler compiler flags
+#########################################################
+
+# default asm flags for all configurations
+ASMFLAGS          = -f elf $(DEFS)
+#
+# debug asm flags
+DEBUG_ASMFLAGS    = -g
+#
+# release asm flags
+RELEASE_ASMFLAGS  =
+
+
+
+#########################################################
+# linker flags
+#########################################################
+
+# linker flags for all
+ALL_LDFLAGS       = -Wall
+
+########## 
+# enforce 32-bit build : 1=yes, 0=no
+##########
+ifeq ($(M32),1)
+ALL_LDFLAGS+=-m32
+endif
+##########
+
+
+ifeq ($(CONFIG), LIBRARY)
+# linker flags for library
+# LDFLAGS           = $(ALL_LDFLAGS) -shared -Wl,-Bsymbolic
+LDFLAGS           = $(ALL_LDFLAGS) -shared
+#
+# debug linker flags for library
+DEBUG_LDFLAGS     = -Wl,-soname,lib$(PRJ_NAME)d.so.$(VER)
+#
+# release linker flags for library
+RELEASE_LDFLAGS   = -Wl,-soname,lib$(PRJ_NAME).so.$(VER)
+#
+else
+ifeq ($(CONFIG), CONSOLE)
+# linker flags for console
+LDFLAGS           = $(ALL_LDFLAGS)
+#
+# debug linker flags for console
+DEBUG_LDFLAGS     =
+#
+# release linker flags for console
+RELEASE_LDFLAGS   =
+#
+endif
+endif
+
+
+
+#########################################################
+# objects that have to be created
+#########################################################
+
+# the object types that have to be created      
+RELEASE_OBJS  = $(OBJS:.o=.r.o)
+DEBUG_OBJS    = $(OBJS:.o=.d.o)
+
+
+#########################################################
+# rules
+#########################################################
+
+# suffixes
+.SUFFIXES: .cpp .asm .r.o .d.o
+
+#########################################################
+# assembler rules
+#########################################################
+
+
+# create release objects
+$(OBJ_DIR)/%.r.o: $(SRC_DIR)/%.asm
+	$(ASM) $(ASMFLAGS) $(RELEASE_ASMFLAGS) -o $@ $<
+
+# create debug objects
+$(OBJ_DIR)/%.d.o: $(SRC_DIR)/%.asm
+	$(ASM) $(ASMFLAGS) $(DEBUG_ASMFLAGS) -o $@ $<
+
+# create release objects
+$(OBJ_DIR)/%.r.o: $(SRC_DIR1)/%.asm
+	$(ASM) $(ASMFLAGS) $(RELEASE_ASMFLAGS) -o $@ $<
+
+# create debug objects
+$(OBJ_DIR)/%.d.o: $(SRC_DIR1)/%.asm
+	$(ASM) $(ASMFLAGS) $(DEBUG_ASMFLAGS) -o $@ $<
+
+# create release objects
+$(OBJ_DIR)/%.r.o: $(SRC_DIR2)/%.asm
+	$(ASM) $(ASMFLAGS) $(RELEASE_ASMFLAGS) -o $@ $<
+
+# create debug objects
+$(OBJ_DIR)/%.d.o: $(SRC_DIR2)/%.asm
+	$(ASM) $(ASMFLAGS) $(DEBUG_ASMFLAGS) -o $@ $<
+
+# create release objects
+$(OBJ_DIR)/%.r.o: $(SRC_DIR3)/%.asm
+	$(ASM) $(ASMFLAGS) $(RELEASE_ASMFLAGS) -o $@ $<
+
+# create debug objects
+$(OBJ_DIR)/%.d.o: $(SRC_DIR3)/%.asm
+	$(ASM) $(ASMFLAGS) $(DEBUG_ASMFLAGS) -o $@ $<
+
+# create release objects
+$(OBJ_DIR)/%.r.o: $(SRC_DIR4)/%.asm
+	$(ASM) $(ASMFLAGS) $(RELEASE_ASMFLAGS) -o $@ $<
+
+# create debug objects
+$(OBJ_DIR)/%.d.o: $(SRC_DIR4)/%.asm
+	$(ASM) $(ASMFLAGS) $(DEBUG_ASMFLAGS) -o $@ $<
+
+
+
+#########################################################
+# c rules
+#########################################################
+
+# Generate dependency files during compilation
+# see also: http://make.paulandlesley.org/autodep.html
+#    2005-01-25 Steffen Kamp (kamp@ient.rwth-aachen.de), RWTH Aachen
+define COMPILE_AND_DEPEND_RELEASE
+        $(CPP) -c -MMD -MF $(OBJ_DIR)/$*.r.d -MT $(OBJ_DIR)/$*.r.o $(CPPFLAGS) $(RELEASE_CPPFLAGS) -o $@ $(CURDIR)/$<
+        @cp $(OBJ_DIR)/$*.r.d $(OBJ_DIR)/$*.r.P; \
+                sed -e 's/#.*//' -e 's/^[^:]*: *//' -e 's/ *\\$$//' \
+                -e '/^$$/ d' -e 's/$$/ :/' < $(OBJ_DIR)/$*.r.d >> $(OBJ_DIR)/$*.r.P; \
+                rm -f $(OBJ_DIR)/$*.r.d
+endef
+define COMPILE_AND_DEPEND_DEBUG
+        $(CPP) -c -MMD -MF $(OBJ_DIR)/$*.d.d -MT $(OBJ_DIR)/$*.d.o $(CPPFLAGS) $(DEBUG_CPPFLAGS) -o $@ $(CURDIR)/$<
+        @cp $(OBJ_DIR)/$*.d.d $(OBJ_DIR)/$*.d.P; \
+                sed -e 's/#.*//' -e 's/^[^:]*: *//' -e 's/ *\\$$//' \
+                -e '/^$$/ d' -e 's/$$/ :/' < $(OBJ_DIR)/$*.d.d >> $(OBJ_DIR)/$*.d.P; \
+                rm -f $(OBJ_DIR)/$*.d.d
+endef
+define COMPILE_AND_DEPEND_RELEASE_C
+        $(CC) -c -MMD -MF $(OBJ_DIR)/$*.r.d -MT $(OBJ_DIR)/$*.r.o $(CPPFLAGS) $(RELEASE_CPPFLAGS) -o $@ $(CURDIR)/$<
+        @cp $(OBJ_DIR)/$*.r.d $(OBJ_DIR)/$*.r.P; \
+                sed -e 's/#.*//' -e 's/^[^:]*: *//' -e 's/ *\\$$//' \
+                -e '/^$$/ d' -e 's/$$/ :/' < $(OBJ_DIR)/$*.r.d >> $(OBJ_DIR)/$*.r.P; \
+                rm -f $(OBJ_DIR)/$*.r.d
+endef
+define COMPILE_AND_DEPEND_DEBUG_C
+        $(CC) -c -MMD -MF $(OBJ_DIR)/$*.d.d -MT $(OBJ_DIR)/$*.d.o $(CPPFLAGS) $(DEBUG_CPPFLAGS) -o $@ $(CURDIR)/$<
+        @cp $(OBJ_DIR)/$*.d.d $(OBJ_DIR)/$*.d.P; \
+                sed -e 's/#.*//' -e 's/^[^:]*: *//' -e 's/ *\\$$//' \
+                -e '/^$$/ d' -e 's/$$/ :/' < $(OBJ_DIR)/$*.d.d >> $(OBJ_DIR)/$*.d.P; \
+                rm -f $(OBJ_DIR)/$*.d.d
+endef
+
+# create release objects
+$(OBJ_DIR)/%.r.o: $(SRC_DIR)/%.cpp
+	$(COMPILE_AND_DEPEND_RELEASE)
+
+# create debug objects
+$(OBJ_DIR)/%.d.o: $(SRC_DIR)/%.cpp
+	$(COMPILE_AND_DEPEND_DEBUG)
+
+# create release objects
+$(OBJ_DIR)/%.r.o: $(SRC_DIR1)/%.cpp
+	$(COMPILE_AND_DEPEND_RELEASE)
+
+# create debug objects
+$(OBJ_DIR)/%.d.o: $(SRC_DIR1)/%.cpp
+	$(COMPILE_AND_DEPEND_DEBUG)
+
+# create release objects
+$(OBJ_DIR)/%.r.o: $(SRC_DIR2)/%.cpp
+	$(COMPILE_AND_DEPEND_RELEASE)
+
+# create debug objects
+$(OBJ_DIR)/%.d.o: $(SRC_DIR2)/%.cpp
+	$(COMPILE_AND_DEPEND_DEBUG)
+
+# create release objects
+$(OBJ_DIR)/%.r.o: $(SRC_DIR3)/%.cpp
+	$(COMPILE_AND_DEPEND_RELEASE)
+
+# create debug objects
+$(OBJ_DIR)/%.d.o: $(SRC_DIR3)/%.cpp
+	$(COMPILE_AND_DEPEND_DEBUG)
+
+# create release objects
+$(OBJ_DIR)/%.r.o: $(SRC_DIR4)/%.cpp
+	$(COMPILE_AND_DEPEND_RELEASE)
+
+# create debug objects
+$(OBJ_DIR)/%.d.o: $(SRC_DIR4)/%.cpp
+	$(COMPILE_AND_DEPEND_DEBUG)
+
+# create release objects
+$(OBJ_DIR)/%.r.o: $(SRC_DIR)/%.c
+	$(COMPILE_AND_DEPEND_RELEASE_C)
+
+# create debug objects
+$(OBJ_DIR)/%.d.o: $(SRC_DIR)/%.c
+	$(COMPILE_AND_DEPEND_DEBUG_C)
+
+# create release objects
+$(OBJ_DIR)/%.r.o: $(SRC_DIR1)/%.c
+	$(COMPILE_AND_DEPEND_RELEASE_C)
+
+# create debug objects
+$(OBJ_DIR)/%.d.o: $(SRC_DIR1)/%.c
+	$(COMPILE_AND_DEPEND_DEBUG_C)
+
+# create release objects
+$(OBJ_DIR)/%.r.o: $(SRC_DIR2)/%.c
+	$(COMPILE_AND_DEPEND_RELEASE_C)
+
+# create debug objects
+$(OBJ_DIR)/%.d.o: $(SRC_DIR2)/%.c
+	$(COMPILE_AND_DEPEND_DEBUG_C)
+
+# create release objects
+$(OBJ_DIR)/%.r.o: $(SRC_DIR3)/%.c
+	$(COMPILE_AND_DEPEND_RELEASE_C)
+
+# create debug objects
+$(OBJ_DIR)/%.d.o: $(SRC_DIR3)/%.c
+	$(COMPILE_AND_DEPEND_DEBUG_C)
+
+# create release objects
+$(OBJ_DIR)/%.r.o: $(SRC_DIR4)/%.c
+	$(COMPILE_AND_DEPEND_RELEASE_C)
+
+# create debug objects
+$(OBJ_DIR)/%.d.o: $(SRC_DIR4)/%.c
+	$(COMPILE_AND_DEPEND_DEBUG_C)
+
+
+#########################################################
+# directory settings
+#########################################################
+
+ifeq ($(CONFIG), LIBRARY)
+# directories that have to be created for a library
+CHECK_DIRS = $(OBJ_DIR) $(LIB_DIR)
+#
+else
+ifeq ($(CONFIG), CONSOLE)
+# directories that have to be created for console and MFC
+CHECK_DIRS = $(OBJ_DIR) $(BIN_DIR)
+#
+endif
+endif
+
+
+#########################################################
+# targets
+#########################################################
+
+all:              	check_errors debug release
+
+debug:            	check_errors \
+					$(CHECK_DIRS) \
+					$(STAT_DEBUG_OUT)
+
+release:          	check_errors \
+					$(CHECK_DIRS) \
+					$(STAT_RELEASE_OUT)
+
+
+#all:              	check_errors debug release
+#
+#debug:            	check_errors \
+#					$(CHECK_DIRS) \
+#					$(DYN_DEBUG_OUT) \
+#					$(STAT_DEBUG_OUT)
+#
+#release:          	check_errors \
+#					$(CHECK_DIRS) \
+#					$(DYN_RELEASE_OUT) \
+#					$(STAT_RELEASE_OUT)
+#
+#stat_debug:       	check_errors \
+#					$(CHECK_DIRS) \
+#					$(STAT_DEBUG_OUT)
+#          
+#dyn_debug:        	check_errors \
+#					$(CHECK_DIRS) \
+#					$(DYN_DEBUG_OUT)
+#
+#stat_release:     	check_errors \
+#					$(CHECK_DIRS) \
+#					$(STAT_RELEASE_OUT)
+#        
+#dyn_release:      	check_errors \
+#					$(CHECK_DIRS) \
+#					$(DYN_RELEASE_OUT)
+
+##########################################################
+# check for errors
+##########################################################
+check_errors:
+	@if [ "$(CONFIG_ERR)" = "TRUE" ]; then\
+		echo "Wrong CONFIG parameter specified: $(CONFIG)";\
+		false;\
+	fi
+
+
+##########################################################
+# create directories
+##########################################################
+
+$(OBJ_DIR):
+	@if [ ! -d $(OBJ_DIR) ]; then\
+		mkdir $(OBJ_DIR);\
+	fi
+
+$(LIB_DIR):
+	@if [ ! -d $(LIB_DIR) ]; then\
+		mkdir $(LIB_DIR);\
+	fi
+
+$(BIN_DIR):
+	@if [ ! -d $(BIN_DIR) ]; then\
+		mkdir $(BIN_DIR);\
+	fi
+
+
+
+##########################################################
+# create output files
+##########################################################
+
+ifeq ($(CONFIG), LIBRARY)
+#
+# create static debug out
+$(STAT_DEBUG_OUT): $(DEBUG_OBJS)
+	$(AR) -crs $@ $(DEBUG_OBJS)
+#
+#
+# create release debug out
+$(STAT_RELEASE_OUT): $(RELEASE_OBJS)
+	$(AR) -crs $@ $(RELEASE_OBJS)
+#
+#
+# create dynamic debug out
+$(DYN_DEBUG_OUT): $(DYN_DEBUG_OUT).$(VER) 
+	ln -fs lib$(PRJ_NAME)d.so.$(VER) $@
+#
+# create dynamic debug out
+$(DYN_DEBUG_OUT).$(VER): $(DEBUG_OBJS) 
+	$(LD) $(LDFLAGS) $(DEBUG_LDFLAGS) -o $@ $(DEBUG_OBJS) -L$(LIB_DIR) $(USER_LIB_DIRS) $(LIBS) $(DEBUG_LIBS) $(DYN_LIBS) $(DYN_DEBUG_LIBS)
+#
+#
+# create dynamic release out
+$(DYN_RELEASE_OUT): $(DYN_RELEASE_OUT).$(VER)
+	ln -fs lib$(PRJ_NAME).so.$(VER) $@
+#
+# create dynamic release out
+$(DYN_RELEASE_OUT).$(VER): $(RELEASE_OBJS)
+	$(LD) $(LDFLAGS) $(RELEASE_LDFLAGS) -o $@ $(RELEASE_OBJS) -L$(LIB_DIR) $(USER_LIB_DIRS) $(LIBS) $(RELEASE_LIBS) $(DYN_LIBS) $(DYN_RELEASE_LIBS)
+#
+#
+#
+#
+#
+else
+ifeq ($(CONFIG), CONSOLE)
+#
+# added linked libraries to target prerequisites - $(*_PREREQS) variables - to force relinking when libraries have been rebuilt
+#    2005-01-25 Steffen Kamp (kamp@ient.rwth-aachen.de), RWTH Aachen
+#
+# create static debug out
+$(STAT_DEBUG_OUT): $(DEBUG_OBJS) $(STAT_DEBUG_PREREQS)
+	$(LD) -o $@ $(LDFLAGS) $(DEBUG_LDFLAGS) $(DEBUG_OBJS) -L$(LIB_DIR) $(USER_LIB_DIRS) $(LIBS) $(DEBUG_LIBS) $(STAT_LIBS) $(STAT_DEBUG_LIBS)
+#
+#
+# create static release out
+$(STAT_RELEASE_OUT): $(RELEASE_OBJS) $(STAT_RELEASE_PREREQS)
+	$(LD) -o $@ $(LDFLAGS) $(RELEASE_LDFLAGS) $(RELEASE_OBJS) -L$(LIB_DIR) $(USER_LIB_DIRS) $(LIBS) $(RELEASE_LIBS) $(STAT_LIBS) $(STAT_RELEASE_LIBS)
+#
+#
+# create dynamic debug out
+$(DYN_DEBUG_OUT): $(DEBUG_OBJS) $(DYN_DEBUG_PREREQS)
+	$(LD) -o $@ $(LDFLAGS) $(DEBUG_LDFLAGS) $(DEBUG_OBJS) -L$(LIB_DIR) $(USER_LIB_DIRS) $(LIBS) $(DEBUG_LIBS) $(DYN_LIBS) $(DYN_DEBUG_LIBS)
+#
+#
+# create dynamic release out
+$(DYN_RELEASE_OUT): $(RELEASE_OBJS) $(DYN_RELEASE_PREREQS)
+	$(LD) -o $@ $(LDFLAGS) $(RELEASE_LDFLAGS) $(RELEASE_OBJS) -L$(LIB_DIR) $(USER_LIB_DIRS) $(LIBS) $(RELEASE_LIBS) $(DYN_LIBS) $(DYN_RELEASE_LIBS)
+#
+#
+endif
+endif
+
+##########################################################
+# delete all produced files
+##########################################################
+
+clean:
+	/bin/rm -rf $(STAT_DEBUG_OUT)
+	/bin/rm -rf $(STAT_RELEASE_OUT)
+	/bin/rm -rf $(DYN_DEBUG_OUT)
+	/bin/rm -rf $(DYN_RELEASE_OUT)
+	/bin/rm -rf $(OBJ_DIR)
+
+ifeq ($(CONFIG), LIBRARY)
+	/bin/rm -rf $(DYN_DEBUG_OUT).$(VER)
+	/bin/rm -rf $(DYN_RELEASE_OUT).$(VER)
+endif
+
+
+##########################################################
+# include dependency files
+##########################################################
+
+-include $(OBJS:.o=.d.P)
+-include $(OBJS:.o=.r.P)
Index: /tags/SHM-9.0/build/linux/lib/TAppCommon/makefile
===================================================================
--- /tags/SHM-9.0/build/linux/lib/TAppCommon/makefile	(revision 1088)
+++ /tags/SHM-9.0/build/linux/lib/TAppCommon/makefile	(revision 1088)
@@ -0,0 +1,61 @@
+# 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	=
+
+ifeq ($(HIGHBITDEPTH), 1)
+HBD=HighBitDepth
+else
+HBD=
+endif
+
+# intermediate directory for object files
+OBJ_DIR			= ./objects$(HBD)
+
+# the library name
+PRJ_NAME	 	= TAppCommon$(HBD)
+
+# 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 \
+
+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: /tags/SHM-9.0/build/linux/lib/TLibCommon/makefile
===================================================================
--- /tags/SHM-9.0/build/linux/lib/TLibCommon/makefile	(revision 1088)
+++ /tags/SHM-9.0/build/linux/lib/TLibCommon/makefile	(revision 1088)
@@ -0,0 +1,89 @@
+# 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	=
+
+ifeq ($(HIGHBITDEPTH), 1)
+HBD=HighBitDepth
+else
+HBD=
+endif
+
+# intermediate directory for object files
+OBJ_DIR			= ./objects$(HBD)
+
+# the library name
+PRJ_NAME	 	= TLibCommon$(HBD)
+
+# version information
+MAJOR_VER		= 0
+MINOR_VER		= 1
+VER				= $(MAJOR_VER).$(MINOR_VER)
+
+# defines to set
+DEFS			= -DMSYS_LINUX
+
+# set objects
+OBJS          	= \
+			$(OBJ_DIR)/Debug.o \
+			$(OBJ_DIR)/TComPicYuv.o \
+			$(OBJ_DIR)/TComYuv.o \
+			$(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)/TComChromaFormat.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)/TComPicYuvMD5.o \
+			$(OBJ_DIR)/TComPrediction.o \
+			$(OBJ_DIR)/TComRdCost.o \
+			$(OBJ_DIR)/TComRom.o \
+			$(OBJ_DIR)/TComSlice.o \
+			$(OBJ_DIR)/TComTrQuant.o \
+			$(OBJ_DIR)/TComTU.o \
+			$(OBJ_DIR)/TComInterpolationFilter.o \
+			$(OBJ_DIR)/libmd5.o \
+			$(OBJ_DIR)/TComWeightPrediction.o \
+			$(OBJ_DIR)/TComRdCostWeightPrediction.o \
+			$(OBJ_DIR)/TComUpsampleFilter.o \
+			$(OBJ_DIR)/TCom3DAsymLUT.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: /tags/SHM-9.0/build/linux/lib/TLibDecoder/makefile
===================================================================
--- /tags/SHM-9.0/build/linux/lib/TLibDecoder/makefile	(revision 1088)
+++ /tags/SHM-9.0/build/linux/lib/TLibDecoder/makefile	(revision 1088)
@@ -0,0 +1,72 @@
+# 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	=
+
+ifeq ($(HIGHBITDEPTH), 1)
+HBD=HighBitDepth
+else
+HBD=
+endif
+
+# intermediate directory for object files
+OBJ_DIR			= ./objects$(HBD)
+
+# the library name
+PRJ_NAME	 	= TLibDecoder$(HBD)
+
+# 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: /tags/SHM-9.0/build/linux/lib/TLibDecoderAnalyser/makefile
===================================================================
--- /tags/SHM-9.0/build/linux/lib/TLibDecoderAnalyser/makefile	(revision 1088)
+++ /tags/SHM-9.0/build/linux/lib/TLibDecoderAnalyser/makefile	(revision 1088)
@@ -0,0 +1,72 @@
+# 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	=
+
+ifeq ($(HIGHBITDEPTH), 1)
+HBD=HighBitDepth
+else
+HBD=
+endif
+
+# intermediate directory for object files
+OBJ_DIR			= ./objects$(HBD)
+
+# the library name
+PRJ_NAME	 	= TLibDecoderAnalyser$(HBD)
+
+# version information
+MAJOR_VER		= 0
+MINOR_VER		= 1
+VER				= $(MAJOR_VER).$(MINOR_VER)
+
+# defines to set
+DEFS			= -DMSYS_LINUX -DRExt__DECODER_DEBUG_BIT_STATISTICS=1
+
+# 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: /tags/SHM-9.0/build/linux/lib/TLibEncoder/makefile
===================================================================
--- /tags/SHM-9.0/build/linux/lib/TLibEncoder/makefile	(revision 1088)
+++ /tags/SHM-9.0/build/linux/lib/TLibEncoder/makefile	(revision 1088)
@@ -0,0 +1,80 @@
+# 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	=
+
+ifeq ($(HIGHBITDEPTH), 1)
+HBD=HighBitDepth
+else
+HBD=
+endif
+
+# intermediate directory for object files
+OBJ_DIR			= ./objects$(HBD)
+
+# the library name
+PRJ_NAME	 	= TLibEncoder$(HBD)
+
+# 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 \
+			$(OBJ_DIR)/TEnc3DAsymLUT.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: /tags/SHM-9.0/build/linux/lib/TLibVideoIO/makefile
===================================================================
--- /tags/SHM-9.0/build/linux/lib/TLibVideoIO/makefile	(revision 1088)
+++ /tags/SHM-9.0/build/linux/lib/TLibVideoIO/makefile	(revision 1088)
@@ -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/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	=
+
+ifeq ($(HIGHBITDEPTH), 1)
+HBD=HighBitDepth
+else
+HBD=
+endif
+
+# intermediate directory for object files
+OBJ_DIR			= ./objects$(HBD)
+
+# the library name
+PRJ_NAME	 	= TLibVideoIO$(HBD)
+
+# 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: /tags/SHM-9.0/build/linux/makefile
===================================================================
--- /tags/SHM-9.0/build/linux/makefile	(revision 1088)
+++ /tags/SHM-9.0/build/linux/makefile	(revision 1088)
@@ -0,0 +1,110 @@
+### enforce 32-bit build : 1=yes, 0=no
+M32?= 0
+ 
+export M32
+
+all:
+	$(MAKE) -C lib/TLibVideoIO 	MM32=$(M32)
+	$(MAKE) -C lib/TLibCommon 	MM32=$(M32)
+	$(MAKE) -C lib/TLibDecoder 	MM32=$(M32)
+	$(MAKE) -C lib/TLibEncoder 	MM32=$(M32)
+	$(MAKE) -C lib/TAppCommon       MM32=$(M32)
+	$(MAKE) -C app/TAppDecoder      MM32=$(M32)
+	$(MAKE) -C app/TAppEncoder      MM32=$(M32)
+	$(MAKE) -C app/TAppDownConvert  MM32=$(M32)	
+	$(MAKE) -C utils/annexBbytecount       MM32=$(M32)
+	$(MAKE) -C utils/convert_NtoMbit_YCbCr MM32=$(M32)
+	$(MAKE) -C lib/TLibDecoderAnalyser 	MM32=$(M32)
+	$(MAKE) -C app/TAppDecoderAnalyser      MM32=$(M32)
+
+debug:
+	$(MAKE) -C lib/TLibVideoIO 	debug MM32=$(M32)
+	$(MAKE) -C lib/TLibCommon 	debug MM32=$(M32)
+	$(MAKE) -C lib/TLibDecoder 	debug MM32=$(M32)
+	$(MAKE) -C lib/TLibEncoder 	debug MM32=$(M32)
+	$(MAKE) -C lib/TAppCommon       debug MM32=$(M32)
+	$(MAKE) -C app/TAppDecoder      debug MM32=$(M32)
+	$(MAKE) -C app/TAppEncoder      debug MM32=$(M32)
+	$(MAKE) -C app/TAppDownConvert  debug MM32=$(M32)
+	$(MAKE) -C utils/annexBbytecount       debug MM32=$(M32)
+	$(MAKE) -C utils/convert_NtoMbit_YCbCr debug MM32=$(M32)
+	$(MAKE) -C lib/TLibDecoderAnalyser 	debug MM32=$(M32)
+	$(MAKE) -C app/TAppDecoderAnalyser      debug MM32=$(M32)
+
+release:
+	$(MAKE) -C lib/TLibVideoIO 	release MM32=$(M32)
+	$(MAKE) -C lib/TLibCommon 	release MM32=$(M32)
+	$(MAKE) -C lib/TLibDecoder 	release MM32=$(M32)
+	$(MAKE) -C lib/TLibEncoder 	release MM32=$(M32)
+	$(MAKE) -C lib/TAppCommon       release MM32=$(M32)
+	$(MAKE) -C app/TAppDecoder      release MM32=$(M32)
+	$(MAKE) -C app/TAppEncoder      release MM32=$(M32)
+	$(MAKE) -C app/TAppDownConvert  release MM32=$(M32)
+	$(MAKE) -C utils/annexBbytecount       release MM32=$(M32)
+	$(MAKE) -C utils/convert_NtoMbit_YCbCr release MM32=$(M32)
+	$(MAKE) -C lib/TLibDecoderAnalyser 	release MM32=$(M32)
+	$(MAKE) -C app/TAppDecoderAnalyser      release MM32=$(M32)
+
+clean: clean_highbitdepth
+	$(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/TAppCommon       clean MM32=$(M32)
+	$(MAKE) -C app/TAppDecoder      clean MM32=$(M32)
+	$(MAKE) -C app/TAppEncoder      clean MM32=$(M32)
+	$(MAKE) -C app/TAppDownConvert  clean MM32=$(M32)
+	$(MAKE) -C utils/annexBbytecount       clean MM32=$(M32)
+	$(MAKE) -C utils/convert_NtoMbit_YCbCr clean MM32=$(M32)
+	$(MAKE) -C lib/TLibDecoderAnalyser 	clean MM32=$(M32)
+	$(MAKE) -C app/TAppDecoderAnalyser      clean MM32=$(M32)
+
+all_highbitdepth:
+	$(MAKE) -C lib/TLibVideoIO 	MM32=$(M32) HIGHBITDEPTH=1
+	$(MAKE) -C lib/TLibCommon 	MM32=$(M32) HIGHBITDEPTH=1
+	$(MAKE) -C lib/TLibDecoder 	MM32=$(M32) HIGHBITDEPTH=1
+	$(MAKE) -C lib/TLibEncoder 	MM32=$(M32) HIGHBITDEPTH=1
+	$(MAKE) -C app/TAppDownConvert 	MM32=$(M32) HIGHBITDEPTH=1
+	$(MAKE) -C lib/TAppCommon       MM32=$(M32) HIGHBITDEPTH=1
+	$(MAKE) -C app/TAppDecoder      MM32=$(M32) HIGHBITDEPTH=1
+	$(MAKE) -C app/TAppEncoder      MM32=$(M32) HIGHBITDEPTH=1
+	$(MAKE) -C lib/TLibDecoderAnalyser 	MM32=$(M32) HIGHBITDEPTH=1
+	$(MAKE) -C app/TAppDecoderAnalyser      MM32=$(M32) HIGHBITDEPTH=1
+
+debug_highbitdepth:
+	$(MAKE) -C lib/TLibVideoIO 	debug MM32=$(M32) HIGHBITDEPTH=1
+	$(MAKE) -C lib/TLibCommon 	debug MM32=$(M32) HIGHBITDEPTH=1
+	$(MAKE) -C lib/TLibDecoder 	debug MM32=$(M32) HIGHBITDEPTH=1
+	$(MAKE) -C lib/TLibEncoder 	debug MM32=$(M32) HIGHBITDEPTH=1
+	$(MAKE) -C app/TAppDownConvert 	debug MM32=$(M32) HIGHBITDEPTH=1
+	$(MAKE) -C lib/TAppCommon       debug MM32=$(M32) HIGHBITDEPTH=1
+	$(MAKE) -C app/TAppDecoder      debug MM32=$(M32) HIGHBITDEPTH=1
+	$(MAKE) -C app/TAppEncoder      debug MM32=$(M32) HIGHBITDEPTH=1
+	$(MAKE) -C lib/TLibDecoderAnalyser 	debug MM32=$(M32) HIGHBITDEPTH=1
+	$(MAKE) -C app/TAppDecoderAnalyser      debug MM32=$(M32) HIGHBITDEPTH=1
+
+release_highbitdepth:
+	$(MAKE) -C lib/TLibVideoIO 	release MM32=$(M32) HIGHBITDEPTH=1
+	$(MAKE) -C lib/TLibCommon 	release MM32=$(M32) HIGHBITDEPTH=1
+	$(MAKE) -C lib/TLibDecoder 	release MM32=$(M32) HIGHBITDEPTH=1
+	$(MAKE) -C lib/TLibEncoder 	release MM32=$(M32) HIGHBITDEPTH=1
+	$(MAKE) -C app/TAppDownConvert 	release MM32=$(M32) HIGHBITDEPTH=1
+	$(MAKE) -C lib/TAppCommon       release MM32=$(M32) HIGHBITDEPTH=1
+	$(MAKE) -C app/TAppDecoder      release MM32=$(M32) HIGHBITDEPTH=1
+	$(MAKE) -C app/TAppEncoder      release MM32=$(M32) HIGHBITDEPTH=1
+	$(MAKE) -C lib/TLibDecoderAnalyser 	release MM32=$(M32) HIGHBITDEPTH=1
+	$(MAKE) -C app/TAppDecoderAnalyser      release MM32=$(M32) HIGHBITDEPTH=1
+
+clean_highbitdepth:
+	$(MAKE) -C lib/TLibVideoIO 	clean MM32=$(M32) HIGHBITDEPTH=1
+	$(MAKE) -C lib/TLibCommon 	clean MM32=$(M32) HIGHBITDEPTH=1
+	$(MAKE) -C lib/TLibDecoder 	clean MM32=$(M32) HIGHBITDEPTH=1
+	$(MAKE) -C lib/TLibEncoder 	clean MM32=$(M32) HIGHBITDEPTH=1
+	$(MAKE) -C app/TAppDownConvert 	clean MM32=$(M32) HIGHBITDEPTH=1
+	$(MAKE) -C lib/TAppCommon       clean MM32=$(M32) HIGHBITDEPTH=1
+	$(MAKE) -C app/TAppDecoder      clean MM32=$(M32) HIGHBITDEPTH=1
+	$(MAKE) -C app/TAppEncoder      clean MM32=$(M32) HIGHBITDEPTH=1
+	$(MAKE) -C lib/TLibDecoderAnalyser 	clean MM32=$(M32) HIGHBITDEPTH=1
+	$(MAKE) -C app/TAppDecoderAnalyser      clean MM32=$(M32) HIGHBITDEPTH=1
+
+everything: all all_highbitdepth
Index: /tags/SHM-9.0/build/linux/utils/annexBbytecount/makefile
===================================================================
--- /tags/SHM-9.0/build/linux/utils/annexBbytecount/makefile	(revision 1088)
+++ /tags/SHM-9.0/build/linux/utils/annexBbytecount/makefile	(revision 1088)
@@ -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: /tags/SHM-9.0/build/linux/utils/convert_NtoMbit_YCbCr/makefile
===================================================================
--- /tags/SHM-9.0/build/linux/utils/convert_NtoMbit_YCbCr/makefile	(revision 1088)
+++ /tags/SHM-9.0/build/linux/utils/convert_NtoMbit_YCbCr/makefile	(revision 1088)
@@ -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: /tags/SHM-9.0/build/vc10/TAppCommon_vc10.vcproj
===================================================================
--- /tags/SHM-9.0/build/vc10/TAppCommon_vc10.vcproj	(revision 1088)
+++ /tags/SHM-9.0/build/vc10/TAppCommon_vc10.vcproj	(revision 1088)
@@ -0,0 +1,301 @@
+<?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)\vc10\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc10\$(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)\vc10\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc10\$(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)\vc10\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc10\$(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)\vc10\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc10\$(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>
+		</Filter>
+		<Filter
+			Name="Header Files"
+			Filter="h;hpp;hxx;hm;inl;inc;xsd"
+			>
+			<File
+				RelativePath="..\..\source\Lib\TAppCommon\program_options_lite.h"
+				>
+			</File>
+		</Filter>
+	</Files>
+	<Globals>
+	</Globals>
+</VisualStudioProject>
Index: /tags/SHM-9.0/build/vc10/TAppCommon_vc10.vcxproj
===================================================================
--- /tags/SHM-9.0/build/vc10/TAppCommon_vc10.vcxproj	(revision 1088)
+++ /tags/SHM-9.0/build/vc10/TAppCommon_vc10.vcxproj	(revision 1088)
@@ -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>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" />
+  </ItemGroup>
+  <ItemGroup>
+    <ClInclude Include="..\..\source\Lib\TAppCommon\program_options_lite.h" />
+  </ItemGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
+  <ImportGroup Label="ExtensionTargets">
+  </ImportGroup>
+</Project>
Index: /tags/SHM-9.0/build/vc10/TAppCommon_vc10.vcxproj.filters
===================================================================
--- /tags/SHM-9.0/build/vc10/TAppCommon_vc10.vcxproj.filters	(revision 1088)
+++ /tags/SHM-9.0/build/vc10/TAppCommon_vc10.vcxproj.filters	(revision 1088)
@@ -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: /tags/SHM-9.0/build/vc10/TAppCommon_vc10.vcxproj.user
===================================================================
--- /tags/SHM-9.0/build/vc10/TAppCommon_vc10.vcxproj.user	(revision 1088)
+++ /tags/SHM-9.0/build/vc10/TAppCommon_vc10.vcxproj.user	(revision 1088)
@@ -0,0 +1,3 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+</Project>
Index: /tags/SHM-9.0/build/vc10/TAppDecoderAnalyser_vc10.vcxproj
===================================================================
--- /tags/SHM-9.0/build/vc10/TAppDecoderAnalyser_vc10.vcxproj	(revision 1088)
+++ /tags/SHM-9.0/build/vc10/TAppDecoderAnalyser_vc10.vcxproj	(revision 1088)
@@ -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>TAppDecoderAnalyser</ProjectName>
+    <ProjectGuid>{6BB4C8D8-449D-4CC1-A5E1-E98AAF94012F}</ProjectGuid>
+    <RootNamespace>TAppDecoderAnalyser</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;RExt__DECODER_DEBUG_BIT_STATISTICS=1;%(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;RExt__DECODER_DEBUG_BIT_STATISTICS=1;%(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="TLibDecoderAnalyser_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: /tags/SHM-9.0/build/vc10/TAppDecoderAnalyser_vc10.vcxproj.filters
===================================================================
--- /tags/SHM-9.0/build/vc10/TAppDecoderAnalyser_vc10.vcxproj.filters	(revision 1088)
+++ /tags/SHM-9.0/build/vc10/TAppDecoderAnalyser_vc10.vcxproj.filters	(revision 1088)
@@ -0,0 +1,30 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <ItemGroup>
+    <ClCompile Include="..\..\source\App\TAppDecoder\decmain.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\App\TAppDecoder\TAppDecTop.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\App\TAppDecoder\TAppDecCfg.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>
+  <ItemGroup>
+    <Filter Include="Header Files">
+      <UniqueIdentifier>{400c04e5-8a2d-4e65-8d57-f59c30e78110}</UniqueIdentifier>
+    </Filter>
+    <Filter Include="Source Files">
+      <UniqueIdentifier>{8fc5970e-5673-47ba-999b-aada746c9b46}</UniqueIdentifier>
+    </Filter>
+  </ItemGroup>
+</Project>
Index: /tags/SHM-9.0/build/vc10/TAppDecoderAnalyser_vc10.vcxproj.user
===================================================================
--- /tags/SHM-9.0/build/vc10/TAppDecoderAnalyser_vc10.vcxproj.user	(revision 1088)
+++ /tags/SHM-9.0/build/vc10/TAppDecoderAnalyser_vc10.vcxproj.user	(revision 1088)
@@ -0,0 +1,3 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+</Project>
Index: /tags/SHM-9.0/build/vc10/TAppDecoder_vc10.vcproj
===================================================================
--- /tags/SHM-9.0/build/vc10/TAppDecoder_vc10.vcproj	(revision 1088)
+++ /tags/SHM-9.0/build/vc10/TAppDecoder_vc10.vcproj	(revision 1088)
@@ -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\vc10\$(PlatformName)\$(ConfigurationName)\"
+			IntermediateDirectory="$(SolutionDir)\vc10\$(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\vc10\$(PlatformName)\$(ConfigurationName)\"
+			IntermediateDirectory="$(SolutionDir)\vc10\$(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\vc10\$(PlatformName)\$(ConfigurationName)\"
+			IntermediateDirectory="$(SolutionDir)\vc10\$(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\vc10\$(PlatformName)\$(ConfigurationName)\"
+			IntermediateDirectory="$(SolutionDir)\vc10\$(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: /tags/SHM-9.0/build/vc10/TAppDecoder_vc10.vcxproj
===================================================================
--- /tags/SHM-9.0/build/vc10/TAppDecoder_vc10.vcxproj	(revision 1088)
+++ /tags/SHM-9.0/build/vc10/TAppDecoder_vc10.vcxproj	(revision 1088)
@@ -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: /tags/SHM-9.0/build/vc10/TAppDecoder_vc10.vcxproj.filters
===================================================================
--- /tags/SHM-9.0/build/vc10/TAppDecoder_vc10.vcxproj.filters	(revision 1088)
+++ /tags/SHM-9.0/build/vc10/TAppDecoder_vc10.vcxproj.filters	(revision 1088)
@@ -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: /tags/SHM-9.0/build/vc10/TAppDecoder_vc10.vcxproj.user
===================================================================
--- /tags/SHM-9.0/build/vc10/TAppDecoder_vc10.vcxproj.user	(revision 1088)
+++ /tags/SHM-9.0/build/vc10/TAppDecoder_vc10.vcxproj.user	(revision 1088)
@@ -0,0 +1,15 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
+    <LocalDebuggerWorkingDirectory>$(ProjectDir)/../../../</LocalDebuggerWorkingDirectory>
+    <DebuggerFlavor>WindowsLocalDebugger</DebuggerFlavor>
+    <LocalDebuggerCommandArguments>-b str/Bus.bin -ls 2</LocalDebuggerCommandArguments>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
+    <LocalDebuggerCommandArguments>-b str/Bus.bin -ls 2</LocalDebuggerCommandArguments>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
+    <LocalDebuggerWorkingDirectory>$(ProjectDir)/../../../</LocalDebuggerWorkingDirectory>
+    <DebuggerFlavor>WindowsLocalDebugger</DebuggerFlavor>
+  </PropertyGroup>
+</Project>
Index: /tags/SHM-9.0/build/vc10/TAppDownConvert/TAppDownConvert.vcxproj
===================================================================
--- /tags/SHM-9.0/build/vc10/TAppDownConvert/TAppDownConvert.vcxproj	(revision 1088)
+++ /tags/SHM-9.0/build/vc10/TAppDownConvert/TAppDownConvert.vcxproj	(revision 1088)
@@ -0,0 +1,136 @@
+﻿<?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">
+    <ProjectGuid>{FB952E1B-681F-4461-9C8B-4F1F8B70E58B}</ProjectGuid>
+    <RootNamespace>TAppDownConvert</RootNamespace>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
+    <ConfigurationType>Application</ConfigurationType>
+    <UseDebugLibraries>true</UseDebugLibraries>
+    <CharacterSet>MultiByte</CharacterSet>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
+    <ConfigurationType>Application</ConfigurationType>
+    <UseDebugLibraries>true</UseDebugLibraries>
+    <CharacterSet>MultiByte</CharacterSet>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
+    <ConfigurationType>Application</ConfigurationType>
+    <UseDebugLibraries>false</UseDebugLibraries>
+    <WholeProgramOptimization>true</WholeProgramOptimization>
+    <CharacterSet>MultiByte</CharacterSet>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
+    <ConfigurationType>Application</ConfigurationType>
+    <UseDebugLibraries>false</UseDebugLibraries>
+    <WholeProgramOptimization>true</WholeProgramOptimization>
+    <CharacterSet>MultiByte</CharacterSet>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
+  <ImportGroup Label="ExtensionSettings">
+  </ImportGroup>
+  <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
+    <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>
+  <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
+    <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>
+  <PropertyGroup Label="UserMacros" />
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
+    <OutDir>$(SolutionDir)\..\bin\vc10\$(Platform)\$(Configuration)\</OutDir>
+    <IntDir>$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
+    <OutDir>$(SolutionDir)\..\bin\vc10\$(Platform)\$(Configuration)\</OutDir>
+    <IntDir>$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
+    <OutDir>$(SolutionDir)\..\bin\vc10\$(Platform)\$(Configuration)\</OutDir>
+    <IntDir>$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
+    <OutDir>$(SolutionDir)\..\bin\vc10\$(Platform)\$(Configuration)\</OutDir>
+    <IntDir>$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+  </PropertyGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
+    <ClCompile>
+      <WarningLevel>Level3</WarningLevel>
+      <Optimization>Disabled</Optimization>
+      <PreprocessorDefinitions>_MBCS;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+    </ClCompile>
+    <Link>
+      <GenerateDebugInformation>true</GenerateDebugInformation>
+    </Link>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
+    <ClCompile>
+      <WarningLevel>Level3</WarningLevel>
+      <Optimization>Disabled</Optimization>
+    </ClCompile>
+    <Link>
+      <GenerateDebugInformation>true</GenerateDebugInformation>
+    </Link>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
+    <ClCompile>
+      <WarningLevel>Level3</WarningLevel>
+      <Optimization>MaxSpeed</Optimization>
+      <FunctionLevelLinking>true</FunctionLevelLinking>
+      <IntrinsicFunctions>true</IntrinsicFunctions>
+      <PreprocessorDefinitions>_MBCS;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+    </ClCompile>
+    <Link>
+      <GenerateDebugInformation>true</GenerateDebugInformation>
+      <EnableCOMDATFolding>true</EnableCOMDATFolding>
+      <OptimizeReferences>true</OptimizeReferences>
+    </Link>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
+    <ClCompile>
+      <WarningLevel>Level3</WarningLevel>
+      <Optimization>MaxSpeed</Optimization>
+      <FunctionLevelLinking>true</FunctionLevelLinking>
+      <IntrinsicFunctions>true</IntrinsicFunctions>
+    </ClCompile>
+    <Link>
+      <GenerateDebugInformation>true</GenerateDebugInformation>
+      <EnableCOMDATFolding>true</EnableCOMDATFolding>
+      <OptimizeReferences>true</OptimizeReferences>
+    </Link>
+  </ItemDefinitionGroup>
+  <ItemGroup>
+    <ClCompile Include="..\..\..\source\App\TAppDownConvert\DownConvert.cpp" />
+    <ClCompile Include="..\..\..\source\App\TAppDownConvert\TAppDownConvert.cpp" />
+  </ItemGroup>
+  <ItemGroup>
+    <ClInclude Include="..\..\..\source\App\TAppDownConvert\DownConvert.h" />
+  </ItemGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
+  <ImportGroup Label="ExtensionTargets">
+  </ImportGroup>
+</Project>
Index: /tags/SHM-9.0/build/vc10/TAppDownConvert/TAppDownConvert.vcxproj.filters
===================================================================
--- /tags/SHM-9.0/build/vc10/TAppDownConvert/TAppDownConvert.vcxproj.filters	(revision 1088)
+++ /tags/SHM-9.0/build/vc10/TAppDownConvert/TAppDownConvert.vcxproj.filters	(revision 1088)
@@ -0,0 +1,22 @@
+﻿<?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>
+    <Filter Include="Resource Files">
+      <UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
+      <Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
+    </Filter>
+  </ItemGroup>
+  <ItemGroup>
+    <ClCompile Include="..\..\..\source\App\TAppDownConvert\TAppDownConvert.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+  </ItemGroup>
+</Project>
Index: /tags/SHM-9.0/build/vc10/TAppDownConvert/TAppDownConvert.vcxproj.user
===================================================================
--- /tags/SHM-9.0/build/vc10/TAppDownConvert/TAppDownConvert.vcxproj.user	(revision 1088)
+++ /tags/SHM-9.0/build/vc10/TAppDownConvert/TAppDownConvert.vcxproj.user	(revision 1088)
@@ -0,0 +1,3 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+</Project>
Index: /tags/SHM-9.0/build/vc10/TAppEncoder_vc10.vcproj
===================================================================
--- /tags/SHM-9.0/build/vc10/TAppEncoder_vc10.vcproj	(revision 1088)
+++ /tags/SHM-9.0/build/vc10/TAppEncoder_vc10.vcproj	(revision 1088)
@@ -0,0 +1,366 @@
+<?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\vc10\$(PlatformName)\$(ConfigurationName)\"
+			IntermediateDirectory="$(SolutionDir)\vc10\$(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\vc10\$(PlatformName)\$(ConfigurationName)\"
+			IntermediateDirectory="$(SolutionDir)\vc10\$(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\vc10\$(PlatformName)\$(ConfigurationName)\"
+			IntermediateDirectory="$(SolutionDir)\vc10\$(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\vc10\$(PlatformName)\$(ConfigurationName)\"
+			IntermediateDirectory="$(SolutionDir)\vc10\$(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\TAppEncLayerCfg.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\TAppEncLayerCfg.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: /tags/SHM-9.0/build/vc10/TAppEncoder_vc10.vcxproj
===================================================================
--- /tags/SHM-9.0/build/vc10/TAppEncoder_vc10.vcxproj	(revision 1088)
+++ /tags/SHM-9.0/build/vc10/TAppEncoder_vc10.vcxproj	(revision 1088)
@@ -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>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>
+      <StackReserveSize>8000000</StackReserveSize>
+    </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>
+      <StackReserveSize>8000000</StackReserveSize>
+    </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\TAppEncLayerCfg.cpp" />
+    <ClCompile Include="..\..\source\App\TAppEncoder\TAppEncTop.cpp" />
+  </ItemGroup>
+  <ItemGroup>
+    <ClInclude Include="..\..\source\App\TAppEncoder\TAppEncCfg.h" />
+    <ClInclude Include="..\..\source\App\TAppEncoder\TAppEncLayerCfg.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="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: /tags/SHM-9.0/build/vc10/TAppEncoder_vc10.vcxproj.filters
===================================================================
--- /tags/SHM-9.0/build/vc10/TAppEncoder_vc10.vcxproj.filters	(revision 1088)
+++ /tags/SHM-9.0/build/vc10/TAppEncoder_vc10.vcxproj.filters	(revision 1088)
@@ -0,0 +1,42 @@
+﻿<?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>
+    <ClCompile Include="..\..\source\App\TAppEncoder\TAppEncLayerCfg.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>
+    <ClInclude Include="..\..\source\App\TAppEncoder\TAppEncLayerCfg.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+  </ItemGroup>
+</Project>
Index: /tags/SHM-9.0/build/vc10/TAppEncoder_vc10.vcxproj.user
===================================================================
--- /tags/SHM-9.0/build/vc10/TAppEncoder_vc10.vcxproj.user	(revision 1088)
+++ /tags/SHM-9.0/build/vc10/TAppEncoder_vc10.vcxproj.user	(revision 1088)
@@ -0,0 +1,17 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
+    <LocalDebuggerCommandArguments>-c cfg/per-sequence-svc/Bus-2x.cfg -c cfg/encoder_randomaccess_scalable.cfg -c cfg/layers.cfg -q0 38 -q1 38 -g 8 -f 9 -b str/Bus.bin -c option.cfg </LocalDebuggerCommandArguments>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
+    <LocalDebuggerWorkingDirectory>$(ProjectDir)/../../../</LocalDebuggerWorkingDirectory>
+    <DebuggerFlavor>WindowsLocalDebugger</DebuggerFlavor>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
+    <LocalDebuggerCommandArguments>-c cfg/per-sequence-svc/CactusCrop-2x.cfg -c cfg/encoder_randomaccess_main.cfg -q0 30 -q1 30 -g 8 -f 17 -b str/CactusCrop.bin -c option.cfg -ibl rec/CactusCropBL-2x_rec.yuv -ibs rec/CactusCropBL-2x_syntax.bin</LocalDebuggerCommandArguments>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
+    <LocalDebuggerWorkingDirectory>$(ProjectDir)/../../../</LocalDebuggerWorkingDirectory>
+    <DebuggerFlavor>WindowsLocalDebugger</DebuggerFlavor>
+  </PropertyGroup>
+</Project>
Index: /tags/SHM-9.0/build/vc10/TLibCommon_vc10.vcproj
===================================================================
--- /tags/SHM-9.0/build/vc10/TLibCommon_vc10.vcproj	(revision 1088)
+++ /tags/SHM-9.0/build/vc10/TLibCommon_vc10.vcproj	(revision 1088)
@@ -0,0 +1,531 @@
+<?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)\vc10\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc10\$(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)\vc10\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc10\$(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)\vc10\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc10\$(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)\vc10\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc10\$(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\TComAdaptiveLoopFilter.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\TComUpsampleFilter.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\TComAdaptiveLoopFilter.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\TComUpsampleFilter.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: /tags/SHM-9.0/build/vc10/TLibCommon_vc10.vcxproj
===================================================================
--- /tags/SHM-9.0/build/vc10/TLibCommon_vc10.vcxproj	(revision 1088)
+++ /tags/SHM-9.0/build/vc10/TLibCommon_vc10.vcxproj	(revision 1088)
@@ -0,0 +1,220 @@
+﻿<?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\Debug.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibCommon\SEI.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TCom3DAsymLUT.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComBitStream.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComCABACTables.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComChromaFormat.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\TComTU.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComUpsampleFilter.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\Debug.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\NAL.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\SEI.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TCom3DAsymLUT.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\TComChromaFormat.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComCodingStatistics.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\TComRectangle.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\TComTU.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComUpsampleFilter.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: /tags/SHM-9.0/build/vc10/TLibCommon_vc10.vcxproj.filters
===================================================================
--- /tags/SHM-9.0/build/vc10/TLibCommon_vc10.vcxproj.filters	(revision 1088)
+++ /tags/SHM-9.0/build/vc10/TLibCommon_vc10.vcxproj.filters	(revision 1088)
@@ -0,0 +1,221 @@
+﻿<?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>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComUpsampleFilter.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TCom3DAsymLUT.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComChromaFormat.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\Debug.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComTU.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>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComUpsampleFilter.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TCom3DAsymLUT.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComChromaFormat.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComCodingStatistics.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComRectangle.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\Debug.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComTU.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+  </ItemGroup>
+</Project>
Index: /tags/SHM-9.0/build/vc10/TLibCommon_vc10.vcxproj.user
===================================================================
--- /tags/SHM-9.0/build/vc10/TLibCommon_vc10.vcxproj.user	(revision 1088)
+++ /tags/SHM-9.0/build/vc10/TLibCommon_vc10.vcxproj.user	(revision 1088)
@@ -0,0 +1,3 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+</Project>
Index: /tags/SHM-9.0/build/vc10/TLibDecoderAnalyser_vc10.vcxproj
===================================================================
--- /tags/SHM-9.0/build/vc10/TLibDecoderAnalyser_vc10.vcxproj	(revision 1088)
+++ /tags/SHM-9.0/build/vc10/TLibDecoderAnalyser_vc10.vcxproj	(revision 1088)
@@ -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>TLibDecoderAnalyser</ProjectName>
+    <ProjectGuid>{68C1251A-55D8-47C9-9052-62F785BD437A}</ProjectGuid>
+    <RootNamespace>TLibDecoderAnalyser</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;RExt__DECODER_DEBUG_BIT_STATISTICS=1;%(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;RExt__DECODER_DEBUG_BIT_STATISTICS=1;%(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: /tags/SHM-9.0/build/vc10/TLibDecoderAnalyser_vc10.vcxproj.filters
===================================================================
--- /tags/SHM-9.0/build/vc10/TLibDecoderAnalyser_vc10.vcxproj.filters	(revision 1088)
+++ /tags/SHM-9.0/build/vc10/TLibDecoderAnalyser_vc10.vcxproj.filters	(revision 1088)
@@ -0,0 +1,90 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <ItemGroup>
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\AnnexBread.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecTop.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>
+  </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\TDecBinCoder.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\SyntaxElementParser.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>
+  <ItemGroup>
+    <Filter Include="Header Files">
+      <UniqueIdentifier>{a5214d8c-1011-4ba6-a7a8-636f1748895c}</UniqueIdentifier>
+    </Filter>
+    <Filter Include="Source Files">
+      <UniqueIdentifier>{66740226-f793-4905-a9b1-120c1c15e160}</UniqueIdentifier>
+    </Filter>
+  </ItemGroup>
+</Project>
Index: /tags/SHM-9.0/build/vc10/TLibDecoderAnalyser_vc10.vcxproj.user
===================================================================
--- /tags/SHM-9.0/build/vc10/TLibDecoderAnalyser_vc10.vcxproj.user	(revision 1088)
+++ /tags/SHM-9.0/build/vc10/TLibDecoderAnalyser_vc10.vcxproj.user	(revision 1088)
@@ -0,0 +1,3 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+</Project>
Index: /tags/SHM-9.0/build/vc10/TLibDecoder_vc10.vcproj
===================================================================
--- /tags/SHM-9.0/build/vc10/TLibDecoder_vc10.vcproj	(revision 1088)
+++ /tags/SHM-9.0/build/vc10/TLibDecoder_vc10.vcproj	(revision 1088)
@@ -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)\vc10\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc10\$(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)\vc10\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc10\$(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)\vc10\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc10\$(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)\vc10\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc10\$(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: /tags/SHM-9.0/build/vc10/TLibDecoder_vc10.vcxproj
===================================================================
--- /tags/SHM-9.0/build/vc10/TLibDecoder_vc10.vcxproj	(revision 1088)
+++ /tags/SHM-9.0/build/vc10/TLibDecoder_vc10.vcxproj	(revision 1088)
@@ -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: /tags/SHM-9.0/build/vc10/TLibDecoder_vc10.vcxproj.filters
===================================================================
--- /tags/SHM-9.0/build/vc10/TLibDecoder_vc10.vcxproj.filters	(revision 1088)
+++ /tags/SHM-9.0/build/vc10/TLibDecoder_vc10.vcxproj.filters	(revision 1088)
@@ -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: /tags/SHM-9.0/build/vc10/TLibDecoder_vc10.vcxproj.user
===================================================================
--- /tags/SHM-9.0/build/vc10/TLibDecoder_vc10.vcxproj.user	(revision 1088)
+++ /tags/SHM-9.0/build/vc10/TLibDecoder_vc10.vcxproj.user	(revision 1088)
@@ -0,0 +1,3 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+</Project>
Index: /tags/SHM-9.0/build/vc10/TLibEncoder_vc10.vcproj
===================================================================
--- /tags/SHM-9.0/build/vc10/TLibEncoder_vc10.vcproj	(revision 1088)
+++ /tags/SHM-9.0/build/vc10/TLibEncoder_vc10.vcproj	(revision 1088)
@@ -0,0 +1,465 @@
+<?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)\vc10\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc10\$(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)\vc10\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc10\$(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)\vc10\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc10\$(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)\vc10\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc10\$(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\TEncAdaptiveLoopFilter.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\TEncAdaptiveLoopFilter.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: /tags/SHM-9.0/build/vc10/TLibEncoder_vc10.vcxproj
===================================================================
--- /tags/SHM-9.0/build/vc10/TLibEncoder_vc10.vcxproj	(revision 1088)
+++ /tags/SHM-9.0/build/vc10/TLibEncoder_vc10.vcxproj	(revision 1088)
@@ -0,0 +1,195 @@
+﻿<?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\TEnc3DAsymLUT.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\TEnc3DAsymLUT.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: /tags/SHM-9.0/build/vc10/TLibEncoder_vc10.vcxproj.filters
===================================================================
--- /tags/SHM-9.0/build/vc10/TLibEncoder_vc10.vcxproj.filters	(revision 1088)
+++ /tags/SHM-9.0/build/vc10/TLibEncoder_vc10.vcxproj.filters	(revision 1088)
@@ -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: /tags/SHM-9.0/build/vc10/TLibEncoder_vc10.vcxproj.user
===================================================================
--- /tags/SHM-9.0/build/vc10/TLibEncoder_vc10.vcxproj.user	(revision 1088)
+++ /tags/SHM-9.0/build/vc10/TLibEncoder_vc10.vcxproj.user	(revision 1088)
@@ -0,0 +1,3 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+</Project>
Index: /tags/SHM-9.0/build/vc10/TLibVideoIO_vc10.vcproj
===================================================================
--- /tags/SHM-9.0/build/vc10/TLibVideoIO_vc10.vcproj	(revision 1088)
+++ /tags/SHM-9.0/build/vc10/TLibVideoIO_vc10.vcproj	(revision 1088)
@@ -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)\vc10\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc10\$(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)\vc10\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc10\$(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)\vc10\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc10\$(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)\vc10\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc10\$(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: /tags/SHM-9.0/build/vc10/TLibVideoIO_vc10.vcxproj
===================================================================
--- /tags/SHM-9.0/build/vc10/TLibVideoIO_vc10.vcxproj	(revision 1088)
+++ /tags/SHM-9.0/build/vc10/TLibVideoIO_vc10.vcxproj	(revision 1088)
@@ -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: /tags/SHM-9.0/build/vc10/TLibVideoIO_vc10.vcxproj.filters
===================================================================
--- /tags/SHM-9.0/build/vc10/TLibVideoIO_vc10.vcxproj.filters	(revision 1088)
+++ /tags/SHM-9.0/build/vc10/TLibVideoIO_vc10.vcxproj.filters	(revision 1088)
@@ -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: /tags/SHM-9.0/build/vc10/TLibVideoIO_vc10.vcxproj.user
===================================================================
--- /tags/SHM-9.0/build/vc10/TLibVideoIO_vc10.vcxproj.user	(revision 1088)
+++ /tags/SHM-9.0/build/vc10/TLibVideoIO_vc10.vcxproj.user	(revision 1088)
@@ -0,0 +1,3 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+</Project>
Index: /tags/SHM-9.0/build/vc8/TAppCommon_vc8.vcproj
===================================================================
--- /tags/SHM-9.0/build/vc8/TAppCommon_vc8.vcproj	(revision 1088)
+++ /tags/SHM-9.0/build/vc8/TAppCommon_vc8.vcproj	(revision 1088)
@@ -0,0 +1,298 @@
+<?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>
+		</Filter>
+		<Filter
+			Name="Header Files"
+			Filter="h;hpp;hxx;hm;inl;inc;xsd"
+			>
+			<File
+				RelativePath="..\..\source\Lib\TAppCommon\program_options_lite.h"
+				>
+			</File>
+		</Filter>
+	</Files>
+	<Globals>
+	</Globals>
+</VisualStudioProject>
Index: /tags/SHM-9.0/build/vc8/TAppDecoder_vc8.vcproj
===================================================================
--- /tags/SHM-9.0/build/vc8/TAppDecoder_vc8.vcproj	(revision 1088)
+++ /tags/SHM-9.0/build/vc8/TAppDecoder_vc8.vcproj	(revision 1088)
@@ -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: /tags/SHM-9.0/build/vc8/TAppEncoder_vc8.vcproj
===================================================================
--- /tags/SHM-9.0/build/vc8/TAppEncoder_vc8.vcproj	(revision 1088)
+++ /tags/SHM-9.0/build/vc8/TAppEncoder_vc8.vcproj	(revision 1088)
@@ -0,0 +1,375 @@
+<?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\TAppEncLayerCfg.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\TAppEncLayerCfg.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: /tags/SHM-9.0/build/vc8/TLibCommon_vc8.vcproj
===================================================================
--- /tags/SHM-9.0/build/vc8/TLibCommon_vc8.vcproj	(revision 1088)
+++ /tags/SHM-9.0/build/vc8/TLibCommon_vc8.vcproj	(revision 1088)
@@ -0,0 +1,564 @@
+<?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\TLibCommon\Debug.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\libmd5\libmd5.c"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\SEI.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TCom3DAsymLUT.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComBitStream.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComCABACTables.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComChromaFormat.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\TComTU.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComUpsampleFilter.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\TLibCommon\Debug.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\TCom3DAsymLUT.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\TComChromaFormat.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComCodingStatistics.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\TComRectangle.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\TComTU.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComUpsampleFilter.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: /tags/SHM-9.0/build/vc8/TLibDecoder_vc8.vcproj
===================================================================
--- /tags/SHM-9.0/build/vc8/TLibDecoder_vc8.vcproj	(revision 1088)
+++ /tags/SHM-9.0/build/vc8/TLibDecoder_vc8.vcproj	(revision 1088)
@@ -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: /tags/SHM-9.0/build/vc8/TLibEncoder_vc8.vcproj
===================================================================
--- /tags/SHM-9.0/build/vc8/TLibEncoder_vc8.vcproj	(revision 1088)
+++ /tags/SHM-9.0/build/vc8/TLibEncoder_vc8.vcproj	(revision 1088)
@@ -0,0 +1,462 @@
+<?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\TEnc3DAsymLUT.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\TEnc3DAsymLUT.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: /tags/SHM-9.0/build/vc8/TLibVideoIO_vc8.vcproj
===================================================================
--- /tags/SHM-9.0/build/vc8/TLibVideoIO_vc8.vcproj	(revision 1088)
+++ /tags/SHM-9.0/build/vc8/TLibVideoIO_vc8.vcproj	(revision 1088)
@@ -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: /tags/SHM-9.0/build/vc9/TAppCommon_vc9.vcproj
===================================================================
--- /tags/SHM-9.0/build/vc9/TAppCommon_vc9.vcproj	(revision 1088)
+++ /tags/SHM-9.0/build/vc9/TAppCommon_vc9.vcproj	(revision 1088)
@@ -0,0 +1,301 @@
+<?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>
+		</Filter>
+		<Filter
+			Name="Header Files"
+			Filter="h;hpp;hxx;hm;inl;inc;xsd"
+			>
+			<File
+				RelativePath="..\..\source\Lib\TAppCommon\program_options_lite.h"
+				>
+			</File>
+		</Filter>
+	</Files>
+	<Globals>
+	</Globals>
+</VisualStudioProject>
Index: /tags/SHM-9.0/build/vc9/TAppCommon_vc9.vcxproj
===================================================================
--- /tags/SHM-9.0/build/vc9/TAppCommon_vc9.vcxproj	(revision 1088)
+++ /tags/SHM-9.0/build/vc9/TAppCommon_vc9.vcxproj	(revision 1088)
@@ -0,0 +1,142 @@
+﻿<?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)\vc9\$(Platform)\$(Configuration)\$(RootNamespace)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)\vc9\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(SolutionDir)\vc9\$(Platform)\$(Configuration)\$(RootNamespace)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(SolutionDir)\vc9\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)\vc9\$(Platform)\$(Configuration)\$(RootNamespace)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)\vc9\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(SolutionDir)\vc9\$(Platform)\$(Configuration)\$(RootNamespace)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(SolutionDir)\vc9\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+  </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" />
+  </ItemGroup>
+  <ItemGroup>
+    <ClInclude Include="..\..\source\Lib\TAppCommon\program_options_lite.h" />
+  </ItemGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
+  <ImportGroup Label="ExtensionTargets">
+  </ImportGroup>
+</Project>
Index: /tags/SHM-9.0/build/vc9/TAppCommon_vc9.vcxproj.filters
===================================================================
--- /tags/SHM-9.0/build/vc9/TAppCommon_vc9.vcxproj.filters	(revision 1088)
+++ /tags/SHM-9.0/build/vc9/TAppCommon_vc9.vcxproj.filters	(revision 1088)
@@ -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>{61c3b510-d4b2-46da-9a25-be492f2fc243}</UniqueIdentifier>
+      <Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
+    </Filter>
+    <Filter Include="Header Files">
+      <UniqueIdentifier>{94c90dc5-7f7b-4776-ba53-bf464ac89d29}</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: /tags/SHM-9.0/build/vc9/TAppCommon_vc9.vcxproj.user
===================================================================
--- /tags/SHM-9.0/build/vc9/TAppCommon_vc9.vcxproj.user	(revision 1088)
+++ /tags/SHM-9.0/build/vc9/TAppCommon_vc9.vcxproj.user	(revision 1088)
@@ -0,0 +1,3 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+</Project>
Index: /tags/SHM-9.0/build/vc9/TAppDecoder_vc9.vcproj
===================================================================
--- /tags/SHM-9.0/build/vc9/TAppDecoder_vc9.vcproj	(revision 1088)
+++ /tags/SHM-9.0/build/vc9/TAppDecoder_vc9.vcproj	(revision 1088)
@@ -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: /tags/SHM-9.0/build/vc9/TAppDecoder_vc9.vcxproj
===================================================================
--- /tags/SHM-9.0/build/vc9/TAppDecoder_vc9.vcxproj	(revision 1088)
+++ /tags/SHM-9.0/build/vc9/TAppDecoder_vc9.vcxproj	(revision 1088)
@@ -0,0 +1,187 @@
+﻿<?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\vc9\$(Platform)\$(Configuration)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)\vc9\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</LinkIncremental>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(SolutionDir)\..\bin\vc9\$(Platform)\$(Configuration)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(SolutionDir)\vc9\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</LinkIncremental>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)\..\bin\vc9\$(Platform)\$(Configuration)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)\vc9\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">false</LinkIncremental>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(SolutionDir)\..\bin\vc9\$(Platform)\$(Configuration)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(SolutionDir)\vc9\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Release|x64'">false</LinkIncremental>
+  </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_vc9.vcxproj">
+      <Project>{d1e8a1c2-15db-4c94-80e8-4f70cf0a2dc5}</Project>
+      <ReferenceOutputAssembly>false</ReferenceOutputAssembly>
+    </ProjectReference>
+    <ProjectReference Include="TLibCommon_vc9.vcxproj">
+      <Project>{78018d78-f890-47e3-a0b7-09d273f0b11d}</Project>
+      <ReferenceOutputAssembly>false</ReferenceOutputAssembly>
+    </ProjectReference>
+    <ProjectReference Include="TLibDecoder_vc9.vcxproj">
+      <Project>{f8b77a48-af6c-4746-a89f-b706aba6ad94}</Project>
+      <ReferenceOutputAssembly>false</ReferenceOutputAssembly>
+    </ProjectReference>
+    <ProjectReference Include="TLibVideoIO_vc9.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: /tags/SHM-9.0/build/vc9/TAppDecoder_vc9.vcxproj.filters
===================================================================
--- /tags/SHM-9.0/build/vc9/TAppDecoder_vc9.vcxproj.filters	(revision 1088)
+++ /tags/SHM-9.0/build/vc9/TAppDecoder_vc9.vcxproj.filters	(revision 1088)
@@ -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>{f91faffd-ddc1-46ee-bf46-c9f336a04889}</UniqueIdentifier>
+      <Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
+    </Filter>
+    <Filter Include="Header Files">
+      <UniqueIdentifier>{53724405-0877-4412-a713-0153d444b64f}</UniqueIdentifier>
+      <Extensions>h;hpp;hxx;hm;inl;inc;xsd</Extensions>
+    </Filter>
+    <Filter Include="Resource Files">
+      <UniqueIdentifier>{f426d7ef-18cf-4428-8729-17e3d457a2d8}</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: /tags/SHM-9.0/build/vc9/TAppDecoder_vc9.vcxproj.user
===================================================================
--- /tags/SHM-9.0/build/vc9/TAppDecoder_vc9.vcxproj.user	(revision 1088)
+++ /tags/SHM-9.0/build/vc9/TAppDecoder_vc9.vcxproj.user	(revision 1088)
@@ -0,0 +1,8 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
+    <LocalDebuggerCommandArguments>-b str/BasketballPass.bin -ls 2 -o0 rec/BasketballPass_l0_drec.yuv -o1 rec/BasketballPass_l1_drec.yuv</LocalDebuggerCommandArguments>
+    <DebuggerFlavor>WindowsLocalDebugger</DebuggerFlavor>
+    <LocalDebuggerWorkingDirectory>$(ProjectDir)/../../../</LocalDebuggerWorkingDirectory>
+  </PropertyGroup>
+</Project>
Index: /tags/SHM-9.0/build/vc9/TAppEncoder_vc9.vcproj
===================================================================
--- /tags/SHM-9.0/build/vc9/TAppEncoder_vc9.vcproj	(revision 1088)
+++ /tags/SHM-9.0/build/vc9/TAppEncoder_vc9.vcproj	(revision 1088)
@@ -0,0 +1,366 @@
+<?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="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="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|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\TAppEncLayerCfg.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\TAppEncLayerCfg.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: /tags/SHM-9.0/build/vc9/TAppEncoder_vc9.vcxproj
===================================================================
--- /tags/SHM-9.0/build/vc9/TAppEncoder_vc9.vcxproj	(revision 1088)
+++ /tags/SHM-9.0/build/vc9/TAppEncoder_vc9.vcxproj	(revision 1088)
@@ -0,0 +1,189 @@
+﻿<?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\vc9\$(Platform)\$(Configuration)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)\vc9\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</LinkIncremental>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(SolutionDir)\..\bin\vc9\$(Platform)\$(Configuration)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(SolutionDir)\vc9\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</LinkIncremental>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)\..\bin\vc9\$(Platform)\$(Configuration)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)\vc9\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">false</LinkIncremental>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(SolutionDir)\..\bin\vc9\$(Platform)\$(Configuration)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(SolutionDir)\vc9\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Release|x64'">false</LinkIncremental>
+  </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\TAppEncLayerCfg.cpp" />
+    <ClCompile Include="..\..\source\App\TAppEncoder\TAppEncTop.cpp" />
+  </ItemGroup>
+  <ItemGroup>
+    <ClInclude Include="..\..\source\App\TAppEncoder\TAppEncCfg.h" />
+    <ClInclude Include="..\..\source\App\TAppEncoder\TAppEncLayerCfg.h" />
+    <ClInclude Include="..\..\source\App\TAppEncoder\TAppEncTop.h" />
+  </ItemGroup>
+  <ItemGroup>
+    <ProjectReference Include="TAppCommon_vc9.vcxproj">
+      <Project>{d1e8a1c2-15db-4c94-80e8-4f70cf0a2dc5}</Project>
+      <ReferenceOutputAssembly>false</ReferenceOutputAssembly>
+    </ProjectReference>
+    <ProjectReference Include="TLibCommon_vc9.vcxproj">
+      <Project>{78018d78-f890-47e3-a0b7-09d273f0b11d}</Project>
+      <ReferenceOutputAssembly>false</ReferenceOutputAssembly>
+    </ProjectReference>
+    <ProjectReference Include="TLibEncoder_vc9.vcxproj">
+      <Project>{47e90995-1fc5-4ee4-a94d-ad474169f0e1}</Project>
+      <ReferenceOutputAssembly>false</ReferenceOutputAssembly>
+    </ProjectReference>
+    <ProjectReference Include="TLibVideoIO_vc9.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: /tags/SHM-9.0/build/vc9/TAppEncoder_vc9.vcxproj.filters
===================================================================
--- /tags/SHM-9.0/build/vc9/TAppEncoder_vc9.vcxproj.filters	(revision 1088)
+++ /tags/SHM-9.0/build/vc9/TAppEncoder_vc9.vcxproj.filters	(revision 1088)
@@ -0,0 +1,42 @@
+﻿<?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>{5a91399d-a287-4a11-b533-6094f5650005}</UniqueIdentifier>
+      <Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
+    </Filter>
+    <Filter Include="Header Files">
+      <UniqueIdentifier>{829a2cbb-01c0-489f-b342-3eb74b2dcb35}</UniqueIdentifier>
+      <Extensions>h;hpp;hxx;hm;inl;inc;xsd</Extensions>
+    </Filter>
+    <Filter Include="Resource Files">
+      <UniqueIdentifier>{2a3d6658-bcc6-4553-8ece-38846d0d457c}</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>
+    <ClCompile Include="..\..\source\App\TAppEncoder\TAppEncLayerCfg.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>
+    <ClInclude Include="..\..\source\App\TAppEncoder\TAppEncLayerCfg.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+  </ItemGroup>
+</Project>
Index: /tags/SHM-9.0/build/vc9/TAppEncoder_vc9.vcxproj.user
===================================================================
--- /tags/SHM-9.0/build/vc9/TAppEncoder_vc9.vcxproj.user	(revision 1088)
+++ /tags/SHM-9.0/build/vc9/TAppEncoder_vc9.vcxproj.user	(revision 1088)
@@ -0,0 +1,10 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
+    <LocalDebuggerCommandArguments>-c cfg/svc/BasketballPass_layers10.cfg -c cfg/encoder_main_lb.cfg -q0 22 -q1 22 -g 4 -f 5 -b str/BasketballPass.bin -c option.cfg</LocalDebuggerCommandArguments>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
+    <LocalDebuggerWorkingDirectory>$(ProjectDir)/../../../</LocalDebuggerWorkingDirectory>
+    <DebuggerFlavor>WindowsLocalDebugger</DebuggerFlavor>
+  </PropertyGroup>
+</Project>
Index: /tags/SHM-9.0/build/vc9/TLibCommon_vc9.vcproj
===================================================================
--- /tags/SHM-9.0/build/vc9/TLibCommon_vc9.vcproj	(revision 1088)
+++ /tags/SHM-9.0/build/vc9/TLibCommon_vc9.vcproj	(revision 1088)
@@ -0,0 +1,567 @@
+<?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\TLibCommon\Debug.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\libmd5\libmd5.c"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\SEI.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TCom3DAsymLUT.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComBitStream.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComCABACTables.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComChromaFormat.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\TComTU.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComUpsampleFilter.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\TLibCommon\Debug.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\TCom3DAsymLUT.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\TComChromaFormat.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComCodingStatistics.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\TComRectangle.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\TComTU.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComUpsampleFilter.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: /tags/SHM-9.0/build/vc9/TLibCommon_vc9.vcxproj
===================================================================
--- /tags/SHM-9.0/build/vc9/TLibCommon_vc9.vcxproj	(revision 1088)
+++ /tags/SHM-9.0/build/vc9/TLibCommon_vc9.vcxproj	(revision 1088)
@@ -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>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)\vc9\$(Platform)\$(Configuration)\$(RootNamespace)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)\vc9\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(SolutionDir)\vc9\$(Platform)\$(Configuration)\$(RootNamespace)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(SolutionDir)\vc9\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)\vc9\$(Platform)\$(Configuration)\$(RootNamespace)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)\vc9\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(SolutionDir)\vc9\$(Platform)\$(Configuration)\$(RootNamespace)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(SolutionDir)\vc9\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+  </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\TComAdaptiveLoopFilter.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\TComUpsampleFilter.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\TComAdaptiveLoopFilter.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\TComUpsampleFilter.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: /tags/SHM-9.0/build/vc9/TLibCommon_vc9.vcxproj.filters
===================================================================
--- /tags/SHM-9.0/build/vc9/TLibCommon_vc9.vcxproj.filters	(revision 1088)
+++ /tags/SHM-9.0/build/vc9/TLibCommon_vc9.vcxproj.filters	(revision 1088)
@@ -0,0 +1,194 @@
+﻿<?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\TComAdaptiveLoopFilter.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>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComUpsampleFilter.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\TComAdaptiveLoopFilter.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>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComUpsampleFilter.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+  </ItemGroup>
+</Project>
Index: /tags/SHM-9.0/build/vc9/TLibCommon_vc9.vcxproj.user
===================================================================
--- /tags/SHM-9.0/build/vc9/TLibCommon_vc9.vcxproj.user	(revision 1088)
+++ /tags/SHM-9.0/build/vc9/TLibCommon_vc9.vcxproj.user	(revision 1088)
@@ -0,0 +1,3 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+</Project>
Index: /tags/SHM-9.0/build/vc9/TLibDecoder_vc9.vcproj
===================================================================
--- /tags/SHM-9.0/build/vc9/TLibDecoder_vc9.vcproj	(revision 1088)
+++ /tags/SHM-9.0/build/vc9/TLibDecoder_vc9.vcproj	(revision 1088)
@@ -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: /tags/SHM-9.0/build/vc9/TLibDecoder_vc9.vcxproj
===================================================================
--- /tags/SHM-9.0/build/vc9/TLibDecoder_vc9.vcxproj	(revision 1088)
+++ /tags/SHM-9.0/build/vc9/TLibDecoder_vc9.vcxproj	(revision 1088)
@@ -0,0 +1,165 @@
+﻿<?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)\vc9\$(Platform)\$(Configuration)\$(RootNamespace)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)\vc9\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(SolutionDir)\vc9\$(Platform)\$(Configuration)\$(RootNamespace)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(SolutionDir)\vc9\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)\vc9\$(Platform)\$(Configuration)\$(RootNamespace)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)\vc9\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(SolutionDir)\vc9\$(Platform)\$(Configuration)\$(RootNamespace)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(SolutionDir)\vc9\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+  </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: /tags/SHM-9.0/build/vc9/TLibDecoder_vc9.vcxproj.filters
===================================================================
--- /tags/SHM-9.0/build/vc9/TLibDecoder_vc9.vcxproj.filters	(revision 1088)
+++ /tags/SHM-9.0/build/vc9/TLibDecoder_vc9.vcxproj.filters	(revision 1088)
@@ -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>{57c32785-e8b2-4ab2-82f6-091ce0690afe}</UniqueIdentifier>
+      <Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
+    </Filter>
+    <Filter Include="Header Files">
+      <UniqueIdentifier>{8351b640-31d1-405d-a45f-7e5469df1a8c}</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: /tags/SHM-9.0/build/vc9/TLibDecoder_vc9.vcxproj.user
===================================================================
--- /tags/SHM-9.0/build/vc9/TLibDecoder_vc9.vcxproj.user	(revision 1088)
+++ /tags/SHM-9.0/build/vc9/TLibDecoder_vc9.vcxproj.user	(revision 1088)
@@ -0,0 +1,3 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+</Project>
Index: /tags/SHM-9.0/build/vc9/TLibEncoder_vc9.vcproj
===================================================================
--- /tags/SHM-9.0/build/vc9/TLibEncoder_vc9.vcproj	(revision 1088)
+++ /tags/SHM-9.0/build/vc9/TLibEncoder_vc9.vcproj	(revision 1088)
@@ -0,0 +1,465 @@
+<?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\TEnc3DAsymLUT.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\TEnc3DAsymLUT.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: /tags/SHM-9.0/build/vc9/TLibEncoder_vc9.vcxproj
===================================================================
--- /tags/SHM-9.0/build/vc9/TLibEncoder_vc9.vcxproj	(revision 1088)
+++ /tags/SHM-9.0/build/vc9/TLibEncoder_vc9.vcxproj	(revision 1088)
@@ -0,0 +1,183 @@
+﻿<?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)\vc9\$(Platform)\$(Configuration)\$(RootNamespace)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)\vc9\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(SolutionDir)\vc9\$(Platform)\$(Configuration)\$(RootNamespace)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(SolutionDir)\vc9\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)\vc9\$(Platform)\$(Configuration)\$(RootNamespace)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)\vc9\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(SolutionDir)\vc9\$(Platform)\$(Configuration)\$(RootNamespace)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(SolutionDir)\vc9\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+  </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\TEncAdaptiveLoopFilter.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\TEncAdaptiveLoopFilter.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: /tags/SHM-9.0/build/vc9/TLibEncoder_vc9.vcxproj.filters
===================================================================
--- /tags/SHM-9.0/build/vc9/TLibEncoder_vc9.vcxproj.filters	(revision 1088)
+++ /tags/SHM-9.0/build/vc9/TLibEncoder_vc9.vcxproj.filters	(revision 1088)
@@ -0,0 +1,146 @@
+﻿<?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>{65968186-a1e6-40bc-bda8-f69881ce59b4}</UniqueIdentifier>
+      <Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
+    </Filter>
+    <Filter Include="Header Files">
+      <UniqueIdentifier>{cb19f901-43b3-4f82-9502-f2c1d70ac336}</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\TEncAdaptiveLoopFilter.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\TEncAdaptiveLoopFilter.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: /tags/SHM-9.0/build/vc9/TLibEncoder_vc9.vcxproj.user
===================================================================
--- /tags/SHM-9.0/build/vc9/TLibEncoder_vc9.vcxproj.user	(revision 1088)
+++ /tags/SHM-9.0/build/vc9/TLibEncoder_vc9.vcxproj.user	(revision 1088)
@@ -0,0 +1,3 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+</Project>
Index: /tags/SHM-9.0/build/vc9/TLibVideoIO_vc9.vcproj
===================================================================
--- /tags/SHM-9.0/build/vc9/TLibVideoIO_vc9.vcproj	(revision 1088)
+++ /tags/SHM-9.0/build/vc9/TLibVideoIO_vc9.vcproj	(revision 1088)
@@ -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: /tags/SHM-9.0/build/vc9/TLibVideoIO_vc9.vcxproj
===================================================================
--- /tags/SHM-9.0/build/vc9/TLibVideoIO_vc9.vcxproj	(revision 1088)
+++ /tags/SHM-9.0/build/vc9/TLibVideoIO_vc9.vcxproj	(revision 1088)
@@ -0,0 +1,142 @@
+﻿<?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)\vc9\$(Platform)\$(Configuration)\$(RootNamespace)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)\vc9\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(SolutionDir)\vc9\$(Platform)\$(Configuration)\$(RootNamespace)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(SolutionDir)\vc9\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)\vc9\$(Platform)\$(Configuration)\$(RootNamespace)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)\vc9\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(SolutionDir)\vc9\$(Platform)\$(Configuration)\$(RootNamespace)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(SolutionDir)\vc9\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+  </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: /tags/SHM-9.0/build/vc9/TLibVideoIO_vc9.vcxproj.filters
===================================================================
--- /tags/SHM-9.0/build/vc9/TLibVideoIO_vc9.vcxproj.filters	(revision 1088)
+++ /tags/SHM-9.0/build/vc9/TLibVideoIO_vc9.vcxproj.filters	(revision 1088)
@@ -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>{911df9cd-3c73-4c8c-b5f0-0e479fc64370}</UniqueIdentifier>
+      <Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
+    </Filter>
+    <Filter Include="Header Files">
+      <UniqueIdentifier>{77db35f6-2e38-4135-84fc-4ceda8d818f7}</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: /tags/SHM-9.0/build/vc9/TLibVideoIO_vc9.vcxproj.user
===================================================================
--- /tags/SHM-9.0/build/vc9/TLibVideoIO_vc9.vcxproj.user	(revision 1088)
+++ /tags/SHM-9.0/build/vc9/TLibVideoIO_vc9.vcxproj.user	(revision 1088)
@@ -0,0 +1,3 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+</Project>
Index: /tags/SHM-9.0/cfg/cfg_extension/Q0108_Extension.cfg
===================================================================
--- /tags/SHM-9.0/cfg/cfg_extension/Q0108_Extension.cfg	(revision 1088)
+++ /tags/SHM-9.0/cfg/cfg_extension/Q0108_Extension.cfg	(revision 1088)
@@ -0,0 +1,26 @@
+InheritCodingStruct1              : -1
+MaxTidIlRefPicsPlus10         : 4           # max_tid_il_ref_pics_plus1 for layer0
+
+#Layer0 prediction structure
+
+Frame1:  B    8   1        0.442    0            0              0           4                2         -8 -9                  0
+Frame2:  B    4   2        0.3536   0            0              1           4                3         -4 -5  4               0
+Frame3:  B    2   3        0.3536   0            0              2           4                4         -2 -3  2 6             0
+Frame4:  B    1   4        0.68     0            0              3           4                5         -1 -2  1 3 7           0
+Frame5:  B    3   4        0.68     0            0              3           4                4         -1 -2  1 5             0
+Frame6:  B    6   3        0.3536   0            0              2           4                4         -2 -3 -4 2             0
+Frame7:  B    5   4        0.68     0            0              3           4                4         -1 -2  1 3             0
+Frame8:  B    7   4        0.68     0            0              3           4                3         -1 -2  1               0
+
+
+#Layer1 prediction structure
+
+Layer1Frame1:  B    8   1        0.442    0            0              0           4                1         -8                     0
+Layer1Frame2:  B    4   2        0.3536   0            0              1           4                2         -4  4                  0
+Layer1Frame3:  B    2   3        0.3536   0            0              2           4                3         -2  2  6               0  
+Layer1Frame4:  B    1   4        0.68     0            0              3           4                4         -1  1  3 7             0 
+Layer1Frame5:  B    3   4        0.68     0            0              3           4                3         -1  1  5               0
+Layer1Frame6:  B    6   3        0.3536   0            0              2           4                3         -2 -4  2               0
+Layer1Frame7:  B    5   4        0.68     0            0              3           4                3         -1  1  3               0
+Layer1Frame8:  B    7   4        0.68     0            0              3           4                2         -1  1                  0
+
Index: /tags/SHM-9.0/cfg/encoder_intra_main.cfg
===================================================================
--- /tags/SHM-9.0/cfg/encoder_intra_main.cfg	(revision 1088)
+++ /tags/SHM-9.0/cfg/encoder_intra_main.cfg	(revision 1088)
@@ -0,0 +1,108 @@
+#======== File I/O =====================
+BitstreamFile                 : str.bin
+#ReconFile                     : rec.yuv
+
+#======== Profile/Level ================
+#Profile                      : main
+NumProfileTierLevel           : 3
+Profile0                      : main                # Profile for BL (NOTE01: this profile applies to whole layers but only BL is outputted)
+                                                    #                (NOTE02: this profile has no effect when NonHEVCBase is set to 1)
+Profile1                      : main                # Profile for BL (NOTE01: this profile applies to HEVC BL only)
+                                                    #                (NOTE02: When NonHEVCBase is set to 1, this profile & associated level should be updated appropriately)
+Profile2                      : scalable-main       # Scalable profile
+
+#======== 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.
+CUTransquantBypassFlagForce: 0 # Constant lossless-value signaling per CU, if TransquantBypassEnableFlag is 1.
+
+### DO NOT ADD ANYTHING BELOW THIS LINE ###
+### DO NOT DELETE THE EMPTY LINE BELOW ###
Index: /tags/SHM-9.0/cfg/encoder_intra_main10.cfg
===================================================================
--- /tags/SHM-9.0/cfg/encoder_intra_main10.cfg	(revision 1088)
+++ /tags/SHM-9.0/cfg/encoder_intra_main10.cfg	(revision 1088)
@@ -0,0 +1,109 @@
+#======== File I/O =====================
+BitstreamFile                 : str.bin
+#ReconFile                     : rec.yuv
+
+#======== Profile/Level ================
+#Profile                      : main10
+NumProfileTierLevel           : 3
+Profile0                      : main10                # Profile for BL (NOTE01: this profile applies to whole layers but only BL is outputted)
+                                                      #                (NOTE02: this profile has no effect when NonHEVCBase is set to 1)
+Profile1                      : main10                # Profile for BL (NOTE01: this profile applies to HEVC BL only)
+                                                      #                (NOTE02: When NonHEVCBase is set to 1, this profile & associated level should be updated appropriately)
+Profile2                      : scalable-main10       # Scalable profile
+
+#======== 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.
+CUTransquantBypassFlagForce: 0 # Constant lossless-value signaling per CU, if TransquantBypassEnableFlag is 1.
+
+                                                        
+### DO NOT ADD ANYTHING BELOW THIS LINE ###
+### DO NOT DELETE THE EMPTY LINE BELOW ###
Index: /tags/SHM-9.0/cfg/encoder_intra_scalable.cfg
===================================================================
--- /tags/SHM-9.0/cfg/encoder_intra_scalable.cfg	(revision 1088)
+++ /tags/SHM-9.0/cfg/encoder_intra_scalable.cfg	(revision 1088)
@@ -0,0 +1,107 @@
+#======== File I/O =====================
+BitstreamFile                 : str.bin
+#ReconFile                     : rec.yuv
+
+#======== Profile ================
+NumProfileTierLevel           : 3
+Profile0                      : main                # Profile for BL (NOTE01: this profile applies to whole layers but only BL is outputted)
+                                                    #                (NOTE02: this profile has no effect when NonHEVCBase is set to 1)
+Profile1                      : main                # Profile for BL (NOTE01: this profile applies to HEVC BL only)
+                                                    #                (NOTE02: When NonHEVCBase is set to 1, this profile & associated level should be updated appropriately)
+Profile2                      : scalable-main       # Scalable profile
+
+#======== Unit definition ================
+MaxCUWidth                    : 64          # Maximum coding unit width in pixel
+MaxCUHeight                   : 64          # Maximum coding unit height in pixel
+MaxPartitionDepth             : 4           # Maximum coding unit depth
+QuadtreeTULog2MaxSize         : 5           # Log2 of maximum transform size for
+                                            # quadtree-based TU coding (2...6)
+QuadtreeTULog2MinSize         : 2           # Log2 of minimum transform size for
+                                            # quadtree-based TU coding (2...6)
+QuadtreeTUMaxDepthInter       : 3
+QuadtreeTUMaxDepthIntra       : 3
+
+#======== Coding Structure =============
+#IntraPeriod                   : 1           # Period of I-Frame ( -1 = only first)
+DecodingRefreshType           : 0           # Random Accesss 0:none, 1:CRA, 2:IDR, 3:Recovery Point SEI
+GOPSize                       : 1           # GOP Size (number of B slice = GOPSize-1)
+#        Type POC QPoffset QPfactor tcOffsetDiv2 betaOffsetDiv2  temporal_id #ref_pics_active #ref_pics reference pictures 
+
+#=========== Motion Search =============
+FastSearch                    : 1           # 0:Full search  1:TZ search
+SearchRange                   : 64          # (0: Search range is a Full frame)
+HadamardME                    : 1           # Use of hadamard measure for fractional ME
+FEN                           : 1           # Fast encoder decision
+FDM                           : 1           # Fast Decision for Merge RD cost
+
+#======== Quantization =============
+#QP                            : 32          # Quantization parameter(0-51)
+MaxDeltaQP                    : 0           # CU-based multi-QP optimization
+MaxCuDQPDepth                 : 0           # Max depth of a minimum CuDQP for sub-LCU-level delta QP
+DeltaQpRD                     : 0           # Slice-based multi-QP optimization
+RDOQ                          : 1           # RDOQ
+RDOQTS                        : 1           # RDOQ for transform skip
+
+#=========== Deblock Filter ============
+DeblockingFilterControlPresent: 0           # Dbl control params present (0=not present, 1=present)
+LoopFilterOffsetInPPS         : 0           # Dbl params: 0=varying params in SliceHeader, param = base_param + GOP_offset_param; 1=constant params in PPS, param = base_param)
+LoopFilterDisable             : 0           # Disable deblocking filter (0=Filter, 1=No Filter)
+LoopFilterBetaOffset_div2     : 0           # base_param: -6 ~ 6
+LoopFilterTcOffset_div2       : 0           # base_param: -6 ~ 6
+DeblockingFilterMetric        : 0           # blockiness metric (automatically configures deblocking parameters in bitstream)
+
+#=========== Misc. ============
+#InternalBitDepth             : 8           # codec operating bit-depth
+
+#=========== Coding Tools =================
+SAO                           : 1           # Sample adaptive offset  (0: OFF, 1: ON)
+AMP                           : 1           # Asymmetric motion partitions (0: OFF, 1: ON)
+TransformSkip                 : 1           # Transform skipping (0: OFF, 1: ON)
+TransformSkipFast             : 1           # Fast Transform skipping (0: OFF, 1: ON)
+SAOLcuBoundary                : 0           # SAOLcuBoundary using non-deblocked pixels (0: OFF, 1: ON)
+
+#============ Slices ================
+SliceMode                : 0                # 0: Disable all slice options.
+                                            # 1: Enforce maximum number of LCU in an slice,
+                                            # 2: Enforce maximum number of bytes in an 'slice'
+                                            # 3: Enforce maximum number of tiles in a slice
+SliceArgument            : 1500             # Argument for 'SliceMode'.
+                                            # If SliceMode==1 it represents max. SliceGranularity-sized blocks per slice.
+                                            # If SliceMode==2 it represents max. bytes per slice.
+                                            # If SliceMode==3 it represents max. tiles per slice.
+
+LFCrossSliceBoundaryFlag : 1                # In-loop filtering, including ALF and DB, is across or not across slice boundary.
+                                            # 0:not across, 1: across
+
+#============ PCM ================
+PCMEnabledFlag                      : 0                # 0: No PCM mode
+PCMLog2MaxSize                      : 5                # Log2 of maximum PCM block size.
+PCMLog2MinSize                      : 3                # Log2 of minimum PCM block size.
+PCMInputBitDepthFlag                : 1                # 0: PCM bit-depth is internal bit-depth. 1: PCM bit-depth is input bit-depth.
+PCMFilterDisableFlag                : 0                # 0: Enable loop filtering on I_PCM samples. 1: Disable loop filtering on I_PCM samples.
+
+#============ Tiles ================
+TileUniformSpacing                  : 0                # 0: the column boundaries are indicated by TileColumnWidth array, the row boundaries are indicated by TileRowHeight array
+                                                       # 1: the column and row boundaries are distributed uniformly
+NumTileColumnsMinus1                : 0                # Number of tile columns in a picture minus 1
+TileColumnWidthArray                : 2 3              # Array containing tile column width values in units of CTU (from left to right in picture)   
+NumTileRowsMinus1                   : 0                # Number of tile rows in a picture minus 1
+TileRowHeightArray                  : 2                # Array containing tile row height values in units of CTU (from top to bottom in picture)
+
+LFCrossTileBoundaryFlag             : 1                # In-loop filtering is across or not across tile boundary.
+                                                       # 0:not across, 1: across 
+
+#============ WaveFront ================
+#WaveFrontSynchro                    : 0                # 0:  No WaveFront synchronisation (WaveFrontSubstreams must be 1 in this case).
+                                                       # >0: WaveFront synchronises with the LCU above and to the right by this many LCUs.
+
+#=========== Quantization Matrix =================
+ScalingList                   : 0                      # ScalingList 0 : off, 1 : default, 2 : file read
+ScalingListFile               : scaling_list.txt       # Scaling List file name. If file is not exist, use Default Matrix.
+
+#============ Lossless ================
+TransquantBypassEnableFlag : 0                         # Value of PPS flag.
+CUTransquantBypassFlagForce: 0                         # Force transquant bypass mode, when transquant_bypass_enable_flag is enabled
+
+### DO NOT ADD ANYTHING BELOW THIS LINE ###
+### DO NOT DELETE THE EMPTY LINE BELOW ###
Index: /tags/SHM-9.0/cfg/encoder_intra_scalable10.cfg
===================================================================
--- /tags/SHM-9.0/cfg/encoder_intra_scalable10.cfg	(revision 1088)
+++ /tags/SHM-9.0/cfg/encoder_intra_scalable10.cfg	(revision 1088)
@@ -0,0 +1,106 @@
+#======== File I/O =====================
+BitstreamFile                 : str.bin
+
+#======== Profile ================
+NumProfileTierLevel           : 3
+Profile0                      : main10                # Profile for BL (NOTE01: this profile applies to whole layers but only BL is outputted)
+                                                      #                (NOTE02: this profile has no effect when NonHEVCBase is set to 1)
+Profile1                      : main10                # Profile for BL (NOTE01: this profile applies to HEVC BL only)
+                                                      #                (NOTE02: When NonHEVCBase is set to 1, this profile & associated level should be updated appropriately)
+Profile2                      : scalable-main10       # Scalable profile
+
+#======== Unit definition ================
+MaxCUWidth                    : 64          # Maximum coding unit width in pixel
+MaxCUHeight                   : 64          # Maximum coding unit height in pixel
+MaxPartitionDepth             : 4           # Maximum coding unit depth
+QuadtreeTULog2MaxSize         : 5           # Log2 of maximum transform size for
+                                            # quadtree-based TU coding (2...6)
+QuadtreeTULog2MinSize         : 2           # Log2 of minimum transform size for
+                                            # quadtree-based TU coding (2...6)
+QuadtreeTUMaxDepthInter       : 3
+QuadtreeTUMaxDepthIntra       : 3
+
+#======== Coding Structure =============
+#IntraPeriod                   : 1           # Period of I-Frame ( -1 = only first)
+DecodingRefreshType           : 0           # Random Accesss 0:none, 1:CRA, 2:IDR, 3:Recovery Point SEI
+GOPSize                       : 1           # GOP Size (number of B slice = GOPSize-1)
+#        Type POC QPoffset QPfactor tcOffsetDiv2 betaOffsetDiv2  temporal_id #ref_pics_active #ref_pics reference pictures  
+
+#=========== Motion Search =============
+FastSearch                    : 1           # 0:Full search  1:TZ search
+SearchRange                   : 64          # (0: Search range is a Full frame)
+HadamardME                    : 1           # Use of hadamard measure for fractional ME
+FEN                           : 1           # Fast encoder decision
+FDM                           : 1           # Fast Decision for Merge RD cost
+
+#======== Quantization =============
+#QP                            : 32          # Quantization parameter(0-51)
+MaxDeltaQP                    : 0           # CU-based multi-QP optimization
+MaxCuDQPDepth                 : 0           # Max depth of a minimum CuDQP for sub-LCU-level delta QP
+DeltaQpRD                     : 0           # Slice-based multi-QP optimization
+RDOQ                          : 1           # RDOQ
+RDOQTS                        : 1           # RDOQ for transform skip
+
+#=========== Deblock Filter ============
+DeblockingFilterControlPresent: 0           # Dbl control params present (0=not present, 1=present)
+LoopFilterOffsetInPPS         : 0           # Dbl params: 0=varying params in SliceHeader, param = base_param + GOP_offset_param; 1=constant params in PPS, param = base_param)
+LoopFilterDisable             : 0           # Disable deblocking filter (0=Filter, 1=No Filter)
+LoopFilterBetaOffset_div2     : 0           # base_param: -6 ~ 6
+LoopFilterTcOffset_div2       : 0           # base_param: -6 ~ 6
+DeblockingFilterMetric        : 0           # blockiness metric (automatically configures deblocking parameters in bitstream)
+
+#=========== Misc. ============
+#InternalBitDepth             : 10          # codec operating bit-depth
+
+#=========== Coding Tools =================
+SAO                           : 1           # Sample adaptive offset  (0: OFF, 1: ON)
+AMP                           : 1           # Asymmetric motion partitions (0: OFF, 1: ON)
+TransformSkip                 : 1           # Transform skipping (0: OFF, 1: ON)
+TransformSkipFast             : 1           # Fast Transform skipping (0: OFF, 1: ON)
+SAOLcuBoundary                : 0           # SAOLcuBoundary using non-deblocked pixels (0: OFF, 1: ON)
+
+#============ Slices ================
+SliceMode                : 0                # 0: Disable all slice options.
+                                            # 1: Enforce maximum number of LCU in an slice,
+                                            # 2: Enforce maximum number of bytes in an 'slice'
+                                            # 3: Enforce maximum number of tiles in a slice
+SliceArgument            : 1500             # Argument for 'SliceMode'.
+                                            # If SliceMode==1 it represents max. SliceGranularity-sized blocks per slice.
+                                            # If SliceMode==2 it represents max. bytes per slice.
+                                            # If SliceMode==3 it represents max. tiles per slice.
+
+LFCrossSliceBoundaryFlag : 1                # In-loop filtering, including ALF and DB, is across or not across slice boundary.
+                                            # 0:not across, 1: across
+
+#============ PCM ================
+PCMEnabledFlag                      : 0                # 0: No PCM mode
+PCMLog2MaxSize                      : 5                # Log2 of maximum PCM block size.
+PCMLog2MinSize                      : 3                # Log2 of minimum PCM block size.
+PCMInputBitDepthFlag                : 1                # 0: PCM bit-depth is internal bit-depth. 1: PCM bit-depth is input bit-depth.
+PCMFilterDisableFlag                : 0                # 0: Enable loop filtering on I_PCM samples. 1: Disable loop filtering on I_PCM samples.
+
+#============ Tiles ================
+TileUniformSpacing                  : 0                # 0: the column boundaries are indicated by TileColumnWidth array, the row boundaries are indicated by TileRowHeight array
+                                                       # 1: the column and row boundaries are distributed uniformly
+NumTileColumnsMinus1                : 0                # Number of tile columns in a picture minus 1
+TileColumnWidthArray                : 2 3              # Array containing tile column width values in units of CTU (from left to right in picture)   
+NumTileRowsMinus1                   : 0                # Number of tile rows in a picture minus 1
+TileRowHeightArray                  : 2                # Array containing tile row height values in units of CTU (from top to bottom in picture)
+
+LFCrossTileBoundaryFlag             : 1                # In-loop filtering is across or not across tile boundary.
+                                                       # 0:not across, 1: across 
+
+#============ WaveFront ================
+#WaveFrontSynchro                    : 0                # 0:  No WaveFront synchronisation (WaveFrontSubstreams must be 1 in this case).
+                                                       # >0: WaveFront synchronises with the LCU above and to the right by this many LCUs.
+
+#=========== Quantization Matrix =================
+ScalingList                   : 0                      # ScalingList 0 : off, 1 : default, 2 : file read
+ScalingListFile               : scaling_list.txt       # Scaling List file name. If file is not exist, use Default Matrix.
+
+#============ Lossless ================
+TransquantBypassEnableFlag : 0                         # Value of PPS flag.
+CUTransquantBypassFlagForce: 0                         # Force transquant bypass mode, when transquant_bypass_enable_flag is enabled
+
+### DO NOT ADD ANYTHING BELOW THIS LINE ###
+### DO NOT DELETE THE EMPTY LINE BELOW ###
Index: /tags/SHM-9.0/cfg/encoder_intra_scalable_8_10.cfg
===================================================================
--- /tags/SHM-9.0/cfg/encoder_intra_scalable_8_10.cfg	(revision 1088)
+++ /tags/SHM-9.0/cfg/encoder_intra_scalable_8_10.cfg	(revision 1088)
@@ -0,0 +1,106 @@
+#======== File I/O =====================
+BitstreamFile                 : str.bin
+
+#======== Profile ================
+NumProfileTierLevel           : 3
+Profile0                      : main                  # Profile for BL (NOTE01: this profile applies to whole layers but only BL is outputted)
+                                                      #                (NOTE02: this profile has no effect when NonHEVCBase is set to 1)
+Profile1                      : main                  # Profile for BL (NOTE01: this profile applies to HEVC BL only)
+                                                      #                (NOTE02: When NonHEVCBase is set to 1, this profile & associated level should be updated appropriately)
+Profile2                      : scalable-main10       # Scalable profile
+
+#======== Unit definition ================
+MaxCUWidth                    : 64          # Maximum coding unit width in pixel
+MaxCUHeight                   : 64          # Maximum coding unit height in pixel
+MaxPartitionDepth             : 4           # Maximum coding unit depth
+QuadtreeTULog2MaxSize         : 5           # Log2 of maximum transform size for
+                                            # quadtree-based TU coding (2...6)
+QuadtreeTULog2MinSize         : 2           # Log2 of minimum transform size for
+                                            # quadtree-based TU coding (2...6)
+QuadtreeTUMaxDepthInter       : 3
+QuadtreeTUMaxDepthIntra       : 3
+
+#======== Coding Structure =============
+#IntraPeriod                   : 1           # Period of I-Frame ( -1 = only first)
+DecodingRefreshType           : 0           # Random Accesss 0:none, 1:CRA, 2:IDR, 3:Recovery Point SEI
+GOPSize                       : 1           # GOP Size (number of B slice = GOPSize-1)
+#        Type POC QPoffset QPfactor tcOffsetDiv2 betaOffsetDiv2  temporal_id #ref_pics_active #ref_pics reference pictures  
+
+#=========== Motion Search =============
+FastSearch                    : 1           # 0:Full search  1:TZ search
+SearchRange                   : 64          # (0: Search range is a Full frame)
+HadamardME                    : 1           # Use of hadamard measure for fractional ME
+FEN                           : 1           # Fast encoder decision
+FDM                           : 1           # Fast Decision for Merge RD cost
+
+#======== Quantization =============
+#QP                            : 32          # Quantization parameter(0-51)
+MaxDeltaQP                    : 0           # CU-based multi-QP optimization
+MaxCuDQPDepth                 : 0           # Max depth of a minimum CuDQP for sub-LCU-level delta QP
+DeltaQpRD                     : 0           # Slice-based multi-QP optimization
+RDOQ                          : 1           # RDOQ
+RDOQTS                        : 1           # RDOQ for transform skip
+
+#=========== Deblock Filter ============
+DeblockingFilterControlPresent: 0           # Dbl control params present (0=not present, 1=present)
+LoopFilterOffsetInPPS         : 0           # Dbl params: 0=varying params in SliceHeader, param = base_param + GOP_offset_param; 1=constant params in PPS, param = base_param)
+LoopFilterDisable             : 0           # Disable deblocking filter (0=Filter, 1=No Filter)
+LoopFilterBetaOffset_div2     : 0           # base_param: -6 ~ 6
+LoopFilterTcOffset_div2       : 0           # base_param: -6 ~ 6
+DeblockingFilterMetric        : 0           # blockiness metric (automatically configures deblocking parameters in bitstream)
+
+#=========== Misc. ============
+#InternalBitDepth             : 10          # codec operating bit-depth
+
+#=========== Coding Tools =================
+SAO                           : 1           # Sample adaptive offset  (0: OFF, 1: ON)
+AMP                           : 1           # Asymmetric motion partitions (0: OFF, 1: ON)
+TransformSkip                 : 1           # Transform skipping (0: OFF, 1: ON)
+TransformSkipFast             : 1           # Fast Transform skipping (0: OFF, 1: ON)
+SAOLcuBoundary                : 0           # SAOLcuBoundary using non-deblocked pixels (0: OFF, 1: ON)
+
+#============ Slices ================
+SliceMode                : 0                # 0: Disable all slice options.
+                                            # 1: Enforce maximum number of LCU in an slice,
+                                            # 2: Enforce maximum number of bytes in an 'slice'
+                                            # 3: Enforce maximum number of tiles in a slice
+SliceArgument            : 1500             # Argument for 'SliceMode'.
+                                            # If SliceMode==1 it represents max. SliceGranularity-sized blocks per slice.
+                                            # If SliceMode==2 it represents max. bytes per slice.
+                                            # If SliceMode==3 it represents max. tiles per slice.
+
+LFCrossSliceBoundaryFlag : 1                # In-loop filtering, including ALF and DB, is across or not across slice boundary.
+                                            # 0:not across, 1: across
+
+#============ PCM ================
+PCMEnabledFlag                      : 0                # 0: No PCM mode
+PCMLog2MaxSize                      : 5                # Log2 of maximum PCM block size.
+PCMLog2MinSize                      : 3                # Log2 of minimum PCM block size.
+PCMInputBitDepthFlag                : 1                # 0: PCM bit-depth is internal bit-depth. 1: PCM bit-depth is input bit-depth.
+PCMFilterDisableFlag                : 0                # 0: Enable loop filtering on I_PCM samples. 1: Disable loop filtering on I_PCM samples.
+
+#============ Tiles ================
+TileUniformSpacing                  : 0                # 0: the column boundaries are indicated by TileColumnWidth array, the row boundaries are indicated by TileRowHeight array
+                                                       # 1: the column and row boundaries are distributed uniformly
+NumTileColumnsMinus1                : 0                # Number of tile columns in a picture minus 1
+TileColumnWidthArray                : 2 3              # Array containing tile column width values in units of CTU (from left to right in picture)   
+NumTileRowsMinus1                   : 0                # Number of tile rows in a picture minus 1
+TileRowHeightArray                  : 2                # Array containing tile row height values in units of CTU (from top to bottom in picture)
+
+LFCrossTileBoundaryFlag             : 1                # In-loop filtering is across or not across tile boundary.
+                                                       # 0:not across, 1: across 
+
+#============ WaveFront ================
+#WaveFrontSynchro                    : 0                # 0:  No WaveFront synchronisation (WaveFrontSubstreams must be 1 in this case).
+                                                       # >0: WaveFront synchronises with the LCU above and to the right by this many LCUs.
+
+#=========== Quantization Matrix =================
+ScalingList                   : 0                      # ScalingList 0 : off, 1 : default, 2 : file read
+ScalingListFile               : scaling_list.txt       # Scaling List file name. If file is not exist, use Default Matrix.
+
+#============ Lossless ================
+TransquantBypassEnableFlag : 0                         # Value of PPS flag.
+CUTransquantBypassFlagForce: 0                         # Force transquant bypass mode, when transquant_bypass_enable_flag is enabled
+
+### DO NOT ADD ANYTHING BELOW THIS LINE ###
+### DO NOT DELETE THE EMPTY LINE BELOW ###
Index: /tags/SHM-9.0/cfg/encoder_lowdelay_P_main.cfg
===================================================================
--- /tags/SHM-9.0/cfg/encoder_lowdelay_P_main.cfg	(revision 1088)
+++ /tags/SHM-9.0/cfg/encoder_lowdelay_P_main.cfg	(revision 1088)
@@ -0,0 +1,122 @@
+#======== File I/O =====================
+BitstreamFile                 : str.bin
+#ReconFile                     : rec.yuv
+
+#======== Profile/Level ================
+#Profile                      : main
+NumProfileTierLevel           : 3
+Profile0                      : main                # Profile for BL (NOTE01: this profile applies to whole layers but only BL is outputted)
+                                                    #                (NOTE02: this profile has no effect when NonHEVCBase is set to 1)
+Profile1                      : main                # Profile for BL (NOTE01: this profile applies to HEVC BL only)
+                                                    #                (NOTE02: When NonHEVCBase is set to 1, this profile & associated level should be updated appropriately)
+Profile2                      : scalable-main       # Scalable profile
+
+#======== 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.
+CUTransquantBypassFlagForce: 0 # Constant lossless-value signaling per CU, if TransquantBypassEnableFlag is 1.
+
+#============ Rate Control ======================
+#RateControl                         : 0                # Rate control: enable rate control
+#TargetBitrate                       : 1000000          # Rate control: target bitrate, in bps
+#KeepHierarchicalBit                 : 2                # Rate control: 0: equal bit allocation; 1: fixed ratio bit allocation; 2: adaptive ratio bit allocation
+#LCULevelRateControl                 : 1                # Rate control: 1: LCU level RC; 0: picture level RC
+#RCLCUSeparateModel                  : 1                # Rate control: use LCU level separate R-lambda model
+#InitialQP                           : 0                # Rate control: initial QP
+#RCForceIntraQP                      : 0                # Rate control: force intra QP to be equal to initial QP
+
+### DO NOT ADD ANYTHING BELOW THIS LINE ###
+### DO NOT DELETE THE EMPTY LINE BELOW ###
Index: /tags/SHM-9.0/cfg/encoder_lowdelay_P_main10.cfg
===================================================================
--- /tags/SHM-9.0/cfg/encoder_lowdelay_P_main10.cfg	(revision 1088)
+++ /tags/SHM-9.0/cfg/encoder_lowdelay_P_main10.cfg	(revision 1088)
@@ -0,0 +1,122 @@
+#======== File I/O =====================
+BitstreamFile                 : str.bin
+#ReconFile                     : rec.yuv
+
+#======== Profile/Level ================
+#Profile                      : main10
+NumProfileTierLevel           : 3
+Profile0                      : main10                # Profile for BL (NOTE01: this profile applies to whole layers but only BL is outputted)
+                                                      #                (NOTE02: this profile has no effect when NonHEVCBase is set to 1)
+Profile1                      : main10                # Profile for BL (NOTE01: this profile applies to HEVC BL only)
+                                                      #                (NOTE02: When NonHEVCBase is set to 1, this profile & associated level should be updated appropriately)
+Profile2                      : scalable-main10       # Scalable profile
+
+#======== 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.
+CUTransquantBypassFlagForce: 0 # Constant lossless-value signaling per CU, if TransquantBypassEnableFlag is 1.
+
+#============ Rate Control ======================
+#RateControl                         : 0                # Rate control: enable rate control
+#TargetBitrate                       : 1000000          # Rate control: target bitrate, in bps
+#KeepHierarchicalBit                 : 2                # Rate control: 0: equal bit allocation; 1: fixed ratio bit allocation; 2: adaptive ratio bit allocation
+#LCULevelRateControl                 : 1                # Rate control: 1: LCU level RC; 0: picture level RC
+#RCLCUSeparateModel                  : 1                # Rate control: use LCU level separate R-lambda model
+#InitialQP                           : 0                # Rate control: initial QP
+#RCForceIntraQP                      : 0                # Rate control: force intra QP to be equal to initial QP
+
+### DO NOT ADD ANYTHING BELOW THIS LINE ###
+### DO NOT DELETE THE EMPTY LINE BELOW ###
Index: /tags/SHM-9.0/cfg/encoder_lowdelay_P_scalable.cfg
===================================================================
--- /tags/SHM-9.0/cfg/encoder_lowdelay_P_scalable.cfg	(revision 1088)
+++ /tags/SHM-9.0/cfg/encoder_lowdelay_P_scalable.cfg	(revision 1088)
@@ -0,0 +1,121 @@
+#======== File I/O =====================
+BitstreamFile                 : str.bin
+#ReconFile                     : rec.yuv
+
+#======== Profile ================
+NumProfileTierLevel           : 3
+Profile0                      : main                # Profile for BL (NOTE01: this profile applies to whole layers but only BL is outputted)
+                                                    #                (NOTE02: this profile has no effect when NonHEVCBase is set to 1)
+Profile1                      : main                # Profile for BL (NOTE01: this profile applies to HEVC BL only)
+                                                    #                (NOTE02: When NonHEVCBase is set to 1, this profile & associated level should be updated appropriately)
+Profile2                      : scalable-main       # Scalable profile
+
+#======== Unit definition ================
+MaxCUWidth                    : 64          # Maximum coding unit width in pixel
+MaxCUHeight                   : 64          # Maximum coding unit height in pixel
+MaxPartitionDepth             : 4           # Maximum coding unit depth
+QuadtreeTULog2MaxSize         : 5           # Log2 of maximum transform size for
+                                            # quadtree-based TU coding (2...6)
+QuadtreeTULog2MinSize         : 2           # Log2 of minimum transform size for
+                                            # quadtree-based TU coding (2...6)
+QuadtreeTUMaxDepthInter       : 3
+QuadtreeTUMaxDepthIntra       : 3
+
+#======== Coding Structure =============
+#IntraPeriod                   : -1          # Period of I-Frame ( -1 = only first)
+DecodingRefreshType           : 0           # Random Accesss 0:none, 1:CRA, 2:IDR, 3:Recovery Point SEI
+GOPSize                       : 4           # GOP Size (number of B slice = GOPSize-1)
+#        Type POC QPoffset QPfactor tcOffsetDiv2 betaOffsetDiv2  temporal_id #ref_pics_active #ref_pics reference pictures predict deltaRPS #ref_idcs reference idcs 
+Frame1:  P    1   3        0.4624   0            0               0           4                4         -1 -5 -9 -13       0
+Frame2:  P    2   2        0.4624   0            0               0           4                4         -1 -2 -6 -10       1      -1       5         1 1 1 0 1
+Frame3:  P    3   3        0.4624   0            0               0           4                4         -1 -3 -7 -11       1      -1       5         0 1 1 1 1            
+Frame4:  P    4   1        0.578    0            0               0           4                4         -1 -4 -8 -12       1      -1       5         0 1 1 1 1
+
+#=========== Motion Search =============
+FastSearch                    : 1           # 0:Full search  1:TZ search
+SearchRange                   : 64          # (0: Search range is a Full frame)
+BipredSearchRange             : 4           # Search range for bi-prediction refinement
+HadamardME                    : 1           # Use of hadamard measure for fractional ME
+FEN                           : 1           # Fast encoder decision
+FDM                           : 1           # Fast Decision for Merge RD cost
+
+#======== Quantization =============
+#QP                            : 32          # Quantization parameter(0-51)
+MaxDeltaQP                    : 0           # CU-based multi-QP optimization
+MaxCuDQPDepth                 : 0           # Max depth of a minimum CuDQP for sub-LCU-level delta QP
+DeltaQpRD                     : 0           # Slice-based multi-QP optimization
+RDOQ                          : 1           # RDOQ
+RDOQTS                        : 1           # RDOQ for transform skip
+TransformSkip                 : 1           # Transform skipping (0: OFF, 1: ON)
+TransformSkipFast             : 1           # Fast Transform skipping (0: OFF, 1: ON)
+
+#=========== Deblock Filter ============
+DeblockingFilterControlPresent: 0           # Dbl control params present (0=not present, 1=present)
+LoopFilterOffsetInPPS         : 0           # Dbl params: 0=varying params in SliceHeader, param = base_param + GOP_offset_param; 1=constant params in PPS, param = base_param)
+LoopFilterDisable             : 0           # Disable deblocking filter (0=Filter, 1=No Filter)
+LoopFilterBetaOffset_div2     : 0           # base_param: -6 ~ 6
+LoopFilterTcOffset_div2       : 0           # base_param: -6 ~ 6
+DeblockingFilterMetric        : 0           # blockiness metric (automatically configures deblocking parameters in bitstream)
+
+#=========== Misc. ============
+#InternalBitDepth             : 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)
+SAOLcuBoundary                : 0           # SAOLcuBoundary using non-deblocked pixels (0: OFF, 1: ON)
+
+#============ Slices ================
+SliceMode                : 0                # 0: Disable all slice options.
+                                            # 1: Enforce maximum number of LCU in an slice,
+                                            # 2: Enforce maximum number of bytes in an 'slice'
+                                            # 3: Enforce maximum number of tiles in a slice
+SliceArgument            : 1500             # Argument for 'SliceMode'.
+                                            # If SliceMode==1 it represents max. SliceGranularity-sized blocks per slice.
+                                            # If SliceMode==2 it represents max. bytes per slice.
+                                            # If SliceMode==3 it represents max. tiles per slice.
+
+LFCrossSliceBoundaryFlag : 1                # In-loop filtering, including ALF and DB, is across or not across slice boundary.
+                                            # 0:not across, 1: across
+
+#============ PCM ================
+PCMEnabledFlag                      : 0                # 0: No PCM mode
+PCMLog2MaxSize                      : 5                # Log2 of maximum PCM block size.
+PCMLog2MinSize                      : 3                # Log2 of minimum PCM block size.
+PCMInputBitDepthFlag                : 1                # 0: PCM bit-depth is internal bit-depth. 1: PCM bit-depth is input bit-depth.
+PCMFilterDisableFlag                : 0                # 0: Enable loop filtering on I_PCM samples. 1: Disable loop filtering on I_PCM samples.
+
+#============ Tiles ================
+TileUniformSpacing                  : 0                # 0: the column boundaries are indicated by TileColumnWidth array, the row boundaries are indicated by TileRowHeight array
+                                                       # 1: the column and row boundaries are distributed uniformly
+NumTileColumnsMinus1                : 0                # Number of tile columns in a picture minus 1
+TileColumnWidthArray                : 2 3              # Array containing tile column width values in units of CTU (from left to right in picture)   
+NumTileRowsMinus1                   : 0                # Number of tile rows in a picture minus 1
+TileRowHeightArray                  : 2                # Array containing tile row height values in units of CTU (from top to bottom in picture)
+
+LFCrossTileBoundaryFlag             : 1                # In-loop filtering is across or not across tile boundary.
+                                                       # 0:not across, 1: across 
+
+#============ WaveFront ================
+#WaveFrontSynchro                    : 0                # 0:  No WaveFront synchronisation (WaveFrontSubstreams must be 1 in this case).
+                                                       # >0: WaveFront synchronises with the LCU above and to the right by this many LCUs.
+
+#=========== Quantization Matrix =================
+ScalingList                   : 0                      # ScalingList 0 : off, 1 : default, 2 : file read
+ScalingListFile               : scaling_list.txt       # Scaling List file name. If file is not exist, use Default Matrix.
+
+#============ Lossless ================
+TransquantBypassEnableFlag : 0                         # Value of PPS flag.
+CUTransquantBypassFlagForce: 0                         # Force transquant bypass mode, when transquant_bypass_enable_flag is enabled
+
+#============ Rate Control ======================
+#RateControl                         : 0                # Rate control: enable rate control
+#TargetBitrate                       : 1000000          # Rate control: target bitrate, in bps
+#KeepHierarchicalBit                 : 2                # Rate control: 0: equal bit allocation; 1: fixed ratio bit allocation; 2: adaptive ratio bit allocation
+#LCULevelRateControl                 : 1                # Rate control: 1: LCU level RC; 0: picture level RC
+#RCLCUSeparateModel                  : 1                # Rate control: use LCU level separate R-lambda model
+#InitialQP                           : 0                # Rate control: initial QP
+#RCForceIntraQP                      : 0                # Rate control: force intra QP to be equal to initial QP
+
+### DO NOT ADD ANYTHING BELOW THIS LINE ###
+### DO NOT DELETE THE EMPTY LINE BELOW ###
Index: /tags/SHM-9.0/cfg/encoder_lowdelay_P_scalable10.cfg
===================================================================
--- /tags/SHM-9.0/cfg/encoder_lowdelay_P_scalable10.cfg	(revision 1088)
+++ /tags/SHM-9.0/cfg/encoder_lowdelay_P_scalable10.cfg	(revision 1088)
@@ -0,0 +1,121 @@
+#======== File I/O =====================
+BitstreamFile                 : str.bin
+#ReconFile                     : rec.yuv
+
+#======== Profile ================
+NumProfileTierLevel           : 3
+Profile0                      : main10                # Profile for BL (NOTE01: this profile applies to whole layers but only BL is outputted)
+                                                      #                (NOTE02: this profile has no effect when NonHEVCBase is set to 1)
+Profile1                      : main10                # Profile for BL (NOTE01: this profile applies to HEVC BL only)
+                                                      #                (NOTE02: When NonHEVCBase is set to 1, this profile & associated level should be updated appropriately)
+Profile2                      : scalable-main10       # Scalable profile
+
+#======== Unit definition ================
+MaxCUWidth                    : 64          # Maximum coding unit width in pixel
+MaxCUHeight                   : 64          # Maximum coding unit height in pixel
+MaxPartitionDepth             : 4           # Maximum coding unit depth
+QuadtreeTULog2MaxSize         : 5           # Log2 of maximum transform size for
+                                            # quadtree-based TU coding (2...6)
+QuadtreeTULog2MinSize         : 2           # Log2 of minimum transform size for
+                                            # quadtree-based TU coding (2...6)
+QuadtreeTUMaxDepthInter       : 3
+QuadtreeTUMaxDepthIntra       : 3
+
+#======== Coding Structure =============
+#IntraPeriod                   : -1          # Period of I-Frame ( -1 = only first)
+DecodingRefreshType           : 0           # Random Accesss 0:none, 1:CRA, 2:IDR, 3:Recovery Point SEI
+GOPSize                       : 4           # GOP Size (number of B slice = GOPSize-1)
+#        Type POC QPoffset QPfactor tcOffsetDiv2 betaOffsetDiv2  temporal_id #ref_pics_active #ref_pics reference pictures predict deltaRPS #ref_idcs reference idcs 
+Frame1:  P    1   3        0.4624   0            0               0           4                4         -1 -5 -9 -13       0
+Frame2:  P    2   2        0.4624   0            0               0           4                4         -1 -2 -6 -10       1      -1       5         1 1 1 0 1
+Frame3:  P    3   3        0.4624   0            0               0           4                4         -1 -3 -7 -11       1      -1       5         0 1 1 1 1            
+Frame4:  P    4   1        0.578    0            0               0           4                4         -1 -4 -8 -12       1      -1       5         0 1 1 1 1
+
+#=========== Motion Search =============
+FastSearch                    : 1           # 0:Full search  1:TZ search
+SearchRange                   : 64          # (0: Search range is a Full frame)
+BipredSearchRange             : 4           # Search range for bi-prediction refinement
+HadamardME                    : 1           # Use of hadamard measure for fractional ME
+FEN                           : 1           # Fast encoder decision
+FDM                           : 1           # Fast Decision for Merge RD cost
+
+#======== Quantization =============
+#QP                            : 32          # Quantization parameter(0-51)
+MaxDeltaQP                    : 0           # CU-based multi-QP optimization
+MaxCuDQPDepth                 : 0           # Max depth of a minimum CuDQP for sub-LCU-level delta QP
+DeltaQpRD                     : 0           # Slice-based multi-QP optimization
+RDOQ                          : 1           # RDOQ
+RDOQTS                        : 1           # RDOQ for transform skip
+TransformSkip                 : 1           # Transform skipping (0: OFF, 1: ON)
+TransformSkipFast             : 1           # Fast Transform skipping (0: OFF, 1: ON)
+
+#=========== Deblock Filter ============
+DeblockingFilterControlPresent: 0           # Dbl control params present (0=not present, 1=present)
+LoopFilterOffsetInPPS         : 0           # Dbl params: 0=varying params in SliceHeader, param = base_param + GOP_offset_param; 1=constant params in PPS, param = base_param)
+LoopFilterDisable             : 0           # Disable deblocking filter (0=Filter, 1=No Filter)
+LoopFilterBetaOffset_div2     : 0           # base_param: -6 ~ 6
+LoopFilterTcOffset_div2       : 0           # base_param: -6 ~ 6
+DeblockingFilterMetric        : 0           # blockiness metric (automatically configures deblocking parameters in bitstream)
+
+#=========== Misc. ============
+#InternalBitDepth             : 10          # codec operating bit-depth
+
+#=========== Coding Tools =================
+SAO                           : 1           # Sample adaptive offset  (0: OFF, 1: ON)
+AMP                           : 1           # Asymmetric motion partitions (0: OFF, 1: ON)
+SAOLcuBoundary                : 0           # SAOLcuBoundary using non-deblocked pixels (0: OFF, 1: ON)
+
+#============ Slices ================
+SliceMode                : 0                # 0: Disable all slice options.
+                                            # 1: Enforce maximum number of LCU in an slice,
+                                            # 2: Enforce maximum number of bytes in an 'slice'
+                                            # 3: Enforce maximum number of tiles in a slice
+SliceArgument            : 1500             # Argument for 'SliceMode'.
+                                            # If SliceMode==1 it represents max. SliceGranularity-sized blocks per slice.
+                                            # If SliceMode==2 it represents max. bytes per slice.
+                                            # If SliceMode==3 it represents max. tiles per slice.
+
+LFCrossSliceBoundaryFlag : 1                # In-loop filtering, including ALF and DB, is across or not across slice boundary.
+                                            # 0:not across, 1: across
+
+#============ PCM ================
+PCMEnabledFlag                      : 0                # 0: No PCM mode
+PCMLog2MaxSize                      : 5                # Log2 of maximum PCM block size.
+PCMLog2MinSize                      : 3                # Log2 of minimum PCM block size.
+PCMInputBitDepthFlag                : 1                # 0: PCM bit-depth is internal bit-depth. 1: PCM bit-depth is input bit-depth.
+PCMFilterDisableFlag                : 0                # 0: Enable loop filtering on I_PCM samples. 1: Disable loop filtering on I_PCM samples.
+
+#============ Tiles ================
+TileUniformSpacing                  : 0                # 0: the column boundaries are indicated by TileColumnWidth array, the row boundaries are indicated by TileRowHeight array
+                                                       # 1: the column and row boundaries are distributed uniformly
+NumTileColumnsMinus1                : 0                # Number of tile columns in a picture minus 1
+TileColumnWidthArray                : 2 3              # Array containing tile column width values in units of CTU (from left to right in picture)   
+NumTileRowsMinus1                   : 0                # Number of tile rows in a picture minus 1
+TileRowHeightArray                  : 2                # Array containing tile row height values in units of CTU (from top to bottom in picture)
+
+LFCrossTileBoundaryFlag             : 1                # In-loop filtering is across or not across tile boundary.
+                                                       # 0:not across, 1: across 
+
+#============ WaveFront ================
+#WaveFrontSynchro                    : 0                # 0:  No WaveFront synchronisation (WaveFrontSubstreams must be 1 in this case).
+                                                       # >0: WaveFront synchronises with the LCU above and to the right by this many LCUs.
+
+#=========== Quantization Matrix =================
+ScalingList                   : 0                      # ScalingList 0 : off, 1 : default, 2 : file read
+ScalingListFile               : scaling_list.txt       # Scaling List file name. If file is not exist, use Default Matrix.
+
+#============ Lossless ================
+TransquantBypassEnableFlag : 0                         # Value of PPS flag.
+CUTransquantBypassFlagForce: 0                         # Force transquant bypass mode, when transquant_bypass_enable_flag is enabled
+
+#============ Rate Control ======================
+#RateControl                         : 0                # Rate control: enable rate control
+#TargetBitrate                       : 1000000          # Rate control: target bitrate, in bps
+#KeepHierarchicalBit                 : 2                # Rate control: 0: equal bit allocation; 1: fixed ratio bit allocation; 2: adaptive ratio bit allocation
+#LCULevelRateControl                 : 1                # Rate control: 1: LCU level RC; 0: picture level RC
+#RCLCUSeparateModel                  : 1                # Rate control: use LCU level separate R-lambda model
+#InitialQP                           : 0                # Rate control: initial QP
+#RCForceIntraQP                      : 0                # Rate control: force intra QP to be equal to initial QP
+
+### DO NOT ADD ANYTHING BELOW THIS LINE ###
+### DO NOT DELETE THE EMPTY LINE BELOW ###
Index: /tags/SHM-9.0/cfg/encoder_lowdelay_P_scalable_8_10.cfg
===================================================================
--- /tags/SHM-9.0/cfg/encoder_lowdelay_P_scalable_8_10.cfg	(revision 1088)
+++ /tags/SHM-9.0/cfg/encoder_lowdelay_P_scalable_8_10.cfg	(revision 1088)
@@ -0,0 +1,121 @@
+#======== File I/O =====================
+BitstreamFile                 : str.bin
+#ReconFile                     : rec.yuv
+
+#======== Profile ================
+NumProfileTierLevel           : 3
+Profile0                      : main                  # Profile for BL (NOTE01: this profile applies to whole layers but only BL is outputted)
+                                                      #                (NOTE02: this profile has no effect when NonHEVCBase is set to 1)
+Profile1                      : main                  # Profile for BL (NOTE01: this profile applies to HEVC BL only)
+                                                      #                (NOTE02: When NonHEVCBase is set to 1, this profile & associated level should be updated appropriately)
+Profile2                      : scalable-main10       # Scalable profile
+
+#======== Unit definition ================
+MaxCUWidth                    : 64          # Maximum coding unit width in pixel
+MaxCUHeight                   : 64          # Maximum coding unit height in pixel
+MaxPartitionDepth             : 4           # Maximum coding unit depth
+QuadtreeTULog2MaxSize         : 5           # Log2 of maximum transform size for
+                                            # quadtree-based TU coding (2...6)
+QuadtreeTULog2MinSize         : 2           # Log2 of minimum transform size for
+                                            # quadtree-based TU coding (2...6)
+QuadtreeTUMaxDepthInter       : 3
+QuadtreeTUMaxDepthIntra       : 3
+
+#======== Coding Structure =============
+#IntraPeriod                   : -1          # Period of I-Frame ( -1 = only first)
+DecodingRefreshType           : 0           # Random Accesss 0:none, 1:CRA, 2:IDR, 3:Recovery Point SEI
+GOPSize                       : 4           # GOP Size (number of B slice = GOPSize-1)
+#        Type POC QPoffset QPfactor tcOffsetDiv2 betaOffsetDiv2  temporal_id #ref_pics_active #ref_pics reference pictures predict deltaRPS #ref_idcs reference idcs 
+Frame1:  P    1   3        0.4624   0            0               0           4                4         -1 -5 -9 -13       0
+Frame2:  P    2   2        0.4624   0            0               0           4                4         -1 -2 -6 -10       1      -1       5         1 1 1 0 1
+Frame3:  P    3   3        0.4624   0            0               0           4                4         -1 -3 -7 -11       1      -1       5         0 1 1 1 1            
+Frame4:  P    4   1        0.578    0            0               0           4                4         -1 -4 -8 -12       1      -1       5         0 1 1 1 1
+
+#=========== Motion Search =============
+FastSearch                    : 1           # 0:Full search  1:TZ search
+SearchRange                   : 64          # (0: Search range is a Full frame)
+BipredSearchRange             : 4           # Search range for bi-prediction refinement
+HadamardME                    : 1           # Use of hadamard measure for fractional ME
+FEN                           : 1           # Fast encoder decision
+FDM                           : 1           # Fast Decision for Merge RD cost
+
+#======== Quantization =============
+#QP                            : 32          # Quantization parameter(0-51)
+MaxDeltaQP                    : 0           # CU-based multi-QP optimization
+MaxCuDQPDepth                 : 0           # Max depth of a minimum CuDQP for sub-LCU-level delta QP
+DeltaQpRD                     : 0           # Slice-based multi-QP optimization
+RDOQ                          : 1           # RDOQ
+RDOQTS                        : 1           # RDOQ for transform skip
+TransformSkip                 : 1           # Transform skipping (0: OFF, 1: ON)
+TransformSkipFast             : 1           # Fast Transform skipping (0: OFF, 1: ON)
+
+#=========== Deblock Filter ============
+DeblockingFilterControlPresent: 0           # Dbl control params present (0=not present, 1=present)
+LoopFilterOffsetInPPS         : 0           # Dbl params: 0=varying params in SliceHeader, param = base_param + GOP_offset_param; 1=constant params in PPS, param = base_param)
+LoopFilterDisable             : 0           # Disable deblocking filter (0=Filter, 1=No Filter)
+LoopFilterBetaOffset_div2     : 0           # base_param: -6 ~ 6
+LoopFilterTcOffset_div2       : 0           # base_param: -6 ~ 6
+DeblockingFilterMetric        : 0           # blockiness metric (automatically configures deblocking parameters in bitstream)
+
+#=========== Misc. ============
+#InternalBitDepth             : 10          # codec operating bit-depth
+
+#=========== Coding Tools =================
+SAO                           : 1           # Sample adaptive offset  (0: OFF, 1: ON)
+AMP                           : 1           # Asymmetric motion partitions (0: OFF, 1: ON)
+SAOLcuBoundary                : 0           # SAOLcuBoundary using non-deblocked pixels (0: OFF, 1: ON)
+
+#============ Slices ================
+SliceMode                : 0                # 0: Disable all slice options.
+                                            # 1: Enforce maximum number of LCU in an slice,
+                                            # 2: Enforce maximum number of bytes in an 'slice'
+                                            # 3: Enforce maximum number of tiles in a slice
+SliceArgument            : 1500             # Argument for 'SliceMode'.
+                                            # If SliceMode==1 it represents max. SliceGranularity-sized blocks per slice.
+                                            # If SliceMode==2 it represents max. bytes per slice.
+                                            # If SliceMode==3 it represents max. tiles per slice.
+
+LFCrossSliceBoundaryFlag : 1                # In-loop filtering, including ALF and DB, is across or not across slice boundary.
+                                            # 0:not across, 1: across
+
+#============ PCM ================
+PCMEnabledFlag                      : 0                # 0: No PCM mode
+PCMLog2MaxSize                      : 5                # Log2 of maximum PCM block size.
+PCMLog2MinSize                      : 3                # Log2 of minimum PCM block size.
+PCMInputBitDepthFlag                : 1                # 0: PCM bit-depth is internal bit-depth. 1: PCM bit-depth is input bit-depth.
+PCMFilterDisableFlag                : 0                # 0: Enable loop filtering on I_PCM samples. 1: Disable loop filtering on I_PCM samples.
+
+#============ Tiles ================
+TileUniformSpacing                  : 0                # 0: the column boundaries are indicated by TileColumnWidth array, the row boundaries are indicated by TileRowHeight array
+                                                       # 1: the column and row boundaries are distributed uniformly
+NumTileColumnsMinus1                : 0                # Number of tile columns in a picture minus 1
+TileColumnWidthArray                : 2 3              # Array containing tile column width values in units of CTU (from left to right in picture)   
+NumTileRowsMinus1                   : 0                # Number of tile rows in a picture minus 1
+TileRowHeightArray                  : 2                # Array containing tile row height values in units of CTU (from top to bottom in picture)
+
+LFCrossTileBoundaryFlag             : 1                # In-loop filtering is across or not across tile boundary.
+                                                       # 0:not across, 1: across 
+
+#============ WaveFront ================
+#WaveFrontSynchro                    : 0                # 0:  No WaveFront synchronisation (WaveFrontSubstreams must be 1 in this case).
+                                                       # >0: WaveFront synchronises with the LCU above and to the right by this many LCUs.
+
+#=========== Quantization Matrix =================
+ScalingList                   : 0                      # ScalingList 0 : off, 1 : default, 2 : file read
+ScalingListFile               : scaling_list.txt       # Scaling List file name. If file is not exist, use Default Matrix.
+
+#============ Lossless ================
+TransquantBypassEnableFlag : 0                         # Value of PPS flag.
+CUTransquantBypassFlagForce: 0                         # Force transquant bypass mode, when transquant_bypass_enable_flag is enabled
+
+#============ Rate Control ======================
+#RateControl                         : 0                # Rate control: enable rate control
+#TargetBitrate                       : 1000000          # Rate control: target bitrate, in bps
+#KeepHierarchicalBit                 : 2                # Rate control: 0: equal bit allocation; 1: fixed ratio bit allocation; 2: adaptive ratio bit allocation
+#LCULevelRateControl                 : 1                # Rate control: 1: LCU level RC; 0: picture level RC
+#RCLCUSeparateModel                  : 1                # Rate control: use LCU level separate R-lambda model
+#InitialQP                           : 0                # Rate control: initial QP
+#RCForceIntraQP                      : 0                # Rate control: force intra QP to be equal to initial QP
+
+### DO NOT ADD ANYTHING BELOW THIS LINE ###
+### DO NOT DELETE THE EMPTY LINE BELOW ###
Index: /tags/SHM-9.0/cfg/encoder_lowdelay_main.cfg
===================================================================
--- /tags/SHM-9.0/cfg/encoder_lowdelay_main.cfg	(revision 1088)
+++ /tags/SHM-9.0/cfg/encoder_lowdelay_main.cfg	(revision 1088)
@@ -0,0 +1,122 @@
+#======== File I/O =====================
+BitstreamFile                 : str.bin
+#ReconFile                     : rec.yuv
+
+#======== Profile/Level ================
+#Profile                       : main
+NumProfileTierLevel           : 3
+Profile0                      : main                # Profile for BL (NOTE01: this profile applies to whole layers but only BL is outputted)
+                                                    #                (NOTE02: this profile has no effect when NonHEVCBase is set to 1)
+Profile1                      : main                # Profile for BL (NOTE01: this profile applies to HEVC BL only)
+                                                    #                (NOTE02: When NonHEVCBase is set to 1, this profile & associated level should be updated appropriately)
+Profile2                      : scalable-main       # Scalable profile
+
+#======== 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.
+CUTransquantBypassFlagForce: 0 # Constant lossless-value signaling per CU, if TransquantBypassEnableFlag is 1.
+
+#============ Rate Control ======================
+#RateControl                         : 0                # Rate control: enable rate control
+#TargetBitrate                       : 1000000          # Rate control: target bitrate, in bps
+#KeepHierarchicalBit                 : 2                # Rate control: 0: equal bit allocation; 1: fixed ratio bit allocation; 2: adaptive ratio bit allocation
+#LCULevelRateControl                 : 1                # Rate control: 1: LCU level RC; 0: picture level RC
+#RCLCUSeparateModel                  : 1                # Rate control: use LCU level separate R-lambda model
+#InitialQP                           : 0                # Rate control: initial QP
+#RCForceIntraQP                      : 0                # Rate control: force intra QP to be equal to initial QP
+
+### DO NOT ADD ANYTHING BELOW THIS LINE ###
+### DO NOT DELETE THE EMPTY LINE BELOW ###
Index: /tags/SHM-9.0/cfg/encoder_lowdelay_main10.cfg
===================================================================
--- /tags/SHM-9.0/cfg/encoder_lowdelay_main10.cfg	(revision 1088)
+++ /tags/SHM-9.0/cfg/encoder_lowdelay_main10.cfg	(revision 1088)
@@ -0,0 +1,122 @@
+#======== File I/O =====================
+BitstreamFile                 : str.bin
+#ReconFile                     : rec.yuv
+
+#======== Profile/Level ================
+#Profile                      : main10
+NumProfileTierLevel           : 3
+Profile0                      : main10                # Profile for BL (NOTE01: this profile applies to whole layers but only BL is outputted)
+                                                      #                (NOTE02: this profile has no effect when NonHEVCBase is set to 1)
+Profile1                      : main10                # Profile for BL (NOTE01: this profile applies to HEVC BL only)
+                                                      #                (NOTE02: When NonHEVCBase is set to 1, this profile & associated level should be updated appropriately)
+Profile2                      : scalable-main10       # Scalable profile
+
+#======== 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.
+CUTransquantBypassFlagForce: 0 # Constant lossless-value signaling per CU, if TransquantBypassEnableFlag is 1.
+
+#============ Rate Control ======================
+#RateControl                         : 0                # Rate control: enable rate control
+#TargetBitrate                       : 1000000          # Rate control: target bitrate, in bps
+#KeepHierarchicalBit                 : 2                # Rate control: 0: equal bit allocation; 1: fixed ratio bit allocation; 2: adaptive ratio bit allocation
+#LCULevelRateControl                 : 1                # Rate control: 1: LCU level RC; 0: picture level RC
+#RCLCUSeparateModel                  : 1                # Rate control: use LCU level separate R-lambda model
+#InitialQP                           : 0                # Rate control: initial QP
+#RCForceIntraQP                      : 0                # Rate control: force intra QP to be equal to initial QP
+
+### DO NOT ADD ANYTHING BELOW THIS LINE ###
+### DO NOT DELETE THE EMPTY LINE BELOW ###
Index: /tags/SHM-9.0/cfg/encoder_lowdelay_scalable.cfg
===================================================================
--- /tags/SHM-9.0/cfg/encoder_lowdelay_scalable.cfg	(revision 1088)
+++ /tags/SHM-9.0/cfg/encoder_lowdelay_scalable.cfg	(revision 1088)
@@ -0,0 +1,121 @@
+#======== File I/O =====================
+BitstreamFile                 : str.bin
+#ReconFile                     : rec.yuv
+
+#======== Profile ================
+NumProfileTierLevel           : 3
+Profile0                      : main                # Profile for BL (NOTE01: this profile applies to whole layers but only BL is outputted)
+                                                    #                (NOTE02: this profile has no effect when NonHEVCBase is set to 1)
+Profile1                      : main                # Profile for BL (NOTE01: this profile applies to HEVC BL only)
+                                                    #                (NOTE02: When NonHEVCBase is set to 1, this profile & associated level should be updated appropriately)
+Profile2                      : scalable-main       # Scalable profile
+
+#======== Unit definition ================
+MaxCUWidth                    : 64          # Maximum coding unit width in pixel
+MaxCUHeight                   : 64          # Maximum coding unit height in pixel
+MaxPartitionDepth             : 4           # Maximum coding unit depth
+QuadtreeTULog2MaxSize         : 5           # Log2 of maximum transform size for
+                                            # quadtree-based TU coding (2...6)
+QuadtreeTULog2MinSize         : 2           # Log2 of minimum transform size for
+                                            # quadtree-based TU coding (2...6)
+QuadtreeTUMaxDepthInter       : 3
+QuadtreeTUMaxDepthIntra       : 3
+
+#======== Coding Structure =============
+#IntraPeriod                   : -1          # Period of I-Frame ( -1 = only first)
+DecodingRefreshType           : 0           # Random Accesss 0:none, 1:CRA, 2:IDR, 3:Recovery Point SEI
+GOPSize                       : 4           # GOP Size (number of B slice = GOPSize-1)
+#        Type POC QPoffset QPfactor tcOffsetDiv2 betaOffsetDiv2  temporal_id #ref_pics_active #ref_pics reference pictures predict deltaRPS #ref_idcs reference idcs 
+Frame1:  B    1   3        0.4624   0            0               0           4                4         -1 -5 -9 -13       0
+Frame2:  B    2   2        0.4624   0            0               0           4                4         -1 -2 -6 -10       1      -1       5         1 1 1 0 1
+Frame3:  B    3   3        0.4624   0            0               0           4                4         -1 -3 -7 -11       1      -1       5         0 1 1 1 1            
+Frame4:  B    4   1        0.578    0            0               0           4                4         -1 -4 -8 -12       1      -1       5         0 1 1 1 1
+
+#=========== Motion Search =============
+FastSearch                    : 1           # 0:Full search  1:TZ search
+SearchRange                   : 64          # (0: Search range is a Full frame)
+BipredSearchRange             : 4           # Search range for bi-prediction refinement
+HadamardME                    : 1           # Use of hadamard measure for fractional ME
+FEN                           : 1           # Fast encoder decision
+FDM                           : 1           # Fast Decision for Merge RD cost
+
+#======== Quantization =============
+#QP                            : 32          # Quantization parameter(0-51)
+MaxDeltaQP                    : 0           # CU-based multi-QP optimization
+MaxCuDQPDepth                 : 0           # Max depth of a minimum CuDQP for sub-LCU-level delta QP
+DeltaQpRD                     : 0           # Slice-based multi-QP optimization
+RDOQ                          : 1           # RDOQ
+RDOQTS                        : 1           # RDOQ for transform skip
+
+#=========== Deblock Filter ============
+DeblockingFilterControlPresent: 0           # Dbl control params present (0=not present, 1=present)
+LoopFilterOffsetInPPS         : 0           # Dbl params: 0=varying params in SliceHeader, param = base_param + GOP_offset_param; 1=constant params in PPS, param = base_param)
+LoopFilterDisable             : 0           # Disable deblocking filter (0=Filter, 1=No Filter)
+LoopFilterBetaOffset_div2     : 0           # base_param: -6 ~ 6
+LoopFilterTcOffset_div2       : 0           # base_param: -6 ~ 6
+DeblockingFilterMetric        : 0           # blockiness metric (automatically configures deblocking parameters in bitstream)
+
+#=========== Misc. ============
+#InternalBitDepth             : 8           # codec operating bit-depth
+
+#=========== Coding Tools =================
+SAO                           : 1           # Sample adaptive offset  (0: OFF, 1: ON)
+AMP                           : 1           # Asymmetric motion partitions (0: OFF, 1: ON)
+TransformSkip                 : 1           # Transform skipping (0: OFF, 1: ON)
+TransformSkipFast             : 1           # Fast Transform skipping (0: OFF, 1: ON)
+SAOLcuBoundary                : 0           # SAOLcuBoundary using non-deblocked pixels (0: OFF, 1: ON)
+
+#============ Slices ================
+SliceMode                : 0                # 0: Disable all slice options.
+                                            # 1: Enforce maximum number of LCU in an slice,
+                                            # 2: Enforce maximum number of bytes in an 'slice'
+                                            # 3: Enforce maximum number of tiles in a slice
+SliceArgument            : 1500             # Argument for 'SliceMode'.
+                                            # If SliceMode==1 it represents max. SliceGranularity-sized blocks per slice.
+                                            # If SliceMode==2 it represents max. bytes per slice.
+                                            # If SliceMode==3 it represents max. tiles per slice.
+
+LFCrossSliceBoundaryFlag : 1                # In-loop filtering, including ALF and DB, is across or not across slice boundary.
+                                            # 0:not across, 1: across
+
+#============ PCM ================
+PCMEnabledFlag                      : 0                # 0: No PCM mode
+PCMLog2MaxSize                      : 5                # Log2 of maximum PCM block size.
+PCMLog2MinSize                      : 3                # Log2 of minimum PCM block size.
+PCMInputBitDepthFlag                : 1                # 0: PCM bit-depth is internal bit-depth. 1: PCM bit-depth is input bit-depth.
+PCMFilterDisableFlag                : 0                # 0: Enable loop filtering on I_PCM samples. 1: Disable loop filtering on I_PCM samples.
+
+#============ Tiles ================
+TileUniformSpacing                  : 0                # 0: the column boundaries are indicated by TileColumnWidth array, the row boundaries are indicated by TileRowHeight array
+                                                       # 1: the column and row boundaries are distributed uniformly
+NumTileColumnsMinus1                : 0                # Number of tile columns in a picture minus 1
+TileColumnWidthArray                : 2 3              # Array containing tile column width values in units of CTU (from left to right in picture)   
+NumTileRowsMinus1                   : 0                # Number of tile rows in a picture minus 1
+TileRowHeightArray                  : 2                # Array containing tile row height values in units of CTU (from top to bottom in picture)
+
+LFCrossTileBoundaryFlag             : 1                # In-loop filtering is across or not across tile boundary.
+                                                       # 0:not across, 1: across 
+
+#============ WaveFront ================
+#WaveFrontSynchro                    : 0                # 0:  No WaveFront synchronisation (WaveFrontSubstreams must be 1 in this case).
+                                                       # >0: WaveFront synchronises with the LCU above and to the right by this many LCUs.
+
+#=========== Quantization Matrix =================
+ScalingList                   : 0                      # ScalingList 0 : off, 1 : default, 2 : file read
+ScalingListFile               : scaling_list.txt       # Scaling List file name. If file is not exist, use Default Matrix.
+
+#============ Lossless ================
+TransquantBypassEnableFlag : 0                         # Value of PPS flag.
+CUTransquantBypassFlagForce: 0                         # Force transquant bypass mode, when transquant_bypass_enable_flag is enabled
+
+#============ Rate Control ======================
+#RateControl                         : 0                # Rate control: enable rate control
+#TargetBitrate                       : 1000000          # Rate control: target bitrate, in bps
+#KeepHierarchicalBit                 : 2                # Rate control: 0: equal bit allocation; 1: fixed ratio bit allocation; 2: adaptive ratio bit allocation
+#LCULevelRateControl                 : 1                # Rate control: 1: LCU level RC; 0: picture level RC
+#RCLCUSeparateModel                  : 1                # Rate control: use LCU level separate R-lambda model
+#InitialQP                           : 0                # Rate control: initial QP
+#RCForceIntraQP                      : 0                # Rate control: force intra QP to be equal to initial QP
+
+### DO NOT ADD ANYTHING BELOW THIS LINE ###
+### DO NOT DELETE THE EMPTY LINE BELOW ###
Index: /tags/SHM-9.0/cfg/encoder_lowdelay_scalable10.cfg
===================================================================
--- /tags/SHM-9.0/cfg/encoder_lowdelay_scalable10.cfg	(revision 1088)
+++ /tags/SHM-9.0/cfg/encoder_lowdelay_scalable10.cfg	(revision 1088)
@@ -0,0 +1,121 @@
+#======== File I/O =====================
+BitstreamFile                 : str.bin
+#ReconFile                     : rec.yuv
+
+#======== Profile ================
+NumProfileTierLevel           : 3
+Profile0                      : main10                # Profile for BL (NOTE01: this profile applies to whole layers but only BL is outputted)
+                                                      #                (NOTE02: this profile has no effect when NonHEVCBase is set to 1)
+Profile1                      : main10                # Profile for BL (NOTE01: this profile applies to HEVC BL only)
+                                                      #                (NOTE02: When NonHEVCBase is set to 1, this profile & associated level should be updated appropriately)
+Profile2                      : scalable-main10       # Scalable profile
+
+#======== Unit definition ================
+MaxCUWidth                    : 64          # Maximum coding unit width in pixel
+MaxCUHeight                   : 64          # Maximum coding unit height in pixel
+MaxPartitionDepth             : 4           # Maximum coding unit depth
+QuadtreeTULog2MaxSize         : 5           # Log2 of maximum transform size for
+                                            # quadtree-based TU coding (2...6)
+QuadtreeTULog2MinSize         : 2           # Log2 of minimum transform size for
+                                            # quadtree-based TU coding (2...6)
+QuadtreeTUMaxDepthInter       : 3
+QuadtreeTUMaxDepthIntra       : 3
+
+#======== Coding Structure =============
+#IntraPeriod                   : -1          # Period of I-Frame ( -1 = only first)
+DecodingRefreshType           : 0           # Random Accesss 0:none, 1:CRA, 2:IDR, 3:Recovery Point SEI
+GOPSize                       : 4           # GOP Size (number of B slice = GOPSize-1)
+#        Type POC QPoffset QPfactor tcOffsetDiv2 betaOffsetDiv2  temporal_id #ref_pics_active #ref_pics reference pictures predict deltaRPS #ref_idcs reference idcs 
+Frame1:  B    1   3        0.4624   0            0               0           4                4         -1 -5 -9 -13       0
+Frame2:  B    2   2        0.4624   0            0               0           4                4         -1 -2 -6 -10       1      -1       5         1 1 1 0 1
+Frame3:  B    3   3        0.4624   0            0               0           4                4         -1 -3 -7 -11       1      -1       5         0 1 1 1 1            
+Frame4:  B    4   1        0.578    0            0               0           4                4         -1 -4 -8 -12       1      -1       5         0 1 1 1 1
+
+#=========== Motion Search =============
+FastSearch                    : 1           # 0:Full search  1:TZ search
+SearchRange                   : 64          # (0: Search range is a Full frame)
+BipredSearchRange             : 4           # Search range for bi-prediction refinement
+HadamardME                    : 1           # Use of hadamard measure for fractional ME
+FEN                           : 1           # Fast encoder decision
+FDM                           : 1           # Fast Decision for Merge RD cost
+
+#======== Quantization =============
+#QP                            : 32          # Quantization parameter(0-51)
+MaxDeltaQP                    : 0           # CU-based multi-QP optimization
+MaxCuDQPDepth                 : 0           # Max depth of a minimum CuDQP for sub-LCU-level delta QP
+DeltaQpRD                     : 0           # Slice-based multi-QP optimization
+RDOQ                          : 1           # RDOQ
+RDOQTS                        : 1           # RDOQ for transform skip
+
+#=========== Deblock Filter ============
+DeblockingFilterControlPresent: 0           # Dbl control params present (0=not present, 1=present)
+LoopFilterOffsetInPPS         : 0           # Dbl params: 0=varying params in SliceHeader, param = base_param + GOP_offset_param; 1=constant params in PPS, param = base_param)
+LoopFilterDisable             : 0           # Disable deblocking filter (0=Filter, 1=No Filter)
+LoopFilterBetaOffset_div2     : 0           # base_param: -6 ~ 6
+LoopFilterTcOffset_div2       : 0           # base_param: -6 ~ 6
+DeblockingFilterMetric        : 0           # blockiness metric (automatically configures deblocking parameters in bitstream)
+
+#=========== Misc. ============
+#InternalBitDepth             : 10          # codec operating bit-depth
+
+#=========== Coding Tools =================
+SAO                           : 1           # Sample adaptive offset  (0: OFF, 1: ON)
+AMP                           : 1           # Asymmetric motion partitions (0: OFF, 1: ON)
+TransformSkip                 : 1           # Transform skipping (0: OFF, 1: ON)
+TransformSkipFast             : 1           # Fast Transform skipping (0: OFF, 1: ON)
+SAOLcuBoundary                : 0           # SAOLcuBoundary using non-deblocked pixels (0: OFF, 1: ON)
+
+#============ Slices ================
+SliceMode                : 0                # 0: Disable all slice options.
+                                            # 1: Enforce maximum number of LCU in an slice,
+                                            # 2: Enforce maximum number of bytes in an 'slice'
+                                            # 3: Enforce maximum number of tiles in a slice
+SliceArgument            : 1500             # Argument for 'SliceMode'.
+                                            # If SliceMode==1 it represents max. SliceGranularity-sized blocks per slice.
+                                            # If SliceMode==2 it represents max. bytes per slice.
+                                            # If SliceMode==3 it represents max. tiles per slice.
+
+LFCrossSliceBoundaryFlag : 1                # In-loop filtering, including ALF and DB, is across or not across slice boundary.
+                                            # 0:not across, 1: across
+
+#============ PCM ================
+PCMEnabledFlag                      : 0                # 0: No PCM mode
+PCMLog2MaxSize                      : 5                # Log2 of maximum PCM block size.
+PCMLog2MinSize                      : 3                # Log2 of minimum PCM block size.
+PCMInputBitDepthFlag                : 1                # 0: PCM bit-depth is internal bit-depth. 1: PCM bit-depth is input bit-depth.
+PCMFilterDisableFlag                : 0                # 0: Enable loop filtering on I_PCM samples. 1: Disable loop filtering on I_PCM samples.
+
+#============ Tiles ================
+TileUniformSpacing                  : 0                # 0: the column boundaries are indicated by TileColumnWidth array, the row boundaries are indicated by TileRowHeight array
+                                                       # 1: the column and row boundaries are distributed uniformly
+NumTileColumnsMinus1                : 0                # Number of tile columns in a picture minus 1
+TileColumnWidthArray                : 2 3              # Array containing tile column width values in units of CTU (from left to right in picture)   
+NumTileRowsMinus1                   : 0                # Number of tile rows in a picture minus 1
+TileRowHeightArray                  : 2                # Array containing tile row height values in units of CTU (from top to bottom in picture)
+
+LFCrossTileBoundaryFlag             : 1                # In-loop filtering is across or not across tile boundary.
+                                                       # 0:not across, 1: across 
+
+#============ WaveFront ================
+#WaveFrontSynchro                    : 0                # 0:  No WaveFront synchronisation (WaveFrontSubstreams must be 1 in this case).
+                                                       # >0: WaveFront synchronises with the LCU above and to the right by this many LCUs.
+
+#=========== Quantization Matrix =================
+ScalingList                   : 0                      # ScalingList 0 : off, 1 : default, 2 : file read
+ScalingListFile               : scaling_list.txt       # Scaling List file name. If file is not exist, use Default Matrix.
+
+#============ Lossless ================
+TransquantBypassEnableFlag : 0                         # Value of PPS flag.
+CUTransquantBypassFlagForce: 0                         # Force transquant bypass mode, when transquant_bypass_enable_flag is enabled
+
+#============ Rate Control ======================
+#RateControl                         : 0                # Rate control: enable rate control
+#TargetBitrate                       : 1000000          # Rate control: target bitrate, in bps
+#KeepHierarchicalBit                 : 2                # Rate control: 0: equal bit allocation; 1: fixed ratio bit allocation; 2: adaptive ratio bit allocation
+#LCULevelRateControl                 : 1                # Rate control: 1: LCU level RC; 0: picture level RC
+#RCLCUSeparateModel                  : 1                # Rate control: use LCU level separate R-lambda model
+#InitialQP                           : 0                # Rate control: initial QP
+#RCForceIntraQP                      : 0                # Rate control: force intra QP to be equal to initial QP
+
+### DO NOT ADD ANYTHING BELOW THIS LINE ###
+### DO NOT DELETE THE EMPTY LINE BELOW ###
Index: /tags/SHM-9.0/cfg/encoder_lowdelay_scalable_8_10.cfg
===================================================================
--- /tags/SHM-9.0/cfg/encoder_lowdelay_scalable_8_10.cfg	(revision 1088)
+++ /tags/SHM-9.0/cfg/encoder_lowdelay_scalable_8_10.cfg	(revision 1088)
@@ -0,0 +1,121 @@
+#======== File I/O =====================
+BitstreamFile                 : str.bin
+#ReconFile                     : rec.yuv
+
+#======== Profile ================
+NumProfileTierLevel           : 3
+Profile0                      : main                  # Profile for BL (NOTE01: this profile applies to whole layers but only BL is outputted)
+                                                      #                (NOTE02: this profile has no effect when NonHEVCBase is set to 1)
+Profile1                      : main                  # Profile for BL (NOTE01: this profile applies to HEVC BL only)
+                                                      #                (NOTE02: When NonHEVCBase is set to 1, this profile & associated level should be updated appropriately)
+Profile2                      : scalable-main10       # Scalable profile
+
+#======== Unit definition ================
+MaxCUWidth                    : 64          # Maximum coding unit width in pixel
+MaxCUHeight                   : 64          # Maximum coding unit height in pixel
+MaxPartitionDepth             : 4           # Maximum coding unit depth
+QuadtreeTULog2MaxSize         : 5           # Log2 of maximum transform size for
+                                            # quadtree-based TU coding (2...6)
+QuadtreeTULog2MinSize         : 2           # Log2 of minimum transform size for
+                                            # quadtree-based TU coding (2...6)
+QuadtreeTUMaxDepthInter       : 3
+QuadtreeTUMaxDepthIntra       : 3
+
+#======== Coding Structure =============
+#IntraPeriod                   : -1          # Period of I-Frame ( -1 = only first)
+DecodingRefreshType           : 0           # Random Accesss 0:none, 1:CRA, 2:IDR, 3:Recovery Point SEI
+GOPSize                       : 4           # GOP Size (number of B slice = GOPSize-1)
+#        Type POC QPoffset QPfactor tcOffsetDiv2 betaOffsetDiv2  temporal_id #ref_pics_active #ref_pics reference pictures predict deltaRPS #ref_idcs reference idcs 
+Frame1:  B    1   3        0.4624   0            0               0           4                4         -1 -5 -9 -13       0
+Frame2:  B    2   2        0.4624   0            0               0           4                4         -1 -2 -6 -10       1      -1       5         1 1 1 0 1
+Frame3:  B    3   3        0.4624   0            0               0           4                4         -1 -3 -7 -11       1      -1       5         0 1 1 1 1            
+Frame4:  B    4   1        0.578    0            0               0           4                4         -1 -4 -8 -12       1      -1       5         0 1 1 1 1
+
+#=========== Motion Search =============
+FastSearch                    : 1           # 0:Full search  1:TZ search
+SearchRange                   : 64          # (0: Search range is a Full frame)
+BipredSearchRange             : 4           # Search range for bi-prediction refinement
+HadamardME                    : 1           # Use of hadamard measure for fractional ME
+FEN                           : 1           # Fast encoder decision
+FDM                           : 1           # Fast Decision for Merge RD cost
+
+#======== Quantization =============
+#QP                            : 32          # Quantization parameter(0-51)
+MaxDeltaQP                    : 0           # CU-based multi-QP optimization
+MaxCuDQPDepth                 : 0           # Max depth of a minimum CuDQP for sub-LCU-level delta QP
+DeltaQpRD                     : 0           # Slice-based multi-QP optimization
+RDOQ                          : 1           # RDOQ
+RDOQTS                        : 1           # RDOQ for transform skip
+
+#=========== Deblock Filter ============
+DeblockingFilterControlPresent: 0           # Dbl control params present (0=not present, 1=present)
+LoopFilterOffsetInPPS         : 0           # Dbl params: 0=varying params in SliceHeader, param = base_param + GOP_offset_param; 1=constant params in PPS, param = base_param)
+LoopFilterDisable             : 0           # Disable deblocking filter (0=Filter, 1=No Filter)
+LoopFilterBetaOffset_div2     : 0           # base_param: -6 ~ 6
+LoopFilterTcOffset_div2       : 0           # base_param: -6 ~ 6
+DeblockingFilterMetric        : 0           # blockiness metric (automatically configures deblocking parameters in bitstream)
+
+#=========== Misc. ============
+#InternalBitDepth             : 10          # codec operating bit-depth
+
+#=========== Coding Tools =================
+SAO                           : 1           # Sample adaptive offset  (0: OFF, 1: ON)
+AMP                           : 1           # Asymmetric motion partitions (0: OFF, 1: ON)
+TransformSkip                 : 1           # Transform skipping (0: OFF, 1: ON)
+TransformSkipFast             : 1           # Fast Transform skipping (0: OFF, 1: ON)
+SAOLcuBoundary                : 0           # SAOLcuBoundary using non-deblocked pixels (0: OFF, 1: ON)
+
+#============ Slices ================
+SliceMode                : 0                # 0: Disable all slice options.
+                                            # 1: Enforce maximum number of LCU in an slice,
+                                            # 2: Enforce maximum number of bytes in an 'slice'
+                                            # 3: Enforce maximum number of tiles in a slice
+SliceArgument            : 1500             # Argument for 'SliceMode'.
+                                            # If SliceMode==1 it represents max. SliceGranularity-sized blocks per slice.
+                                            # If SliceMode==2 it represents max. bytes per slice.
+                                            # If SliceMode==3 it represents max. tiles per slice.
+
+LFCrossSliceBoundaryFlag : 1                # In-loop filtering, including ALF and DB, is across or not across slice boundary.
+                                            # 0:not across, 1: across
+
+#============ PCM ================
+PCMEnabledFlag                      : 0                # 0: No PCM mode
+PCMLog2MaxSize                      : 5                # Log2 of maximum PCM block size.
+PCMLog2MinSize                      : 3                # Log2 of minimum PCM block size.
+PCMInputBitDepthFlag                : 1                # 0: PCM bit-depth is internal bit-depth. 1: PCM bit-depth is input bit-depth.
+PCMFilterDisableFlag                : 0                # 0: Enable loop filtering on I_PCM samples. 1: Disable loop filtering on I_PCM samples.
+
+#============ Tiles ================
+TileUniformSpacing                  : 0                # 0: the column boundaries are indicated by TileColumnWidth array, the row boundaries are indicated by TileRowHeight array
+                                                       # 1: the column and row boundaries are distributed uniformly
+NumTileColumnsMinus1                : 0                # Number of tile columns in a picture minus 1
+TileColumnWidthArray                : 2 3              # Array containing tile column width values in units of CTU (from left to right in picture)   
+NumTileRowsMinus1                   : 0                # Number of tile rows in a picture minus 1
+TileRowHeightArray                  : 2                # Array containing tile row height values in units of CTU (from top to bottom in picture)
+
+LFCrossTileBoundaryFlag             : 1                # In-loop filtering is across or not across tile boundary.
+                                                       # 0:not across, 1: across 
+
+#============ WaveFront ================
+#WaveFrontSynchro                    : 0                # 0:  No WaveFront synchronisation (WaveFrontSubstreams must be 1 in this case).
+                                                       # >0: WaveFront synchronises with the LCU above and to the right by this many LCUs.
+
+#=========== Quantization Matrix =================
+ScalingList                   : 0                      # ScalingList 0 : off, 1 : default, 2 : file read
+ScalingListFile               : scaling_list.txt       # Scaling List file name. If file is not exist, use Default Matrix.
+
+#============ Lossless ================
+TransquantBypassEnableFlag : 0                         # Value of PPS flag.
+CUTransquantBypassFlagForce: 0                         # Force transquant bypass mode, when transquant_bypass_enable_flag is enabled
+
+#============ Rate Control ======================
+#RateControl                         : 0                # Rate control: enable rate control
+#TargetBitrate                       : 1000000          # Rate control: target bitrate, in bps
+#KeepHierarchicalBit                 : 2                # Rate control: 0: equal bit allocation; 1: fixed ratio bit allocation; 2: adaptive ratio bit allocation
+#LCULevelRateControl                 : 1                # Rate control: 1: LCU level RC; 0: picture level RC
+#RCLCUSeparateModel                  : 1                # Rate control: use LCU level separate R-lambda model
+#InitialQP                           : 0                # Rate control: initial QP
+#RCForceIntraQP                      : 0                # Rate control: force intra QP to be equal to initial QP
+
+### DO NOT ADD ANYTHING BELOW THIS LINE ###
+### DO NOT DELETE THE EMPTY LINE BELOW ###
Index: /tags/SHM-9.0/cfg/encoder_randomaccess_main.cfg
===================================================================
--- /tags/SHM-9.0/cfg/encoder_randomaccess_main.cfg	(revision 1088)
+++ /tags/SHM-9.0/cfg/encoder_randomaccess_main.cfg	(revision 1088)
@@ -0,0 +1,127 @@
+#======== File I/O =====================
+BitstreamFile                 : str.bin
+#ReconFile                     : rec.yuv
+
+#======== Profile/Level ================
+#Profile                      : main
+NumProfileTierLevel           : 3
+Profile0                      : main                # Profile for BL (NOTE01: this profile applies to whole layers but only BL is outputted)
+                                                    #                (NOTE02: this profile has no effect when NonHEVCBase is set to 1)
+Profile1                      : main                # Profile for BL (NOTE01: this profile applies to HEVC BL only)
+                                                    #                (NOTE02: When NonHEVCBase is set to 1, this profile & associated level should be updated appropriately)
+Profile2                      : scalable-main       # Scalable profile
+
+#======== 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.
+CUTransquantBypassFlagForce: 0 # Constant lossless-value signaling per CU, if TransquantBypassEnableFlag is 1.
+
+#============ Rate Control ======================
+#RateControl                         : 0                # Rate control: enable rate control
+#TargetBitrate                       : 1000000          # Rate control: target bitrate, in bps
+#KeepHierarchicalBit                 : 2                # Rate control: 0: equal bit allocation; 1: fixed ratio bit allocation; 2: adaptive ratio bit allocation
+#LCULevelRateControl                 : 1                # Rate control: 1: LCU level RC; 0: picture level RC
+#RCLCUSeparateModel                  : 1                # Rate control: use LCU level separate R-lambda model
+#InitialQP                           : 0                # Rate control: initial QP
+#RCForceIntraQP                      : 0                # Rate control: force intra QP to be equal to initial QP
+
+### DO NOT ADD ANYTHING BELOW THIS LINE ###
+### DO NOT DELETE THE EMPTY LINE BELOW ###
+
Index: /tags/SHM-9.0/cfg/encoder_randomaccess_main10.cfg
===================================================================
--- /tags/SHM-9.0/cfg/encoder_randomaccess_main10.cfg	(revision 1088)
+++ /tags/SHM-9.0/cfg/encoder_randomaccess_main10.cfg	(revision 1088)
@@ -0,0 +1,127 @@
+#======== File I/O =====================
+BitstreamFile                 : str.bin
+#ReconFile                     : rec.yuv
+
+#======== Profile/Level ================
+#Profile                      : main10
+NumProfileTierLevel           : 3
+Profile0                      : main10                # Profile for BL (NOTE01: this profile applies to whole layers but only BL is outputted)
+                                                      #                (NOTE02: this profile has no effect when NonHEVCBase is set to 1)
+Profile1                      : main10                # Profile for BL (NOTE01: this profile applies to HEVC BL only)
+                                                      #                (NOTE02: When NonHEVCBase is set to 1, this profile & associated level should be updated appropriately)
+Profile2                      : scalable-main10       # Scalable profile
+
+#======== 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.
+CUTransquantBypassFlagForce: 0 # Constant lossless-value signaling per CU, if TransquantBypassEnableFlag is 1.
+
+#============ Rate Control ======================
+#RateControl                         : 0                # Rate control: enable rate control
+#TargetBitrate                       : 1000000          # Rate control: target bitrate, in bps
+#KeepHierarchicalBit                 : 2                # Rate control: 0: equal bit allocation; 1: fixed ratio bit allocation; 2: adaptive ratio bit allocation
+#LCULevelRateControl                 : 1                # Rate control: 1: LCU level RC; 0: picture level RC
+#RCLCUSeparateModel                  : 1                # Rate control: use LCU level separate R-lambda model
+#InitialQP                           : 0                # Rate control: initial QP
+#RCForceIntraQP                      : 0                # Rate control: force intra QP to be equal to initial QP
+
+### DO NOT ADD ANYTHING BELOW THIS LINE ###
+### DO NOT DELETE THE EMPTY LINE BELOW ###
+
Index: /tags/SHM-9.0/cfg/encoder_randomaccess_scalable.cfg
===================================================================
--- /tags/SHM-9.0/cfg/encoder_randomaccess_scalable.cfg	(revision 1088)
+++ /tags/SHM-9.0/cfg/encoder_randomaccess_scalable.cfg	(revision 1088)
@@ -0,0 +1,126 @@
+#======== File I/O =====================
+BitstreamFile                 : str.bin
+#ReconFile                     : rec.yuv
+
+#======== Profile ================
+NumProfileTierLevel           : 3
+Profile0                      : main                # Profile for BL (NOTE01: this profile applies to whole layers but only BL is outputted)
+                                                    #                (NOTE02: this profile has no effect when NonHEVCBase is set to 1)
+Profile1                      : main                # Profile for BL (NOTE01: this profile applies to HEVC BL only)
+                                                    #                (NOTE02: When NonHEVCBase is set to 1, this profile & associated level should be updated appropriately)
+Profile2                      : scalable-main       # Scalable profile
+
+#======== Unit definition ================
+MaxCUWidth                    : 64          # Maximum coding unit width in pixel
+MaxCUHeight                   : 64          # Maximum coding unit height in pixel
+MaxPartitionDepth             : 4           # Maximum coding unit depth
+QuadtreeTULog2MaxSize         : 5           # Log2 of maximum transform size for
+                                            # quadtree-based TU coding (2...6)
+QuadtreeTULog2MinSize         : 2           # Log2 of minimum transform size for
+                                            # quadtree-based TU coding (2...6)
+QuadtreeTUMaxDepthInter       : 3
+QuadtreeTUMaxDepthIntra       : 3
+
+#======== Coding Structure =============
+#IntraPeriod                   : 32          # Period of I-Frame ( -1 = only first)
+DecodingRefreshType           : 1           # Random Accesss 0:none, 1:CRA, 2:IDR, 3:Recovery Point SEI
+GOPSize                       : 8           # GOP Size (number of B slice = GOPSize-1)
+#        Type POC QPoffset QPfactor tcOffsetDiv2 betaOffsetDiv2 temporal_id #ref_pics_active #ref_pics reference pictures     predict deltaRPS #ref_idcs reference idcs 
+Frame1:  B    8   1        0.442    0            0              0           4                4         -8 -10 -12 -16         0
+Frame2:  B    4   2        0.3536   0            0              0           2                3         -4 -6  4               1       4        5         1 1 0 0 1
+Frame3:  B    2   3        0.3536   0            0              0           2                4         -2 -4  2 6             1       2        4         1 1 1 1  
+Frame4:  B    1   4        0.68     0            0              1           2                4         -1  1  3 7             1       1        5         1 0 1 1 1 
+Frame5:  B    3   4        0.68     0            0              1           2                4         -1 -3  1 5             1      -2        5         1 1 1 1 0
+Frame6:  B    6   3        0.3536   0            0              0           2                4         -2 -4 -6 2             1      -3        5         1 1 1 1 0
+Frame7:  B    5   4        0.68     0            0              1           2                4         -1 -5  1 3             1       1        5         1 0 1 1 1  
+Frame8:  B    7   4        0.68     0            0              1           2                4         -1 -3 -7 1             1      -2        5         1 1 1 1 0
+
+#=========== Motion Search =============
+FastSearch                    : 1           # 0:Full search  1:TZ search
+SearchRange                   : 64          # (0: Search range is a Full frame)
+BipredSearchRange             : 4           # Search range for bi-prediction refinement
+HadamardME                    : 1           # Use of hadamard measure for fractional ME
+FEN                           : 1           # Fast encoder decision
+FDM                           : 1           # Fast Decision for Merge RD cost
+
+#======== Quantization =============
+#QP                            : 32          # Quantization parameter(0-51)
+MaxDeltaQP                    : 0           # CU-based multi-QP optimization
+MaxCuDQPDepth                 : 0           # Max depth of a minimum CuDQP for sub-LCU-level delta QP
+DeltaQpRD                     : 0           # Slice-based multi-QP optimization
+RDOQ                          : 1           # RDOQ
+RDOQTS                        : 1           # RDOQ for transform skip
+
+#=========== Deblock Filter ============
+DeblockingFilterControlPresent: 0           # Dbl control params present (0=not present, 1=present)
+LoopFilterOffsetInPPS         : 0           # Dbl params: 0=varying params in SliceHeader, param = base_param + GOP_offset_param; 1=constant params in PPS, param = base_param)
+LoopFilterDisable             : 0           # Disable deblocking filter (0=Filter, 1=No Filter)
+LoopFilterBetaOffset_div2     : 0           # base_param: -6 ~ 6
+LoopFilterTcOffset_div2       : 0           # base_param: -6 ~ 6
+DeblockingFilterMetric        : 0           # blockiness metric (automatically configures deblocking parameters in bitstream)
+
+#=========== Misc. ============
+#InternalBitDepth             : 8           # codec operating bit-depth
+
+#=========== Coding Tools =================
+SAO                           : 1           # Sample adaptive offset  (0: OFF, 1: ON)
+AMP                           : 1           # Asymmetric motion partitions (0: OFF, 1: ON)
+TransformSkip                 : 1           # Transform skipping (0: OFF, 1: ON)
+TransformSkipFast             : 1           # Fast Transform skipping (0: OFF, 1: ON)
+SAOLcuBoundary                : 0           # SAOLcuBoundary using non-deblocked pixels (0: OFF, 1: ON)
+
+#============ Slices ================
+SliceMode                : 0                # 0: Disable all slice options.
+                                            # 1: Enforce maximum number of LCU in an slice,
+                                            # 2: Enforce maximum number of bytes in an 'slice'
+                                            # 3: Enforce maximum number of tiles in a slice
+SliceArgument            : 1500             # Argument for 'SliceMode'.
+                                            # If SliceMode==1 it represents max. SliceGranularity-sized blocks per slice.
+                                            # If SliceMode==2 it represents max. bytes per slice.
+                                            # If SliceMode==3 it represents max. tiles per slice.
+
+LFCrossSliceBoundaryFlag : 1                # In-loop filtering, including ALF and DB, is across or not across slice boundary.
+                                            # 0:not across, 1: across
+
+#============ PCM ================
+PCMEnabledFlag                      : 0                # 0: No PCM mode
+PCMLog2MaxSize                      : 5                # Log2 of maximum PCM block size.
+PCMLog2MinSize                      : 3                # Log2 of minimum PCM block size.
+PCMInputBitDepthFlag                : 1                # 0: PCM bit-depth is internal bit-depth. 1: PCM bit-depth is input bit-depth.
+PCMFilterDisableFlag                : 0                # 0: Enable loop filtering on I_PCM samples. 1: Disable loop filtering on I_PCM samples.
+
+#============ Tiles ================
+TileUniformSpacing                  : 0                # 0: the column boundaries are indicated by TileColumnWidth array, the row boundaries are indicated by TileRowHeight array
+                                                       # 1: the column and row boundaries are distributed uniformly
+NumTileColumnsMinus1                : 0                # Number of tile columns in a picture minus 1
+TileColumnWidthArray                : 2 3              # Array containing tile column width values in units of CTU (from left to right in picture)   
+NumTileRowsMinus1                   : 0                # Number of tile rows in a picture minus 1
+TileRowHeightArray                  : 2                # Array containing tile row height values in units of CTU (from top to bottom in picture)
+
+LFCrossTileBoundaryFlag             : 1                # In-loop filtering is across or not across tile boundary.
+                                                       # 0:not across, 1: across 
+
+#============ WaveFront ================
+#WaveFrontSynchro                    : 0                # 0:  No WaveFront synchronisation (WaveFrontSubstreams must be 1 in this case).
+                                                       # >0: WaveFront synchronises with the LCU above and to the right by this many LCUs.
+
+#=========== Quantization Matrix =================
+ScalingList                   : 0                      # ScalingList 0 : off, 1 : default, 2 : file read
+ScalingListFile               : scaling_list.txt       # Scaling List file name. If file is not exist, use Default Matrix.
+
+#============ Lossless ================
+TransquantBypassEnableFlag : 0                         # Value of PPS flag.
+CUTransquantBypassFlagForce: 0                         # Force transquant bypass mode, when transquant_bypass_enable_flag is enabled
+
+#============ Rate Control ======================
+#RateControl                         : 0                # Rate control: enable rate control
+#TargetBitrate                       : 1000000          # Rate control: target bitrate, in bps
+#KeepHierarchicalBit                 : 2                # Rate control: 0: equal bit allocation; 1: fixed ratio bit allocation; 2: adaptive ratio bit allocation
+#LCULevelRateControl                 : 1                # Rate control: 1: LCU level RC; 0: picture level RC
+#RCLCUSeparateModel                  : 1                # Rate control: use LCU level separate R-lambda model
+#InitialQP                           : 0                # Rate control: initial QP
+#RCForceIntraQP                      : 0                # Rate control: force intra QP to be equal to initial QP
+
+### DO NOT ADD ANYTHING BELOW THIS LINE ###
+### DO NOT DELETE THE EMPTY LINE BELOW ###
+
Index: /tags/SHM-9.0/cfg/encoder_randomaccess_scalable10.cfg
===================================================================
--- /tags/SHM-9.0/cfg/encoder_randomaccess_scalable10.cfg	(revision 1088)
+++ /tags/SHM-9.0/cfg/encoder_randomaccess_scalable10.cfg	(revision 1088)
@@ -0,0 +1,126 @@
+#======== File I/O =====================
+BitstreamFile                 : str.bin
+#ReconFile                     : rec.yuv
+
+#======== Profile ================
+NumProfileTierLevel           : 3
+Profile0                      : main10                # Profile for BL (NOTE01: this profile applies to whole layers but only BL is outputted)
+                                                      #                (NOTE02: this profile has no effect when NonHEVCBase is set to 1)
+Profile1                      : main10                # Profile for BL (NOTE01: this profile applies to HEVC BL only)
+                                                      #                (NOTE02: When NonHEVCBase is set to 1, this profile & associated level should be updated appropriately)
+Profile2                      : scalable-main10       # Scalable profile
+
+#======== Unit definition ================
+MaxCUWidth                    : 64          # Maximum coding unit width in pixel
+MaxCUHeight                   : 64          # Maximum coding unit height in pixel
+MaxPartitionDepth             : 4           # Maximum coding unit depth
+QuadtreeTULog2MaxSize         : 5           # Log2 of maximum transform size for
+                                            # quadtree-based TU coding (2...6)
+QuadtreeTULog2MinSize         : 2           # Log2 of minimum transform size for
+                                            # quadtree-based TU coding (2...6)
+QuadtreeTUMaxDepthInter       : 3
+QuadtreeTUMaxDepthIntra       : 3
+
+#======== Coding Structure =============
+#IntraPeriod                   : 32          # Period of I-Frame ( -1 = only first)
+DecodingRefreshType           : 1           # Random Accesss 0:none, 1:CRA, 2:IDR, 3:Recovery Point SEI
+GOPSize                       : 8           # GOP Size (number of B slice = GOPSize-1)
+#        Type POC QPoffset QPfactor tcOffsetDiv2 betaOffsetDiv2 temporal_id #ref_pics_active #ref_pics reference pictures     predict deltaRPS #ref_idcs reference idcs 
+Frame1:  B    8   1        0.442    0            0              0           4                4         -8 -10 -12 -16         0
+Frame2:  B    4   2        0.3536   0            0              0           2                3         -4 -6  4               1       4        5         1 1 0 0 1
+Frame3:  B    2   3        0.3536   0            0              0           2                4         -2 -4  2 6             1       2        4         1 1 1 1  
+Frame4:  B    1   4        0.68     0            0              1           2                4         -1  1  3 7             1       1        5         1 0 1 1 1 
+Frame5:  B    3   4        0.68     0            0              1           2                4         -1 -3  1 5             1      -2        5         1 1 1 1 0
+Frame6:  B    6   3        0.3536   0            0              0           2                4         -2 -4 -6 2             1      -3        5         1 1 1 1 0
+Frame7:  B    5   4        0.68     0            0              1           2                4         -1 -5  1 3             1       1        5         1 0 1 1 1  
+Frame8:  B    7   4        0.68     0            0              1           2                4         -1 -3 -7 1             1      -2        5         1 1 1 1 0
+
+#=========== Motion Search =============
+FastSearch                    : 1           # 0:Full search  1:TZ search
+SearchRange                   : 64          # (0: Search range is a Full frame)
+BipredSearchRange             : 4           # Search range for bi-prediction refinement
+HadamardME                    : 1           # Use of hadamard measure for fractional ME
+FEN                           : 1           # Fast encoder decision
+FDM                           : 1           # Fast Decision for Merge RD cost
+
+#======== Quantization =============
+#QP                            : 32          # Quantization parameter(0-51)
+MaxDeltaQP                    : 0           # CU-based multi-QP optimization
+MaxCuDQPDepth                 : 0           # Max depth of a minimum CuDQP for sub-LCU-level delta QP
+DeltaQpRD                     : 0           # Slice-based multi-QP optimization
+RDOQ                          : 1           # RDOQ
+RDOQTS                        : 1           # RDOQ for transform skip
+
+#=========== Deblock Filter ============
+DeblockingFilterControlPresent: 0           # Dbl control params present (0=not present, 1=present)
+LoopFilterOffsetInPPS         : 0           # Dbl params: 0=varying params in SliceHeader, param = base_param + GOP_offset_param; 1=constant params in PPS, param = base_param)
+LoopFilterDisable             : 0           # Disable deblocking filter (0=Filter, 1=No Filter)
+LoopFilterBetaOffset_div2     : 0           # base_param: -6 ~ 6
+LoopFilterTcOffset_div2       : 0           # base_param: -6 ~ 6
+DeblockingFilterMetric        : 0           # blockiness metric (automatically configures deblocking parameters in bitstream)
+
+#=========== Misc. ============
+#InternalBitDepth             : 10           # codec operating bit-depth
+
+#=========== Coding Tools =================
+SAO                           : 1           # Sample adaptive offset  (0: OFF, 1: ON)
+AMP                           : 1           # Asymmetric motion partitions (0: OFF, 1: ON)
+TransformSkip                 : 1           # Transform skipping (0: OFF, 1: ON)
+TransformSkipFast             : 1           # Fast Transform skipping (0: OFF, 1: ON)
+SAOLcuBoundary                : 0           # SAOLcuBoundary using non-deblocked pixels (0: OFF, 1: ON)
+
+#============ Slices ================
+SliceMode                : 0                # 0: Disable all slice options.
+                                            # 1: Enforce maximum number of LCU in an slice,
+                                            # 2: Enforce maximum number of bytes in an 'slice'
+                                            # 3: Enforce maximum number of tiles in a slice
+SliceArgument            : 1500             # Argument for 'SliceMode'.
+                                            # If SliceMode==1 it represents max. SliceGranularity-sized blocks per slice.
+                                            # If SliceMode==2 it represents max. bytes per slice.
+                                            # If SliceMode==3 it represents max. tiles per slice.
+
+LFCrossSliceBoundaryFlag : 1                # In-loop filtering, including ALF and DB, is across or not across slice boundary.
+                                            # 0:not across, 1: across
+
+#============ PCM ================
+PCMEnabledFlag                      : 0                # 0: No PCM mode
+PCMLog2MaxSize                      : 5                # Log2 of maximum PCM block size.
+PCMLog2MinSize                      : 3                # Log2 of minimum PCM block size.
+PCMInputBitDepthFlag                : 1                # 0: PCM bit-depth is internal bit-depth. 1: PCM bit-depth is input bit-depth.
+PCMFilterDisableFlag                : 0                # 0: Enable loop filtering on I_PCM samples. 1: Disable loop filtering on I_PCM samples.
+
+#============ Tiles ================
+TileUniformSpacing                  : 0                # 0: the column boundaries are indicated by TileColumnWidth array, the row boundaries are indicated by TileRowHeight array
+                                                       # 1: the column and row boundaries are distributed uniformly
+NumTileColumnsMinus1                : 0                # Number of tile columns in a picture minus 1
+TileColumnWidthArray                : 2 3              # Array containing tile column width values in units of CTU (from left to right in picture)   
+NumTileRowsMinus1                   : 0                # Number of tile rows in a picture minus 1
+TileRowHeightArray                  : 2                # Array containing tile row height values in units of CTU (from top to bottom in picture)
+
+LFCrossTileBoundaryFlag             : 1                # In-loop filtering is across or not across tile boundary.
+                                                       # 0:not across, 1: across 
+
+#============ WaveFront ================
+#WaveFrontSynchro                    : 0                # 0:  No WaveFront synchronisation (WaveFrontSubstreams must be 1 in this case).
+                                                       # >0: WaveFront synchronises with the LCU above and to the right by this many LCUs.
+
+#=========== Quantization Matrix =================
+ScalingList                   : 0                      # ScalingList 0 : off, 1 : default, 2 : file read
+ScalingListFile               : scaling_list.txt       # Scaling List file name. If file is not exist, use Default Matrix.
+
+#============ Lossless ================
+TransquantBypassEnableFlag : 0                         # Value of PPS flag.
+CUTransquantBypassFlagForce: 0                         # Force transquant bypass mode, when transquant_bypass_enable_flag is enabled
+
+#============ Rate Control ======================
+#RateControl                         : 0                # Rate control: enable rate control
+#TargetBitrate                       : 1000000          # Rate control: target bitrate, in bps
+#KeepHierarchicalBit                 : 2                # Rate control: 0: equal bit allocation; 1: fixed ratio bit allocation; 2: adaptive ratio bit allocation
+#LCULevelRateControl                 : 1                # Rate control: 1: LCU level RC; 0: picture level RC
+#RCLCUSeparateModel                  : 1                # Rate control: use LCU level separate R-lambda model
+#InitialQP                           : 0                # Rate control: initial QP
+#RCForceIntraQP                      : 0                # Rate control: force intra QP to be equal to initial QP
+
+### DO NOT ADD ANYTHING BELOW THIS LINE ###
+### DO NOT DELETE THE EMPTY LINE BELOW ###
+
Index: /tags/SHM-9.0/cfg/encoder_randomaccess_scalable_8_10.cfg
===================================================================
--- /tags/SHM-9.0/cfg/encoder_randomaccess_scalable_8_10.cfg	(revision 1088)
+++ /tags/SHM-9.0/cfg/encoder_randomaccess_scalable_8_10.cfg	(revision 1088)
@@ -0,0 +1,126 @@
+#======== File I/O =====================
+BitstreamFile                 : str.bin
+#ReconFile                     : rec.yuv
+
+#======== Profile ================
+NumProfileTierLevel           : 3
+Profile0                      : main                  # Profile for BL (NOTE01: this profile applies to whole layers but only BL is outputted)
+                                                      #                (NOTE02: this profile has no effect when NonHEVCBase is set to 1)
+Profile1                      : main                  # Profile for BL (NOTE01: this profile applies to HEVC BL only)
+                                                      #                (NOTE02: When NonHEVCBase is set to 1, this profile & associated level should be updated appropriately)
+Profile2                      : scalable-main10       # Scalable profile
+
+#======== Unit definition ================
+MaxCUWidth                    : 64          # Maximum coding unit width in pixel
+MaxCUHeight                   : 64          # Maximum coding unit height in pixel
+MaxPartitionDepth             : 4           # Maximum coding unit depth
+QuadtreeTULog2MaxSize         : 5           # Log2 of maximum transform size for
+                                            # quadtree-based TU coding (2...6)
+QuadtreeTULog2MinSize         : 2           # Log2 of minimum transform size for
+                                            # quadtree-based TU coding (2...6)
+QuadtreeTUMaxDepthInter       : 3
+QuadtreeTUMaxDepthIntra       : 3
+
+#======== Coding Structure =============
+#IntraPeriod                   : 32          # Period of I-Frame ( -1 = only first)
+DecodingRefreshType           : 1           # Random Accesss 0:none, 1:CRA, 2:IDR, 3:Recovery Point SEI
+GOPSize                       : 8           # GOP Size (number of B slice = GOPSize-1)
+#        Type POC QPoffset QPfactor tcOffsetDiv2 betaOffsetDiv2 temporal_id #ref_pics_active #ref_pics reference pictures     predict deltaRPS #ref_idcs reference idcs 
+Frame1:  B    8   1        0.442    0            0              0           4                4         -8 -10 -12 -16         0
+Frame2:  B    4   2        0.3536   0            0              0           2                3         -4 -6  4               1       4        5         1 1 0 0 1
+Frame3:  B    2   3        0.3536   0            0              0           2                4         -2 -4  2 6             1       2        4         1 1 1 1  
+Frame4:  B    1   4        0.68     0            0              1           2                4         -1  1  3 7             1       1        5         1 0 1 1 1 
+Frame5:  B    3   4        0.68     0            0              1           2                4         -1 -3  1 5             1      -2        5         1 1 1 1 0
+Frame6:  B    6   3        0.3536   0            0              0           2                4         -2 -4 -6 2             1      -3        5         1 1 1 1 0
+Frame7:  B    5   4        0.68     0            0              1           2                4         -1 -5  1 3             1       1        5         1 0 1 1 1  
+Frame8:  B    7   4        0.68     0            0              1           2                4         -1 -3 -7 1             1      -2        5         1 1 1 1 0
+
+#=========== Motion Search =============
+FastSearch                    : 1           # 0:Full search  1:TZ search
+SearchRange                   : 64          # (0: Search range is a Full frame)
+BipredSearchRange             : 4           # Search range for bi-prediction refinement
+HadamardME                    : 1           # Use of hadamard measure for fractional ME
+FEN                           : 1           # Fast encoder decision
+FDM                           : 1           # Fast Decision for Merge RD cost
+
+#======== Quantization =============
+#QP                            : 32          # Quantization parameter(0-51)
+MaxDeltaQP                    : 0           # CU-based multi-QP optimization
+MaxCuDQPDepth                 : 0           # Max depth of a minimum CuDQP for sub-LCU-level delta QP
+DeltaQpRD                     : 0           # Slice-based multi-QP optimization
+RDOQ                          : 1           # RDOQ
+RDOQTS                        : 1           # RDOQ for transform skip
+
+#=========== Deblock Filter ============
+DeblockingFilterControlPresent: 0           # Dbl control params present (0=not present, 1=present)
+LoopFilterOffsetInPPS         : 0           # Dbl params: 0=varying params in SliceHeader, param = base_param + GOP_offset_param; 1=constant params in PPS, param = base_param)
+LoopFilterDisable             : 0           # Disable deblocking filter (0=Filter, 1=No Filter)
+LoopFilterBetaOffset_div2     : 0           # base_param: -6 ~ 6
+LoopFilterTcOffset_div2       : 0           # base_param: -6 ~ 6
+DeblockingFilterMetric        : 0           # blockiness metric (automatically configures deblocking parameters in bitstream)
+
+#=========== Misc. ============
+#InternalBitDepth             : 10           # codec operating bit-depth
+
+#=========== Coding Tools =================
+SAO                           : 1           # Sample adaptive offset  (0: OFF, 1: ON)
+AMP                           : 1           # Asymmetric motion partitions (0: OFF, 1: ON)
+TransformSkip                 : 1           # Transform skipping (0: OFF, 1: ON)
+TransformSkipFast             : 1           # Fast Transform skipping (0: OFF, 1: ON)
+SAOLcuBoundary                : 0           # SAOLcuBoundary using non-deblocked pixels (0: OFF, 1: ON)
+
+#============ Slices ================
+SliceMode                : 0                # 0: Disable all slice options.
+                                            # 1: Enforce maximum number of LCU in an slice,
+                                            # 2: Enforce maximum number of bytes in an 'slice'
+                                            # 3: Enforce maximum number of tiles in a slice
+SliceArgument            : 1500             # Argument for 'SliceMode'.
+                                            # If SliceMode==1 it represents max. SliceGranularity-sized blocks per slice.
+                                            # If SliceMode==2 it represents max. bytes per slice.
+                                            # If SliceMode==3 it represents max. tiles per slice.
+
+LFCrossSliceBoundaryFlag : 1                # In-loop filtering, including ALF and DB, is across or not across slice boundary.
+                                            # 0:not across, 1: across
+
+#============ PCM ================
+PCMEnabledFlag                      : 0                # 0: No PCM mode
+PCMLog2MaxSize                      : 5                # Log2 of maximum PCM block size.
+PCMLog2MinSize                      : 3                # Log2 of minimum PCM block size.
+PCMInputBitDepthFlag                : 1                # 0: PCM bit-depth is internal bit-depth. 1: PCM bit-depth is input bit-depth.
+PCMFilterDisableFlag                : 0                # 0: Enable loop filtering on I_PCM samples. 1: Disable loop filtering on I_PCM samples.
+
+#============ Tiles ================
+TileUniformSpacing                  : 0                # 0: the column boundaries are indicated by TileColumnWidth array, the row boundaries are indicated by TileRowHeight array
+                                                       # 1: the column and row boundaries are distributed uniformly
+NumTileColumnsMinus1                : 0                # Number of tile columns in a picture minus 1
+TileColumnWidthArray                : 2 3              # Array containing tile column width values in units of CTU (from left to right in picture)   
+NumTileRowsMinus1                   : 0                # Number of tile rows in a picture minus 1
+TileRowHeightArray                  : 2                # Array containing tile row height values in units of CTU (from top to bottom in picture)
+
+LFCrossTileBoundaryFlag             : 1                # In-loop filtering is across or not across tile boundary.
+                                                       # 0:not across, 1: across 
+
+#============ WaveFront ================
+#WaveFrontSynchro                    : 0                # 0:  No WaveFront synchronisation (WaveFrontSubstreams must be 1 in this case).
+                                                       # >0: WaveFront synchronises with the LCU above and to the right by this many LCUs.
+
+#=========== Quantization Matrix =================
+ScalingList                   : 0                      # ScalingList 0 : off, 1 : default, 2 : file read
+ScalingListFile               : scaling_list.txt       # Scaling List file name. If file is not exist, use Default Matrix.
+
+#============ Lossless ================
+TransquantBypassEnableFlag : 0                         # Value of PPS flag.
+CUTransquantBypassFlagForce: 0                         # Force transquant bypass mode, when transquant_bypass_enable_flag is enabled
+
+#============ Rate Control ======================
+#RateControl                         : 0                # Rate control: enable rate control
+#TargetBitrate                       : 1000000          # Rate control: target bitrate, in bps
+#KeepHierarchicalBit                 : 2                # Rate control: 0: equal bit allocation; 1: fixed ratio bit allocation; 2: adaptive ratio bit allocation
+#LCULevelRateControl                 : 1                # Rate control: 1: LCU level RC; 0: picture level RC
+#RCLCUSeparateModel                  : 1                # Rate control: use LCU level separate R-lambda model
+#InitialQP                           : 0                # Rate control: initial QP
+#RCForceIntraQP                      : 0                # Rate control: force intra QP to be equal to initial QP
+
+### DO NOT ADD ANYTHING BELOW THIS LINE ###
+### DO NOT DELETE THE EMPTY LINE BELOW ###
+
Index: /tags/SHM-9.0/cfg/layers.cfg
===================================================================
--- /tags/SHM-9.0/cfg/layers.cfg	(revision 1088)
+++ /tags/SHM-9.0/cfg/layers.cfg	(revision 1088)
@@ -0,0 +1,61 @@
+NumLayers                     : 2
+NonHEVCBase                   : 0
+ScalabilityMask1              : 0           # Multiview
+ScalabilityMask2              : 1           # Scalable
+ScalabilityMask3              : 0           # Auxiliary pictures
+AdaptiveResolutionChange      : 0           # Resolution change frame (0: disable)
+SkipPictureAtArcSwitch        : 0           # Code higher layer picture as skip at ARC switching (0: disable (default), 1: enable)
+MaxTidRefPresentFlag          : 1           # max_tid_ref_present_flag (0=not present, 1=present(default))
+CrossLayerPictureTypeAlignFlag: 1           # Picture type alignment across layers
+CrossLayerIrapAlignFlag       : 1           # Align IRAP across layers
+SEIpictureDigest              : 1
+
+#============= LAYER 0 ==================
+QP0                           : 22
+MaxTidIlRefPicsPlus10         : 2           # max_tid_il_ref_pics_plus1 for layer0
+#============ Rate Control ==============
+RateControl0                  : 0           # Rate control: enable rate control for layer 0
+TargetBitrate0                : 1000000     # Rate control: target bitrate for layer 0, in bps
+KeepHierarchicalBit0          : 1           # Rate control: keep hierarchical bit allocation for layer 0 in rate control algorithm
+LCULevelRateControl0          : 1           # Rate control: 1: LCU level RC for layer 0; 0: picture level RC for layer 0
+RCLCUSeparateModel0           : 1           # Rate control: use LCU level separate R-lambda model for layer 0
+InitialQP0                    : 0           # Rate control: initial QP for layer 0
+RCForceIntraQP0               : 0           # Rate control: force intra QP to be equal to initial QP for layer 0
+
+#============ WaveFront ================
+WaveFrontSynchro0             : 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.
+
+#============= LAYER 1 ==================
+QP1                           : 20
+NumSamplePredRefLayers1       : 1           # number of sample pred reference layers
+SamplePredRefLayerIds1        : 0           # reference layer id
+NumMotionPredRefLayers1       : 1           # number of motion pred reference layers
+MotionPredRefLayerIds1        : 0           # reference layer id
+NumActiveRefLayers1           : 1           # number of active reference layers
+PredLayerIds1                 : 0           # inter-layer prediction layer index within available reference layers
+
+#============ Rate Control ==============
+RateControl1                  : 0           # Rate control: enable rate control for layer 1
+TargetBitrate1                : 1000000     # Rate control: target bitrate for layer 1, in bps
+KeepHierarchicalBit1          : 1           # Rate control: keep hierarchical bit allocation for layer 1 in rate control algorithm
+LCULevelRateControl1          : 1           # Rate control: 1: LCU level RC for layer 1; 0: picture level RC for layer 1
+RCLCUSeparateModel1           : 1           # Rate control: use LCU level separate R-lambda model for layer 1
+InitialQP1                    : 0           # Rate control: initial QP for layer 1
+RCForceIntraQP1               : 0           # Rate control: force intra QP to be equal to initial QP for layer 1
+
+#============ WaveFront ================
+WaveFrontSynchro1             : 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.
+
+NumLayerSets                  : 2           # Include default layer set, value of 0 not allowed
+NumLayerInIdList1             : 2           # 0-th layer set is default, need not specify LayerSetLayerIdList0 or NumLayerInIdList0
+LayerSetLayerIdList1          : 0 1
+
+NumAddLayerSets                      : 0
+NumOutputLayerSets                   : 2           # Include defualt OLS, value of 0 not allowed
+DefaultTargetOutputLayerIdc          : 1
+NumOutputLayersInOutputLayerSet      : 1           # The number of layers in the 0-th OLS should not be specified, 
+# ListOfOutputLayers0 need not be specified
+ListOfOutputLayers1	                 : 1
+ListOfProfileTierLevelOls1           : 1 2
Index: /tags/SHM-9.0/cfg/layers_avcbase.cfg
===================================================================
--- /tags/SHM-9.0/cfg/layers_avcbase.cfg	(revision 1088)
+++ /tags/SHM-9.0/cfg/layers_avcbase.cfg	(revision 1088)
@@ -0,0 +1,58 @@
+NumLayers                     : 2
+NonHEVCBase                   : 1
+ScalabilityMask1              : 0           # Multiview
+ScalabilityMask2              : 1           # Scalable
+AdaptiveResolutionChange      : 0           # Resolution change frame (0: disable)
+CrossLayerPictureTypeAlignFlag: 0           # Picture type alignment across layers
+CrossLayerIrapAlignFlag       : 0           # Align IRAP across layers
+MaxTidRefPresentFlag          : 1           # max_tid_ref_present_flag (0=not present, 1=present(default))
+SEIpictureDigest              : 1
+
+#============= LAYER 0 ==================
+QP0                           : 22
+MaxTidIlRefPicsPlus10         : 2           # max_tid_il_ref_pics_plus1 for layer0
+#============ Rate Control ==============
+RateControl0                  : 0           # Rate control: enable rate control for layer 0
+TargetBitrate0                : 1000000     # Rate control: target bitrate for layer 0, in bps
+KeepHierarchicalBit0          : 1           # Rate control: keep hierarchical bit allocation for layer 0 in rate control algorithm
+LCULevelRateControl0          : 1           # Rate control: 1: LCU level RC for layer 0; 0: picture level RC for layer 0
+RCLCUSeparateModel0           : 1           # Rate control: use LCU level separate R-lambda model for layer 0
+InitialQP0                    : 0           # Rate control: initial QP for layer 0
+RCForceIntraQP0               : 0           # Rate control: force intra QP to be equal to initial QP for layer 0
+
+#============ WaveFront ================
+WaveFrontSynchro0             : 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.
+
+#============= LAYER 1 ==================
+QP1                           : 20
+NumSamplePredRefLayers1       : 1           # number of sample pred reference layers
+SamplePredRefLayerIds1        : 0           # reference layer id
+NumMotionPredRefLayers1       : 0           # number of motion pred reference layers
+MotionPredRefLayerIds1        : 0           # reference layer id
+NumActiveRefLayers1           : 1           # number of active reference layers
+PredLayerIds1                 : 0           # inter-layer prediction layer index within available reference layers
+
+#============ Rate Control ==============
+RateControl1                  : 0           # Rate control: enable rate control for layer 1
+TargetBitrate1                : 1000000     # Rate control: target bitrate for layer 1, in bps
+KeepHierarchicalBit1          : 1           # Rate control: keep hierarchical bit allocation for layer 1 in rate control algorithm
+LCULevelRateControl1          : 1           # Rate control: 1: LCU level RC for layer 1; 0: picture level RC for layer 1
+RCLCUSeparateModel1           : 1           # Rate control: use LCU level separate R-lambda model for layer 1
+InitialQP1                    : 0           # Rate control: initial QP for layer 1
+RCForceIntraQP1               : 0           # Rate control: force intra QP to be equal to initial QP for layer 1
+
+WaveFrontSynchro1             : 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.
+
+NumLayerSets                  : 2           # Include default layer set, value of 0 not allowed
+NumLayerInIdList1             : 2           # 0-th layer set is default, need not specify LayerSetLayerIdList0 or NumLayerInIdList0
+LayerSetLayerIdList1          : 0 1
+
+NumAddLayerSets                      : 0
+NumOutputLayerSets                   : 2           # Include defualt OLS, value of 0 not allowed
+DefaultTargetOutputLayerIdc          : 1
+NumOutputLayersInOutputLayerSet      : 1           # The number of layers in the 0-th OLS should not be specified,  
+# ListOfOutputLayers0 need not be specified
+ListOfOutputLayers1	                 : 1
+ListOfProfileTierLevelOls1           : 1 2
Index: /tags/SHM-9.0/cfg/per-sequence-svc-avcbase/BQTerrace-1.5x.cfg
===================================================================
--- /tags/SHM-9.0/cfg/per-sequence-svc-avcbase/BQTerrace-1.5x.cfg	(revision 1088)
+++ /tags/SHM-9.0/cfg/per-sequence-svc-avcbase/BQTerrace-1.5x.cfg	(revision 1088)
@@ -0,0 +1,29 @@
+FrameSkip                     : 0           # Number of frames to be skipped in input
+FramesToBeEncoded             : 600         # Number of frames to be coded
+
+Level0                        : 4.1         # Level of the whole bitstream
+Level1                        : 3.1         # Level of the base layer
+Level2                        : 4.1         # Level of the enhancement layer
+
+#======== File I/O ===============
+InputFile0                    : BQTerrace_1280x720_60_zerophase_0.9pi.yuv
+FrameRate0                    : 60          # Frame Rate per second
+InputBitDepth0                : 8           # Input bitdepth for layer 0
+SourceWidth0                  : 1280        # Input  frame width
+SourceHeight0                 : 720         # Input  frame height
+RepFormatIdx0                 : 0           # Index of corresponding rep_format() in the VPS
+IntraPeriod0                  : 64          # Period of I-Frame ( -1 = only first)
+ConformanceMode0              : 1           # conformance mode
+QP0                           : 22
+LayerPTLIndex0                : 1
+
+InputFile1                    : BQTerrace_1920x1080_60.yuv
+FrameRate1                    : 60          # Frame Rate per second
+InputBitDepth1                : 8           # Input bitdepth for layer 1
+SourceWidth1                  : 1920        # Input  frame width
+SourceHeight1                 : 1080        # Input  frame height
+RepFormatIdx1                 : 1           # Index of corresponding rep_format() in the VPS
+IntraPeriod1                  : 64          # Period of I-Frame ( -1 = only first)
+ConformanceMode1              : 1           # conformance mode
+QP1                           : 20
+LayerPTLIndex1                : 2
Index: /tags/SHM-9.0/cfg/per-sequence-svc-avcbase/BQTerrace-2x.cfg
===================================================================
--- /tags/SHM-9.0/cfg/per-sequence-svc-avcbase/BQTerrace-2x.cfg	(revision 1088)
+++ /tags/SHM-9.0/cfg/per-sequence-svc-avcbase/BQTerrace-2x.cfg	(revision 1088)
@@ -0,0 +1,37 @@
+FrameSkip                     : 0           # Number of frames to be skipped in input
+FramesToBeEncoded             : 600         # Number of frames to be coded
+
+Level0                        : 4.1         # Level of the whole bitstream
+Level1                        : 3.1         # Level of the base layer
+Level2                        : 4.1         # Level of the enhancement layer
+
+#======== File I/O ===============
+InputFile0                    : BQTerrace_960x544_60_zerophase_0.9pi.yuv
+FrameRate0                    : 60          # Frame Rate per second
+InputBitDepth0                : 8           # Input bitdepth for layer 0
+SourceWidth0                  : 960         # Input  frame width
+SourceHeight0                 : 544         # Input  frame height
+RepFormatIdx0                 : 0           # Index of corresponding rep_format() in the VPS
+IntraPeriod0                  : 64          # Period of I-Frame ( -1 = only first)
+ConformanceMode0              : 1           # conformance mode
+QP0                           : 22
+LayerPTLIndex0                : 1
+
+InputFile1                    : BQTerrace_1920x1080_60.yuv
+FrameRate1                    : 60          # Frame Rate per second
+InputBitDepth1                : 8           # Input bitdepth for layer 1
+SourceWidth1                  : 1920        # Input  frame width
+SourceHeight1                 : 1080        # Input  frame height
+RepFormatIdx1                 : 1           # Index of corresponding rep_format() in the VPS
+IntraPeriod1                  : 64          # Period of I-Frame ( -1 = only first)
+ConformanceMode1              : 1           # conformance mode
+QP1                           : 20
+LayerPTLIndex1                : 2
+
+#============= Reference location offset parameters ==================
+NumRefLocationOffsets1         : 1        # Number of reference location offset parameters
+RefLocationOffsetLayerId1                : 0        # List of ref layer id (i-th entry for i-th ref loc offset parameters)
+ScaledRefLayerOffsetPresentFlag1 : 0        # List of scaled ref layer offset present flags
+RefRegionOffsetPresentFlag1      : 1        # List of ref region offset present flags
+RefRegionBottomOffset1           : 2        # List of ref region bottom offsets
+ResamplePhaseSetPresentFlag1     : 0        # List of resample phase set present flags
Index: /tags/SHM-9.0/cfg/per-sequence-svc-avcbase/BQTerrace-SNR.cfg
===================================================================
--- /tags/SHM-9.0/cfg/per-sequence-svc-avcbase/BQTerrace-SNR.cfg	(revision 1088)
+++ /tags/SHM-9.0/cfg/per-sequence-svc-avcbase/BQTerrace-SNR.cfg	(revision 1088)
@@ -0,0 +1,35 @@
+FrameSkip                     : 0           # Number of frames to be skipped in input
+FramesToBeEncoded             : 600         # Number of frames to be coded
+
+Level0                        : 4.1         # Level of the whole bitstream
+Level1                        : 4.1         # Level of the base layer
+Level2                        : 4.1         # Level of the enhancement layer
+
+#======== File I/O ===============
+InputFile0                    : BQTerrace_1920x1088_60.yuv
+FrameRate0                    : 60          # Frame Rate per second
+InputBitDepth0                : 8           # Input bitdepth for layer 0
+SourceWidth0                  : 1920        # Input  frame width
+SourceHeight0                 : 1088        # Input  frame height
+RepFormatIdx0                 : 0           # Index of corresponding rep_format() in the VPS
+IntraPeriod0                  : 64          # Period of I-Frame ( -1 = only first)
+ConformanceMode0              : 1           # conformance mode
+QP0                           : 22
+LayerPTLIndex0                : 1
+
+InputFile1                    : BQTerrace_1920x1080_60.yuv
+FrameRate1                    : 60          # Frame Rate per second
+InputBitDepth1                : 8           # Input bitdepth for layer 1
+SourceWidth1                  : 1920        # Input  frame width
+SourceHeight1                 : 1080        # Input  frame height
+RepFormatIdx1                 : 1           # Index of corresponding rep_format() in the VPS
+IntraPeriod1                  : 64          # Period of I-Frame ( -1 = only first)
+ConformanceMode1              : 1           # conformance mode
+NumRefLocationOffsets1         : 1        # Number of reference location offset parameters
+RefLocationOffsetLayerId1                : 0        # List of ref layer id (i-th entry for i-th ref loc offset parameters)
+ScaledRefLayerOffsetPresentFlag1 : 0        # List of scaled ref layer offset present flags
+RefRegionOffsetPresentFlag1      : 1        # List of ref region offset present flags
+RefRegionBottomOffset1           : 4        # List of ref region bottom offsets
+ResamplePhaseSetPresentFlag1     : 0        # List of resample phase set present flags
+QP1                           : 20
+LayerPTLIndex1                : 2
Index: /tags/SHM-9.0/cfg/per-sequence-svc-avcbase/BasketballDrive-1.5x.cfg
===================================================================
--- /tags/SHM-9.0/cfg/per-sequence-svc-avcbase/BasketballDrive-1.5x.cfg	(revision 1088)
+++ /tags/SHM-9.0/cfg/per-sequence-svc-avcbase/BasketballDrive-1.5x.cfg	(revision 1088)
@@ -0,0 +1,29 @@
+FrameSkip                     : 0           # Number of frames to be skipped in input
+FramesToBeEncoded             : 500         # Number of frames to be coded
+
+Level0                        : 4.1         # Level of the whole bitstream
+Level1                        : 3.1         # Level of the base layer
+Level2                        : 4.1         # Level of the enhancement layer
+
+#======== File I/O ===============
+InputFile0                    : BasketballDrive_1280x720_50_zerophase_0.9pi.yuv
+FrameRate0                    : 50          # Frame Rate per second
+InputBitDepth0                : 8           # Input bitdepth for layer 0
+SourceWidth0                  : 1280        # Input  frame width
+SourceHeight0                 : 720         # Input  frame height
+RepFormatIdx0                 : 0           # Index of corresponding rep_format() in the VPS
+IntraPeriod0                  : 48          # Period of I-Frame ( -1 = only first)
+ConformanceMode0              : 1           # conformance mode
+QP0                           : 22
+LayerPTLIndex0                : 1
+
+InputFile1                    : BasketballDrive_1920x1080_50.yuv
+FrameRate1                    : 50          # Frame Rate per second
+InputBitDepth1                : 8           # Input bitdepth for layer 1
+SourceWidth1                  : 1920        # Input  frame width
+SourceHeight1                 : 1080        # Input  frame height
+RepFormatIdx1                 : 1           # Index of corresponding rep_format() in the VPS
+IntraPeriod1                  : 48          # Period of I-Frame ( -1 = only first)
+ConformanceMode1              : 1           # conformance mode
+QP1                           : 20
+LayerPTLIndex1                : 2
Index: /tags/SHM-9.0/cfg/per-sequence-svc-avcbase/BasketballDrive-2x.cfg
===================================================================
--- /tags/SHM-9.0/cfg/per-sequence-svc-avcbase/BasketballDrive-2x.cfg	(revision 1088)
+++ /tags/SHM-9.0/cfg/per-sequence-svc-avcbase/BasketballDrive-2x.cfg	(revision 1088)
@@ -0,0 +1,37 @@
+FrameSkip                     : 0           # Number of frames to be skipped in input
+FramesToBeEncoded             : 500         # Number of frames to be coded
+
+Level0                        : 4.1         # Level of the whole bitstream
+Level1                        : 3.1         # Level of the base layer
+Level2                        : 4.1         # Level of the enhancement layer
+
+#======== File I/O ===============
+InputFile0                    : BasketballDrive_960x544_50_zerophase_0.9pi.yuv
+FrameRate0                    : 50          # Frame Rate per second
+InputBitDepth0                : 8           # Input bitdepth for layer 0
+SourceWidth0                  : 960         # Input  frame width
+SourceHeight0                 : 544         # Input  frame height
+RepFormatIdx0                 : 0           # Index of corresponding rep_format() in the VPS
+IntraPeriod0                  : 48          # Period of I-Frame ( -1 = only first)
+ConformanceMode0              : 1           # conformance mode
+QP0                           : 22
+LayerPTLIndex0                : 1
+
+InputFile1                    : BasketballDrive_1920x1080_50.yuv
+FrameRate1                    : 50          # Frame Rate per second
+InputBitDepth1                : 8           # Input bitdepth for layer 1
+SourceWidth1                  : 1920        # Input  frame width
+SourceHeight1                 : 1080        # Input  frame height
+RepFormatIdx1                 : 1           # Index of corresponding rep_format() in the VPS
+IntraPeriod1                  : 48          # Period of I-Frame ( -1 = only first)
+ConformanceMode1              : 1           # conformance mode
+QP1                           : 20
+LayerPTLIndex1                : 2
+
+#============= Reference location offset parameters ==================
+NumRefLocationOffsets1         : 1        # Number of reference location offset parameters
+RefLocationOffsetLayerId1                : 0        # List of ref layer id (i-th entry for i-th ref loc offset parameters)
+ScaledRefLayerOffsetPresentFlag1 : 0        # List of scaled ref layer offset present flags
+RefRegionOffsetPresentFlag1      : 1        # List of ref region offset present flags
+RefRegionBottomOffset1           : 2        # List of ref region bottom offsets
+ResamplePhaseSetPresentFlag1     : 0        # List of resample phase set present flags
Index: /tags/SHM-9.0/cfg/per-sequence-svc-avcbase/BasketballDrive-SNR.cfg
===================================================================
--- /tags/SHM-9.0/cfg/per-sequence-svc-avcbase/BasketballDrive-SNR.cfg	(revision 1088)
+++ /tags/SHM-9.0/cfg/per-sequence-svc-avcbase/BasketballDrive-SNR.cfg	(revision 1088)
@@ -0,0 +1,35 @@
+FrameSkip                     : 0           # Number of frames to be skipped in input
+FramesToBeEncoded             : 500         # Number of frames to be coded
+
+Level0                        : 4.1         # Level of the whole bitstream
+Level1                        : 4.1         # Level of the base layer
+Level2                        : 4.1         # Level of the enhancement layer
+
+#======== File I/O ===============
+InputFile0                    : BasketballDrive_1920x1088_50.yuv
+FrameRate0                    : 50          # Frame Rate per second
+InputBitDepth0                : 8           # Input bitdepth for layer 0
+SourceWidth0                  : 1920        # Input  frame width
+SourceHeight0                 : 1088        # Input  frame height
+RepFormatIdx0                 : 0           # Index of corresponding rep_format() in the VPS
+IntraPeriod0                  : 48          # Period of I-Frame ( -1 = only first)
+ConformanceMode0              : 1           # conformance mode
+QP0                           : 22
+LayerPTLIndex0                : 1
+
+InputFile1                    : BasketballDrive_1920x1080_50.yuv
+FrameRate1                    : 50          # Frame Rate per second
+InputBitDepth1                : 8           # Input bitdepth for layer 1
+SourceWidth1                  : 1920        # Input  frame width
+SourceHeight1                 : 1080        # Input  frame height
+RepFormatIdx1                 : 1           # Index of corresponding rep_format() in the VPS
+IntraPeriod1                  : 48          # Period of I-Frame ( -1 = only first)
+ConformanceMode1              : 1           # conformance mode
+NumRefLocationOffsets1         : 1        # Number of reference location offset parameters
+RefLocationOffsetLayerId1                : 0        # List of ref layer id (i-th entry for i-th ref loc offset parameters)
+ScaledRefLayerOffsetPresentFlag1 : 0        # List of scaled ref layer offset present flags
+RefRegionOffsetPresentFlag1      : 1        # List of ref region offset present flags
+RefRegionBottomOffset1           : 4        # List of ref region bottom offsets
+ResamplePhaseSetPresentFlag1     : 0        # List of resample phase set present flags
+QP1                           : 20
+LayerPTLIndex1                : 2
Index: /tags/SHM-9.0/cfg/per-sequence-svc-avcbase/Cactus-1.5x.cfg
===================================================================
--- /tags/SHM-9.0/cfg/per-sequence-svc-avcbase/Cactus-1.5x.cfg	(revision 1088)
+++ /tags/SHM-9.0/cfg/per-sequence-svc-avcbase/Cactus-1.5x.cfg	(revision 1088)
@@ -0,0 +1,29 @@
+FrameSkip                     : 0           # Number of frames to be skipped in input
+FramesToBeEncoded             : 500         # Number of frames to be coded
+
+Level0                        : 4.1         # Level of the whole bitstream
+Level1                        : 3.1         # Level of the base layer
+Level2                        : 4.1         # Level of the enhancement layer
+
+#======== File I/O ===============
+InputFile0                    : Cactus_1280x720_50_zerophase_0.9pi.yuv
+FrameRate0                    : 50          # Frame Rate per second
+InputBitDepth0                : 8           # Input bitdepth for layer 0
+SourceWidth0                  : 1280        # Input  frame width
+SourceHeight0                 : 720         # Input  frame height
+RepFormatIdx0                 : 0           # Index of corresponding rep_format() in the VPS
+IntraPeriod0                  : 48          # Period of I-Frame ( -1 = only first)
+ConformanceMode0              : 1           # conformance mode
+QP0                           : 22
+LayerPTLIndex0                : 1
+
+InputFile1                    : Cactus_1920x1080_50.yuv
+FrameRate1                    : 50          # Frame Rate per second
+InputBitDepth1                : 8           # Input bitdepth for layer 1
+SourceWidth1                  : 1920        # Input  frame width
+SourceHeight1                 : 1080        # Input  frame height
+RepFormatIdx1                 : 1           # Index of corresponding rep_format() in the VPS
+IntraPeriod1                  : 48          # Period of I-Frame ( -1 = only first)
+ConformanceMode1              : 1           # conformance mode
+QP1                           : 20
+LayerPTLIndex1                : 2
Index: /tags/SHM-9.0/cfg/per-sequence-svc-avcbase/Cactus-2x.cfg
===================================================================
--- /tags/SHM-9.0/cfg/per-sequence-svc-avcbase/Cactus-2x.cfg	(revision 1088)
+++ /tags/SHM-9.0/cfg/per-sequence-svc-avcbase/Cactus-2x.cfg	(revision 1088)
@@ -0,0 +1,37 @@
+FrameSkip                     : 0           # Number of frames to be skipped in input
+FramesToBeEncoded             : 500         # Number of frames to be coded
+
+Level0                        : 4.1         # Level of the whole bitstream
+Level1                        : 3.1         # Level of the base layer
+Level2                        : 4.1         # Level of the enhancement layer
+
+#======== File I/O ===============
+InputFile0                    : Cactus_960x544_50_zerophase_0.9pi.yuv
+FrameRate0                    : 50          # Frame Rate per second
+InputBitDepth0                : 8           # Input bitdepth for layer 0
+SourceWidth0                  : 960         # Input  frame width
+SourceHeight0                 : 544         # Input  frame height
+RepFormatIdx0                 : 0           # Index of corresponding rep_format() in the VPS
+IntraPeriod0                  : 48          # Period of I-Frame ( -1 = only first)
+ConformanceMode0              : 1           # conformance mode
+QP0                           : 22
+LayerPTLIndex0                : 1
+
+InputFile1                    : Cactus_1920x1080_50.yuv
+FrameRate1                    : 50          # Frame Rate per second
+InputBitDepth1                : 8           # Input bitdepth for layer 1
+SourceWidth1                  : 1920        # Input  frame width
+SourceHeight1                 : 1080        # Input  frame height
+RepFormatIdx1                 : 1           # Index of corresponding rep_format() in the VPS
+IntraPeriod1                  : 48          # Period of I-Frame ( -1 = only first)
+ConformanceMode1              : 1           # conformance mode
+QP1                           : 20
+LayerPTLIndex1                : 2
+
+#============= Reference location offset parameters ==================
+NumRefLocationOffsets1         : 1        # Number of reference location offset parameters
+RefLocationOffsetLayerId1                : 0        # List of ref layer id (i-th entry for i-th ref loc offset parameters)
+ScaledRefLayerOffsetPresentFlag1 : 0        # List of scaled ref layer offset present flags
+RefRegionOffsetPresentFlag1      : 1        # List of ref region offset present flags
+RefRegionBottomOffset1           : 2        # List of ref region bottom offsets
+ResamplePhaseSetPresentFlag1     : 0        # List of resample phase set present flags
Index: /tags/SHM-9.0/cfg/per-sequence-svc-avcbase/Cactus-SNR.cfg
===================================================================
--- /tags/SHM-9.0/cfg/per-sequence-svc-avcbase/Cactus-SNR.cfg	(revision 1088)
+++ /tags/SHM-9.0/cfg/per-sequence-svc-avcbase/Cactus-SNR.cfg	(revision 1088)
@@ -0,0 +1,35 @@
+FrameSkip                     : 0           # Number of frames to be skipped in input
+FramesToBeEncoded             : 500         # Number of frames to be coded
+
+Level0                        : 4.1         # Level of the whole bitstream
+Level1                        : 4.1         # Level of the base layer
+Level2                        : 4.1         # Level of the enhancement layer
+
+#======== File I/O ===============
+InputFile0                    : Cactus_1920x1088_50.yuv
+FrameRate0                    : 50          # Frame Rate per second
+InputBitDepth0                : 8           # Input bitdepth for layer 0
+SourceWidth0                  : 1920        # Input  frame width
+SourceHeight0                 : 1088        # Input  frame height
+RepFormatIdx0                 : 0           # Index of corresponding rep_format() in the VPS
+IntraPeriod0                  : 48          # Period of I-Frame ( -1 = only first)
+ConformanceMode0              : 1           # conformance mode
+QP0                           : 22
+LayerPTLIndex0                : 1
+
+InputFile1                    : Cactus_1920x1080_50.yuv
+FrameRate1                    : 50          # Frame Rate per second
+InputBitDepth1                : 8           # Input bitdepth for layer 1
+SourceWidth1                  : 1920        # Input  frame width
+SourceHeight1                 : 1080        # Input  frame height
+RepFormatIdx1                 : 1           # Index of corresponding rep_format() in the VPS
+IntraPeriod1                  : 48          # Period of I-Frame ( -1 = only first)
+ConformanceMode1              : 1           # conformance mode
+NumRefLocationOffsets1         : 1        # Number of reference location offset parameters
+RefLocationOffsetLayerId1                : 0        # List of ref layer id (i-th entry for i-th ref loc offset parameters)
+ScaledRefLayerOffsetPresentFlag1 : 0        # List of scaled ref layer offset present flags
+RefRegionOffsetPresentFlag1      : 1        # List of ref region offset present flags
+RefRegionBottomOffset1           : 4        # List of ref region bottom offsets
+ResamplePhaseSetPresentFlag1     : 0        # List of resample phase set present flags
+QP1                           : 20
+LayerPTLIndex1                : 2
Index: /tags/SHM-9.0/cfg/per-sequence-svc-avcbase/Kimono-1.5x.cfg
===================================================================
--- /tags/SHM-9.0/cfg/per-sequence-svc-avcbase/Kimono-1.5x.cfg	(revision 1088)
+++ /tags/SHM-9.0/cfg/per-sequence-svc-avcbase/Kimono-1.5x.cfg	(revision 1088)
@@ -0,0 +1,29 @@
+FrameSkip                     : 0           # Number of frames to be skipped in input
+FramesToBeEncoded             : 240         # Number of frames to be coded
+
+Level0                        : 4           # Level of the whole bitstream
+Level1                        : 3.1         # Level of the base layer
+Level2                        : 4           # Level of the enhancement layer
+
+#======== File I/O ===============
+InputFile0                    : Kimono1_1280x720_24_zerophase_0.9pi.yuv
+FrameRate0                    : 24          # Frame Rate per second
+InputBitDepth0                : 8           # Input bitdepth for layer 0
+SourceWidth0                  : 1280        # Input  frame width
+SourceHeight0                 : 720         # Input  frame height
+RepFormatIdx0                 : 0           # Index of corresponding rep_format() in the VPS
+IntraPeriod0                  : 24          # Period of I-Frame ( -1 = only first)
+ConformanceMode0              : 1           # conformance mode
+QP0                           : 22
+LayerPTLIndex0                : 1
+
+InputFile1                    : Kimono1_1920x1080_24.yuv
+FrameRate1                    : 24          # Frame Rate per second
+InputBitDepth1                : 8           # Input bitdepth for layer 1
+SourceWidth1                  : 1920        # Input  frame width
+SourceHeight1                 : 1080        # Input  frame height
+RepFormatIdx1                 : 1           # Index of corresponding rep_format() in the VPS
+IntraPeriod1                  : 24          # Period of I-Frame ( -1 = only first)
+ConformanceMode1              : 1           # conformance mode
+QP1                           : 20
+LayerPTLIndex1                : 2
Index: /tags/SHM-9.0/cfg/per-sequence-svc-avcbase/Kimono-2x.cfg
===================================================================
--- /tags/SHM-9.0/cfg/per-sequence-svc-avcbase/Kimono-2x.cfg	(revision 1088)
+++ /tags/SHM-9.0/cfg/per-sequence-svc-avcbase/Kimono-2x.cfg	(revision 1088)
@@ -0,0 +1,37 @@
+FrameSkip                     : 0           # Number of frames to be skipped in input
+FramesToBeEncoded             : 240         # Number of frames to be coded
+
+Level0                        : 4           # Level of the whole bitstream
+Level1                        : 3.1         # Level of the base layer
+Level2                        : 4           # Level of the enhancement layer
+
+#======== File I/O ===============
+InputFile0                    : O:/Kimono1_960x544_24_zerophase_0.9pi.yuv
+FrameRate0                    : 24          # Frame Rate per second
+InputBitDepth0                : 8           # Input bitdepth for layer 0
+SourceWidth0                  : 960         # Input  frame width
+SourceHeight0                 : 544         # Input  frame height
+RepFormatIdx0                 : 0           # Index of corresponding rep_format() in the VPS
+IntraPeriod0                  : 24          # Period of I-Frame ( -1 = only first)
+ConformanceMode0              : 1           # conformance mode
+QP0                           : 22
+LayerPTLIndex0                : 1
+
+InputFile1                    : O:/Kimono1_1920x1080_24.yuv
+FrameRate1                    : 24          # Frame Rate per second
+InputBitDepth1                : 8           # Input bitdepth for layer 1
+SourceWidth1                  : 1920        # Input  frame width
+SourceHeight1                 : 1080        # Input  frame height
+RepFormatIdx1                 : 1           # Index of corresponding rep_format() in the VPS
+IntraPeriod1                  : 24          # Period of I-Frame ( -1 = only first)
+ConformanceMode1              : 1           # conformance mode
+QP1                           : 20
+LayerPTLIndex1                : 2
+
+#============= Reference location offset parameters ==================
+NumRefLocationOffsets1         : 1        # Number of reference location offset parameters
+RefLocationOffsetLayerId1                : 0        # List of ref layer id (i-th entry for i-th ref loc offset parameters)
+ScaledRefLayerOffsetPresentFlag1 : 0        # List of scaled ref layer offset present flags
+RefRegionOffsetPresentFlag1      : 1        # List of ref region offset present flags
+RefRegionBottomOffset1           : 2        # List of ref region bottom offsets
+ResamplePhaseSetPresentFlag1     : 0        # List of resample phase set present flags
Index: /tags/SHM-9.0/cfg/per-sequence-svc-avcbase/Kimono-SNR.cfg
===================================================================
--- /tags/SHM-9.0/cfg/per-sequence-svc-avcbase/Kimono-SNR.cfg	(revision 1088)
+++ /tags/SHM-9.0/cfg/per-sequence-svc-avcbase/Kimono-SNR.cfg	(revision 1088)
@@ -0,0 +1,35 @@
+FrameSkip                     : 0           # Number of frames to be skipped in input
+FramesToBeEncoded             : 240         # Number of frames to be coded
+
+Level0                        : 4           # Level of the whole bitstream
+Level1                        : 4           # Level of the base layer
+Level2                        : 4           # Level of the enhancement layer
+
+#======== File I/O ===============
+InputFile0                    : Kimono1_1920x1088_24.yuv
+FrameRate0                    : 24          # Frame Rate per second
+InputBitDepth0                : 8           # Input bitdepth for layer 0
+SourceWidth0                  : 1920        # Input  frame width
+SourceHeight0                 : 1088        # Input  frame height
+RepFormatIdx0                 : 0           # Index of corresponding rep_format() in the VPS
+IntraPeriod0                  : 24          # Period of I-Frame ( -1 = only first)
+ConformanceMode0              : 1           # conformance mode
+QP0                           : 22
+LayerPTLIndex0                : 1
+
+InputFile1                    : Kimono1_1920x1080_24.yuv
+FrameRate1                    : 24          # Frame Rate per second
+InputBitDepth1                : 8           # Input bitdepth for layer 1
+SourceWidth1                  : 1920        # Input  frame width
+SourceHeight1                 : 1080        # Input  frame height
+RepFormatIdx1                 : 1           # Index of corresponding rep_format() in the VPS
+IntraPeriod1                  : 24          # Period of I-Frame ( -1 = only first)
+ConformanceMode1              : 1           # conformance mode
+NumRefLocationOffsets1         : 1        # Number of reference location offset parameters
+RefLocationOffsetLayerId1                : 0        # List of ref layer id (i-th entry for i-th ref loc offset parameters)
+ScaledRefLayerOffsetPresentFlag1 : 0        # List of scaled ref layer offset present flags
+RefRegionOffsetPresentFlag1      : 1        # List of ref region offset present flags
+RefRegionBottomOffset1           : 4        # List of ref region bottom offsets
+ResamplePhaseSetPresentFlag1     : 0        # List of resample phase set present flags
+QP1                           : 20
+LayerPTLIndex1                : 2
Index: /tags/SHM-9.0/cfg/per-sequence-svc-avcbase/ParkScene-1.5x.cfg
===================================================================
--- /tags/SHM-9.0/cfg/per-sequence-svc-avcbase/ParkScene-1.5x.cfg	(revision 1088)
+++ /tags/SHM-9.0/cfg/per-sequence-svc-avcbase/ParkScene-1.5x.cfg	(revision 1088)
@@ -0,0 +1,29 @@
+FrameSkip                     : 0           # Number of frames to be skipped in input
+FramesToBeEncoded             : 240         # Number of frames to be coded
+
+Level0                        : 4           # Level of the whole bitstream
+Level1                        : 3.1         # Level of the base layer
+Level2                        : 4           # Level of the enhancement layer
+
+#======== File I/O ===============
+InputFile0                    : ParkScene_1280x720_24_zerophase_0.9pi.yuv
+FrameRate0                    : 24          # Frame Rate per second
+InputBitDepth0                : 8           # Input bitdepth for layer 0
+SourceWidth0                  : 1280        # Input  frame width
+SourceHeight0                 : 720         # Input  frame height
+RepFormatIdx0                 : 0           # Index of corresponding rep_format() in the VPS
+IntraPeriod0                  : 24          # Period of I-Frame ( -1 = only first)
+ConformanceMode0              : 1           # conformance mode
+QP0                           : 22
+LayerPTLIndex0                : 1
+
+InputFile1                    : ParkScene_1920x1080_24.yuv
+FrameRate1                    : 24          # Frame Rate per second
+InputBitDepth1                : 8           # Input bitdepth for layer 1
+SourceWidth1                  : 1920        # Input  frame width
+SourceHeight1                 : 1080        # Input  frame height
+RepFormatIdx1                 : 1           # Index of corresponding rep_format() in the VPS
+IntraPeriod1                  : 24          # Period of I-Frame ( -1 = only first)
+ConformanceMode1              : 1           # conformance mode
+QP1                           : 20
+LayerPTLIndex1                : 2
Index: /tags/SHM-9.0/cfg/per-sequence-svc-avcbase/ParkScene-2x.cfg
===================================================================
--- /tags/SHM-9.0/cfg/per-sequence-svc-avcbase/ParkScene-2x.cfg	(revision 1088)
+++ /tags/SHM-9.0/cfg/per-sequence-svc-avcbase/ParkScene-2x.cfg	(revision 1088)
@@ -0,0 +1,37 @@
+FrameSkip                     : 0           # Number of frames to be skipped in input
+FramesToBeEncoded             : 240         # Number of frames to be coded
+
+Level0                        : 4           # Level of the whole bitstream
+Level1                        : 3.1         # Level of the base layer
+Level2                        : 4           # Level of the enhancement layer
+
+#======== File I/O ===============
+InputFile0                    : ParkScene_960x544_24_zerophase_0.9pi.yuv
+FrameRate0                    : 24          # Frame Rate per second
+InputBitDepth0                : 8           # Input bitdepth for layer 0
+SourceWidth0                  : 960         # Input  frame width
+SourceHeight0                 : 544         # Input  frame height
+RepFormatIdx0                 : 0           # Index of corresponding rep_format() in the VPS
+IntraPeriod0                  : 24          # Period of I-Frame ( -1 = only first)
+ConformanceMode0              : 1           # conformance mode
+QP0                           : 22
+LayerPTLIndex0                : 1
+
+InputFile1                    : ParkScene_1920x1080_24.yuv
+FrameRate1                    : 24          # Frame Rate per second
+InputBitDepth1                : 8           # Input bitdepth for layer 1
+SourceWidth1                  : 1920        # Input  frame width
+SourceHeight1                 : 1080        # Input  frame height
+RepFormatIdx1                 : 1           # Index of corresponding rep_format() in the VPS
+IntraPeriod1                  : 24          # Period of I-Frame ( -1 = only first)
+ConformanceMode1              : 1           # conformance mode
+QP1                           : 20
+LayerPTLIndex1                : 2
+
+#============= Reference location offset parameters ==================
+NumRefLocationOffsets1         : 1        # Number of reference location offset parameters
+RefLocationOffsetLayerId1                : 0        # List of ref layer id (i-th entry for i-th ref loc offset parameters)
+ScaledRefLayerOffsetPresentFlag1 : 0        # List of scaled ref layer offset present flags
+RefRegionOffsetPresentFlag1      : 1        # List of ref region offset present flags
+RefRegionBottomOffset1           : 2        # List of ref region bottom offsets
+ResamplePhaseSetPresentFlag1     : 0        # List of resample phase set present flags
Index: /tags/SHM-9.0/cfg/per-sequence-svc-avcbase/ParkScene-SNR.cfg
===================================================================
--- /tags/SHM-9.0/cfg/per-sequence-svc-avcbase/ParkScene-SNR.cfg	(revision 1088)
+++ /tags/SHM-9.0/cfg/per-sequence-svc-avcbase/ParkScene-SNR.cfg	(revision 1088)
@@ -0,0 +1,35 @@
+FrameSkip                     : 0           # Number of frames to be skipped in input
+FramesToBeEncoded             : 240         # Number of frames to be coded
+
+Level0                        : 4           # Level of the whole bitstream
+Level1                        : 4           # Level of the base layer
+Level2                        : 4           # Level of the enhancement layer
+
+#======== File I/O ===============
+InputFile0                    : ParkScene_1920x1088_24.yuv
+FrameRate0                    : 24          # Frame Rate per second
+InputBitDepth0                : 8           # Input bitdepth for layer 0
+SourceWidth0                  : 1920        # Input  frame width
+SourceHeight0                 : 1088        # Input  frame height
+RepFormatIdx0                 : 0           # Index of corresponding rep_format() in the VPS
+IntraPeriod0                  : 24          # Period of I-Frame ( -1 = only first)
+ConformanceMode0              : 1           # conformance mode
+QP0                           : 22
+LayerPTLIndex0                : 1
+
+InputFile1                    : ParkScene_1920x1080_24.yuv
+FrameRate1                    : 24          # Frame Rate per second
+InputBitDepth1                : 8           # Input bitdepth for layer 1
+SourceWidth1                  : 1920        # Input  frame width
+SourceHeight1                 : 1080        # Input  frame height
+RepFormatIdx1                 : 1           # Index of corresponding rep_format() in the VPS
+IntraPeriod1                  : 24          # Period of I-Frame ( -1 = only first)
+ConformanceMode1              : 1           # conformance mode
+NumRefLocationOffsets1         : 1        # Number of reference location offset parameters
+RefLocationOffsetLayerId1                : 0        # List of ref layer id (i-th entry for i-th ref loc offset parameters)
+ScaledRefLayerOffsetPresentFlag1 : 0        # List of scaled ref layer offset present flags
+RefRegionOffsetPresentFlag1      : 1        # List of ref region offset present flags
+RefRegionBottomOffset1           : 4        # List of ref region bottom offsets
+ResamplePhaseSetPresentFlag1     : 0        # List of resample phase set present flags
+QP1                           : 20
+LayerPTLIndex1                : 2
Index: /tags/SHM-9.0/cfg/per-sequence-svc-avcbase/PeopleOnStreet-2x.cfg
===================================================================
--- /tags/SHM-9.0/cfg/per-sequence-svc-avcbase/PeopleOnStreet-2x.cfg	(revision 1088)
+++ /tags/SHM-9.0/cfg/per-sequence-svc-avcbase/PeopleOnStreet-2x.cfg	(revision 1088)
@@ -0,0 +1,29 @@
+FrameSkip                     : 0           # Number of frames to be skipped in input
+FramesToBeEncoded             : 150         # Number of frames to be coded
+
+Level0                        : 5           # Level of the whole bitstream
+Level1                        : 4           # Level of the base layer
+Level2                        : 5           # Level of the enhancement layer
+
+#======== File I/O ===============
+InputFile0                    : PeopleOnStreet_1280x800_30_crop_zerophase_0.9pi.yuv
+FrameRate0                    : 30          # Frame Rate per second
+InputBitDepth0                : 8           # Input bitdepth for layer 0
+SourceWidth0                  : 1280        # Input  frame width
+SourceHeight0                 : 800         # Input  frame height
+RepFormatIdx0                 : 0           # Index of corresponding rep_format() in the VPS
+IntraPeriod0                  : 32          # Period of I-Frame ( -1 = only first)
+ConformanceMode0              : 1           # conformance mode
+QP0                           : 22
+LayerPTLIndex0                : 1
+
+InputFile1                    : PeopleOnStreet_2560x1600_30_crop.yuv
+FrameRate1                    : 30          # Frame Rate per second
+InputBitDepth1                : 8           # Input bitdepth for layer 1
+SourceWidth1                  : 2560        # Input  frame width
+SourceHeight1                 : 1600        # Input  frame height
+RepFormatIdx1                 : 1           # Index of corresponding rep_format() in the VPS
+IntraPeriod1                  : 32          # Period of I-Frame ( -1 = only first)
+ConformanceMode1              : 1           # conformance mode
+QP1                           : 20
+LayerPTLIndex1                : 2
Index: /tags/SHM-9.0/cfg/per-sequence-svc-avcbase/PeopleOnStreet-SNR.cfg
===================================================================
--- /tags/SHM-9.0/cfg/per-sequence-svc-avcbase/PeopleOnStreet-SNR.cfg	(revision 1088)
+++ /tags/SHM-9.0/cfg/per-sequence-svc-avcbase/PeopleOnStreet-SNR.cfg	(revision 1088)
@@ -0,0 +1,29 @@
+FrameSkip                     : 0           # Number of frames to be skipped in input
+FramesToBeEncoded             : 150         # Number of frames to be coded
+
+Level0                        : 5           # Level of the whole bitstream
+Level1                        : 5           # Level of the base layer
+Level2                        : 5           # Level of the enhancement layer
+
+#======== File I/O ===============
+InputFile0                    : PeopleOnStreet_2560x1600_30_crop.yuv
+FrameRate0                    : 30          # Frame Rate per second
+InputBitDepth0                : 8           # Input bitdepth for layer 0
+SourceWidth0                  : 2560        # Input  frame width
+SourceHeight0                 : 1600        # Input  frame height
+RepFormatIdx0                 : 0           # Index of corresponding rep_format() in the VPS
+IntraPeriod0                  : 32          # Period of I-Frame ( -1 = only first)
+ConformanceMode0              : 1           # conformance mode
+QP0                           : 22
+LayerPTLIndex0                : 1
+
+InputFile1                    : PeopleOnStreet_2560x1600_30_crop.yuv
+FrameRate1                    : 30          # Frame Rate per second
+InputBitDepth1                : 8           # Input bitdepth for layer 1
+SourceWidth1                  : 2560        # Input  frame width
+SourceHeight1                 : 1600        # Input  frame height
+RepFormatIdx1                 : 0           # Index of corresponding rep_format() in the VPS
+IntraPeriod1                  : 32          # Period of I-Frame ( -1 = only first)
+ConformanceMode1              : 1           # conformance mode
+QP1                           : 20
+LayerPTLIndex1                : 2
Index: /tags/SHM-9.0/cfg/per-sequence-svc-avcbase/Traffic-2x.cfg
===================================================================
--- /tags/SHM-9.0/cfg/per-sequence-svc-avcbase/Traffic-2x.cfg	(revision 1088)
+++ /tags/SHM-9.0/cfg/per-sequence-svc-avcbase/Traffic-2x.cfg	(revision 1088)
@@ -0,0 +1,29 @@
+FrameSkip                     : 0           # Number of frames to be skipped in input
+FramesToBeEncoded             : 150         # Number of frames to be coded
+
+Level0                        : 5           # Level of the whole bitstream
+Level1                        : 4           # Level of the base layer
+Level2                        : 5           # Level of the enhancement layer
+
+#======== File I/O ===============
+InputFile0                    : Traffic_1280x800_30_crop_zerophase_0.9pi.yuv
+FrameRate0                    : 30          # Frame Rate per second
+InputBitDepth0                : 8           # Input bitdepth for layer 0
+SourceWidth0                  : 1280        # Input  frame width
+SourceHeight0                 : 800         # Input  frame height
+RepFormatIdx0                 : 0           # Index of corresponding rep_format() in the VPS
+IntraPeriod0                  : 32          # Period of I-Frame ( -1 = only first)
+ConformanceMode0              : 1           # conformance mode
+QP0                           : 22
+LayerPTLIndex0                : 1
+
+InputFile1                    : Traffic_2560x1600_30_crop.yuv
+FrameRate1                    : 30          # Frame Rate per second
+InputBitDepth1                : 8           # Input bitdepth for layer 1
+SourceWidth1                  : 2560        # Input  frame width
+SourceHeight1                 : 1600        # Input  frame height
+RepFormatIdx1                 : 1           # Index of corresponding rep_format() in the VPS
+IntraPeriod1                  : 32          # Period of I-Frame ( -1 = only first)
+ConformanceMode1              : 1           # conformance mode
+QP1                           : 20
+LayerPTLIndex1                : 2
Index: /tags/SHM-9.0/cfg/per-sequence-svc-avcbase/Traffic-SNR.cfg
===================================================================
--- /tags/SHM-9.0/cfg/per-sequence-svc-avcbase/Traffic-SNR.cfg	(revision 1088)
+++ /tags/SHM-9.0/cfg/per-sequence-svc-avcbase/Traffic-SNR.cfg	(revision 1088)
@@ -0,0 +1,29 @@
+FrameSkip                     : 0           # Number of frames to be skipped in input
+FramesToBeEncoded             : 150         # Number of frames to be coded
+
+Level0                        : 5           # Level of the whole bitstream
+Level1                        : 5           # Level of the base layer
+Level2                        : 5           # Level of the enhancement layer
+
+#======== File I/O ===============
+InputFile0                    : Traffic_2560x1600_30_crop.yuv
+FrameRate0                    : 30          # Frame Rate per second
+InputBitDepth0                : 8           # Input bitdepth for layer 0
+SourceWidth0                  : 2560        # Input  frame width
+SourceHeight0                 : 1600        # Input  frame height
+RepFormatIdx0                 : 0           # Index of corresponding rep_format() in the VPS
+IntraPeriod0                  : 32          # Period of I-Frame ( -1 = only first)
+ConformanceMode0              : 1           # conformance mode
+QP0                           : 22
+LayerPTLIndex0                : 1
+
+InputFile1                    : Traffic_2560x1600_30_crop.yuv
+FrameRate1                    : 30          # Frame Rate per second
+InputBitDepth1                : 8           # Input bitdepth for layer 1
+SourceWidth1                  : 2560        # Input  frame width
+SourceHeight1                 : 1600        # Input  frame height
+RepFormatIdx1                 : 0           # Index of corresponding rep_format() in the VPS
+IntraPeriod1                  : 32          # Period of I-Frame ( -1 = only first)
+ConformanceMode1              : 1           # conformance mode
+QP1                           : 20
+LayerPTLIndex1                : 2
Index: /tags/SHM-9.0/cfg/per-sequence-svc/BQTerrace-1.5x.cfg
===================================================================
--- /tags/SHM-9.0/cfg/per-sequence-svc/BQTerrace-1.5x.cfg	(revision 1088)
+++ /tags/SHM-9.0/cfg/per-sequence-svc/BQTerrace-1.5x.cfg	(revision 1088)
@@ -0,0 +1,29 @@
+FrameSkip                     : 0           # Number of frames to be skipped in input
+FramesToBeEncoded             : 600         # Number of frames to be coded
+
+Level0                        : 4.1         # Level of the whole bitstream
+Level1                        : 3.1         # Level of the base layer
+Level2                        : 4.1         # Level of the enhancement layer
+
+#======== File I/O ===============
+InputFile0                    : BQTerrace_1280x720_60_zerophase_0.9pi.yuv
+FrameRate0                    : 60          # Frame Rate per second
+InputBitDepth0                : 8           # Input bitdepth for layer 0
+SourceWidth0                  : 1280        # Input  frame width
+SourceHeight0                 : 720         # Input  frame height
+RepFormatIdx0                 : 0           # Index of corresponding rep_format() in the VPS
+IntraPeriod0                  : 64          # Period of I-Frame ( -1 = only first)
+ConformanceMode0              : 1           # conformance mode
+QP0                           : 22
+LayerPTLIndex0                : 1
+
+InputFile1                    : BQTerrace_1920x1080_60.yuv
+FrameRate1                    : 60          # Frame Rate per second
+InputBitDepth1                : 8           # Input bitdepth for layer 1
+SourceWidth1                  : 1920        # Input  frame width
+SourceHeight1                 : 1080        # Input  frame height
+RepFormatIdx1                 : 1           # Index of corresponding rep_format() in the VPS
+IntraPeriod1                  : 64          # Period of I-Frame ( -1 = only first)
+ConformanceMode1              : 1           # conformance mode
+QP1                           : 20
+LayerPTLIndex1                : 2
Index: /tags/SHM-9.0/cfg/per-sequence-svc/BQTerrace-2x.cfg
===================================================================
--- /tags/SHM-9.0/cfg/per-sequence-svc/BQTerrace-2x.cfg	(revision 1088)
+++ /tags/SHM-9.0/cfg/per-sequence-svc/BQTerrace-2x.cfg	(revision 1088)
@@ -0,0 +1,37 @@
+FrameSkip                     : 0           # Number of frames to be skipped in input
+FramesToBeEncoded             : 600         # Number of frames to be coded
+
+Level0                        : 4.1         # Level of the whole bitstream
+Level1                        : 3.1         # Level of the base layer
+Level2                        : 4.1         # Level of the enhancement layer
+
+#======== File I/O ===============
+InputFile0                    : BQTerrace_960x540_60_zerophase_0.9pi.yuv
+FrameRate0                    : 60          # Frame Rate per second
+InputBitDepth0                : 8           # Input bitdepth for layer 0
+SourceWidth0                  : 960         # Input  frame width
+SourceHeight0                 : 540         # Input  frame height
+RepFormatIdx0                 : 0           # Index of corresponding rep_format() in the VPS
+IntraPeriod0                  : 64          # Period of I-Frame ( -1 = only first)
+ConformanceMode0              : 1           # conformance mode
+QP0                           : 22
+LayerPTLIndex0                : 1
+
+InputFile1                    : BQTerrace_1920x1080_60.yuv
+FrameRate1                    : 60          # Frame Rate per second
+InputBitDepth1                : 8           # Input bitdepth for layer 1
+SourceWidth1                  : 1920        # Input  frame width
+SourceHeight1                 : 1080        # Input  frame height
+RepFormatIdx1                 : 1           # Index of corresponding rep_format() in the VPS
+IntraPeriod1                  : 64          # Period of I-Frame ( -1 = only first)
+ConformanceMode1              : 1           # conformance mode
+QP1                           : 20
+LayerPTLIndex1                : 2
+
+#============= Reference location offset parameters ==================
+NumRefLocationOffsets1         : 1        # Number of reference location offset parameters
+RefLocationOffsetLayerId1                : 0        # List of ref layer id (i-th entry for i-th ref loc offset parameters)
+ScaledRefLayerOffsetPresentFlag1 : 0        # List of scaled ref layer offset present flags
+RefRegionOffsetPresentFlag1      : 1        # List of ref region offset present flags
+RefRegionBottomOffset1           : 2        # List of ref region bottom offsets
+ResamplePhaseSetPresentFlag1     : 0        # List of resample phase set present flags
Index: /tags/SHM-9.0/cfg/per-sequence-svc/BQTerrace-SNR.cfg
===================================================================
--- /tags/SHM-9.0/cfg/per-sequence-svc/BQTerrace-SNR.cfg	(revision 1088)
+++ /tags/SHM-9.0/cfg/per-sequence-svc/BQTerrace-SNR.cfg	(revision 1088)
@@ -0,0 +1,29 @@
+FrameSkip                     : 0           # Number of frames to be skipped in input
+FramesToBeEncoded             : 600         # Number of frames to be coded
+
+Level0                        : 4.1         # Level of the whole bitstream
+Level1                        : 4.1         # Level of the base layer
+Level2                        : 4.1         # Level of the enhancement layer
+
+#======== File I/O ===============
+InputFile0                    : BQTerrace_1920x1080_60.yuv
+FrameRate0                    : 60          # Frame Rate per second
+InputBitDepth0                : 8           # Input bitdepth for layer 0
+SourceWidth0                  : 1920        # Input  frame width
+SourceHeight0                 : 1080        # Input  frame height
+RepFormatIdx0                 : 0           # Index of corresponding rep_format() in the VPS
+IntraPeriod0                  : 64          # Period of I-Frame ( -1 = only first)
+ConformanceMode0              : 1           # conformance mode
+QP0                           : 22
+LayerPTLIndex0                : 1
+
+InputFile1                    : BQTerrace_1920x1080_60.yuv
+FrameRate1                    : 60          # Frame Rate per second
+InputBitDepth1                : 8           # Input bitdepth for layer 1
+SourceWidth1                  : 1920        # Input  frame width
+SourceHeight1                 : 1080        # Input  frame height
+RepFormatIdx1                 : 0           # Index of corresponding rep_format() in the VPS
+IntraPeriod1                  : 64          # Period of I-Frame ( -1 = only first)
+ConformanceMode1              : 1           # conformance mode
+QP1                           : 20
+LayerPTLIndex1                : 2
Index: /tags/SHM-9.0/cfg/per-sequence-svc/BasketballDrive-1.5x.cfg
===================================================================
--- /tags/SHM-9.0/cfg/per-sequence-svc/BasketballDrive-1.5x.cfg	(revision 1088)
+++ /tags/SHM-9.0/cfg/per-sequence-svc/BasketballDrive-1.5x.cfg	(revision 1088)
@@ -0,0 +1,29 @@
+FrameSkip                     : 0           # Number of frames to be skipped in input
+FramesToBeEncoded             : 500         # Number of frames to be coded
+
+Level0                        : 4.1         # Level of the whole bitstream
+Level1                        : 3.1         # Level of the base layer
+Level2                        : 4.1         # Level of the enhancement layer
+
+#======== File I/O ===============
+InputFile0                    : BasketballDrive_1280x720_50_zerophase_0.9pi.yuv
+FrameRate0                    : 50          # Frame Rate per second
+InputBitDepth0                : 8           # Input bitdepth for layer 0
+SourceWidth0                  : 1280        # Input  frame width
+SourceHeight0                 : 720         # Input  frame height
+RepFormatIdx0                 : 0           # Index of corresponding rep_format() in the VPS
+IntraPeriod0                  : 48          # Period of I-Frame ( -1 = only first)
+ConformanceMode0              : 1           # conformance mode
+QP0                           : 22
+LayerPTLIndex0                : 1
+
+InputFile1                    : BasketballDrive_1920x1080_50.yuv
+FrameRate1                    : 50          # Frame Rate per second
+InputBitDepth1                : 8           # Input bitdepth for layer 1
+SourceWidth1                  : 1920        # Input  frame width
+SourceHeight1                 : 1080        # Input  frame height
+RepFormatIdx1                 : 1           # Index of corresponding rep_format() in the VPS
+IntraPeriod1                  : 48          # Period of I-Frame ( -1 = only first)
+ConformanceMode1              : 1           # conformance mode
+QP1                           : 20
+LayerPTLIndex1                : 2
Index: /tags/SHM-9.0/cfg/per-sequence-svc/BasketballDrive-2x.cfg
===================================================================
--- /tags/SHM-9.0/cfg/per-sequence-svc/BasketballDrive-2x.cfg	(revision 1088)
+++ /tags/SHM-9.0/cfg/per-sequence-svc/BasketballDrive-2x.cfg	(revision 1088)
@@ -0,0 +1,37 @@
+FrameSkip                     : 0           # Number of frames to be skipped in input
+FramesToBeEncoded             : 500         # Number of frames to be coded
+
+Level0                        : 4.1         # Level of the whole bitstream
+Level1                        : 3.1         # Level of the base layer
+Level2                        : 4.1         # Level of the enhancement layer
+
+#======== File I/O ===============
+InputFile0                    : BasketballDrive_960x540_50_zerophase_0.9pi.yuv
+FrameRate0                    : 50          # Frame Rate per second
+InputBitDepth0                : 8           # Input bitdepth for layer 0
+SourceWidth0                  : 960         # Input  frame width
+SourceHeight0                 : 540         # Input  frame height
+RepFormatIdx0                 : 0           # Index of corresponding rep_format() in the VPS
+IntraPeriod0                  : 48          # Period of I-Frame ( -1 = only first)
+ConformanceMode0              : 1           # conformance mode
+QP0                           : 22
+LayerPTLIndex0                : 1
+
+InputFile1                    : BasketballDrive_1920x1080_50.yuv
+FrameRate1                    : 50          # Frame Rate per second
+InputBitDepth1                : 8           # Input bitdepth for layer 1
+SourceWidth1                  : 1920        # Input  frame width
+SourceHeight1                 : 1080        # Input  frame height
+RepFormatIdx1                 : 1           # Index of corresponding rep_format() in the VPS
+IntraPeriod1                  : 48          # Period of I-Frame ( -1 = only first)
+ConformanceMode1              : 1           # conformance mode
+QP1                           : 20
+LayerPTLIndex1                : 2
+
+#============= Reference location offset parameters ==================
+NumRefLocationOffsets1         : 1        # Number of reference location offset parameters
+RefLocationOffsetLayerId1                : 0        # List of ref layer id (i-th entry for i-th ref loc offset parameters)
+ScaledRefLayerOffsetPresentFlag1 : 0        # List of scaled ref layer offset present flags
+RefRegionOffsetPresentFlag1      : 1        # List of ref region offset present flags
+RefRegionBottomOffset1           : 2        # List of ref region bottom offsets
+ResamplePhaseSetPresentFlag1     : 0        # List of resample phase set present flags
Index: /tags/SHM-9.0/cfg/per-sequence-svc/BasketballDrive-SNR.cfg
===================================================================
--- /tags/SHM-9.0/cfg/per-sequence-svc/BasketballDrive-SNR.cfg	(revision 1088)
+++ /tags/SHM-9.0/cfg/per-sequence-svc/BasketballDrive-SNR.cfg	(revision 1088)
@@ -0,0 +1,29 @@
+FrameSkip                     : 0           # Number of frames to be skipped in input
+FramesToBeEncoded             : 500         # Number of frames to be coded
+
+Level0                        : 4.1         # Level of the whole bitstream
+Level1                        : 4.1         # Level of the base layer
+Level2                        : 4.1         # Level of the enhancement layer
+
+#======== File I/O ===============
+InputFile0                    : BasketballDrive_1920x1080_50.yuv
+FrameRate0                    : 50          # Frame Rate per second
+InputBitDepth0                : 8           # Input bitdepth for layer 0
+SourceWidth0                  : 1920        # Input  frame width
+SourceHeight0                 : 1080        # Input  frame height
+RepFormatIdx0                 : 0           # Index of corresponding rep_format() in the VPS
+IntraPeriod0                  : 48          # Period of I-Frame ( -1 = only first)
+ConformanceMode0              : 1           # conformance mode
+QP0                           : 22
+LayerPTLIndex0                : 1
+
+InputFile1                    : BasketballDrive_1920x1080_50.yuv
+FrameRate1                    : 50          # Frame Rate per second
+InputBitDepth1                : 8           # Input bitdepth for layer 1
+SourceWidth1                  : 1920        # Input  frame width
+SourceHeight1                 : 1080        # Input  frame height
+RepFormatIdx1                 : 0           # Index of corresponding rep_format() in the VPS
+IntraPeriod1                  : 48          # Period of I-Frame ( -1 = only first)
+ConformanceMode1              : 1           # conformance mode
+QP1                           : 20
+LayerPTLIndex1                : 2
Index: /tags/SHM-9.0/cfg/per-sequence-svc/CGS-Birthday-b10-1x.cfg
===================================================================
--- /tags/SHM-9.0/cfg/per-sequence-svc/CGS-Birthday-b10-1x.cfg	(revision 1088)
+++ /tags/SHM-9.0/cfg/per-sequence-svc/CGS-Birthday-b10-1x.cfg	(revision 1088)
@@ -0,0 +1,32 @@
+CGS                           : 1
+FrameSkip                     : 0           # Number of frames to be skipped in input
+FramesToBeEncoded             : 300         # Number of frames to be coded
+
+Level0                        : 4.1         # Level of the whole bitstream
+Level1                        : 4.1         # Level of the base layer
+Level2                        : 4.1         # Level of the enhancement layer
+
+#======== File I/O ===============
+InputFile0                    : O:\BT709_Birthday_1920x1080_60_10bit_zerophase_0.9pi.yuv
+FrameRate0                    : 60          # Frame Rate per second
+SourceWidth0                  : 1920        # Input  frame width
+SourceHeight0                 : 1080        # Input  frame height
+IntraPeriod0                  : 64          # Period of I-Frame ( -1 = only first)
+ConformanceMode0              : 1           # conformance mode
+QP0                           : 22
+InputBitDepth0                : 10          # Input bitdepth
+InternalBitDepth0             : 10          # codec operating bit-depth for layer 0
+RepFormatIdx0                 : 0           # Index of corresponding rep_format() in the VPS
+LayerPTLIndex0                : 1
+
+InputFile1                    : O:\BT2020_Birthday_1920x1080_60_10bit_zerophase_0.9pi.yuv
+FrameRate1                    : 60          # Frame Rate per second
+SourceWidth1                  : 1920        # Input  frame width
+SourceHeight1                 : 1080        # Input  frame height
+IntraPeriod1                  : 64          # Period of I-Frame ( -1 = only first)
+ConformanceMode1              : 1           # conformance mode
+QP1                           : 20
+InputBitDepth1                : 10          # Input bitdepth
+InternalBitDepth1             : 10          # codec operating bit-depth for layer 1
+RepFormatIdx1                 : 0           # Index of corresponding rep_format() in the VPS
+LayerPTLIndex1                : 2
Index: /tags/SHM-9.0/cfg/per-sequence-svc/CGS-Birthday-b8-2x.cfg
===================================================================
--- /tags/SHM-9.0/cfg/per-sequence-svc/CGS-Birthday-b8-2x.cfg	(revision 1088)
+++ /tags/SHM-9.0/cfg/per-sequence-svc/CGS-Birthday-b8-2x.cfg	(revision 1088)
@@ -0,0 +1,32 @@
+CGS                           : 1
+FrameSkip                     : 0           # Number of frames to be skipped in input
+FramesToBeEncoded             : 300         # Number of frames to be coded
+
+Level0                        : 5.1         # Level of the whole bitstream
+Level1                        : 4.1         # Level of the base layer
+Level2                        : 5.1         # Level of the enhancement layer
+
+#======== File I/O ===============
+InputFile0                    : BT709_Birthday_1920x1080_60_zerophase_0.9pi.yuv
+FrameRate0                    : 60          # Frame Rate per second
+SourceWidth0                  : 1920        # Input  frame width
+SourceHeight0                 : 1080        # Input  frame height
+IntraPeriod0                  : 64          # Period of I-Frame ( -1 = only first)
+ConformanceMode0              : 1           # conformance mode
+QP0                           : 22
+InputBitDepth0                : 8           # Input bitdepth
+InternalBitDepth0             : 8           # codec operating bit-depth for layer 0
+RepFormatIdx0                 : 0           # Index of corresponding rep_format() in the VPS
+LayerPTLIndex0                : 1
+
+InputFile1                    : BT2020_Birthday_3840x2160_60_10bit.yuv
+FrameRate1                    : 60          # Frame Rate per second
+SourceWidth1                  : 3840        # Input  frame width
+SourceHeight1                 : 2160        # Input  frame height
+IntraPeriod1                  : 64          # Period of I-Frame ( -1 = only first)
+ConformanceMode1              : 1           # conformance mode
+QP1                           : 20
+InputBitDepth1                : 10          # Input bitdepth
+InternalBitDepth1             : 10          # codec operating bit-depth for layer 1
+RepFormatIdx1                 : 1           # Index of corresponding rep_format() in the VPS
+LayerPTLIndex1                : 2
Index: /tags/SHM-9.0/cfg/per-sequence-svc/CGS-BirthdayFlashPart1-b10-1x.cfg
===================================================================
--- /tags/SHM-9.0/cfg/per-sequence-svc/CGS-BirthdayFlashPart1-b10-1x.cfg	(revision 1088)
+++ /tags/SHM-9.0/cfg/per-sequence-svc/CGS-BirthdayFlashPart1-b10-1x.cfg	(revision 1088)
@@ -0,0 +1,32 @@
+CGS                           : 1
+FrameSkip                     : 0           # Number of frames to be skipped in input
+FramesToBeEncoded             : 300         # Number of frames to be coded
+
+Level0                        : 4.1         # Level of the whole bitstream
+Level1                        : 4.1         # Level of the base layer
+Level2                        : 4.1         # Level of the enhancement layer
+
+#======== File I/O ===============
+InputFile0                    : BT709_BirthdayFlashPart1_1920x1080_60_10bit_zerophase_0.9pi.yuv
+FrameRate0                    : 60          # Frame Rate per second
+SourceWidth0                  : 1920        # Input  frame width
+SourceHeight0                 : 1080        # Input  frame height
+IntraPeriod0                  : 64          # Period of I-Frame ( -1 = only first)
+ConformanceMode0              : 1           # conformance mode
+QP0                           : 22
+InputBitDepth0                : 10          # Input bitdepth
+InternalBitDepth0             : 10          # codec operating bit-depth for layer 0
+RepFormatIdx0                 : 0           # Index of corresponding rep_format() in the VPS
+LayerPTLIndex0                : 1
+
+InputFile1                    : BT2020_BirthdayFlashPart1_1920x1080_60_10bit_zerophase_0.9pi.yuv
+FrameRate1                    : 60          # Frame Rate per second
+SourceWidth1                  : 1920        # Input  frame width
+SourceHeight1                 : 1080        # Input  frame height
+IntraPeriod1                  : 64          # Period of I-Frame ( -1 = only first)
+ConformanceMode1              : 1           # conformance mode
+QP1                           : 20
+InputBitDepth1                : 10          # Input bitdepth
+InternalBitDepth1             : 10          # codec operating bit-depth for layer 1
+RepFormatIdx1                 : 0           # Index of corresponding rep_format() in the VPS
+LayerPTLIndex1                : 2
Index: /tags/SHM-9.0/cfg/per-sequence-svc/CGS-BirthdayFlashPart1-b8-2x.cfg
===================================================================
--- /tags/SHM-9.0/cfg/per-sequence-svc/CGS-BirthdayFlashPart1-b8-2x.cfg	(revision 1088)
+++ /tags/SHM-9.0/cfg/per-sequence-svc/CGS-BirthdayFlashPart1-b8-2x.cfg	(revision 1088)
@@ -0,0 +1,32 @@
+CGS                           : 1
+FrameSkip                     : 0           # Number of frames to be skipped in input
+FramesToBeEncoded             : 300         # Number of frames to be coded
+
+Level0                        : 5.1         # Level of the whole bitstream
+Level1                        : 4.1         # Level of the base layer
+Level2                        : 5.1         # Level of the enhancement layer
+
+#======== File I/O ===============
+InputFile0                    : BT709_BirthdayFlashPart1_1920x1080_60_zerophase_0.9pi.yuv
+FrameRate0                    : 60          # Frame Rate per second
+SourceWidth0                  : 1920        # Input  frame width
+SourceHeight0                 : 1080        # Input  frame height
+IntraPeriod0                  : 64          # Period of I-Frame ( -1 = only first)
+ConformanceMode0              : 1           # conformance mode
+QP0                           : 22
+InputBitDepth0                : 8           # Input bitdepth
+InternalBitDepth0             : 8           # codec operating bit-depth for layer 0
+RepFormatIdx0                 : 0           # Index of corresponding rep_format() in the VPS
+LayerPTLIndex0                : 1
+
+InputFile1                    : BT2020_BirthdayFlashPart1_3840x2160_60_10bit.yuv
+FrameRate1                    : 60          # Frame Rate per second
+SourceWidth1                  : 3840        # Input  frame width
+SourceHeight1                 : 2160        # Input  frame height
+IntraPeriod1                  : 64          # Period of I-Frame ( -1 = only first)
+ConformanceMode1              : 1           # conformance mode
+QP1                           : 20
+InputBitDepth1                : 10          # Input bitdepth
+InternalBitDepth1             : 10          # codec operating bit-depth for layer 1
+RepFormatIdx1                 : 1           # Index of corresponding rep_format() in the VPS
+LayerPTLIndex1                : 2
Index: /tags/SHM-9.0/cfg/per-sequence-svc/CGS-BirthdayFlashPart2-b10-1x.cfg
===================================================================
--- /tags/SHM-9.0/cfg/per-sequence-svc/CGS-BirthdayFlashPart2-b10-1x.cfg	(revision 1088)
+++ /tags/SHM-9.0/cfg/per-sequence-svc/CGS-BirthdayFlashPart2-b10-1x.cfg	(revision 1088)
@@ -0,0 +1,32 @@
+CGS                           : 1
+FrameSkip                     : 0           # Number of frames to be skipped in input
+FramesToBeEncoded             : 300         # Number of frames to be coded
+
+Level0                        : 4.1         # Level of the whole bitstream
+Level1                        : 4.1         # Level of the base layer
+Level2                        : 4.1         # Level of the enhancement layer
+
+#======== File I/O ===============
+InputFile0                    : BT709_BirthdayFlashPart2_1920x1080_60_10bit_zerophase_0.9pi.yuv
+FrameRate0                    : 60          # Frame Rate per second
+SourceWidth0                  : 1920        # Input  frame width
+SourceHeight0                 : 1080        # Input  frame height
+IntraPeriod0                  : 64          # Period of I-Frame ( -1 = only first)
+ConformanceMode0              : 1           # conformance mode
+QP0                           : 22
+InputBitDepth0                : 10          # Input bitdepth
+InternalBitDepth0             : 10          # codec operating bit-depth for layer 0
+RepFormatIdx0                 : 0           # Index of corresponding rep_format() in the VPS
+LayerPTLIndex0                : 1
+
+InputFile1                    : BT2020_BirthdayFlashPart2_1920x1080_60_10bit_zerophase_0.9pi.yuv
+FrameRate1                    : 60          # Frame Rate per second
+SourceWidth1                  : 1920        # Input  frame width
+SourceHeight1                 : 1080        # Input  frame height
+IntraPeriod1                  : 64          # Period of I-Frame ( -1 = only first)
+ConformanceMode1              : 1           # conformance mode
+QP1                           : 20
+InputBitDepth1                : 10          # Input bitdepth
+InternalBitDepth1             : 10          # codec operating bit-depth for layer 1
+RepFormatIdx1                 : 0           # Index of corresponding rep_format() in the VPS
+LayerPTLIndex1                : 2
Index: /tags/SHM-9.0/cfg/per-sequence-svc/CGS-BirthdayFlashPart2-b8-2x.cfg
===================================================================
--- /tags/SHM-9.0/cfg/per-sequence-svc/CGS-BirthdayFlashPart2-b8-2x.cfg	(revision 1088)
+++ /tags/SHM-9.0/cfg/per-sequence-svc/CGS-BirthdayFlashPart2-b8-2x.cfg	(revision 1088)
@@ -0,0 +1,32 @@
+CGS                           : 1
+FrameSkip                     : 0           # Number of frames to be skipped in input
+FramesToBeEncoded             : 300         # Number of frames to be coded
+
+Level0                        : 5.1         # Level of the whole bitstream
+Level1                        : 4.1         # Level of the base layer
+Level2                        : 5.1         # Level of the enhancement layer
+
+#======== File I/O ===============
+InputFile0                    : BT709_BirthdayFlashPart2_1920x1080_60_zerophase_0.9pi.yuv
+FrameRate0                    : 60          # Frame Rate per second
+SourceWidth0                  : 1920        # Input  frame width
+SourceHeight0                 : 1080        # Input  frame height
+IntraPeriod0                  : 64          # Period of I-Frame ( -1 = only first)
+ConformanceMode0              : 1           # conformance mode
+QP0                           : 22
+InputBitDepth0                : 8           # Input bitdepth
+InternalBitDepth0             : 8           # codec operating bit-depth for layer 0
+RepFormatIdx0                 : 0           # Index of corresponding rep_format() in the VPS
+LayerPTLIndex0                : 1
+
+InputFile1                    : BT2020_BirthdayFlashPart2_3840x2160_60_10bit.yuv
+FrameRate1                    : 60          # Frame Rate per second
+SourceWidth1                  : 3840        # Input  frame width
+SourceHeight1                 : 2160        # Input  frame height
+IntraPeriod1                  : 64          # Period of I-Frame ( -1 = only first)
+ConformanceMode1              : 1           # conformance mode
+QP1                           : 20
+InputBitDepth1                : 10          # Input bitdepth
+InternalBitDepth1             : 10          # codec operating bit-depth for layer 1
+RepFormatIdx1                 : 1           # Index of corresponding rep_format() in the VPS
+LayerPTLIndex1                : 2
Index: /tags/SHM-9.0/cfg/per-sequence-svc/CGS-Parakeets-b10-1x.cfg
===================================================================
--- /tags/SHM-9.0/cfg/per-sequence-svc/CGS-Parakeets-b10-1x.cfg	(revision 1088)
+++ /tags/SHM-9.0/cfg/per-sequence-svc/CGS-Parakeets-b10-1x.cfg	(revision 1088)
@@ -0,0 +1,32 @@
+CGS                           : 1
+FrameSkip                     : 0           # Number of frames to be skipped in input
+FramesToBeEncoded             : 250         # Number of frames to be coded
+
+Level0                        : 4.1         # Level of the whole bitstream
+Level1                        : 4.1         # Level of the base layer
+Level2                        : 4.1         # Level of the enhancement layer
+
+#======== File I/O ===============
+InputFile0                    : BT709_Parakeets_1920x1080_50_10bit_zerophase_0.9pi.yuv
+FrameRate0                    : 50          # Frame Rate per second
+SourceWidth0                  : 1920        # Input  frame width
+SourceHeight0                 : 1080        # Input  frame height
+IntraPeriod0                  : 48          # Period of I-Frame ( -1 = only first)
+ConformanceMode0              : 1           # conformance mode
+QP0                           : 22
+InputBitDepth0                : 10          # Input bitdepth
+InternalBitDepth0             : 10          # codec operating bit-depth for layer 0
+RepFormatIdx0                 : 0           # Index of corresponding rep_format() in the VPS
+LayerPTLIndex0                : 1
+
+InputFile1                    : BT2020_Parakeets_1920x1080_50_10bit_zerophase_0.9pi.yuv
+FrameRate1                    : 50          # Frame Rate per second
+SourceWidth1                  : 1920        # Input  frame width
+SourceHeight1                 : 1080        # Input  frame height
+IntraPeriod1                  : 48          # Period of I-Frame ( -1 = only first)
+ConformanceMode1              : 1           # conformance mode
+QP1                           : 20
+InputBitDepth1                : 10          # Input bitdepth
+InternalBitDepth1             : 10          # codec operating bit-depth for layer 1
+RepFormatIdx1                 : 0           # Index of corresponding rep_format() in the VPS
+LayerPTLIndex1                : 2
Index: /tags/SHM-9.0/cfg/per-sequence-svc/CGS-Parakeets-b8-2x.cfg
===================================================================
--- /tags/SHM-9.0/cfg/per-sequence-svc/CGS-Parakeets-b8-2x.cfg	(revision 1088)
+++ /tags/SHM-9.0/cfg/per-sequence-svc/CGS-Parakeets-b8-2x.cfg	(revision 1088)
@@ -0,0 +1,32 @@
+CGS                           : 1
+FrameSkip                     : 0           # Number of frames to be skipped in input
+FramesToBeEncoded             : 250         # Number of frames to be coded
+
+Level0                        : 5.1         # Level of the whole bitstream
+Level1                        : 4.1         # Level of the base layer
+Level2                        : 5.1         # Level of the enhancement layer
+
+#======== File I/O ===============
+InputFile0                    : BT709_Parakeets_1920x1080_50_zerophase_0.9pi.yuv
+FrameRate0                    : 50          # Frame Rate per second
+SourceWidth0                  : 1920        # Input  frame width
+SourceHeight0                 : 1080        # Input  frame height
+IntraPeriod0                  : 48          # Period of I-Frame ( -1 = only first)
+ConformanceMode0              : 1           # conformance mode
+QP0                           : 22
+InputBitDepth0                : 8           # Input bitdepth
+InternalBitDepth0             : 8           # codec operating bit-depth for layer 0
+RepFormatIdx0                 : 0           # Index of corresponding rep_format() in the VPS
+LayerPTLIndex0                : 1
+
+InputFile1                    : BT2020_Parakeets_3840x2160_50_10bit.yuv
+FrameRate1                    : 50          # Frame Rate per second
+SourceWidth1                  : 3840        # Input  frame width
+SourceHeight1                 : 2160        # Input  frame height
+IntraPeriod1                  : 48          # Period of I-Frame ( -1 = only first)
+ConformanceMode1              : 1           # conformance mode
+QP1                           : 20
+InputBitDepth1                : 10          # Input bitdepth
+InternalBitDepth1             : 10          # codec operating bit-depth for layer 1
+RepFormatIdx1                 : 1           # Index of corresponding rep_format() in the VPS
+LayerPTLIndex1                : 2
Index: /tags/SHM-9.0/cfg/per-sequence-svc/CGS-TableCar-b10-1x.cfg
===================================================================
--- /tags/SHM-9.0/cfg/per-sequence-svc/CGS-TableCar-b10-1x.cfg	(revision 1088)
+++ /tags/SHM-9.0/cfg/per-sequence-svc/CGS-TableCar-b10-1x.cfg	(revision 1088)
@@ -0,0 +1,32 @@
+CGS                           : 1
+FrameSkip                     : 0           # Number of frames to be skipped in input
+FramesToBeEncoded             : 300         # Number of frames to be coded
+
+Level0                        : 4.1         # Level of the whole bitstream
+Level1                        : 4.1         # Level of the base layer
+Level2                        : 4.1         # Level of the enhancement layer
+
+#======== File I/O ===============
+InputFile0                    : BT709_TableCar_1920x1080_60_10bit_zerophase_0.9pi.yuv
+FrameRate0                    : 60          # Frame Rate per second
+SourceWidth0                  : 1920        # Input  frame width
+SourceHeight0                 : 1080        # Input  frame height
+IntraPeriod0                  : 64          # Period of I-Frame ( -1 = only first)
+ConformanceMode0              : 1           # conformance mode
+QP0                           : 22
+InputBitDepth0                : 10          # Input bitdepth
+InternalBitDepth0             : 10          # codec operating bit-depth for layer 0
+RepFormatIdx0                 : 0           # Index of corresponding rep_format() in the VPS
+LayerPTLIndex0                : 1
+
+InputFile1                    : BT2020_TableCar_1920x1080_60_10bit_zerophase_0.9pi.yuv
+FrameRate1                    : 60          # Frame Rate per second
+SourceWidth1                  : 1920        # Input  frame width
+SourceHeight1                 : 1080        # Input  frame height
+IntraPeriod1                  : 64          # Period of I-Frame ( -1 = only first)
+ConformanceMode1              : 1           # conformance mode
+QP1                           : 20
+InputBitDepth1                : 10          # Input bitdepth
+InternalBitDepth1             : 10          # codec operating bit-depth for layer 1
+RepFormatIdx1                 : 0           # Index of corresponding rep_format() in the VPS
+LayerPTLIndex1                : 2
Index: /tags/SHM-9.0/cfg/per-sequence-svc/CGS-TableCar-b8-2x.cfg
===================================================================
--- /tags/SHM-9.0/cfg/per-sequence-svc/CGS-TableCar-b8-2x.cfg	(revision 1088)
+++ /tags/SHM-9.0/cfg/per-sequence-svc/CGS-TableCar-b8-2x.cfg	(revision 1088)
@@ -0,0 +1,32 @@
+CGS                           : 1
+FrameSkip                     : 0           # Number of frames to be skipped in input
+FramesToBeEncoded             : 300         # Number of frames to be coded
+
+Level0                        : 5.1         # Level of the whole bitstream
+Level1                        : 4.1         # Level of the base layer
+Level2                        : 5.1         # Level of the enhancement layer
+
+#======== File I/O ===============
+InputFile0                    : BT709_TableCar_1920x1080_60_zerophase_0.9pi.yuv
+FrameRate0                    : 60          # Frame Rate per second
+SourceWidth0                  : 1920        # Input  frame width
+SourceHeight0                 : 1080        # Input  frame height
+IntraPeriod0                  : 64          # Period of I-Frame ( -1 = only first)
+ConformanceMode0              : 1           # conformance mode
+QP0                           : 22
+InputBitDepth0                : 8           # Input bitdepth
+InternalBitDepth0             : 8           # codec operating bit-depth for layer 0
+RepFormatIdx0                 : 0           # Index of corresponding rep_format() in the VPS
+LayerPTLIndex0                : 1
+
+InputFile1                    : BT2020_TableCar_3840x2160_60_10bit.yuv
+FrameRate1                    : 60          # Frame Rate per second
+SourceWidth1                  : 3840        # Input  frame width
+SourceHeight1                 : 2160        # Input  frame height
+IntraPeriod1                  : 64          # Period of I-Frame ( -1 = only first)
+ConformanceMode1              : 1           # conformance mode
+QP1                           : 20
+InputBitDepth1                : 10          # Input bitdepth
+InternalBitDepth1             : 10          # codec operating bit-depth for layer 1
+RepFormatIdx1                 : 1           # Index of corresponding rep_format() in the VPS
+LayerPTLIndex1                : 2
Index: /tags/SHM-9.0/cfg/per-sequence-svc/Cactus-1.5x.cfg
===================================================================
--- /tags/SHM-9.0/cfg/per-sequence-svc/Cactus-1.5x.cfg	(revision 1088)
+++ /tags/SHM-9.0/cfg/per-sequence-svc/Cactus-1.5x.cfg	(revision 1088)
@@ -0,0 +1,29 @@
+FrameSkip                     : 0           # Number of frames to be skipped in input
+FramesToBeEncoded             : 500         # Number of frames to be coded
+
+Level0                        : 4.1         # Level of the whole bitstream
+Level1                        : 3.1         # Level of the base layer
+Level2                        : 4.1         # Level of the enhancement layer
+
+#======== File I/O ===============
+InputFile0                    : Cactus_1280x720_50_zerophase_0.9pi.yuv
+FrameRate0                    : 50          # Frame Rate per second
+InputBitDepth0                : 8           # Input bitdepth for layer 0
+SourceWidth0                  : 1280        # Input  frame width
+SourceHeight0                 : 720         # Input  frame height
+RepFormatIdx0                 : 0           # Index of corresponding rep_format() in the VPS
+IntraPeriod0                  : 48          # Period of I-Frame ( -1 = only first)
+ConformanceMode0              : 1           # conformance mode
+QP0                           : 22
+LayerPTLIndex0                : 1
+
+InputFile1                    : Cactus_1920x1080_50.yuv
+FrameRate1                    : 50          # Frame Rate per second
+InputBitDepth1                : 8           # Input bitdepth for layer 1
+SourceWidth1                  : 1920        # Input  frame width
+SourceHeight1                 : 1080        # Input  frame height
+RepFormatIdx1                 : 1           # Index of corresponding rep_format() in the VPS
+IntraPeriod1                  : 48          # Period of I-Frame ( -1 = only first)
+ConformanceMode1              : 1           # conformance mode
+QP1                           : 20
+LayerPTLIndex1                : 2
Index: /tags/SHM-9.0/cfg/per-sequence-svc/Cactus-2x.cfg
===================================================================
--- /tags/SHM-9.0/cfg/per-sequence-svc/Cactus-2x.cfg	(revision 1088)
+++ /tags/SHM-9.0/cfg/per-sequence-svc/Cactus-2x.cfg	(revision 1088)
@@ -0,0 +1,37 @@
+FrameSkip                     : 0           # Number of frames to be skipped in input
+FramesToBeEncoded             : 500         # Number of frames to be coded
+
+Level0                        : 4.1         # Level of the whole bitstream
+Level1                        : 3.1         # Level of the base layer
+Level2                        : 4.1         # Level of the enhancement layer
+
+#======== File I/O ===============
+InputFile0                    : Cactus_960x540_50_zerophase_0.9pi.yuv
+FrameRate0                    : 50          # Frame Rate per second
+InputBitDepth0                : 8           # Input bitdepth for layer 0
+SourceWidth0                  : 960         # Input  frame width
+SourceHeight0                 : 540         # Input  frame height
+RepFormatIdx0                 : 0           # Index of corresponding rep_format() in the VPS
+IntraPeriod0                  : 48          # Period of I-Frame ( -1 = only first)
+ConformanceMode0              : 1           # conformance mode
+QP0                           : 22
+LayerPTLIndex0                : 1
+
+InputFile1                    : Cactus_1920x1080_50.yuv
+FrameRate1                    : 50          # Frame Rate per second
+InputBitDepth1                : 8           # Input bitdepth for layer 1
+SourceWidth1                  : 1920        # Input  frame width
+SourceHeight1                 : 1080        # Input  frame height
+RepFormatIdx1                 : 1           # Index of corresponding rep_format() in the VPS
+IntraPeriod1                  : 48          # Period of I-Frame ( -1 = only first)
+ConformanceMode1              : 1           # conformance mode
+QP1                           : 20
+LayerPTLIndex1                : 2
+
+#============= Reference location offset parameters ==================
+NumRefLocationOffsets1         : 1        # Number of reference location offset parameters
+RefLocationOffsetLayerId1                : 0        # List of ref layer id (i-th entry for i-th ref loc offset parameters)
+ScaledRefLayerOffsetPresentFlag1 : 0        # List of scaled ref layer offset present flags
+RefRegionOffsetPresentFlag1      : 1        # List of ref region offset present flags
+RefRegionBottomOffset1           : 2        # List of ref region bottom offsets
+ResamplePhaseSetPresentFlag1     : 0        # List of resample phase set present flags
Index: /tags/SHM-9.0/cfg/per-sequence-svc/Cactus-SNR.cfg
===================================================================
--- /tags/SHM-9.0/cfg/per-sequence-svc/Cactus-SNR.cfg	(revision 1088)
+++ /tags/SHM-9.0/cfg/per-sequence-svc/Cactus-SNR.cfg	(revision 1088)
@@ -0,0 +1,29 @@
+FrameSkip                     : 0           # Number of frames to be skipped in input
+FramesToBeEncoded             : 500         # Number of frames to be coded
+
+Level0                        : 4.1         # Level of the whole bitstream
+Level1                        : 4.1         # Level of the base layer
+Level2                        : 4.1         # Level of the enhancement layer
+
+#======== File I/O ===============
+InputFile0                    : Cactus_1920x1080_50.yuv
+FrameRate0                    : 50          # Frame Rate per second
+InputBitDepth0                : 8           # Input bitdepth for layer 0
+SourceWidth0                  : 1920        # Input  frame width
+SourceHeight0                 : 1080        # Input  frame height
+RepFormatIdx0                 : 0           # Index of corresponding rep_format() in the VPS
+IntraPeriod0                  : 48          # Period of I-Frame ( -1 = only first)
+ConformanceMode0              : 1           # conformance mode
+QP0                           : 22
+LayerPTLIndex0                : 1
+
+InputFile1                    : Cactus_1920x1080_50.yuv
+FrameRate1                    : 50          # Frame Rate per second
+InputBitDepth1                : 8           # Input bitdepth for layer 1
+SourceWidth1                  : 1920        # Input  frame width
+SourceHeight1                 : 1080        # Input  frame height
+RepFormatIdx1                 : 0           # Index of corresponding rep_format() in the VPS
+IntraPeriod1                  : 48          # Period of I-Frame ( -1 = only first)
+ConformanceMode1              : 1           # conformance mode
+QP1                           : 20
+LayerPTLIndex1                : 2
Index: /tags/SHM-9.0/cfg/per-sequence-svc/Kimono-1.5x.cfg
===================================================================
--- /tags/SHM-9.0/cfg/per-sequence-svc/Kimono-1.5x.cfg	(revision 1088)
+++ /tags/SHM-9.0/cfg/per-sequence-svc/Kimono-1.5x.cfg	(revision 1088)
@@ -0,0 +1,29 @@
+FrameSkip                     : 0           # Number of frames to be skipped in input
+FramesToBeEncoded             : 240         # Number of frames to be coded
+
+Level0                        : 4           # Level of the whole bitstream
+Level1                        : 3.1         # Level of the base layer
+Level2                        : 4           # Level of the enhancement layer
+
+#======== File I/O ===============
+InputFile0                    : Kimono1_1280x720_24_zerophase_0.9pi.yuv
+FrameRate0                    : 24          # Frame Rate per second
+InputBitDepth0                : 8           # Input bitdepth for layer 0
+SourceWidth0                  : 1280        # Input  frame width
+SourceHeight0                 : 720         # Input  frame height
+RepFormatIdx0                 : 0           # Index of corresponding rep_format() in the VPS
+IntraPeriod0                  : 24          # Period of I-Frame ( -1 = only first)
+ConformanceMode0              : 1           # conformance mode
+QP0                           : 22
+LayerPTLIndex0                : 1
+
+InputFile1                    : Kimono1_1920x1080_24.yuv
+FrameRate1                    : 24          # Frame Rate per second
+InputBitDepth1                : 8           # Input bitdepth for layer 1
+SourceWidth1                  : 1920        # Input  frame width
+SourceHeight1                 : 1080        # Input  frame height
+RepFormatIdx1                 : 1           # Index of corresponding rep_format() in the VPS
+IntraPeriod1                  : 24          # Period of I-Frame ( -1 = only first)
+ConformanceMode1              : 1           # conformance mode
+QP1                           : 20
+LayerPTLIndex1                : 2
Index: /tags/SHM-9.0/cfg/per-sequence-svc/Kimono-2x.cfg
===================================================================
--- /tags/SHM-9.0/cfg/per-sequence-svc/Kimono-2x.cfg	(revision 1088)
+++ /tags/SHM-9.0/cfg/per-sequence-svc/Kimono-2x.cfg	(revision 1088)
@@ -0,0 +1,37 @@
+FrameSkip                     : 0           # Number of frames to be skipped in input
+FramesToBeEncoded             : 240         # Number of frames to be coded
+
+Level0                        : 4           # Level of the whole bitstream
+Level1                        : 3.1         # Level of the base layer
+Level2                        : 4           # Level of the enhancement layer
+
+#======== File I/O ===============
+InputFile0                    : Kimono1_960x540_24_zerophase_0.9pi.yuv
+FrameRate0                    : 24          # Frame Rate per second
+InputBitDepth0                : 8           # Input bitdepth for layer 0
+SourceWidth0                  : 960         # Input  frame width
+SourceHeight0                 : 540         # Input  frame height
+RepFormatIdx0                 : 0           # Index of corresponding rep_format() in the VPS
+IntraPeriod0                  : 24          # Period of I-Frame ( -1 = only first)
+ConformanceMode0              : 1           # conformance mode
+QP0                           : 22
+LayerPTLIndex0                : 1
+
+InputFile1                    : Kimono1_1920x1080_24.yuv
+FrameRate1                    : 24          # Frame Rate per second
+InputBitDepth1                : 8           # Input bitdepth for layer 1
+SourceWidth1                  : 1920        # Input  frame width
+SourceHeight1                 : 1080        # Input  frame height
+RepFormatIdx1                 : 1           # Index of corresponding rep_format() in the VPS
+IntraPeriod1                  : 24          # Period of I-Frame ( -1 = only first)
+ConformanceMode1              : 1           # conformance mode
+QP1                           : 20
+LayerPTLIndex1                : 2
+
+#============= Reference location offset parameters ==================
+NumRefLocationOffsets1         : 1        # Number of reference location offset parameters
+RefLocationOffsetLayerId1                : 0        # List of ref layer id (i-th entry for i-th ref loc offset parameters)
+ScaledRefLayerOffsetPresentFlag1 : 0        # List of scaled ref layer offset present flags
+RefRegionOffsetPresentFlag1      : 1        # List of ref region offset present flags
+RefRegionBottomOffset1           : 2        # List of ref region bottom offsets
+ResamplePhaseSetPresentFlag1     : 0        # List of resample phase set present flags
Index: /tags/SHM-9.0/cfg/per-sequence-svc/Kimono-SNR.cfg
===================================================================
--- /tags/SHM-9.0/cfg/per-sequence-svc/Kimono-SNR.cfg	(revision 1088)
+++ /tags/SHM-9.0/cfg/per-sequence-svc/Kimono-SNR.cfg	(revision 1088)
@@ -0,0 +1,29 @@
+FrameSkip                     : 0           # Number of frames to be skipped in input
+FramesToBeEncoded             : 240         # Number of frames to be coded
+
+Level0                        : 4           # Level of the whole bitstream
+Level1                        : 4           # Level of the base layer
+Level2                        : 4           # Level of the enhancement layer
+
+#======== File I/O ===============
+InputFile0                    : Kimono1_1920x1080_24.yuv
+FrameRate0                    : 24          # Frame Rate per second
+InputBitDepth0                : 8           # Input bitdepth for layer 0
+SourceWidth0                  : 1920        # Input  frame width
+SourceHeight0                 : 1080        # Input  frame height
+RepFormatIdx0                 : 0           # Index of corresponding rep_format() in the VPS
+IntraPeriod0                  : 24          # Period of I-Frame ( -1 = only first)
+ConformanceMode0              : 1           # conformance mode
+QP0                           : 22
+LayerPTLIndex0                : 1
+
+InputFile1                    : Kimono1_1920x1080_24.yuv
+FrameRate1                    : 24          # Frame Rate per second
+InputBitDepth1                : 8           # Input bitdepth for layer 1
+SourceWidth1                  : 1920        # Input  frame width
+SourceHeight1                 : 1080        # Input  frame height
+RepFormatIdx1                 : 0           # Index of corresponding rep_format() in the VPS
+IntraPeriod1                  : 24          # Period of I-Frame ( -1 = only first)
+ConformanceMode1              : 1           # conformance mode
+QP1                           : 20
+LayerPTLIndex1                : 2
Index: /tags/SHM-9.0/cfg/per-sequence-svc/ParkScene-1.5x.cfg
===================================================================
--- /tags/SHM-9.0/cfg/per-sequence-svc/ParkScene-1.5x.cfg	(revision 1088)
+++ /tags/SHM-9.0/cfg/per-sequence-svc/ParkScene-1.5x.cfg	(revision 1088)
@@ -0,0 +1,29 @@
+FrameSkip                     : 0           # Number of frames to be skipped in input
+FramesToBeEncoded             : 240         # Number of frames to be coded
+
+Level0                        : 4           # Level of the whole bitstream
+Level1                        : 3.1         # Level of the base layer
+Level2                        : 4           # Level of the enhancement layer
+
+#======== File I/O ===============
+InputFile0                    : ParkScene_1280x720_24_zerophase_0.9pi.yuv
+FrameRate0                    : 24          # Frame Rate per second
+InputBitDepth0                : 8           # Input bitdepth for layer 0
+SourceWidth0                  : 1280        # Input  frame width
+SourceHeight0                 : 720         # Input  frame height
+RepFormatIdx0                 : 0           # Index of corresponding rep_format() in the VPS
+IntraPeriod0                  : 24          # Period of I-Frame ( -1 = only first)
+ConformanceMode0              : 1           # conformance mode
+QP0                           : 22
+LayerPTLIndex0                : 1
+
+InputFile1                    : ParkScene_1920x1080_24.yuv
+FrameRate1                    : 24          # Frame Rate per second
+InputBitDepth1                : 8           # Input bitdepth for layer 1
+SourceWidth1                  : 1920        # Input  frame width
+SourceHeight1                 : 1080        # Input  frame height
+RepFormatIdx1                 : 1           # Index of corresponding rep_format() in the VPS
+IntraPeriod1                  : 24          # Period of I-Frame ( -1 = only first)
+ConformanceMode1              : 1           # conformance mode
+QP1                           : 20
+LayerPTLIndex1                : 2
Index: /tags/SHM-9.0/cfg/per-sequence-svc/ParkScene-2x.cfg
===================================================================
--- /tags/SHM-9.0/cfg/per-sequence-svc/ParkScene-2x.cfg	(revision 1088)
+++ /tags/SHM-9.0/cfg/per-sequence-svc/ParkScene-2x.cfg	(revision 1088)
@@ -0,0 +1,37 @@
+FrameSkip                     : 0           # Number of frames to be skipped in input
+FramesToBeEncoded             : 240         # Number of frames to be coded
+
+Level0                        : 4           # Level of the whole bitstream
+Level1                        : 3.1         # Level of the base layer
+Level2                        : 4           # Level of the enhancement layer
+
+#======== File I/O ===============
+InputFile0                    : ParkScene_960x540_24_zerophase_0.9pi.yuv
+FrameRate0                    : 24          # Frame Rate per second
+InputBitDepth0                : 8           # Input bitdepth for layer 0
+SourceWidth0                  : 960         # Input  frame width
+SourceHeight0                 : 540         # Input  frame height
+RepFormatIdx0                 : 0           # Index of corresponding rep_format() in the VPS
+IntraPeriod0                  : 24          # Period of I-Frame ( -1 = only first)
+ConformanceMode0              : 1           # conformance mode
+QP0                           : 22
+LayerPTLIndex0                : 1
+
+InputFile1                    : ParkScene_1920x1080_24.yuv
+FrameRate1                    : 24          # Frame Rate per second
+InputBitDepth1                : 8           # Input bitdepth for layer 1
+SourceWidth1                  : 1920        # Input  frame width
+SourceHeight1                 : 1080        # Input  frame height
+RepFormatIdx1                 : 1           # Index of corresponding rep_format() in the VPS
+IntraPeriod1                  : 24          # Period of I-Frame ( -1 = only first)
+ConformanceMode1              : 1           # conformance mode
+QP1                           : 20
+LayerPTLIndex1                : 2
+
+#============= Reference location offset parameters ==================
+NumRefLocationOffsets1         : 1        # Number of reference location offset parameters
+RefLocationOffsetLayerId1                : 0        # List of ref layer id (i-th entry for i-th ref loc offset parameters)
+ScaledRefLayerOffsetPresentFlag1 : 0        # List of scaled ref layer offset present flags
+RefRegionOffsetPresentFlag1      : 1        # List of ref region offset present flags
+RefRegionBottomOffset1           : 2        # List of ref region bottom offsets
+ResamplePhaseSetPresentFlag1     : 0        # List of resample phase set present flags
Index: /tags/SHM-9.0/cfg/per-sequence-svc/ParkScene-SNR.cfg
===================================================================
--- /tags/SHM-9.0/cfg/per-sequence-svc/ParkScene-SNR.cfg	(revision 1088)
+++ /tags/SHM-9.0/cfg/per-sequence-svc/ParkScene-SNR.cfg	(revision 1088)
@@ -0,0 +1,29 @@
+FrameSkip                     : 0           # Number of frames to be skipped in input
+FramesToBeEncoded             : 240         # Number of frames to be coded
+
+Level0                        : 4           # Level of the whole bitstream
+Level1                        : 4           # Level of the base layer
+Level2                        : 4           # Level of the enhancement layer
+
+#======== File I/O ===============
+InputFile0                    : ParkScene_1920x1080_24.yuv
+FrameRate0                    : 24          # Frame Rate per second
+InputBitDepth0                : 8           # Input bitdepth for layer 0
+SourceWidth0                  : 1920        # Input  frame width
+SourceHeight0                 : 1080        # Input  frame height
+RepFormatIdx0                 : 0           # Index of corresponding rep_format() in the VPS
+IntraPeriod0                  : 24          # Period of I-Frame ( -1 = only first)
+ConformanceMode0              : 1           # conformance mode
+QP0                           : 22
+LayerPTLIndex0                : 1
+
+InputFile1                    : ParkScene_1920x1080_24.yuv
+FrameRate1                    : 24          # Frame Rate per second
+InputBitDepth1                : 8           # Input bitdepth for layer 1
+SourceWidth1                  : 1920        # Input  frame width
+SourceHeight1                 : 1080        # Input  frame height
+RepFormatIdx1                 : 0           # Index of corresponding rep_format() in the VPS
+IntraPeriod1                  : 24          # Period of I-Frame ( -1 = only first)
+ConformanceMode1              : 1           # conformance mode
+QP1                           : 20
+LayerPTLIndex1                : 2
Index: /tags/SHM-9.0/cfg/per-sequence-svc/PeopleOnStreet-2x.cfg
===================================================================
--- /tags/SHM-9.0/cfg/per-sequence-svc/PeopleOnStreet-2x.cfg	(revision 1088)
+++ /tags/SHM-9.0/cfg/per-sequence-svc/PeopleOnStreet-2x.cfg	(revision 1088)
@@ -0,0 +1,29 @@
+FrameSkip                     : 0           # Number of frames to be skipped in input
+FramesToBeEncoded             : 150         # Number of frames to be coded
+
+Level0                        : 5           # Level of the whole bitstream
+Level1                        : 4           # Level of the base layer
+Level2                        : 5           # Level of the enhancement layer
+
+#======== File I/O ===============
+InputFile0                    : PeopleOnStreet_1280x800_30_crop_zerophase_0.9pi.yuv
+FrameRate0                    : 30          # Frame Rate per second
+InputBitDepth0                : 8           # Input bitdepth for layer 0
+SourceWidth0                  : 1280        # Input  frame width
+SourceHeight0                 : 800         # Input  frame height
+RepFormatIdx0                 : 0           # Index of corresponding rep_format() in the VPS
+IntraPeriod0                  : 32          # Period of I-Frame ( -1 = only first)
+ConformanceMode0              : 1           # conformance mode
+QP0                           : 22
+LayerPTLIndex0                : 1
+
+InputFile1                    : PeopleOnStreet_2560x1600_30_crop.yuv
+FrameRate1                    : 30          # Frame Rate per second
+InputBitDepth1                : 8           # Input bitdepth for layer 1
+SourceWidth1                  : 2560        # Input  frame width
+SourceHeight1                 : 1600        # Input  frame height
+RepFormatIdx1                 : 1           # Index of corresponding rep_format() in the VPS
+IntraPeriod1                  : 32          # Period of I-Frame ( -1 = only first)
+ConformanceMode1              : 1           # conformance mode
+QP1                           : 20
+LayerPTLIndex1                : 2
Index: /tags/SHM-9.0/cfg/per-sequence-svc/PeopleOnStreet-SNR.cfg
===================================================================
--- /tags/SHM-9.0/cfg/per-sequence-svc/PeopleOnStreet-SNR.cfg	(revision 1088)
+++ /tags/SHM-9.0/cfg/per-sequence-svc/PeopleOnStreet-SNR.cfg	(revision 1088)
@@ -0,0 +1,29 @@
+FrameSkip                     : 0           # Number of frames to be skipped in input
+FramesToBeEncoded             : 150         # Number of frames to be coded
+
+Level0                        : 5           # Level of the whole bitstream
+Level1                        : 5           # Level of the base layer
+Level2                        : 5           # Level of the enhancement layer
+
+#======== File I/O ===============
+InputFile0                    : PeopleOnStreet_2560x1600_30_crop.yuv
+FrameRate0                    : 30          # Frame Rate per second
+InputBitDepth0                : 8           # Input bitdepth for layer 0
+SourceWidth0                  : 2560        # Input  frame width
+SourceHeight0                 : 1600        # Input  frame height
+RepFormatIdx0                 : 0           # Index of corresponding rep_format() in the VPS
+IntraPeriod0                  : 32          # Period of I-Frame ( -1 = only first)
+ConformanceMode0              : 1           # conformance mode
+QP0                           : 22
+LayerPTLIndex0                : 1
+
+InputFile1                    : PeopleOnStreet_2560x1600_30_crop.yuv
+FrameRate1                    : 30          # Frame Rate per second
+InputBitDepth1                : 8           # Input bitdepth for layer 1
+SourceWidth1                  : 2560        # Input  frame width
+SourceHeight1                 : 1600        # Input  frame height
+RepFormatIdx1                 : 0           # Index of corresponding rep_format() in the VPS
+IntraPeriod1                  : 32          # Period of I-Frame ( -1 = only first)
+ConformanceMode1              : 1           # conformance mode
+QP1                           : 20
+LayerPTLIndex1                : 2
Index: /tags/SHM-9.0/cfg/per-sequence-svc/Traffic-2x.cfg
===================================================================
--- /tags/SHM-9.0/cfg/per-sequence-svc/Traffic-2x.cfg	(revision 1088)
+++ /tags/SHM-9.0/cfg/per-sequence-svc/Traffic-2x.cfg	(revision 1088)
@@ -0,0 +1,29 @@
+FrameSkip                     : 0           # Number of frames to be skipped in input
+FramesToBeEncoded             : 150         # Number of frames to be coded
+
+Level0                        : 5           # Level of the whole bitstream
+Level1                        : 4           # Level of the base layer
+Level2                        : 5           # Level of the enhancement layer
+
+#======== File I/O ===============
+InputFile0                    : Traffic_1280x800_30_crop_zerophase_0.9pi.yuv
+FrameRate0                    : 30          # Frame Rate per second
+InputBitDepth0                : 8           # Input bitdepth for layer 0
+SourceWidth0                  : 1280        # Input  frame width
+SourceHeight0                 : 800         # Input  frame height
+RepFormatIdx0                 : 0           # Index of corresponding rep_format() in the VPS
+IntraPeriod0                  : 32          # Period of I-Frame ( -1 = only first)
+ConformanceMode0              : 1           # conformance mode
+QP0                           : 22
+LayerPTLIndex0                : 1
+
+InputFile1                    : Traffic_2560x1600_30_crop.yuv
+FrameRate1                    : 30          # Frame Rate per second
+InputBitDepth1                : 8           # Input bitdepth for layer 1
+SourceWidth1                  : 2560        # Input  frame width
+SourceHeight1                 : 1600        # Input  frame height
+RepFormatIdx1                 : 1           # Index of corresponding rep_format() in the VPS
+IntraPeriod1                  : 32          # Period of I-Frame ( -1 = only first)
+ConformanceMode1              : 1           # conformance mode
+QP1                           : 20
+LayerPTLIndex1                : 2
Index: /tags/SHM-9.0/cfg/per-sequence-svc/Traffic-SNR.cfg
===================================================================
--- /tags/SHM-9.0/cfg/per-sequence-svc/Traffic-SNR.cfg	(revision 1088)
+++ /tags/SHM-9.0/cfg/per-sequence-svc/Traffic-SNR.cfg	(revision 1088)
@@ -0,0 +1,29 @@
+FrameSkip                     : 0           # Number of frames to be skipped in input
+FramesToBeEncoded             : 150         # Number of frames to be coded
+
+Level0                        : 5           # Level of the whole bitstream
+Level1                        : 5           # Level of the base layer
+Level2                        : 5           # Level of the enhancement layer
+
+#======== File I/O ===============
+InputFile0                    : Traffic_2560x1600_30_crop.yuv
+FrameRate0                    : 30          # Frame Rate per second
+InputBitDepth0                : 8           # Input bitdepth for layer 0
+SourceWidth0                  : 2560        # Input  frame width
+SourceHeight0                 : 1600        # Input  frame height
+RepFormatIdx0                 : 0           # Index of corresponding rep_format() in the VPS
+IntraPeriod0                  : 32          # Period of I-Frame ( -1 = only first)
+ConformanceMode0              : 1           # conformance mode
+QP0                           : 22
+LayerPTLIndex0                : 1
+
+InputFile1                    : Traffic_2560x1600_30_crop.yuv
+FrameRate1                    : 30          # Frame Rate per second
+InputBitDepth1                : 8           # Input bitdepth for layer 1
+SourceWidth1                  : 2560        # Input  frame width
+SourceHeight1                 : 1600        # Input  frame height
+RepFormatIdx1                 : 0           # Index of corresponding rep_format() in the VPS
+IntraPeriod1                  : 32          # Period of I-Frame ( -1 = only first)
+ConformanceMode1              : 1           # conformance mode
+QP1                           : 20
+LayerPTLIndex1                : 2
Index: /tags/SHM-9.0/compat/msvc/stdint.h
===================================================================
--- /tags/SHM-9.0/compat/msvc/stdint.h	(revision 1088)
+++ /tags/SHM-9.0/compat/msvc/stdint.h	(revision 1088)
@@ -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: /tags/SHM-9.0/doc/readme.txt
===================================================================
--- /tags/SHM-9.0/doc/readme.txt	(revision 1088)
+++ /tags/SHM-9.0/doc/readme.txt	(revision 1088)
@@ -0,0 +1,7 @@
+TAppEncoder -c cfg/encoder_randomaccess_main.cfg -c cfg/per-sequence-svc/BasketballDrive-2x.cfg -c cfg/layers.cfg -q0 22 -q1 22 -b str/BasketballDrive.bin -o0 rec/BasketballDrive_l0_rec.yuv -o1 rec/BasketballDrive_l1_rec.yuv
+
+TAppDecoder -b str/BasketballDrive.bin -ls 2 -o0 rec/BasketballDrive_l0_drec.yuv -o1 rec/BasketballDrive_l1_drec.yuv
+
+For AVC base layer tests the following should be used:
+ cfg/layers_avcbase.cfg configuration file
+ -ibl <BLrecon.yuv> option to specify the reconstructed base layer input
Index: /tags/SHM-9.0/source/App/TAppDecoder/TAppDecCfg.cpp
===================================================================
--- /tags/SHM-9.0/source/App/TAppDecoder/TAppDecCfg.cpp	(revision 1088)
+++ /tags/SHM-9.0/source/App/TAppDecoder/TAppDecCfg.cpp	(revision 1088)
@@ -0,0 +1,292 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TAppDecCfg.cpp
+    \brief    Decoder configuration class
+*/
+
+#include <cstdio>
+#include <cstring>
+#include <string>
+#include "TAppDecCfg.h"
+#include "TAppCommon/program_options_lite.h"
+#include "TLibCommon/TComChromaFormat.h"
+#if SVC_EXTENSION
+#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;
+#if SVC_EXTENSION
+  string cfg_ReconFile [MAX_LAYERS];
+  Int layerNum, targetLayerId;
+#if OUTPUT_LAYER_SET_INDEX
+  Int olsIdx;
+#endif
+#if CONFORMANCE_BITSTREAM_MODE
+  string cfg_confPrefix;
+#endif
+#if AVC_BASE
+  string cfg_BLReconFile;
+#endif
+#else
+  string cfg_ReconFile;
+#endif
+
+  string cfg_TargetDecLayerIdSetFile;
+  string outputColourSpaceConvert;
+
+  po::Options opts;
+  opts.addOptions()
+
+
+  ("help",                      do_help,                               false,      "this help text")
+  ("BitstreamFile,b",           cfg_BitstreamFile,                     string(""), "bitstream input file name")
+#if SVC_EXTENSION
+  ("ReconFileL%d,-o%d",   cfg_ReconFile,   string(""), MAX_LAYERS, "Layer %d reconstructed YUV output file name\n"
+                                                     "YUV writing is skipped if omitted")
+#if AVC_BASE
+  ("BLReconFile,-ibl",    cfg_BLReconFile,  string(""), "BL reconstructed YUV input file name")
+#if !REPN_FORMAT_IN_VPS
+  ("BLSourceWidth,-wdt",    m_iBLSourceWidth,        0, "BL source picture width")
+  ("BLSourceHeight,-hgt",   m_iBLSourceHeight,       0, "BL source picture height")
+#endif
+#endif
+#if FIX_CONF_MODE
+  ("TargetLayerId,-lid", targetLayerId, -1, "Target layer id")
+  ("LayerNum,-ls", layerNum, MAX_NUM_LAYER_IDS, "Target layer id") // Legacy option
+#else
+  ("LayerNum,-ls", nLayerNum, 1, "Number of layers to be decoded.")
+#endif
+#if OUTPUT_LAYER_SET_INDEX
+  ("OutpuLayerSetIdx,-olsidx", olsIdx, -1, "Index of output layer set to be decoded.")
+#endif
+#if CONFORMANCE_BITSTREAM_MODE
+  ("ConformanceBitstremMode,-confMode", m_confModeFlag, false, "Enable generation of conformance bitstream metadata; True: Generate metadata, False: No metadata generated")
+  ("ConformanceMetadataPrefix,-confPrefix", cfg_confPrefix, string(""), "Prefix for the file name of the conformance data. Default name - 'decodedBitstream'")
+#endif
+#else
+  ("ReconFile,o",               cfg_ReconFile,                         string(""), "reconstructed YUV output file name\n"
+                                                                                   "YUV writing is skipped if omitted")
+#endif
+
+  ("SkipFrames,s",              m_iSkipFrame,                          0,          "number of frames to skip before random access")
+  ("OutputBitDepth,d",          m_outputBitDepth[CHANNEL_TYPE_LUMA],   0,          "bit depth of YUV output luma component (default: use 0 for native depth)")
+  ("OutputBitDepthC,d",         m_outputBitDepth[CHANNEL_TYPE_CHROMA], 0,          "bit depth of YUV output chroma component (default: use 0 for native depth)")
+  ("OutputColourSpaceConvert",  outputColourSpaceConvert,              string(""), "Colour space conversion to apply to input 444 video. Permitted values are (empty string=UNCHANGED) " + getListOfColourSpaceConverts(false))
+  ("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")
+  ("SEINoDisplay",              m_decodedNoDisplaySEIEnabled,          true,       "Control handling of decoded no display SEI messages")
+  ("TarDecLayerIdSetFile,l",    cfg_TargetDecLayerIdSetFile,           string(""), "targetDecLayerIdSet file name. The file should include white space separated LayerId values to be decoded. Omitting the option or a value of -1 in the file decodes all layers.")
+  ("RespectDefDispWindow,w",    m_respectDefDispWindow,                0,          "Only output content inside the default display window\n")
+#if O0043_BEST_EFFORT_DECODING
+  ("ForceDecodeBitDepth",       m_forceDecodeBitDepth,                 0U,         "Force the decoder to operate at a particular bit-depth (best effort decoding)")
+#endif
+#if Q0074_COLOUR_REMAPPING_SEI
+  ("SEIColourRemappingInfo", m_colourRemapSEIEnabled, false, "Control handling of Colour Remapping Information SEI messages\n"
+                                              "\t1: apply colour remapping on decoded pictures if available in the bitstream\n"
+                                              "\t0: ignore SEI message")
+#endif
+  ;
+
+  po::setDefaults(opts);
+  const list<const Char*>& argv_unhandled = po::scanArgv(opts, argc, (const Char**) argv);
+
+  for (list<const Char*>::const_iterator it = argv_unhandled.begin(); it != argv_unhandled.end(); it++)
+  {
+    fprintf(stderr, "Unhandled argument ignored: `%s'\n", *it);
+  }
+
+  if (argc == 1 || do_help)
+  {
+    po::doHelp(cout, opts);
+    return false;
+  }
+
+  m_outputColourSpaceConvert = stringToInputColourSpaceConvert(outputColourSpaceConvert, false);
+  if (m_outputColourSpaceConvert>=NUMBER_INPUT_COLOUR_SPACE_CONVERSIONS)
+  {
+    fprintf(stderr, "Bad output colour space conversion string\n");
+    return false;
+  }
+
+  /* convert std::string to c string for compatability */
+  m_pchBitstreamFile = cfg_BitstreamFile.empty() ? NULL : strdup(cfg_BitstreamFile.c_str());
+#if SVC_EXTENSION
+  if( targetLayerId < 0 )
+  {
+    targetLayerId = layerNum - 1;
+  }
+
+  assert( targetLayerId >= 0 );
+#if !FIX_CONF_MODE
+  assert( m_tgtLayerId < MAX_LAYERS );  // If this is wrong, it should be caught by asserts in other locations.
+#endif
+#if O0137_MAX_LAYERID
+  assert( targetLayerId < MAX_NUM_LAYER_IDS );
+#endif
+#if OUTPUT_LAYER_SET_INDEX
+#if CONFORMANCE_BITSTREAM_MODE
+  if( m_confModeFlag )
+  {
+    assert( olsIdx != -1 ); // In the conformance mode, target output layer set index is to be explicitly specified.
+
+    if( cfg_confPrefix.empty() )
+    {
+      m_confPrefix = string("decodedBitstream");
+    }
+    else
+    {
+      m_confPrefix = cfg_confPrefix;
+    }
+      // Open metadata file and write
+    char fileNameSuffix[255];
+    sprintf(fileNameSuffix, "%s-OLS%d.opl", m_confPrefix.c_str(), olsIdx);  // olsIdx is the target output layer set index.
+    m_metadataFileName = string(fileNameSuffix);
+    m_metadataFileRefresh = true;
+
+    // Decoded layer YUV files
+#if FIX_CONF_MODE
+    for(Int layer= 0; layer < MAX_VPS_LAYER_IDX_PLUS1; layer++ )
+#else
+    for(UInt layer=0; layer<= m_tgtLayerId; layer++)
+#endif
+    {
+      sprintf(fileNameSuffix, "%s-L%d.yuv", m_confPrefix.c_str(), layer);  // olsIdx is the target output layer set index.
+      m_decodedYuvLayerFileName[layer] = std::string( fileNameSuffix );
+      m_decodedYuvLayerRefresh[layer] = true;
+    }
+  }
+#endif
+  m_commonDecoderParams.setTargetOutputLayerSetIdx( olsIdx );
+  m_commonDecoderParams.setTargetLayerId( targetLayerId );
+#endif
+#if FIX_CONF_MODE
+  for(Int layer = 0; layer < MAX_VPS_LAYER_IDX_PLUS1; layer++ )
+  {
+#else
+  for(UInt layer=0; layer<= m_tgtLayerId; layer++)
+  {
+    assert( layer < MAX_LAYERS );
+#endif
+    m_pchReconFile[layer] = cfg_ReconFile[layer].empty() ? NULL : strdup(cfg_ReconFile[layer].c_str());
+  }
+#if AVC_BASE
+  m_pchBLReconFile = cfg_BLReconFile.empty() ? NULL : strdup(cfg_BLReconFile.c_str());
+#endif
+#else
+  m_pchReconFile = cfg_ReconFile.empty() ? NULL : strdup(cfg_ReconFile.c_str());
+#endif
+
+  if (!m_pchBitstreamFile)
+  {
+    fprintf(stderr, "No input file specified, 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 within 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 !R0235_SMALLEST_LAYER_ID  // LayerId=0 is not required anymore in some cases
+      if ( m_targetDecLayerIdSet.size() > 0 && !isLayerIdZeroIncluded )
+      {
+        fprintf(stderr, "TargetDecLayerIdSet must contain LayerId=0, aborting" );
+        return false;
+      }
+#endif
+    }
+    else
+    {
+      fprintf(stderr, "File %s could not be opened. Using all LayerIds as default.\n", cfg_TargetDecLayerIdSetFile.c_str() );
+    }
+#if OUTPUT_LAYER_SET_INDEX  
+    this->getCommonDecoderParams()->setTargetDecLayerIdSet( &m_targetDecLayerIdSet );
+#endif
+  }
+
+  return true;
+}
+
+//! \}
Index: /tags/SHM-9.0/source/App/TAppDecoder/TAppDecCfg.h
===================================================================
--- /tags/SHM-9.0/source/App/TAppDecoder/TAppDecCfg.h	(revision 1088)
+++ /tags/SHM-9.0/source/App/TAppDecoder/TAppDecCfg.h	(revision 1088)
@@ -0,0 +1,156 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TAppDecCfg.h
+    \brief    Decoder configuration class (header)
+*/
+
+#ifndef __TAPPDECCFG__
+#define __TAPPDECCFG__
+
+#if _MSC_VER > 1000
+#pragma once
+#endif // _MSC_VER > 1000
+
+#include "TLibCommon/CommonDef.h"
+#include <vector>
+
+//! \ingroup TAppDecoder
+//! \{
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// Decoder configuration class
+class TAppDecCfg
+{
+protected:
+  Char*         m_pchBitstreamFile;                     ///< input bitstream file name
+#if SVC_EXTENSION
+  Char*         m_pchReconFile [MAX_LAYERS];          ///< output reconstruction file name
+#else
+  Char*         m_pchReconFile;                         ///< output reconstruction file name
+#endif
+  Int           m_iSkipFrame;                           ///< counter for frames prior to the random access point to skip
+  Int           m_outputBitDepth[MAX_NUM_CHANNEL_TYPE]; ///< bit depth used for writing output
+  InputColourSpaceConversion m_outputColourSpaceConvert;
+
+  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
+  Bool          m_decodedNoDisplaySEIEnabled;         ///< Enable(true)/disable(false) writing only pictures that get displayed based on the no display SEI message
+#if Q0074_COLOUR_REMAPPING_SEI
+  Bool          m_colourRemapSEIEnabled;              ///< Enable the Colour Remapping Information SEI message if available (remapping decoded pictures)
+#endif
+
+#if SVC_EXTENSION
+#if AVC_BASE
+  Char*         m_pchBLReconFile;                     ///< input BL reconstruction file name
+#if !REPN_FORMAT_IN_VPS
+  Int           m_iBLSourceWidth;
+  Int           m_iBLSourceHeight;
+#endif
+#endif
+#endif
+
+  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 O0043_BEST_EFFORT_DECODING
+  UInt          m_forceDecodeBitDepth;                ///< if non-zero, force the bit depth at the decoder (best effort decoding)
+#endif
+  std::string   m_outputDecodedSEIMessagesFilename;   ///< filename to output decoded SEI messages to. If '-', then use stdout. If empty, do not output details.
+#if OUTPUT_LAYER_SET_INDEX
+  CommonDecoderParams             m_commonDecoderParams;
+#endif
+#if CONFORMANCE_BITSTREAM_MODE
+  Bool          m_confModeFlag;
+  std::string   m_confPrefix;
+  std::string   m_metadataFileName;
+  Bool          m_metadataFileRefresh;
+  std::string   m_decodedYuvLayerFileName[63];
+  Bool          m_decodedYuvLayerRefresh[63];
+#endif
+
+public:
+  TAppDecCfg()
+  : m_pchBitstreamFile(NULL)
+#if !SVC_EXTENSION
+  , m_pchReconFile(NULL)
+#endif
+  , m_iSkipFrame(0)
+  , m_outputColourSpaceConvert(IPCOLOURSPACE_UNCHANGED)
+  , m_iMaxTemporalLayer(-1)
+  , m_decodedPictureHashSEIEnabled(0)
+  , m_decodedNoDisplaySEIEnabled(false)
+#if Q0074_COLOUR_REMAPPING_SEI
+  , m_colourRemapSEIEnabled(0)
+#endif
+#if SVC_EXTENSION
+#if AVC_BASE && !REPN_FORMAT_IN_VPS
+  , m_iBLSourceWidth(0)
+  , m_iBLSourceHeight(0)
+#endif
+#endif
+  , m_respectDefDispWindow(0)
+#if O0043_BEST_EFFORT_DECODING
+  , m_forceDecodeBitDepth(0)
+#endif
+  {
+    for (UInt channelTypeIndex = 0; channelTypeIndex < MAX_NUM_CHANNEL_TYPE; channelTypeIndex++)
+      m_outputBitDepth[channelTypeIndex] = 0;
+  }
+
+  virtual ~TAppDecCfg() {}
+
+  Bool  parseCfg        ( Int argc, Char* argv[] );   ///< initialize option class from configuration
+#if OUTPUT_LAYER_SET_INDEX
+  CommonDecoderParams* getCommonDecoderParams() {return &m_commonDecoderParams;}
+#endif
+#if CONFORMANCE_BITSTREAM_MODE
+  Bool const getConfModeFlag() { return m_confModeFlag;  }
+  std::string const getConfPrefix() { return m_confPrefix;}
+  std::string const getMetadataFileName() { return m_metadataFileName; }
+  Bool const getMetadataFileRefresh() {return m_metadataFileRefresh; }
+  Void setMetadataFileRefresh(Bool const x) {m_metadataFileRefresh = x; }
+  Void setDecodedYuvLayerFileName(Int layerId, std::string x) {  m_decodedYuvLayerFileName[layerId] = x; }
+  std::string const getDecodedYuvLayerFileName(Int layerId) {  return m_decodedYuvLayerFileName[layerId]; }
+  Bool const getDecodedYuvLayerRefresh(Int const layerId) {return m_decodedYuvLayerRefresh[layerId]; }
+  Void setDecodedYuvLayerRefresh(Int const layerId, Bool const x) {m_decodedYuvLayerRefresh[layerId] = x; }
+#endif
+};
+
+//! \}
+
+#endif
+
+
Index: /tags/SHM-9.0/source/App/TAppDecoder/TAppDecTop.cpp
===================================================================
--- /tags/SHM-9.0/source/App/TAppDecoder/TAppDecTop.cpp	(revision 1088)
+++ /tags/SHM-9.0/source/App/TAppDecoder/TAppDecTop.cpp	(revision 1088)
@@ -0,0 +1,1862 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TAppDecTop.cpp
+    \brief    Decoder application class
+*/
+
+#include <list>
+#include <vector>
+#include <stdio.h>
+#include <fcntl.h>
+#include <assert.h>
+
+#include "TAppDecTop.h"
+#include "TLibDecoder/AnnexBread.h"
+#include "TLibDecoder/NALread.h"
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+#include "TLibCommon/TComCodingStatistics.h"
+#endif
+#if CONFORMANCE_BITSTREAM_MODE
+#include "TLibCommon/TComPicYuv.h"
+#include "libmd5/MD5.h"
+#endif
+
+//! \ingroup TAppDecoder
+//! \{
+
+// ====================================================================================================================
+// Constructor / destructor / initialization / destroy
+// ====================================================================================================================
+
+#if SVC_EXTENSION
+TAppDecTop::TAppDecTop()
+{
+  for(UInt layer=0; layer < MAX_LAYERS; layer++)
+  {
+    m_aiPOCLastDisplay[layer]  = -MAX_INT;
+    m_apcTDecTop[layer] = &m_acTDecTop[layer];
+  }
+}
+#else
+TAppDecTop::TAppDecTop()
+: m_iPOCLastDisplay(-MAX_INT)
+{
+}
+#endif
+
+Void TAppDecTop::create()
+{
+}
+
+Void TAppDecTop::destroy()
+{
+  if (m_pchBitstreamFile)
+  {
+    free (m_pchBitstreamFile);
+    m_pchBitstreamFile = NULL;
+  }
+#if SVC_EXTENSION
+#if FIX_CONF_MODE
+  for(Int i = 0; i < MAX_VPS_LAYER_IDX_PLUS1; i++ )
+#else
+  for( Int i = 0; i <= m_tgtLayerId; i++ )
+#endif
+  {
+    if( m_pchReconFile[i] )
+    {
+      free ( m_pchReconFile[i] );
+      m_pchReconFile[i] = NULL;
+    }
+  }
+#if AVC_BASE
+  if( m_pchBLReconFile )
+  {
+    free ( m_pchBLReconFile );
+    m_pchBLReconFile = NULL;
+  }
+#endif
+#else
+  if (m_pchReconFile)
+  {
+    free (m_pchReconFile);
+    m_pchReconFile = 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
+ .
+ */
+#if SVC_EXTENSION
+Void TAppDecTop::decode()
+{
+  Int                poc;
+  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);
+  }
+
+  InputByteStream bytestream(bitstreamFile);
+
+  if (!m_outputDecodedSEIMessagesFilename.empty() && m_outputDecodedSEIMessagesFilename!="-")
+  {
+    m_seiMessageFileStream.open(m_outputDecodedSEIMessagesFilename.c_str(), std::ios::out);
+    if (!m_seiMessageFileStream.is_open() || !m_seiMessageFileStream.good())
+    {
+      fprintf(stderr, "\nUnable to open file `%s' for writing decoded SEI messages\n", m_outputDecodedSEIMessagesFilename.c_str());
+      exit(EXIT_FAILURE);
+    }
+  }
+
+  // create & initialize internal classes
+  xCreateDecLib();
+  xInitDecLib  ();  
+
+  // main decoder loop
+  Bool openedReconFile[MAX_LAYERS]; // reconstruction file not yet opened. (must be performed after SPS is seen)
+  Bool loopFiltered[MAX_LAYERS];
+  memset( loopFiltered, false, sizeof( loopFiltered ) );
+
+#if FIX_CONF_MODE
+  for(UInt layer = 0; layer < MAX_VPS_LAYER_IDX_PLUS1; layer++)
+#else
+  for(UInt layer=0; layer<=m_tgtLayerId; layer++)
+#endif
+  {
+    openedReconFile[layer] = false;
+    m_aiPOCLastDisplay[layer] += m_iSkipFrame;      // set the last displayed POC correctly for skip forward.
+  }
+
+  UInt curLayerId = 0;     // current layer to be reconstructed
+
+#if AVC_BASE
+  TComPic pcBLPic;
+  fstream streamYUV;
+  if( m_pchBLReconFile )
+  {
+    streamYUV.open( m_pchBLReconFile, fstream::in | fstream::binary );
+  }
+  TComList<TComPic*> *cListPic = m_acTDecTop[0].getListPic();
+  m_acTDecTop[0].setBLReconFile( &streamYUV );
+  pcBLPic.setLayerId( 0 );
+  cListPic->pushBack( &pcBLPic );
+#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. */
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+    TComCodingStatistics::TComCodingStatisticsData backupStats(TComCodingStatistics::GetStatistics());
+    streampos location = bitstreamFile.tellg() - streampos(bytestream.GetNumBufferedBytes());
+#else
+    streampos location = bitstreamFile.tellg();
+#endif
+    AnnexBStats stats = AnnexBStats();
+
+    vector<uint8_t> nalUnit;
+    InputNALUnit nalu;
+    byteStreamNALUnit(bytestream, nalUnit, stats);
+
+    // call actual decoding function
+    Bool bNewPicture = false;
+    Bool bNewPOC = false;
+
+    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( (m_iMaxTemporalLayer >= 0 && nalu.m_temporalId > m_iMaxTemporalLayer) || !isNaluWithinTargetDecLayerIdSet(&nalu)  ||
+#if FIX_CONF_MODE
+        (nalu.m_layerId > m_commonDecoderParams.getTargetLayerId()) )
+#else
+        (nalu.m_layerId > m_tgtLayerId) )
+#endif
+      {
+        bNewPicture = false;
+      }
+      else
+      {
+        bNewPicture = m_acTDecTop[nalu.m_layerId].decode(nalu, m_iSkipFrame, m_aiPOCLastDisplay[nalu.m_layerId], curLayerId, bNewPOC);
+#if POC_RESET_IDC_DECODER
+        if ( (bNewPicture && m_acTDecTop[nalu.m_layerId].getParseIdc() == 3) || (m_acTDecTop[nalu.m_layerId].getParseIdc() == 0) )
+#else
+        if (bNewPicture)
+#endif
+        {
+          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) */
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+          bitstreamFile.seekg(location);
+          bytestream.reset();
+          TComCodingStatistics::SetStatistics(backupStats);
+#else
+          bitstreamFile.seekg(location-streamoff(3));
+          bytestream.reset();
+#endif
+        }
+#if POC_RESET_IDC_DECODER
+        else if(m_acTDecTop[nalu.m_layerId].getParseIdc() == 1) 
+        {
+          bitstreamFile.clear();
+          // This is before third parse of the NAL unit, and 
+          // location points to correct beginning of the NALU
+          bitstreamFile.seekg(location);
+          bytestream.reset();
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+          TComCodingStatistics::SetStatistics(backupStats);
+#endif
+        }
+#endif
+      }
+    }
+
+#if POC_RESET_IDC_DECODER
+    if ( ( (bNewPicture && m_acTDecTop[nalu.m_layerId].getParseIdc() == 3) || m_acTDecTop[nalu.m_layerId].getParseIdc() == 0 || !bitstreamFile || nalu.m_nalUnitType == NAL_UNIT_EOS ) && 
+        !m_acTDecTop[nalu.m_layerId].getFirstSliceInSequence() )
+#else
+    if ( (bNewPicture || !bitstreamFile || nalu.m_nalUnitType == NAL_UNIT_EOS) &&
+        !m_acTDecTop[nalu.m_layerId].getFirstSliceInSequence() )
+#endif
+    {
+#if O0194_DIFFERENT_BITDEPTH_EL_BL
+      //Bug fix: The bit depth was not set correctly for each layer when doing DBF
+      g_bitDepth[CHANNEL_TYPE_LUMA]   = g_bitDepthLayer[CHANNEL_TYPE_LUMA][curLayerId];
+      g_bitDepth[CHANNEL_TYPE_CHROMA] = g_bitDepthLayer[CHANNEL_TYPE_CHROMA][curLayerId];
+#endif
+      if (!loopFiltered[curLayerId] || bitstreamFile)
+      {
+        m_acTDecTop[curLayerId].executeLoopFilters(poc, pcListPic);
+      }
+      loopFiltered[curLayerId] = (nalu.m_nalUnitType == NAL_UNIT_EOS);
+#if EARLY_REF_PIC_MARKING
+      m_acTDecTop[curLayerId].earlyPicMarking(m_iMaxTemporalLayer, m_targetDecLayerIdSet);
+#endif
+      if (nalu.m_nalUnitType == NAL_UNIT_EOS)
+      {
+        m_acTDecTop[nalu.m_layerId].setFirstSliceInSequence(true);
+      }
+    }
+    else if ( (bNewPicture || !bitstreamFile || nalu.m_nalUnitType == NAL_UNIT_EOS ) &&
+              m_acTDecTop[nalu.m_layerId].getFirstSliceInSequence () ) 
+    {
+      m_acTDecTop[nalu.m_layerId].setFirstSliceInPicture (true);
+    }
+
+#if POC_RESET_IDC_DECODER
+    if( bNewPicture && m_acTDecTop[nalu.m_layerId].getParseIdc() == 0 )
+    {
+      outputAllPictures( nalu.m_layerId, true );
+    }
+#endif
+
+    if( pcListPic )
+    {
+      if ( m_pchReconFile[curLayerId] && !openedReconFile[curLayerId] )
+      {
+        for (UInt channelType = 0; channelType < MAX_NUM_CHANNEL_TYPE; channelType++)
+        {
+          if (m_outputBitDepth[channelType] == 0) m_outputBitDepth[channelType] = g_bitDepth[channelType];
+        }
+        m_acTVideoIOYuvReconFile[curLayerId].open( m_pchReconFile[curLayerId], true, m_outputBitDepth, m_outputBitDepth, g_bitDepth ); // write mode
+
+        openedReconFile[curLayerId] = true;
+      }
+#if ALIGNED_BUMPING
+      Bool outputPicturesFlag = true;  
+#if NO_OUTPUT_OF_PRIOR_PICS
+      if( m_acTDecTop[nalu.m_layerId].getNoOutputPriorPicsFlag() )
+      {
+        outputPicturesFlag = false;
+      }
+#endif
+
+      if (nalu.m_nalUnitType == NAL_UNIT_EOS) // End of sequence
+      {
+        flushAllPictures( nalu.m_layerId, outputPicturesFlag );       
+      }
+
+#if POC_RESET_IDC_DECODER
+      if( bNewPicture && m_acTDecTop[nalu.m_layerId].getParseIdc() != 0 )
+      // New picture, slice header parsed but picture not decoded
+#else
+      if( bNewPicture ) // New picture, slice header parsed but picture not decoded
+#endif
+      {
+#if NO_OUTPUT_OF_PRIOR_PICS
+        if( 
+#else
+        if ( bNewPOC &&
+#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 ) )
+        {
+          flushAllPictures( nalu.m_layerId, outputPicturesFlag );
+        }
+        else
+        {
+          this->checkOutputBeforeDecoding( nalu.m_layerId );
+        }
+      }
+
+      /* The following code has to be executed when the last DU of the picture is decoded
+         TODO: Need code to identify end of decoding a picture
+      {
+        this->checkOutputAfterDecoding( );
+      } */
+#else
+      if ( bNewPicture && bNewPOC &&
+           (   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 ) )
+      {
+        xFlushOutput( pcListPic, curLayerId );
+      }
+      if (nalu.m_nalUnitType == NAL_UNIT_EOS)
+      {
+        xFlushOutput( pcListPic, curLayerId );        
+      }
+      // write reconstruction to file
+      if(bNewPicture)
+      {
+        xWriteOutput( pcListPic, curLayerId, nalu.m_temporalId );
+      }
+#endif
+    }
+  }
+#if ALIGNED_BUMPING
+   flushAllPictures( true );   
+#else
+  for(UInt layer = 0; layer <= m_tgtLayerId; layer++)
+  {
+    xFlushOutput( m_acTDecTop[layer].getListPic(), layer );
+  }
+#endif
+  // delete buffers
+#if AVC_BASE
+  UInt layerIdxmin = m_acTDecTop[0].getBLReconFile()->is_open() ? 1 : 0;
+
+  if( streamYUV.is_open() )
+  {
+    streamYUV.close();
+  }
+  pcBLPic.destroy();
+
+#if FIX_CONF_MODE
+  for(UInt layer = layerIdxmin; layer < MAX_VPS_LAYER_IDX_PLUS1; layer++)
+#else
+  for(UInt layer = layerIdxmin; layer <= m_tgtLayerId; layer++)
+#endif
+#else
+  for(UInt layer = 0; layer <= m_tgtLayerId; layer++)
+#endif
+  {
+    m_acTDecTop[layer].deletePicBuffer();
+  }
+
+  // destroy internal classes
+  xDestroyDecLib();
+}
+#else
+Void TAppDecTop::decode()
+{
+  Int                 poc;
+  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);
+  }
+
+  InputByteStream bytestream(bitstreamFile);
+
+  if (!m_outputDecodedSEIMessagesFilename.empty() && m_outputDecodedSEIMessagesFilename!="-")
+  {
+    m_seiMessageFileStream.open(m_outputDecodedSEIMessagesFilename.c_str(), std::ios::out);
+    if (!m_seiMessageFileStream.is_open() || !m_seiMessageFileStream.good())
+    {
+      fprintf(stderr, "\nUnable to open file `%s' for writing decoded SEI messages\n", m_outputDecodedSEIMessagesFilename.c_str());
+      exit(EXIT_FAILURE);
+    }
+  }
+
+  // create & initialize internal classes
+  xCreateDecLib();
+  xInitDecLib  ();
+  m_iPOCLastDisplay += m_iSkipFrame;      // set the last displayed POC correctly for skip forward.
+
+  // main decoder loop
+  Bool openedReconFile = false; // reconstruction file not yet opened. (must be performed after SPS is seen)
+  Bool loopFiltered = false;
+
+  while (!!bitstreamFile)
+  {
+    /* location serves to work around a design fault in the decoder, whereby
+     * the process of reading a new slice that is the first slice of a new frame
+     * requires the TDecTop::decode() method to be called again with the same
+     * nal unit. */
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+    TComCodingStatistics::TComCodingStatisticsData backupStats(TComCodingStatistics::GetStatistics());
+    streampos location = bitstreamFile.tellg() - streampos(bytestream.GetNumBufferedBytes());
+#else
+    streampos location = bitstreamFile.tellg();
+#endif
+    AnnexBStats stats = AnnexBStats();
+
+    vector<uint8_t> nalUnit;
+    InputNALUnit nalu;
+    byteStreamNALUnit(bytestream, nalUnit, stats);
+
+    // call actual decoding function
+    Bool bNewPicture = false;
+    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( (m_iMaxTemporalLayer >= 0 && nalu.m_temporalId > m_iMaxTemporalLayer) || !isNaluWithinTargetDecLayerIdSet(&nalu)  )
+      {
+        bNewPicture = false;
+      }
+      else
+      {
+        bNewPicture = m_cTDecTop.decode(nalu, m_iSkipFrame, m_iPOCLastDisplay);
+        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) */
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+          bitstreamFile.seekg(location);
+          bytestream.reset();
+          TComCodingStatistics::SetStatistics(backupStats);
+#else
+          bitstreamFile.seekg(location-streamoff(3));
+          bytestream.reset();
+#endif
+        }
+      }
+    }
+
+    if ( (bNewPicture || !bitstreamFile || nalu.m_nalUnitType == NAL_UNIT_EOS) &&
+        !m_cTDecTop.getFirstSliceInSequence () )
+    {
+      if (!loopFiltered || bitstreamFile)
+      {
+        m_cTDecTop.executeLoopFilters(poc, pcListPic);
+      }
+      loopFiltered = (nalu.m_nalUnitType == NAL_UNIT_EOS);
+      if (nalu.m_nalUnitType == NAL_UNIT_EOS)
+      {
+        m_cTDecTop.setFirstSliceInSequence(true);
+      }
+    }
+    else if ( (bNewPicture || !bitstreamFile || nalu.m_nalUnitType == NAL_UNIT_EOS ) &&
+              m_cTDecTop.getFirstSliceInSequence () ) 
+    {
+      m_cTDecTop.setFirstSliceInPicture (true);
+    }
+
+    if( pcListPic )
+    {
+      if ( m_pchReconFile && !openedReconFile )
+      {
+        for (UInt channelType = 0; channelType < MAX_NUM_CHANNEL_TYPE; channelType++)
+        {
+          if (m_outputBitDepth[channelType] == 0) m_outputBitDepth[channelType] = g_bitDepth[channelType];
+        }
+
+        m_cTVideoIOYuvReconFile.open( m_pchReconFile, true, m_outputBitDepth, m_outputBitDepth, g_bitDepth ); // write mode
+        openedReconFile = true;
+      }
+      // write reconstruction to file
+      if( bNewPicture )
+      {
+        xWriteOutput( pcListPic, nalu.m_temporalId );
+      }
+      if ( (bNewPicture || nalu.m_nalUnitType == NAL_UNIT_CODED_SLICE_CRA) && m_cTDecTop.getNoOutputPriorPicsFlag() )
+      {
+        m_cTDecTop.checkNoOutputPriorPics( pcListPic );
+        m_cTDecTop.setNoOutputPriorPicsFlag (false);
+      }
+      if ( bNewPicture &&
+           (   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 ) )
+      {
+        xFlushOutput( pcListPic );
+      }
+      if (nalu.m_nalUnitType == NAL_UNIT_EOS)
+      {
+        xWriteOutput( pcListPic, nalu.m_temporalId );
+        m_cTDecTop.setFirstSliceInPicture (false);
+      }
+      // write reconstruction to file -- for additional bumping as defined in C.5.2.3
+      if(!bNewPicture && nalu.m_nalUnitType >= NAL_UNIT_CODED_SLICE_TRAIL_N && nalu.m_nalUnitType <= NAL_UNIT_RESERVED_VCL31)
+      {
+        xWriteOutput( pcListPic, nalu.m_temporalId );
+      }
+    }
+  }
+
+  xFlushOutput( pcListPic );
+  // delete buffers
+  m_cTDecTop.deletePicBuffer();
+
+  // destroy internal classes
+  xDestroyDecLib();
+}
+#endif
+
+// ====================================================================================================================
+// Protected member functions
+// ====================================================================================================================
+
+Void TAppDecTop::xCreateDecLib()
+{
+#if SVC_EXTENSION
+  // initialize global variables
+  initROM();
+
+#if FIX_CONF_MODE
+  for(UInt layer = 0; layer < MAX_VPS_LAYER_IDX_PLUS1; layer++)
+#else
+  for(UInt layer = 0; layer <= m_tgtLayerId; layer++)
+#endif
+  {
+    // set layer ID
+    m_acTDecTop[layer].setLayerId                      ( layer );
+
+    // create decoder class
+    m_acTDecTop[layer].create();
+
+    m_acTDecTop[layer].setLayerDec(m_apcTDecTop);
+  }
+#else
+  // create decoder class
+  m_cTDecTop.create();
+#endif
+}
+
+Void TAppDecTop::xDestroyDecLib()
+{
+#if SVC_EXTENSION
+  // destroy ROM
+  destroyROM();
+
+#if FIX_CONF_MODE
+  for(UInt layer = 0; layer < MAX_VPS_LAYER_IDX_PLUS1; layer++)
+#else
+  for(UInt layer = 0; layer <= m_tgtLayerId; layer++)
+#endif
+  {
+    if ( m_pchReconFile[layer] )
+    {
+      m_acTVideoIOYuvReconFile[layer].close();
+    }
+
+    // destroy decoder class
+    m_acTDecTop[layer].destroy();
+  }
+#else
+  if ( m_pchReconFile )
+  {
+    m_cTVideoIOYuvReconFile. close();
+  }
+
+  // destroy decoder class
+  m_cTDecTop.destroy();
+#endif
+}
+
+Void TAppDecTop::xInitDecLib()
+{
+  // initialize decoder class
+#if SVC_EXTENSION
+#if FIX_CONF_MODE
+  for(UInt layer = 0; layer < MAX_VPS_LAYER_IDX_PLUS1; layer++)
+#else
+  for(UInt layer = 0; layer <= m_tgtLayerId; layer++)
+#endif
+  {
+    m_acTDecTop[layer].init();
+    m_acTDecTop[layer].setDecodedPictureHashSEIEnabled(m_decodedPictureHashSEIEnabled);
+#if Q0074_COLOUR_REMAPPING_SEI
+    m_acTDecTop[layer].setColourRemappingInfoSEIEnabled(m_colourRemapSEIEnabled);
+#endif
+#if FIX_CONF_MODE
+    m_acTDecTop[layer].setNumLayer( MAX_LAYERS );
+#else
+    m_acTDecTop[layer].setNumLayer( m_tgtLayerId + 1 );
+#endif
+#if OUTPUT_LAYER_SET_INDEX
+    m_acTDecTop[layer].setCommonDecoderParams( &m_commonDecoderParams );
+#endif
+  }
+#if CONFORMANCE_BITSTREAM_MODE
+#if FIX_CONF_MODE
+  for(UInt layer = 0; layer < MAX_VPS_LAYER_IDX_PLUS1; layer++)
+#else
+  for(UInt layer = 0; layer < MAX_LAYERS; layer++)
+#endif
+  {
+    m_acTDecTop[layer].setConfModeFlag( m_confModeFlag );
+  }
+#endif
+#else
+  m_cTDecTop.init();
+  m_cTDecTop.setDecodedPictureHashSEIEnabled(m_decodedPictureHashSEIEnabled);
+#if O0043_BEST_EFFORT_DECODING
+  m_cTDecTop.setForceDecodeBitDepth(m_forceDecodeBitDepth);
+#endif
+  if (!m_outputDecodedSEIMessagesFilename.empty())
+  {
+    std::ostream &os=m_seiMessageFileStream.is_open() ? m_seiMessageFileStream : std::cout;
+    m_cTDecTop.setDecodedSEIMessageOutputStream(&os);
+  }
+#if Q0074_COLOUR_REMAPPING_SEI
+  m_cTDecTop.setColourRemappingInfoSEIEnabled(m_colourRemapSEIEnabled);
+#endif
+#endif
+}
+
+/** \param pcListPic list of pictures to be written to file
+    \todo            DYN_REF_FREE should be revised
+ */
+#if SVC_EXTENSION
+Void TAppDecTop::xWriteOutput( TComList<TComPic*>* pcListPic, UInt layerId, UInt tId )
+#else
+Void TAppDecTop::xWriteOutput( TComList<TComPic*>* pcListPic, UInt tId )
+#endif
+{
+  if (pcListPic->empty())
+  {
+    return;
+  }
+
+  TComList<TComPic*>::iterator iterPic   = pcListPic->begin();
+  Int numPicsNotYetDisplayed = 0;
+  Int dpbFullness = 0;
+#if SVC_EXTENSION
+TComSPS* activeSPS = m_acTDecTop[layerId].getActiveSPS();
+#else
+  TComSPS* activeSPS = m_cTDecTop.getActiveSPS();
+#endif
+  UInt numReorderPicsHighestTid;
+  UInt maxDecPicBufferingHighestTid;
+  UInt maxNrSublayers = activeSPS->getMaxTLayers();
+
+  if(m_iMaxTemporalLayer == -1 || m_iMaxTemporalLayer >= maxNrSublayers)
+  {
+    numReorderPicsHighestTid = activeSPS->getNumReorderPics(maxNrSublayers-1);
+    maxDecPicBufferingHighestTid =  activeSPS->getMaxDecPicBuffering(maxNrSublayers-1); 
+  }
+  else
+  {
+    numReorderPicsHighestTid = activeSPS->getNumReorderPics(m_iMaxTemporalLayer);
+    maxDecPicBufferingHighestTid = activeSPS->getMaxDecPicBuffering(m_iMaxTemporalLayer); 
+  }
+
+  while (iterPic != pcListPic->end())
+  {
+    TComPic* pcPic = *(iterPic);
+#if SVC_EXTENSION
+    if(pcPic->getOutputMark() && pcPic->getPOC() > m_aiPOCLastDisplay[layerId])
+#else
+    if(pcPic->getOutputMark() && pcPic->getPOC() > m_iPOCLastDisplay)
+#endif
+    {
+       numPicsNotYetDisplayed++;
+      dpbFullness++;
+    }
+    else if(pcPic->getSlice( 0 )->isReferenced())
+    {
+      dpbFullness++;
+    }
+    iterPic++;
+  }
+
+  iterPic = pcListPic->begin();
+
+  if (numPicsNotYetDisplayed>2)
+  {
+    iterPic++;
+  }
+
+  TComPic* pcPic = *(iterPic);
+  if (numPicsNotYetDisplayed>2 && pcPic->isField()) //Field Decoding
+  {
+    TComList<TComPic*>::iterator endPic   = pcListPic->end();
+    endPic--;
+    iterPic   = pcListPic->begin();
+    while (iterPic != endPic)
+    {
+      TComPic* pcPicTop = *(iterPic);
+      iterPic++;
+      TComPic* pcPicBottom = *(iterPic);
+
+#if SVC_EXTENSION
+      if( pcPicTop->getOutputMark() && pcPicBottom->getOutputMark() &&
+        (numPicsNotYetDisplayed >  numReorderPicsHighestTid || dpbFullness > maxDecPicBufferingHighestTid) &&
+        (!(pcPicTop->getPOC()%2) && pcPicBottom->getPOC() == pcPicTop->getPOC()+1) &&        
+        (pcPicTop->getPOC() == m_aiPOCLastDisplay[layerId]+1 || m_aiPOCLastDisplay[layerId]<0) )
+#else
+      if ( pcPicTop->getOutputMark() && pcPicBottom->getOutputMark() &&
+          (numPicsNotYetDisplayed >  numReorderPicsHighestTid || dpbFullness > maxDecPicBufferingHighestTid) &&
+          (!(pcPicTop->getPOC()%2) && pcPicBottom->getPOC() == pcPicTop->getPOC()+1) &&
+          (pcPicTop->getPOC() == m_iPOCLastDisplay+1 || m_iPOCLastDisplay < 0))
+#endif
+      {
+        // write to file
+        numPicsNotYetDisplayed = numPicsNotYetDisplayed-2;
+#if SVC_EXTENSION
+        if ( m_pchReconFile[layerId] )
+        {
+          const Window &conf = pcPicTop->getConformanceWindow();
+          const Window &defDisp = m_respectDefDispWindow ? pcPicTop->getDefDisplayWindow() : Window();
+          const Bool isTff = pcPicTop->isTopField();
+
+          Bool display = true;
+          if( m_decodedNoDisplaySEIEnabled )
+          {
+            SEIMessages noDisplay = getSeisByType(pcPic->getSEIs(), SEI::NO_DISPLAY );
+            const SEINoDisplay *nd = ( noDisplay.size() > 0 ) ? (SEINoDisplay*) *(noDisplay.begin()) : NULL;
+            if( (nd != NULL) && nd->m_noDisplay )
+            {
+              display = false;
+            }
+          }
+
+          if (display)
+          {            
+#if REPN_FORMAT_IN_VPS
+            UInt chromaFormatIdc = pcPic->getSlice(0)->getChromaFormatIdc();
+            Int xScal =  TComSPS::getWinUnitX( chromaFormatIdc ), yScal = TComSPS::getWinUnitY( chromaFormatIdc );
+
+            m_acTVideoIOYuvReconFile[layerId].write( pcPicTop->getPicYuvRec(), pcPicBottom->getPicYuvRec(),
+              m_outputColourSpaceConvert,
+              conf.getWindowLeftOffset()  * xScal + defDisp.getWindowLeftOffset(),
+              conf.getWindowRightOffset() * xScal + defDisp.getWindowRightOffset(),
+              conf.getWindowTopOffset()   * yScal + defDisp.getWindowTopOffset(),
+              conf.getWindowBottomOffset()* yScal + defDisp.getWindowBottomOffset(), NUM_CHROMA_FORMAT, isTff );
+#else
+            m_acTVideoIOYuvReconFile[layerId].write( pcPicTop->getPicYuvRec(), pcPicBottom->getPicYuvRec(),
+              m_outputColourSpaceConvert,
+              conf.getWindowLeftOffset()   + defDisp.getWindowLeftOffset(),
+              conf.getWindowRightOffset()  + defDisp.getWindowRightOffset(),
+              conf.getWindowTopOffset()    + defDisp.getWindowTopOffset(),
+              conf.getWindowBottomOffset() + defDisp.getWindowBottomOffset(), NUM_CHROMA_FORMAT, isTff );
+#endif
+          }
+        }
+
+        // update POC of display order
+        m_aiPOCLastDisplay[layerId] = pcPicBottom->getPOC();
+#else
+        if ( m_pchReconFile )
+        {
+          const Window &conf = pcPicTop->getConformanceWindow();
+          const Window &defDisp = m_respectDefDispWindow ? pcPicTop->getDefDisplayWindow() : Window();
+          const Bool isTff = pcPicTop->isTopField();
+
+          Bool display = true;
+          if( m_decodedNoDisplaySEIEnabled )
+          {
+            SEIMessages noDisplay = getSeisByType(pcPic->getSEIs(), SEI::NO_DISPLAY );
+            const SEINoDisplay *nd = ( noDisplay.size() > 0 ) ? (SEINoDisplay*) *(noDisplay.begin()) : NULL;
+            if( (nd != NULL) && nd->m_noDisplay )
+            {
+              display = false;
+            }
+          }
+
+          if (display)
+          {
+            m_cTVideoIOYuvReconFile.write( pcPicTop->getPicYuvRec(), pcPicBottom->getPicYuvRec(),
+                                           m_outputColourSpaceConvert,
+                                           conf.getWindowLeftOffset() + defDisp.getWindowLeftOffset(),
+                                           conf.getWindowRightOffset() + defDisp.getWindowRightOffset(),
+                                           conf.getWindowTopOffset() + defDisp.getWindowTopOffset(),
+                                           conf.getWindowBottomOffset() + defDisp.getWindowBottomOffset(), NUM_CHROMA_FORMAT, isTff );
+          }
+        }
+
+        // update POC of display order
+        m_iPOCLastDisplay = pcPicBottom->getPOC();
+#endif
+
+        // erase non-referenced picture in the reference picture list after display
+        if ( !pcPicTop->getSlice(0)->isReferenced() && pcPicTop->getReconMark() == true )
+        {
+#if !DYN_REF_FREE
+          pcPicTop->setReconMark(false);
+
+          // mark it should be extended later
+          pcPicTop->getPicYuvRec()->setBorderExtension( false );
+
+#else
+          pcPicTop->destroy();
+          pcListPic->erase( iterPic );
+          iterPic = pcListPic->begin(); // to the beginning, non-efficient way, have to be revised!
+          continue;
+#endif
+        }
+        if ( !pcPicBottom->getSlice(0)->isReferenced() && pcPicBottom->getReconMark() == true )
+        {
+#if !DYN_REF_FREE
+          pcPicBottom->setReconMark(false);
+
+          // mark it should be extended later
+          pcPicBottom->getPicYuvRec()->setBorderExtension( false );
+
+#else
+          pcPicBottom->destroy();
+          pcListPic->erase( iterPic );
+          iterPic = pcListPic->begin(); // to the beginning, non-efficient way, have to be revised!
+          continue;
+#endif
+        }
+        pcPicTop->setOutputMark(false);
+        pcPicBottom->setOutputMark(false);
+      }
+    }
+  }
+  else if (!pcPic->isField()) //Frame Decoding
+  {
+    iterPic = pcListPic->begin();
+
+    while (iterPic != pcListPic->end())
+    {
+      pcPic = *(iterPic);
+
+#if SVC_EXTENSION
+      if( pcPic->getOutputMark() && pcPic->getPOC() > m_aiPOCLastDisplay[layerId] &&
+        (numPicsNotYetDisplayed >  numReorderPicsHighestTid || dpbFullness > maxDecPicBufferingHighestTid) )
+#else
+      if(pcPic->getOutputMark() && pcPic->getPOC() > m_iPOCLastDisplay &&
+        (numPicsNotYetDisplayed >  numReorderPicsHighestTid || dpbFullness > maxDecPicBufferingHighestTid))
+#endif
+      {
+        // write to file
+         numPicsNotYetDisplayed--;
+        if(pcPic->getSlice(0)->isReferenced() == false)
+        {
+          dpbFullness--;
+        }
+#if SVC_EXTENSION
+        if( m_pchReconFile[layerId] )
+        {
+          const Window &conf = pcPic->getConformanceWindow();
+          const Window &defDisp = m_respectDefDispWindow ? pcPic->getDefDisplayWindow() : Window();          
+#if REPN_FORMAT_IN_VPS
+          UInt chromaFormatIdc = pcPic->getSlice(0)->getChromaFormatIdc();
+          Int xScal =  TComSPS::getWinUnitX( chromaFormatIdc ), yScal = TComSPS::getWinUnitY( chromaFormatIdc );
+
+          m_acTVideoIOYuvReconFile[layerId].write( pcPic->getPicYuvRec(), m_outputColourSpaceConvert,
+            conf.getWindowLeftOffset()  * xScal + defDisp.getWindowLeftOffset(),
+            conf.getWindowRightOffset() * xScal + defDisp.getWindowRightOffset(),
+            conf.getWindowTopOffset()   * yScal + defDisp.getWindowTopOffset(),
+            conf.getWindowBottomOffset()* yScal + defDisp.getWindowBottomOffset() );
+#else
+          m_acTVideoIOYuvReconFile[layerId].write( pcPic->getPicYuvRec(), m_outputColourSpaceConvert,
+            conf.getWindowLeftOffset()   + defDisp.getWindowLeftOffset(),
+            conf.getWindowRightOffset()  + defDisp.getWindowRightOffset(),
+            conf.getWindowTopOffset()    + defDisp.getWindowTopOffset(),
+            conf.getWindowBottomOffset() + defDisp.getWindowBottomOffset() );
+#endif
+        }
+
+        // update POC of display order
+        m_aiPOCLastDisplay[layerId] = pcPic->getPOC();
+#else
+        if ( m_pchReconFile )
+        {
+          const Window &conf    = pcPic->getConformanceWindow();
+          const Window &defDisp = m_respectDefDispWindow ? pcPic->getDefDisplayWindow() : Window();
+
+          m_cTVideoIOYuvReconFile.write( pcPic->getPicYuvRec(),
+                                         m_outputColourSpaceConvert,
+                                         conf.getWindowLeftOffset() + defDisp.getWindowLeftOffset(),
+                                         conf.getWindowRightOffset() + defDisp.getWindowRightOffset(),
+                                         conf.getWindowTopOffset() + defDisp.getWindowTopOffset(),
+                                         conf.getWindowBottomOffset() + defDisp.getWindowBottomOffset() );
+        }
+
+        // update POC of display order
+        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 SVC_EXTENSION
+Void TAppDecTop::xFlushOutput( TComList<TComPic*>* pcListPic, UInt layerId )
+#else
+Void TAppDecTop::xFlushOutput( TComList<TComPic*>* pcListPic )
+#endif
+{
+  if(!pcListPic || pcListPic->empty())
+  {
+    return;
+  }
+  TComList<TComPic*>::iterator iterPic   = pcListPic->begin();
+
+  iterPic   = pcListPic->begin();
+  TComPic* pcPic = *(iterPic);
+
+  if (pcPic->isField()) //Field Decoding
+  {
+    TComList<TComPic*>::iterator endPic   = pcListPic->end();
+    endPic--;
+    TComPic *pcPicTop, *pcPicBottom = NULL;
+    while (iterPic != endPic)
+    {
+      pcPicTop = *(iterPic);
+      iterPic++;
+      pcPicBottom = *(iterPic);
+
+      if ( pcPicTop->getOutputMark() && pcPicBottom->getOutputMark() && !(pcPicTop->getPOC()%2) && (pcPicBottom->getPOC() == pcPicTop->getPOC()+1) )
+      {
+        // write to file
+#if SVC_EXTENSION
+        if ( m_pchReconFile[layerId] )
+        {
+          const Window &conf = pcPicTop->getConformanceWindow();
+          const Window &defDisp = m_respectDefDispWindow ? pcPicTop->getDefDisplayWindow() : Window();
+          const Bool isTff = pcPicTop->isTopField();          
+#if REPN_FORMAT_IN_VPS
+          UInt chromaFormatIdc = pcPic->getSlice(0)->getChromaFormatIdc();
+          Int xScal =  TComSPS::getWinUnitX( chromaFormatIdc ), yScal = TComSPS::getWinUnitY( chromaFormatIdc );
+
+          m_acTVideoIOYuvReconFile[layerId].write( pcPicTop->getPicYuvRec(), pcPicBottom->getPicYuvRec(), m_outputColourSpaceConvert,
+            conf.getWindowLeftOffset()  *xScal + defDisp.getWindowLeftOffset(),
+            conf.getWindowRightOffset() *xScal + defDisp.getWindowRightOffset(),
+            conf.getWindowTopOffset()   *yScal + defDisp.getWindowTopOffset(),
+            conf.getWindowBottomOffset()*yScal + defDisp.getWindowBottomOffset(), NUM_CHROMA_FORMAT, isTff );
+#else
+          m_acTVideoIOYuvReconFile[layerId].write( pcPicTop->getPicYuvRec(), pcPicBottom->getPicYuvRec(), m_outputColourSpaceConvert,
+            conf.getWindowLeftOffset()   + defDisp.getWindowLeftOffset(),
+            conf.getWindowRightOffset()  + defDisp.getWindowRightOffset(),
+            conf.getWindowTopOffset()    + defDisp.getWindowTopOffset(),
+            conf.getWindowBottomOffset() + defDisp.getWindowBottomOffset(), NUM_CHROMA_FORMAT, isTff );
+#endif
+        }
+
+        // update POC of display order
+        m_aiPOCLastDisplay[layerId] = pcPicBottom->getPOC();
+#else
+        if ( m_pchReconFile )
+        {
+          const Window &conf = pcPicTop->getConformanceWindow();
+          const Window &defDisp = m_respectDefDispWindow ? pcPicTop->getDefDisplayWindow() : Window();
+          const Bool isTff = pcPicTop->isTopField();
+          m_cTVideoIOYuvReconFile.write( pcPicTop->getPicYuvRec(), pcPicBottom->getPicYuvRec(),
+                                         m_outputColourSpaceConvert,
+                                         conf.getWindowLeftOffset() + defDisp.getWindowLeftOffset(),
+                                         conf.getWindowRightOffset() + defDisp.getWindowRightOffset(),
+                                         conf.getWindowTopOffset() + defDisp.getWindowTopOffset(),
+                                         conf.getWindowBottomOffset() + defDisp.getWindowBottomOffset(), NUM_CHROMA_FORMAT, isTff );
+        }
+
+        // update POC of display order
+        m_iPOCLastDisplay = pcPicBottom->getPOC();
+#endif
+
+        // erase non-referenced picture in the reference picture list after display
+        if ( !pcPicTop->getSlice(0)->isReferenced() && pcPicTop->getReconMark() == true )
+        {
+#if !DYN_REF_FREE
+          pcPicTop->setReconMark(false);
+
+          // mark it should be extended later
+          pcPicTop->getPicYuvRec()->setBorderExtension( false );
+
+#else
+          pcPicTop->destroy();
+          pcListPic->erase( iterPic );
+          iterPic = pcListPic->begin(); // to the beginning, non-efficient way, have to be revised!
+          continue;
+#endif
+        }
+        if ( !pcPicBottom->getSlice(0)->isReferenced() && pcPicBottom->getReconMark() == true )
+        {
+#if !DYN_REF_FREE
+          pcPicBottom->setReconMark(false);
+
+          // mark it should be extended later
+          pcPicBottom->getPicYuvRec()->setBorderExtension( false );
+
+#else
+          pcPicBottom->destroy();
+          pcListPic->erase( iterPic );
+          iterPic = pcListPic->begin(); // to the beginning, non-efficient way, have to be revised!
+          continue;
+#endif
+        }
+        pcPicTop->setOutputMark(false);
+        pcPicBottom->setOutputMark(false);
+
+#if !DYN_REF_FREE
+        if(pcPicTop)
+        {
+          pcPicTop->destroy();
+          delete pcPicTop;
+          pcPicTop = NULL;
+        }
+#endif
+      }
+    }
+    if(pcPicBottom)
+    {
+      pcPicBottom->destroy();
+      delete pcPicBottom;
+      pcPicBottom = NULL;
+    }
+  }
+  else //Frame decoding
+  {
+    while (iterPic != pcListPic->end())
+    {
+      pcPic = *(iterPic);
+
+      if ( pcPic->getOutputMark() )
+      {
+        // write to file
+#if SVC_EXTENSION
+        if ( m_pchReconFile[layerId] )
+        {
+          const Window &conf = pcPic->getConformanceWindow();
+          const Window &defDisp = m_respectDefDispWindow ? pcPic->getDefDisplayWindow() : Window();          
+#if REPN_FORMAT_IN_VPS
+          UInt chromaFormatIdc = pcPic->getSlice(0)->getChromaFormatIdc();
+          Int xScal =  TComSPS::getWinUnitX( chromaFormatIdc ), yScal = TComSPS::getWinUnitY( chromaFormatIdc );
+
+          m_acTVideoIOYuvReconFile[layerId].write( pcPic->getPicYuvRec(), m_outputColourSpaceConvert,
+            conf.getWindowLeftOffset()  *xScal + defDisp.getWindowLeftOffset(),
+            conf.getWindowRightOffset() *xScal + defDisp.getWindowRightOffset(),
+            conf.getWindowTopOffset()   *yScal + defDisp.getWindowTopOffset(),
+            conf.getWindowBottomOffset()*yScal + defDisp.getWindowBottomOffset() );
+#else
+          m_acTVideoIOYuvReconFile[layerId].write( pcPic->getPicYuvRec(), m_outputColourSpaceConvert,
+            conf.getWindowLeftOffset()   + defDisp.getWindowLeftOffset(),
+            conf.getWindowRightOffset()  + defDisp.getWindowRightOffset(),
+            conf.getWindowTopOffset()    + defDisp.getWindowTopOffset(),
+            conf.getWindowBottomOffset() + defDisp.getWindowBottomOffset() );
+#endif
+        }
+
+        // update POC of display order
+        m_aiPOCLastDisplay[layerId] = pcPic->getPOC();
+#else
+        if ( m_pchReconFile )
+        {
+          const Window &conf    = pcPic->getConformanceWindow();
+          const Window &defDisp = m_respectDefDispWindow ? pcPic->getDefDisplayWindow() : Window();
+
+          m_cTVideoIOYuvReconFile.write( pcPic->getPicYuvRec(),
+                                         m_outputColourSpaceConvert,
+                                         conf.getWindowLeftOffset() + defDisp.getWindowLeftOffset(),
+                                         conf.getWindowRightOffset() + defDisp.getWindowRightOffset(),
+                                         conf.getWindowTopOffset() + defDisp.getWindowTopOffset(),
+                                         conf.getWindowBottomOffset() + defDisp.getWindowBottomOffset() );
+        }
+
+        // update POC of display order
+        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 !SVC_EXTENSION
+#if !DYN_REF_FREE
+      if(pcPic)
+      {
+        pcPic->destroy();
+        delete pcPic;
+        pcPic = NULL;
+      }
+#endif
+#endif
+      iterPic++;
+    }
+  }
+#if SVC_EXTENSION
+  m_aiPOCLastDisplay[layerId] = -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;
+  }
+#if R0235_SMALLEST_LAYER_ID
+  if (nalu->m_layerId == 0 && (nalu->m_nalUnitType == NAL_UNIT_VPS || nalu->m_nalUnitType == NAL_UNIT_SPS || nalu->m_nalUnitType == NAL_UNIT_PPS || nalu->m_nalUnitType == NAL_UNIT_EOS))
+  {
+    return true;
+  }
+#endif
+  for (std::vector<Int>::iterator it = m_targetDecLayerIdSet.begin(); it != m_targetDecLayerIdSet.end(); it++)
+  {
+    if ( nalu->m_reservedZero6Bits == (*it) )
+    {
+      return true;
+    }
+  }
+  return false;
+}
+#if ALIGNED_BUMPING
+// Function outputs a picture, and marks it as not needed for output.
+Void TAppDecTop::xOutputAndMarkPic( TComPic *pic, const Char *reconFile, const Int layerId, Int &pocLastDisplay, DpbStatus &dpbStatus )
+{
+  if ( reconFile )
+  {
+    const Window &conf = pic->getConformanceWindow();
+    const Window &defDisp = m_respectDefDispWindow ? pic->getDefDisplayWindow() : Window();
+    Int xScal =  1, yScal = 1;
+#if REPN_FORMAT_IN_VPS
+    UInt chromaFormatIdc = pic->getSlice(0)->getChromaFormatIdc();
+    xScal = TComSPS::getWinUnitX( chromaFormatIdc );
+    yScal = TComSPS::getWinUnitY( chromaFormatIdc );
+#endif
+    TComPicYuv* pPicCYuvRec = pic->getPicYuvRec();
+    m_acTVideoIOYuvReconFile[layerId].write( pPicCYuvRec, m_outputColourSpaceConvert,
+      conf.getWindowLeftOffset()  * xScal + defDisp.getWindowLeftOffset(),
+      conf.getWindowRightOffset() * xScal + defDisp.getWindowRightOffset(),
+      conf.getWindowTopOffset()   * yScal + defDisp.getWindowTopOffset(),
+      conf.getWindowBottomOffset()* yScal + defDisp.getWindowBottomOffset() );
+  }
+  // update POC of display order
+  pocLastDisplay = pic->getPOC();
+
+  // Mark as not needed for output
+  pic->setOutputMark(false);
+
+  // "erase" non-referenced picture in the reference picture list after display
+  if ( !pic->getSlice(0)->isReferenced() && pic->getReconMark() == true )
+  {
+    pic->setReconMark(false);
+
+    // mark it should be extended later
+    pic->getPicYuvRec()->setBorderExtension( false );
+
+#if RESOLUTION_BASED_DPB
+    dpbStatus.m_numPicsInLayer[layerIdx]--;
+#endif
+#if FIX_ALIGN_BUMPING
+    dpbStatus.m_numPicsInSubDpb[dpbStatus.m_layerIdToSubDpbIdMap[layerId]]--;
+#else
+    dpbStatus.m_numPicsInSubDpb[layerIdx]--;
+#endif
+  }
+}
+
+Void TAppDecTop::flushAllPictures(Int layerId, Bool outputPictures)
+{
+  // First "empty" all pictures that are not used for reference and not needed for output
+  emptyUnusedPicturesNotNeededForOutput();
+
+  if( outputPictures )  // All pictures in the DPB in that layer are to be output; this means other pictures would also be output
+  {
+    std::vector<Int>  listOfPocs;
+#if FIX_ALIGN_BUMPING
+    std::vector<Int>  listOfPocsInEachLayer[MAX_VPS_LAYER_IDX_PLUS1];
+    std::vector<Int>  listOfPocsPositionInEachLayer[MAX_VPS_LAYER_IDX_PLUS1];
+#else
+    std::vector<Int>  listOfPocsInEachLayer[MAX_LAYERS];
+    std::vector<Int>  listOfPocsPositionInEachLayer[MAX_LAYERS];
+#endif
+    DpbStatus dpbStatus;
+
+    // Find the status of the DPB
+    xFindDPBStatus(listOfPocs, listOfPocsInEachLayer, listOfPocsPositionInEachLayer, dpbStatus);
+
+    if( listOfPocs.size() )
+    {
+      while( listOfPocsInEachLayer[layerId].size() )    // As long as there picture in the layer to be output
+      {
+        bumpingProcess( listOfPocs, listOfPocsInEachLayer, listOfPocsPositionInEachLayer, dpbStatus );
+      }
+    }
+  }
+
+  // Now remove all pictures from the layer DPB?
+  markAllPicturesAsErased(layerId);
+}
+Void TAppDecTop::flushAllPictures(Bool outputPictures)
+{
+  // First "empty" all pictures that are not used for reference and not needed for output
+  emptyUnusedPicturesNotNeededForOutput();
+
+  if( outputPictures )  // All pictures in the DPB are to be output
+  {
+    std::vector<Int>  listOfPocs;
+#if FIX_ALIGN_BUMPING
+    std::vector<Int>  listOfPocsInEachLayer[MAX_VPS_LAYER_IDX_PLUS1];
+    std::vector<Int>  listOfPocsPositionInEachLayer[MAX_VPS_LAYER_IDX_PLUS1];
+#else
+    std::vector<Int>  listOfPocsInEachLayer[MAX_LAYERS];
+    std::vector<Int>  listOfPocsPositionInEachLayer[MAX_LAYERS];
+#endif
+    DpbStatus dpbStatus;
+
+    // Find the status of the DPB
+#if POC_RESET_IDC_DECODER
+    xFindDPBStatus(listOfPocs, listOfPocsInEachLayer, listOfPocsPositionInEachLayer, dpbStatus, false);
+#else
+    xFindDPBStatus(listOfPocs, listOfPocsInEachLayer, listOfPocsPositionInEachLayer, dpbStatus);
+#endif
+
+    while( dpbStatus.m_numAUsNotDisplayed )
+    {
+      bumpingProcess( listOfPocs, listOfPocsInEachLayer, listOfPocsPositionInEachLayer, dpbStatus );
+    }
+  }
+
+  // Now remove all pictures from the DPB?
+  markAllPicturesAsErased();
+}
+
+Void TAppDecTop::markAllPicturesAsErased()
+{
+#if FIX_ALIGN_BUMPING
+  for(Int i = 0; i < MAX_VPS_LAYER_IDX_PLUS1; i++)
+#else
+  for(Int i = 0; i < MAX_LAYERS; i++)
+#endif
+  {
+    markAllPicturesAsErased(i);
+  }
+}
+
+Void TAppDecTop::markAllPicturesAsErased(Int layerIdx)
+{
+  TComList<TComPic*>::iterator  iterPic = m_acTDecTop[layerIdx].getListPic()->begin();
+  Int iSize = Int( m_acTDecTop[layerIdx].getListPic()->size() );
+  
+  for (Int i = 0; i < iSize; i++ )
+  {
+    TComPic* pcPic = *(iterPic++);
+
+    if( pcPic )
+    {
+      pcPic->destroy();
+
+      // pcPic is statically created for the external (AVC) base layer, no need to delete it
+#if VPS_AVC_BL_FLAG_REMOVAL
+      if( !m_acTDecTop[layerIdx].getParameterSetManager()->getActiveVPS()->getNonHEVCBaseLayerFlag() || layerIdx )
+#else
+      if( !m_acTDecTop[layerIdx].getParameterSetManager()->getActiveVPS()->getAvcBaseLayerFlag() || layerIdx )
+#endif
+      {
+        delete pcPic;
+        pcPic = NULL;
+      }
+    }
+  }
+
+  m_acTDecTop[layerIdx].getListPic()->clear();
+}
+
+Void TAppDecTop::checkOutputBeforeDecoding(Int layerIdx)
+{
+    
+  std::vector<Int>  listOfPocs;
+#if FIX_ALIGN_BUMPING
+  std::vector<Int>  listOfPocsInEachLayer[MAX_VPS_LAYER_IDX_PLUS1];
+  std::vector<Int>  listOfPocsPositionInEachLayer[MAX_VPS_LAYER_IDX_PLUS1];
+#else
+  std::vector<Int>  listOfPocsInEachLayer[MAX_LAYERS];
+  std::vector<Int>  listOfPocsPositionInEachLayer[MAX_LAYERS];
+#endif
+  DpbStatus dpbStatus;
+
+  // First "empty" all pictures that are not used for reference and not needed for output
+  emptyUnusedPicturesNotNeededForOutput();
+
+  // Find the status of the DPB
+  xFindDPBStatus(listOfPocs, listOfPocsInEachLayer, listOfPocsPositionInEachLayer, dpbStatus);
+
+  // If not picture to be output, return
+  if( listOfPocs.size() == 0 )
+  {
+    return;
+  }
+
+  // Find DPB-information from the VPS
+  DpbStatus maxDpbLimit;
+#if RESOLUTION_BASED_DPB
+  Int targetLsIdx, subDpbIdx;
+  TComVPS *vps = findDpbParametersFromVps(listOfPocs, listOfPocsInEachLayer, listOfPocsPositionInEachLayer, maxDpbLimit);
+
+  if( getCommonDecoderParams()->getTargetOutputLayerSetIdx() == 0 )
+  {
+    targetLsIdx = 0;
+    subDpbIdx   = 0; 
+  }
+  else
+  {
+    targetLsIdx = vps->getOutputLayerSetIdx( getCommonDecoderParams()->getTargetOutputLayerSetIdx() );
+    subDpbIdx   = vps->getSubDpbAssigned( targetLsIdx, layerIdx );
+  }
+#else
+#if FIX_ALIGN_BUMPING
+  Int subDpbIdx = getCommonDecoderParams()->getTargetOutputLayerSetIdx() == 0 
+                  ? dpbStatus.m_layerIdToSubDpbIdMap[0] 
+                  : dpbStatus.m_layerIdToSubDpbIdMap[layerIdx];
+#else
+  Int subDpbIdx = getCommonDecoderParams()->getTargetOutputLayerSetIdx() == 0 ? 0 : layerIdx;
+#endif
+  findDpbParametersFromVps(listOfPocs, listOfPocsInEachLayer, listOfPocsPositionInEachLayer, maxDpbLimit);
+#endif
+  // Assume that listOfPocs is sorted in increasing order - if not have to sort it.
+  while( ifInvokeBumpingBeforeDecoding(dpbStatus, maxDpbLimit, layerIdx, subDpbIdx) )
+  {
+    bumpingProcess( listOfPocs, listOfPocsInEachLayer, listOfPocsPositionInEachLayer, dpbStatus );
+  }  
+}
+
+Void TAppDecTop::checkOutputAfterDecoding()
+{    
+  std::vector<Int>  listOfPocs;
+#if FIX_ALIGN_BUMPING
+  std::vector<Int>  listOfPocsInEachLayer[MAX_VPS_LAYER_IDX_PLUS1];
+  std::vector<Int>  listOfPocsPositionInEachLayer[MAX_VPS_LAYER_IDX_PLUS1];
+#else
+  std::vector<Int>  listOfPocsInEachLayer[MAX_LAYERS];
+  std::vector<Int>  listOfPocsPositionInEachLayer[MAX_LAYERS];
+#endif
+  DpbStatus dpbStatus;
+
+  // First "empty" all pictures that are not used for reference and not needed for output
+  emptyUnusedPicturesNotNeededForOutput();
+
+  // Find the status of the DPB
+  xFindDPBStatus(listOfPocs, listOfPocsInEachLayer, listOfPocsPositionInEachLayer, dpbStatus);
+
+  // If not picture to be output, return
+  if( listOfPocs.size() == 0 )
+  {
+    return;
+  }
+
+  // Find DPB-information from the VPS
+  DpbStatus maxDpbLimit;
+  findDpbParametersFromVps(listOfPocs, listOfPocsInEachLayer, listOfPocsPositionInEachLayer, maxDpbLimit);
+
+  // Assume that listOfPocs is sorted in increasing order - if not have to sort it.
+  while( ifInvokeBumpingAfterDecoding(dpbStatus, maxDpbLimit) )
+  {
+    bumpingProcess( listOfPocs, listOfPocsInEachLayer, listOfPocsPositionInEachLayer, dpbStatus );
+  }  
+}
+
+Void TAppDecTop::bumpingProcess(std::vector<Int> &listOfPocs, std::vector<Int> *listOfPocsInEachLayer, std::vector<Int> *listOfPocsPositionInEachLayer, DpbStatus &dpbStatus)
+{
+  // Choose the smallest POC value
+  Int pocValue = *(listOfPocs.begin());
+  std::vector<int>::iterator it;
+  TComList<TComPic*>::iterator iterPic;
+#if FIX_ALIGN_BUMPING
+  for( Int dpbLayerCtr = 0; dpbLayerCtr < dpbStatus.m_numLayers; dpbLayerCtr++)
+  {
+    Int layerId  = dpbStatus.m_targetDecLayerIdList[dpbLayerCtr];
+#else
+  for( Int layerIdx = 0; layerIdx < dpbStatus.m_numLayers; layerIdx++)
+  {
+#endif
+    // Check if picture with pocValue is present.
+    it = find( listOfPocsInEachLayer[layerId].begin(), listOfPocsInEachLayer[layerId].end(), pocValue );
+    if( it != listOfPocsInEachLayer[layerId].end() )  // picture found.
+    {
+      Int picPosition = (Int)std::distance( listOfPocsInEachLayer[layerId].begin(), it );
+      Int j;
+      for(j = 0, iterPic = m_acTDecTop[layerId].getListPic()->begin(); j < listOfPocsPositionInEachLayer[layerId][picPosition]; j++) // Picture to be output
+      {
+        iterPic++;
+      }
+      TComPic *pic = *iterPic;
+
+      xOutputAndMarkPic( pic, m_pchReconFile[layerId], layerId, m_aiPOCLastDisplay[layerId], dpbStatus );
+
+#if CONFORMANCE_BITSTREAM_MODE
+      FILE *fptr;
+      if( m_confModeFlag )
+      {
+        if( m_metadataFileRefresh )
+        {
+          fptr = fopen( this->getMetadataFileName().c_str(), "w" );
+          fprintf(fptr, " LayerId      POC    MD5\n");
+          fprintf(fptr, "------------------------\n");
+        }
+        else
+        {
+          fptr = fopen( this->getMetadataFileName().c_str(), "a+" );
+        }
+        this->setMetadataFileRefresh(false);
+
+        TComDigest recon_digest;
+        Int numChar = calcMD5(*pic->getPicYuvRec(), recon_digest);
+        fprintf(fptr, "%8d%9d    MD5:%s\n", pic->getLayerId(), pic->getSlice(0)->getPOC(), digestToString(recon_digest, numChar).c_str());
+        fclose(fptr);
+      }
+#endif
+
+      listOfPocsInEachLayer[layerId].erase( it );
+      listOfPocsPositionInEachLayer[layerId].erase( listOfPocsPositionInEachLayer[layerId].begin() + picPosition );
+#if FIX_ALIGN_BUMPING
+      dpbStatus.m_numPicsInSubDpb[dpbStatus.m_layerIdToSubDpbIdMap[layerId]]--;
+#endif
+    }
+  }
+#if !FIX_ALIGN_BUMPING
+  // Update sub-DPB status
+  for( Int subDpbIdx = 0; subDpbIdx < dpbStatus.m_numSubDpbs; subDpbIdx++)
+  {
+    dpbStatus.m_numPicsInSubDpb[subDpbIdx]--;
+  }
+#endif
+  dpbStatus.m_numAUsNotDisplayed--;
+
+#if CONFORMANCE_BITSTREAM_MODE
+  if( m_confModeFlag )
+  {
+    for( Int dpbLayerCtr = 0; dpbLayerCtr < dpbStatus.m_numLayers; dpbLayerCtr++)
+    {
+      Int layerId = dpbStatus.m_targetDecLayerIdList[dpbLayerCtr];
+      // Output all picutres "decoded" in that layer that have POC less than the current picture
+      std::vector<TComPic> *layerBuffer = (m_acTDecTop->getLayerDec(layerId))->getConfListPic();
+      // Write all pictures to the file.
+      if( this->getDecodedYuvLayerRefresh(layerId) )
+      {
+        m_outputBitDepth[CHANNEL_TYPE_LUMA]   = g_bitDepth[CHANNEL_TYPE_LUMA]   = g_bitDepthLayer[CHANNEL_TYPE_LUMA][layerId];
+        m_outputBitDepth[CHANNEL_TYPE_CHROMA] = g_bitDepth[CHANNEL_TYPE_CHROMA] = g_bitDepthLayer[CHANNEL_TYPE_CHROMA][layerId];
+
+        char tempFileName[256];
+        strcpy(tempFileName, this->getDecodedYuvLayerFileName( layerId ).c_str());
+        m_confReconFile[layerId].open(tempFileName, true, m_outputBitDepth, m_outputBitDepth, g_bitDepth ); // write mode
+        this->setDecodedYuvLayerRefresh( layerId, false );
+      }
+
+      std::vector<TComPic>::iterator itPic;
+      for(itPic = layerBuffer->begin(); itPic != layerBuffer->end(); itPic++)
+      {
+        TComPic checkPic = *itPic;
+        const Window &conf = checkPic.getConformanceWindow();
+        const Window &defDisp = m_respectDefDispWindow ? checkPic.getDefDisplayWindow() : Window();
+        Int xScal = 1, yScal = 1;
+  #if REPN_FORMAT_IN_VPS
+        UInt chromaFormatIdc = checkPic.getSlice(0)->getChromaFormatIdc();
+        xScal = TComSPS::getWinUnitX( chromaFormatIdc );
+        yScal = TComSPS::getWinUnitY( chromaFormatIdc );
+  #endif
+        if( checkPic.getPOC() <= pocValue )
+        {
+          TComPicYuv* pPicCYuvRec = checkPic.getPicYuvRec();
+          m_confReconFile[layerId].write( pPicCYuvRec, m_outputColourSpaceConvert,
+            conf.getWindowLeftOffset()  * xScal + defDisp.getWindowLeftOffset(),
+            conf.getWindowRightOffset() * xScal + defDisp.getWindowRightOffset(),
+            conf.getWindowTopOffset()   * yScal + defDisp.getWindowTopOffset(),
+            conf.getWindowBottomOffset()* yScal + defDisp.getWindowBottomOffset() );
+          layerBuffer->erase(itPic);
+          itPic = layerBuffer->begin();  // Ensure doesn't go to infinite loop
+          if(layerBuffer->size() == 0)
+          {
+            break;
+          }
+        }
+      }
+    }
+  }
+#endif
+
+  // Remove the picture from the listOfPocs
+  listOfPocs.erase( listOfPocs.begin() );
+}
+
+TComVPS *TAppDecTop::findDpbParametersFromVps(std::vector<Int> const &listOfPocs, std::vector<Int> const *listOfPocsInEachLayer, std::vector<Int> const *listOfPocsPositionInEachLayer, DpbStatus &maxDpbLimit)
+{
+  Int targetOutputLsIdx = getCommonDecoderParams()->getTargetOutputLayerSetIdx();
+  TComVPS *vps = NULL;
+
+  if( targetOutputLsIdx == 0 )   // Only base layer is output
+  {
+    TComSPS *sps = NULL;
+    assert( listOfPocsInEachLayer[0].size() != 0 );
+    TComList<TComPic*>::iterator iterPic;
+    Int j;
+    for(j = 0, iterPic = m_acTDecTop[0].getListPic()->begin(); j < listOfPocsPositionInEachLayer[0][0]; j++) // Picture to be output
+    {
+      iterPic++;
+    }
+    TComPic *pic = *iterPic;
+    sps = pic->getSlice(0)->getSPS();   assert( sps->getLayerId() == 0 );
+    vps = pic->getSlice(0)->getVPS();
+    Int highestTId = sps->getMaxTLayers() - 1;
+
+    maxDpbLimit.m_numAUsNotDisplayed = sps->getNumReorderPics( highestTId ); // m_numAUsNotDisplayed is only variable name - stores reorderpics
+    maxDpbLimit.m_maxLatencyIncrease = sps->getMaxLatencyIncrease( highestTId ) > 0;
+    if( maxDpbLimit.m_maxLatencyIncrease )
+    {
+      maxDpbLimit.m_maxLatencyPictures = sps->getMaxLatencyIncrease( highestTId ) + sps->getNumReorderPics( highestTId ) - 1;
+    }
+#if RESOLUTION_BASED_DPB
+    maxDpbLimit.m_numPicsInLayer[0] = sps->getMaxDecPicBuffering( highestTId );
+#endif
+    maxDpbLimit.m_numPicsInSubDpb[0] = sps->getMaxDecPicBuffering( highestTId );
+  }
+  else
+  {
+    // -------------------------------------
+    // Find the VPS used for the pictures
+    // -------------------------------------
+#if FIX_ALIGN_BUMPING
+    for(Int i = 0; i < MAX_VPS_LAYER_IDX_PLUS1; i++)
+#else
+    for(Int i = 0; i < MAX_LAYERS; i++)
+#endif
+    {
+      if( m_acTDecTop[i].getListPic()->empty() )
+      {
+        assert( listOfPocsInEachLayer[i].size() == 0 );
+        continue;
+      }
+      std::vector<Int>::const_iterator it;
+      it = find( listOfPocsInEachLayer[i].begin(), listOfPocsInEachLayer[i].end(), listOfPocs[0] );
+      TComList<TComPic*>::iterator iterPic;
+      if( it != listOfPocsInEachLayer[i].end() )
+      {
+        Int picPosition = (Int)std::distance( listOfPocsInEachLayer[i].begin(), it );
+        Int j;
+        for(j = 0, iterPic = m_acTDecTop[i].getListPic()->begin(); j < listOfPocsPositionInEachLayer[i][picPosition]; j++) // Picture to be output
+        {
+          iterPic++;
+        }
+        TComPic *pic = *iterPic;
+        vps = pic->getSlice(0)->getVPS();
+        break;
+      }
+    }
+
+    Int targetLsIdx       = vps->getOutputLayerSetIdx( getCommonDecoderParams()->getTargetOutputLayerSetIdx() );
+    Int highestTId = vps->getMaxTLayers() - 1;
+
+    maxDpbLimit.m_numAUsNotDisplayed = vps->getMaxVpsNumReorderPics( targetOutputLsIdx, highestTId ); // m_numAUsNotDisplayed is only variable name - stores reorderpics
+    maxDpbLimit.m_maxLatencyIncrease  = vps->getMaxVpsLatencyIncreasePlus1(targetOutputLsIdx, highestTId ) > 0;
+    if( maxDpbLimit.m_maxLatencyIncrease )
+    {
+      maxDpbLimit.m_maxLatencyPictures = vps->getMaxVpsNumReorderPics( targetOutputLsIdx, highestTId ) + vps->getMaxVpsLatencyIncreasePlus1(targetOutputLsIdx, highestTId ) - 1;
+    }
+    for(Int i = 0; i < vps->getNumLayersInIdList( targetLsIdx ); i++)
+    {
+#if RESOUTION_BASED_DPB
+      maxDpbLimit.m_numPicsInLayer[i] = vps->getMaxVpsLayerDecPicBuffMinus1( targetOutputLsIdx, i, highestTId ) + 1;
+      maxDpbLimit.m_numPicsInSubDpb[vps->getSubDpbAssigned( targetLsIdx, i )] = vps->getMaxVpsDecPicBufferingMinus1( targetOutputLsIdx, vps->getSubDpbAssigned( targetLsIdx, i ), highestTId) + 1;
+#else
+      maxDpbLimit.m_numPicsInSubDpb[i] = vps->getMaxVpsDecPicBufferingMinus1( targetOutputLsIdx, i, highestTId) + 1;
+#endif
+    }
+    // -------------------------------------
+  }
+  return vps;
+}
+Void TAppDecTop::emptyUnusedPicturesNotNeededForOutput()
+{
+#if FIX_ALIGN_BUMPING
+  for(Int layerIdx = 0; layerIdx < MAX_VPS_LAYER_IDX_PLUS1; layerIdx++)
+#else
+  for(Int layerIdx = 0; layerIdx < MAX_LAYERS; layerIdx++)
+#endif
+  {
+    TComList <TComPic*> *pcListPic = m_acTDecTop[layerIdx].getListPic();
+    TComList<TComPic*>::iterator iterPic = pcListPic->begin();
+    while ( iterPic != pcListPic->end() )
+    {
+      TComPic *pic = *iterPic;
+      if( !pic->getSlice(0)->isReferenced() && !pic->getOutputMark() )
+      {
+        // Emtpy the picture buffer
+        pic->setReconMark( false );
+      }
+      iterPic++;
+    }
+  }
+}
+
+Bool TAppDecTop::ifInvokeBumpingBeforeDecoding( const DpbStatus &dpbStatus, const DpbStatus &dpbLimit, const Int layerIdx, const Int subDpbIdx )
+{
+  Bool retVal = false;
+  // Number of reorder picutres
+  retVal |= ( dpbStatus.m_numAUsNotDisplayed > dpbLimit.m_numAUsNotDisplayed );
+
+  // Number of pictures in each sub-DPB
+  retVal |= ( dpbStatus.m_numPicsInSubDpb[subDpbIdx] >= dpbLimit.m_numPicsInSubDpb[subDpbIdx] );
+  
+#if RESOLUTION_BASED_DPB
+  // Number of pictures in each layer
+  retVal |= ( dpbStatus.m_numPicsInLayer[layerIdx] >= dpbLimit.m_numPicsInLayer[layerIdx]);
+#endif
+
+  return retVal;
+}
+
+Bool TAppDecTop::ifInvokeBumpingAfterDecoding( const DpbStatus &dpbStatus, const DpbStatus &dpbLimit )
+{
+  Bool retVal = false;
+
+  // Number of reorder picutres
+  retVal |= ( dpbStatus.m_numAUsNotDisplayed > dpbLimit.m_numAUsNotDisplayed );
+
+  return retVal;
+}
+
+Void TAppDecTop::xFindDPBStatus( std::vector<Int> &listOfPocs
+                            , std::vector<Int> *listOfPocsInEachLayer
+                            , std::vector<Int> *listOfPocsPositionInEachLayer
+                            , DpbStatus &dpbStatus
+#if POC_RESET_IDC_DECODER
+                            , Bool notOutputCurrAu
+#endif
+                            )
+{
+  TComVPS *vps = NULL;
+  dpbStatus.init();
+#if FIX_ALIGN_BUMPING
+  for( Int i = 0; i < MAX_VPS_LAYER_IDX_PLUS1; i++ )
+#else
+  for( Int i = 0; i < MAX_LAYERS; i++ )
+#endif
+  {
+    if( m_acTDecTop[i].getListPic()->empty() )
+    {
+      continue;
+    }
+    
+    // To check # AUs that have at least one picture not output,
+    // For each layer, populate listOfPOcs if not already present
+    TComList<TComPic*>::iterator iterPic = m_acTDecTop[i].getListPic()->begin();
+    Int picPositionInList = 0;
+    while (iterPic != m_acTDecTop[i].getListPic()->end())
+    {
+      TComPic* pic = *(iterPic);
+      if( pic->getReconMark() )
+      {
+        if( vps == NULL )
+        {
+          vps = pic->getSlice(0)->getVPS();
+        }
+#if POC_RESET_IDC_DECODER
+        if( !(pic->isCurrAu() && notOutputCurrAu ) )
+        {
+#endif
+          std::vector<Int>::iterator it;
+          if( pic->getOutputMark() ) // && pic->getPOC() > m_aiPOCLastDisplay[i])
+          {
+            it = find( listOfPocs.begin(), listOfPocs.end(), pic->getPOC() ); // Check if already included
+            if( it == listOfPocs.end() )  // New POC value - i.e. new AU - add to the list
+            {
+              listOfPocs.push_back( pic->getPOC() );
+            }
+            listOfPocsInEachLayer         [i].push_back( pic->getPOC()    );    // POC to be output in each layer
+            listOfPocsPositionInEachLayer [i].push_back( picPositionInList  );  // For ease of access
+          }
+          if( pic->getSlice(0)->isReferenced() || pic->getOutputMark() )
+          {
+#if RESOLUTION_BASED_DPB
+            dpbStatus.m_numPicsInLayer[i]++;  // Count pictures that are "used for reference" or "needed for output"
+#else
+            dpbStatus.m_numPicsInSubDpb[i]++;  // Count pictures that are "used for reference" or "needed for output"
+#endif
+          }
+#if POC_RESET_IDC_DECODER
+        }
+#endif
+      }
+      iterPic++;
+      picPositionInList++;
+    }
+  }
+
+  assert( vps != NULL );    // No picture in any DPB?
+  std::sort( listOfPocs.begin(), listOfPocs.end() );    // Sort in increasing order of POC
+  Int targetLsIdx = vps->getOutputLayerSetIdx( getCommonDecoderParams()->getTargetOutputLayerSetIdx() );
+  // Update status
+  dpbStatus.m_numAUsNotDisplayed = (Int)listOfPocs.size();   // Number of AUs not displayed
+  dpbStatus.m_numLayers = vps->getNumLayersInIdList( targetLsIdx );
+#if FIX_ALIGN_BUMPING
+  for(Int i = 0; i < dpbStatus.m_numLayers; i++)
+  {
+    dpbStatus.m_layerIdToSubDpbIdMap[vps->getLayerSetLayerIdList(targetLsIdx, i)] = i;
+    dpbStatus.m_targetDecLayerIdList[i] = vps->getLayerSetLayerIdList(targetLsIdx, i);  // Layer Id stored in a particular sub-DPB
+  }
+  dpbStatus.m_numSubDpbs = vps->getNumSubDpbs( targetLsIdx ); 
+#else
+  dpbStatus.m_numSubDpbs = vps->getNumSubDpbs( vps->getOutputLayerSetIdx(
+                                                      this->getCommonDecoderParams()->getTargetOutputLayerSetIdx() ) );
+#endif
+
+#if FIX_ALIGN_BUMPING
+  for(Int i = 0; i < MAX_VPS_LAYER_IDX_PLUS1; i++)
+#else
+  for(Int i = 0; i < dpbStatus.m_numLayers; i++)
+#endif
+  {
+    dpbStatus.m_numPicsNotDisplayedInLayer[i] = (Int)listOfPocsInEachLayer[i].size();
+#if RESOLUTION_BASED_DPB
+    dpbStatus.m_numPicsInSubDpb[vps->getSubDpbAssigned(targetLsIdx,i)] += dpbStatus.m_numPicsInLayer[i];
+    dpbStatus.m_numPicsInSubDpb[i] += dpbStatus.m_numPicsInLayer[i];
+#endif
+  }
+  assert( dpbStatus.m_numAUsNotDisplayed != -1 );
+}  
+
+#if POC_RESET_IDC_DECODER
+Void TAppDecTop::outputAllPictures(Int layerId, Bool notOutputCurrPic)
+{
+  { // All pictures in the DPB in that layer are to be output; this means other pictures would also be output
+    std::vector<Int>  listOfPocs;
+#if FIX_ALIGN_BUMPING
+    std::vector<Int>  listOfPocsInEachLayer[MAX_VPS_LAYER_IDX_PLUS1];
+    std::vector<Int>  listOfPocsPositionInEachLayer[MAX_VPS_LAYER_IDX_PLUS1];
+#else
+    std::vector<Int>  listOfPocsInEachLayer[MAX_LAYERS];
+    std::vector<Int>  listOfPocsPositionInEachLayer[MAX_LAYERS];
+#endif
+    DpbStatus dpbStatus;
+
+    // Find the status of the DPB
+    xFindDPBStatus(listOfPocs, listOfPocsInEachLayer, listOfPocsPositionInEachLayer, dpbStatus, notOutputCurrPic);
+
+    if( listOfPocs.size() )
+    {
+      while( listOfPocsInEachLayer[layerId].size() )    // As long as there picture in the layer to be output
+      {
+        bumpingProcess( listOfPocs, listOfPocsInEachLayer, listOfPocsPositionInEachLayer, dpbStatus );
+      }
+    }
+  }
+}
+#endif
+#endif
+//! \}
Index: /tags/SHM-9.0/source/App/TAppDecoder/TAppDecTop.h
===================================================================
--- /tags/SHM-9.0/source/App/TAppDecoder/TAppDecTop.h	(revision 1088)
+++ /tags/SHM-9.0/source/App/TAppDecoder/TAppDecTop.h	(revision 1088)
@@ -0,0 +1,184 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TAppDecTop.h
+    \brief    Decoder application class (header)
+*/
+
+#ifndef __TAPPDECTOP__
+#define __TAPPDECTOP__
+
+#if _MSC_VER > 1000
+#pragma once
+#endif // _MSC_VER > 1000
+
+#include "TLibVideoIO/TVideoIOYuv.h"
+#include "TLibCommon/TComList.h"
+#include "TLibCommon/TComPicYuv.h"
+#include "TLibDecoder/TDecTop.h"
+#include "TAppDecCfg.h"
+
+//! \ingroup TAppDecoder
+//! \{
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+#if ALIGNED_BUMPING
+struct DpbStatus;
+#endif
+/// decoder application class
+class TAppDecTop : public TAppDecCfg
+{
+private:
+  // class interface
+#if SVC_EXTENSION
+  TDecTop                         m_acTDecTop [MAX_LAYERS];                             ///< decoder class [WARNING] suppose to use MAX_NUM_LAYER_IDS but decoder crashes, pending for further investigation
+  TDecTop*                        m_apcTDecTop [MAX_NUM_LAYER_IDS];                     ///< decoder point class 
+  TVideoIOYuv                     m_acTVideoIOYuvReconFile [MAX_NUM_LAYER_IDS];         ///< reconstruction YUV class
+#else
+  TDecTop                         m_cTDecTop;                     ///< decoder class
+  TVideoIOYuv                     m_cTVideoIOYuvReconFile;        ///< reconstruction YUV class
+#endif
+  
+  // for output control  
+#if SVC_EXTENSION
+#if CONFORMANCE_BITSTREAM_MODE
+  TVideoIOYuv                      m_confReconFile[63];        ///< decode YUV files
+#endif 
+  Int                             m_aiPOCLastDisplay [MAX_LAYERS]; ///< last POC in display order
+#else
+  Int                             m_iPOCLastDisplay;              ///< last POC in display order
+#endif
+  std::ofstream                   m_seiMessageFileStream;         ///< Used for outputing SEI messages.  
+
+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 SVC_EXTENSION
+  Void  xWriteOutput      ( TComList<TComPic*>* pcListPic, UInt layerId, UInt tId ); ///< write YUV to file
+  Void  xFlushOutput      ( TComList<TComPic*>* pcListPic, UInt layerId ); ///< flush all remaining decoded pictures to file
+#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
+#if ALIGNED_BUMPING
+  Void checkOutputBeforeDecoding(Int layerIdx);
+  Void checkOutputAfterDecoding();
+  Void flushAllPictures(Bool outputPictures); 
+  Void flushAllPictures(Int layerId, Bool outputPictures);
+
+  Void xOutputAndMarkPic( TComPic *pic, const Char *reconFile, const Int layerId, Int &pocLastDisplay, DpbStatus &dpbStatus);
+#if POC_RESET_IDC_DECODER
+  Void outputAllPictures(Int layerId, Bool notOutputCurrAu);
+#endif
+  Void xFindDPBStatus( std::vector<Int> &listOfPocs
+                            , std::vector<Int> *listOfPocsInEachLayer
+                            , std::vector<Int> *listOfPocsPositionInEachLayer
+                            , DpbStatus &dpbStatus
+#if POC_RESET_IDC_DECODER
+                            , Bool notOutputCurrAu = true
+#endif
+                            );
+
+  Bool ifInvokeBumpingBeforeDecoding( const DpbStatus &dpbStatus, const DpbStatus &dpbLimit, const Int layerIdx, const Int subDpbIdx );
+  Bool ifInvokeBumpingAfterDecoding ( const DpbStatus &dpbStatus, const DpbStatus &dpbLimit );
+  Void bumpingProcess(std::vector<Int> &listOfPocs, std::vector<Int> *listOfPocsInEachLayer, std::vector<Int> *listOfPocsPositionInEachLayer, DpbStatus &dpbStatus);
+  Void emptyUnusedPicturesNotNeededForOutput();
+  Void markAllPicturesAsErased();
+  Void markAllPicturesAsErased(Int layerIdx);
+  TComVPS* findDpbParametersFromVps(std::vector<Int> const &listOfPocs, std::vector<Int> const *listOfPocsInEachLayer, std::vector<Int> const *listOfPocsPositionInEachLayer, DpbStatus &maxDpbLimit);
+#endif
+};
+
+#if ALIGNED_BUMPING
+struct DpbStatus
+{
+  // Number of AUs and pictures
+  Int m_numAUsNotDisplayed;
+  Int m_numPicsNotDisplayedInLayer[MAX_LAYERS];
+#if RESOLUTION_BASED_DPB
+  Int m_numPicsInLayer[MAX_LAYERS];   // Pictures marked as used_for_reference or needed for output in the layer
+#endif
+  Int m_numPicsInSubDpb[MAX_LAYERS];  // Pictures marked as used_for_reference or needed for output in the sub-DPB
+#if FIX_ALIGN_BUMPING
+  Int m_layerIdToSubDpbIdMap[MAX_VPS_LAYER_IDX_PLUS1];
+  Int m_targetDecLayerIdList[MAX_LAYERS];
+#endif
+  Bool m_maxLatencyIncrease;
+  Int m_maxLatencyPictures;
+  
+  Int m_numSubDpbs;
+  Int m_numLayers;
+
+  DpbStatus()
+  {
+    init();
+  }
+  Void init()
+  {
+    m_numAUsNotDisplayed = 0;
+    m_maxLatencyIncrease  = false;
+    m_maxLatencyPictures  = 0;
+#if RESOLUTION_BASED_DPB
+    ::memset( m_numPicsInLayer,  0, sizeof(m_numPicsInLayer)  );
+#endif
+    ::memset( m_numPicsInSubDpb, 0, sizeof(m_numPicsInSubDpb) );
+    ::memset(m_numPicsNotDisplayedInLayer, 0, sizeof(m_numPicsNotDisplayedInLayer) );
+    m_numSubDpbs = -1;
+    m_numLayers = -1;
+#if FIX_ALIGN_BUMPING
+    ::memset( m_targetDecLayerIdList, 0, sizeof(m_targetDecLayerIdList) );
+    for(Int i = 0; i < MAX_VPS_LAYER_IDX_PLUS1; i++)
+    {
+      m_layerIdToSubDpbIdMap[i] = -1;
+    }
+#endif
+  }
+};
+#endif
+//! \}
+
+#endif
+
Index: /tags/SHM-9.0/source/App/TAppDecoder/decmain.cpp
===================================================================
--- /tags/SHM-9.0/source/App/TAppDecoder/decmain.cpp	(revision 1088)
+++ /tags/SHM-9.0/source/App/TAppDecoder/decmain.cpp	(revision 1088)
@@ -0,0 +1,100 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     decmain.cpp
+    \brief    Decoder application main
+*/
+
+#include <stdlib.h>
+#include <stdio.h>
+#include <time.h>
+#include "TAppDecTop.h"
+
+//! \ingroup TAppDecoder
+//! \{
+
+Bool g_md5_mismatch = false; ///< top level flag that indicates if there has been a decoding mismatch
+
+// ====================================================================================================================
+// Main function
+// ====================================================================================================================
+
+int main(int argc, char* argv[])
+{
+  TAppDecTop  cTAppDecTop;
+
+  // print information
+  fprintf( stdout, "\n" );
+#if SVC_EXTENSION
+  fprintf( stdout, "SHM software: Decoder Version [%s]", NV_VERSION );
+#else
+  fprintf( stdout, "HM software: Decoder Version [%s] (including RExt)", 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;
+  clock_t 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: /tags/SHM-9.0/source/App/TAppDownConvert/DownConvert.cpp
===================================================================
--- /tags/SHM-9.0/source/App/TAppDownConvert/DownConvert.cpp	(revision 1088)
+++ /tags/SHM-9.0/source/App/TAppDownConvert/DownConvert.cpp	(revision 1088)
@@ -0,0 +1,582 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "DownConvert.h"
+
+#include <cmath>
+#include <cstring>
+
+
+#define  TMM_TABLE_SIZE          512
+
+
+//=================================================
+//
+//   G E N E R A L   M A I N   F U N C T I O N S
+//
+//=================================================
+
+DownConvert::DownConvert()
+: m_iImageStride            ( 0 )
+, m_paiImageBuffer          ( 0 )
+, m_paiTmp1dBuffer          ( 0 )
+{
+}
+  
+DownConvert::~DownConvert()
+{
+  xDestroy();
+}
+
+bool
+DownConvert::init( int iMaxWidth, int iMaxHeight, int iMaxMargin )
+{
+  xDestroy();
+
+  iMaxWidth                += 2 * iMaxMargin;
+  iMaxHeight               += 2 * iMaxMargin;
+  int iPicSize              =   iMaxWidth * iMaxHeight;
+  int iMaxDim               = ( iMaxWidth > iMaxHeight ? iMaxWidth : iMaxHeight );
+  m_iImageStride            = iMaxWidth;
+  m_paiImageBuffer          = new int [ iPicSize ];
+  m_paiTmp1dBuffer          = new int [ iMaxDim ];
+
+  ROFRS( m_paiImageBuffer,          true );
+  ROFRS( m_paiTmp1dBuffer,          true );
+
+  return false;
+}
+
+void
+DownConvert::destroy()
+{
+  delete this;
+}
+
+//===========================================================================
+//
+//   M A I N   F U N C T I O N S   F O R   D O W N C O N V E R T   T O O L
+//
+//===========================================================================
+
+
+void
+DownConvert::downsamplingSVC( unsigned char*    pucBufferY,   int   iStrideY,
+                              unsigned char*    pucBufferU,   int   iStrideU,
+                              unsigned char*    pucBufferV,   int   iStrideV,
+                              ResizeParameters* pcParameters, bool  bBotCoincided )
+{
+  int   iBaseW                  =   pcParameters->m_iFrameWidth;
+  int   iBaseH                  =   pcParameters->m_iFrameHeight;
+  int   iCurrW                  =   pcParameters->m_iRefLayerFrmWidth;
+  int   iCurrH                  =   pcParameters->m_iRefLayerFrmHeight;
+  bool  bTopAndBottomResampling = ( pcParameters->m_bRefLayerFrameMbsOnlyFlag == false  &&
+                                    pcParameters->m_bRefLayerFieldPicFlag     == false  &&
+                                    pcParameters->m_bFrameMbsOnlyFlag         == false  &&
+                                    pcParameters->m_bFieldPicFlag             == false    );
+  bool  bVerticalDownsampling   = ( pcParameters->m_bFrameMbsOnlyFlag         == true   &&
+                                    pcParameters->m_bRefLayerFieldPicFlag     == true     );
+  bool  bCurrBotField           = ( pcParameters->m_bFieldPicFlag             == true   &&
+                                    pcParameters->m_bBotFieldFlag             == true     );
+  bool  bBotFieldFlag           = ( pcParameters->m_bRefLayerFrameMbsOnlyFlag ?  false
+                                  : pcParameters->m_bFieldPicFlag             ?  pcParameters->m_bBotFieldFlag
+                                  : pcParameters->m_bRefLayerFieldPicFlag     ?  pcParameters->m_bRefLayerBotFieldFlag
+                                  : false );
+  int   iBaseField              = ( pcParameters->m_bRefLayerFrameMbsOnlyFlag ?  0 : 1 );
+  int   iCurrField              = ( pcParameters->m_bFieldPicFlag             ?  1 : 0 );
+  int   iBaseBot                = ( bBotFieldFlag ? 1 : 0 );
+  int   iCurrBot                = ( bCurrBotField ? 1 : 0 );
+
+  //==== check bot field coincided parameter for interlaced to progressive resampling =====
+  if( pcParameters->m_bRefLayerFrameMbsOnlyFlag && ! pcParameters->m_bFrameMbsOnlyFlag )
+  {
+    bBotFieldFlag = bBotCoincided;
+  }
+
+  //=======================
+  //=====   L U M A   =====
+  //=======================
+  assert( bTopAndBottomResampling == false );
+  if( !bTopAndBottomResampling )
+  {
+    unsigned char* pSrc = pucBufferY + iStrideY * iCurrBot;
+    unsigned char* pDes = pucBufferY + iStrideY * iBaseBot;
+    xCopyToImageBuffer  ( pSrc,         iCurrW, iCurrH >> iCurrField, iStrideY << iCurrField );
+    xCompDownsampling   ( pcParameters, false,  bBotFieldFlag,        bVerticalDownsampling  );
+    xCopyFromImageBuffer( pDes,         iBaseW, iBaseH >> iBaseField, iStrideY << iBaseField );
+  }
+
+  iBaseW >>= 1;
+  iBaseH >>= 1;
+  iCurrW >>= 1;
+  iCurrH >>= 1;
+
+  //===========================
+  //=====   C H R O M A   =====
+  //===========================
+  if( !bTopAndBottomResampling )
+  {
+    //===== U =====
+    unsigned char* pSrc = pucBufferU + iStrideU * iCurrBot;
+    unsigned char* pDes = pucBufferU + iStrideU * iBaseBot;
+    xCopyToImageBuffer  ( pSrc,         iCurrW, iCurrH >> iCurrField, iStrideU << iCurrField );
+    xCompDownsampling   ( pcParameters, true,   bBotFieldFlag,        bVerticalDownsampling  );
+    xCopyFromImageBuffer( pDes,         iBaseW, iBaseH >> iBaseField, iStrideU << iBaseField );
+
+    //===== V =====
+    pSrc = pucBufferV + iStrideV * iCurrBot;
+    pDes = pucBufferV + iStrideV * iBaseBot;
+    xCopyToImageBuffer  ( pSrc,         iCurrW, iCurrH >> iCurrField, iStrideV << iCurrField );
+    xCompDownsampling   ( pcParameters, true,   bBotFieldFlag,        bVerticalDownsampling  );
+    xCopyFromImageBuffer( pDes,         iBaseW, iBaseH >> iBaseField, iStrideV << iBaseField );
+  }
+}
+
+
+//======================================================
+//
+//   G E N E R A L   H E L P E R    F U N C T I O N S
+//
+//======================================================
+
+void
+DownConvert::xDestroy()
+{
+  delete [] m_paiImageBuffer;
+  delete [] m_paiTmp1dBuffer;
+  m_paiImageBuffer          = 0;
+  m_paiTmp1dBuffer          = 0;
+}
+
+int
+DownConvert::xClip( int iValue, int imin, int imax )
+{
+  ROTRS( iValue < imin, imin );
+  ROTRS( iValue > imax, imax );
+  return iValue;
+}
+
+
+//===============================================================================
+//
+//   H E L P E R   F U N C T I O N S   F O R   D O W N C O N V E R T   T O O L
+//
+//===============================================================================
+
+void
+DownConvert::xCopyToImageBuffer( unsigned char* pucSrc, int iWidth, int iHeight, int iStride )
+{
+  int* piDes = m_paiImageBuffer;
+  for( int j = 0; j < iHeight; j++ )
+  {
+    for( int i = 0; i < iWidth;  i++ )
+    {
+      piDes[i] = (int)pucSrc[i];
+    }
+    piDes   += m_iImageStride;
+    pucSrc  += iStride;
+  }
+}
+
+void
+DownConvert::xCopyFromImageBuffer( unsigned char* pucDes, int iWidth, int iHeight, int iStride )
+{
+  int* piSrc = m_paiImageBuffer;
+  for( int j = 0; j < iHeight; j++ )
+  {
+    for( int i = 0; i < iWidth;  i++ )
+    {
+      pucDes[i] = (unsigned char)piSrc[i];
+    }
+    pucDes  += iStride;
+    piSrc   += m_iImageStride;
+  }
+}
+
+void
+DownConvert::xCompDownsampling( ResizeParameters* pcParameters, bool bChroma, bool bBotFlag, bool bVerticalDownsampling )
+{
+  //===== set general parameters =====
+  int   iBotField   = ( bBotFlag ? 1 : 0 );
+  int   iFactor     = ( !bChroma ? 1 : 2 );
+  int   iRefPhaseX  = ( !bChroma ? 0 : pcParameters->m_iChromaPhaseX );
+  int   iRefPhaseY  = ( !bChroma ? 0 : pcParameters->m_iChromaPhaseY );
+  int   iPhaseX     = ( !bChroma ? 0 : pcParameters->m_iRefLayerChromaPhaseX );
+  int   iPhaseY     = ( !bChroma ? 0 : pcParameters->m_iRefLayerChromaPhaseY );
+  int   iRefW       = pcParameters->m_iFrameWidth         / iFactor;  // reference layer frame width
+  int   iRefH       = pcParameters->m_iFrameHeight        / iFactor;  // reference layer frame height
+  int   iOutW       = pcParameters->m_iScaledRefFrmWidth  / iFactor;  // scaled reference layer frame width
+  int   iOutH       = pcParameters->m_iScaledRefFrmHeight / iFactor;  // scaled reference layer frame height
+  int   iGlobalW    = pcParameters->m_iRefLayerFrmWidth   / iFactor;  // current frame width
+  int   iGlobalH    = pcParameters->m_iRefLayerFrmHeight  / iFactor;  // current frame height
+  int   iLeftOffset = pcParameters->m_iLeftFrmOffset      / iFactor;  // current left frame offset
+  int   iTopOffset  = pcParameters->m_iTopFrmOffset       / iFactor;  // current  top frame offset
+
+  //===== set input/output size =====
+  int   iBaseField  = ( pcParameters->m_bRefLayerFrameMbsOnlyFlag ? 0 : 1 );
+  int   iCurrField  = ( pcParameters->m_bRefLayerFrameMbsOnlyFlag && pcParameters->m_bFrameMbsOnlyFlag ? 0 : 1 );
+  int   iBaseW      = iRefW;
+  int   iBaseH      = iRefH       >> iBaseField;
+  int   iCurrW      = iGlobalW;
+  int   iCurrH      = iGlobalH    >> iCurrField;
+  int   iLOffset    = iLeftOffset;
+  int   iTOffset    = iTopOffset  >> iCurrField;
+  int   iROffset    = iCurrW - iLOffset -   iOutW;
+  int   iBOffset    = iCurrH - iTOffset - ( iOutH >> iCurrField );
+
+  //===== set position calculation parameters =====
+  int   iScaledW    = iOutW;
+  int   iScaledH    = ( ! pcParameters->m_bRefLayerFrameMbsOnlyFlag || pcParameters->m_bFrameMbsOnlyFlag ? iOutH : iOutH / 2 );
+  int   iShiftX     = ( pcParameters->m_iLevelIdc <= 30 ? 16 : 31 - CeilLog2( iScaledW ) );
+  int   iShiftY     = ( pcParameters->m_iLevelIdc <= 30 ? 16 : 31 - CeilLog2( iScaledH ) );
+  int   iScaleX     = ( ( (unsigned int)iScaledW << iShiftX ) + ( iRefW >> 1 ) ) / iRefW;
+  int   iScaleY     = ( ( (unsigned int)iScaledH << iShiftY ) + ( iRefH >> 1 ) ) / iRefH;
+  if( ! pcParameters->m_bFrameMbsOnlyFlag || ! pcParameters->m_bRefLayerFrameMbsOnlyFlag )
+  {
+    if( pcParameters->m_bRefLayerFrameMbsOnlyFlag )
+    {
+      iPhaseY       = iPhaseY + 4 * iBotField + ( 3 - iFactor );
+#if ZERO_PHASE
+      iRefPhaseY    = 2 * iRefPhaseY + 0;
+#else
+      iRefPhaseY    = 2 * iRefPhaseY + 2;
+#endif
+    }
+    else
+    {
+      iPhaseY       = iPhaseY    + 4 * iBotField;
+      iRefPhaseY    = iRefPhaseY + 4 * iBotField;
+    }
+  }
+#if ZERO_PHASE
+  int   iAddX       = ( ( ( iScaledW * ( 0 + iRefPhaseX ) ) << ( iShiftX - 2 ) ) + ( iRefW >> 1 ) ) / iRefW + ( 1 << ( iShiftX - 5 ) );
+  int   iAddY       = ( ( ( iScaledH * ( 0 + iRefPhaseY ) ) << ( iShiftY - 2 ) ) + ( iRefH >> 1 ) ) / iRefH + ( 1 << ( iShiftY - 5 ) );
+  int   iDeltaX     = 4 * ( 0 + iPhaseX ) - ( iLeftOffset << 4 );
+  int   iDeltaY     = 4 * ( 0 + iPhaseY ) - ( iTopOffset  << 4 );
+#else
+  int   iAddX       = ( ( ( iScaledW * ( 2 + iRefPhaseX ) ) << ( iShiftX - 2 ) ) + ( iRefW >> 1 ) ) / iRefW + ( 1 << ( iShiftX - 5 ) );
+  int   iAddY       = ( ( ( iScaledH * ( 2 + iRefPhaseY ) ) << ( iShiftY - 2 ) ) + ( iRefH >> 1 ) ) / iRefH + ( 1 << ( iShiftY - 5 ) );
+  int   iDeltaX     = 4 * ( 2 + iPhaseX ) - ( iLeftOffset << 4 );
+  int   iDeltaY     = 4 * ( 2 + iPhaseY ) - ( iTopOffset  << 4 );
+#endif
+  if( ! pcParameters->m_bFrameMbsOnlyFlag || ! pcParameters->m_bRefLayerFrameMbsOnlyFlag )
+  {
+#if ZERO_PHASE
+    iAddY           = ( ( ( iScaledH * ( 0 + iRefPhaseY ) ) << ( iShiftY - 3 ) ) + ( iRefH >> 1 ) ) / iRefH + ( 1 << ( iShiftY - 5 ) );
+    iDeltaY         = 2 * ( 0 + iPhaseY ) - ( iTopOffset  << 3 );
+#else
+    iAddY           = ( ( ( iScaledH * ( 2 + iRefPhaseY ) ) << ( iShiftY - 3 ) ) + ( iRefH >> 1 ) ) / iRefH + ( 1 << ( iShiftY - 5 ) );
+    iDeltaY         = 2 * ( 2 + iPhaseY ) - ( iTopOffset  << 3 );
+#endif
+  }
+
+  //===== vertical downsampling to generate a field signal from a progressive frame =====
+  if( bVerticalDownsampling )
+  {
+    xVertDownsampling( iCurrW, iCurrH, bBotFlag );
+  }
+
+  //===== basic downsampling of a frame or field =====
+  xBasicDownsampling( iBaseW,   iBaseH,   iCurrW,   iCurrH,
+                      iLOffset, iTOffset, iROffset, iBOffset,
+                      iShiftX,  iShiftY,  iScaleX,  iScaleY,
+                      iAddX,    iAddY,    iDeltaX,  iDeltaY );
+}
+
+void
+DownConvert::xVertDownsampling( int   iBaseW,
+                                int   iBaseH,
+                                bool  bBotFlag )
+{
+  int aiVertFilter[13]  = { 2, 0, -4, -3, 5, 19, 26, 19, 5, -3, -4, 0, 2 };
+  int iBotField         = ( bBotFlag ? 1 : 0 );
+  int iCurrW            = iBaseW;
+  int iCurrH            = iBaseH << 1;
+
+  //===== vertical downsampling =====
+  for( int j = 0; j < iCurrW; j++ )
+  {
+    int* piSrc = &m_paiImageBuffer[j];
+    for( int i = 0; i < iBaseH; i++ )
+    {
+      m_paiTmp1dBuffer[i] = 0;
+      for( int k = 0; k < 13; k++ )
+      {
+        int m = xClip( 2 * i + iBotField + k - 6, 0, iCurrH - 1 );
+        m_paiTmp1dBuffer[i] += aiVertFilter[k] * piSrc[m*m_iImageStride];
+      }
+      m_paiTmp1dBuffer[i] = ( m_paiTmp1dBuffer[i] + 32 ) >> 6;
+    }
+    //--- clip and copy back to image buffer ---
+    for( int n = 0; n < iBaseH; n++ )
+    {
+      piSrc[n*m_iImageStride] = xClip( m_paiTmp1dBuffer[n], 0, 255 );
+    }
+  }
+}
+
+void
+DownConvert::xBasicDownsampling( int iBaseW,   int iBaseH,   int iCurrW,   int iCurrH,
+                                 int iLOffset, int iTOffset, int iROffset, int iBOffset,
+                                 int iShiftX,  int iShiftY,  int iScaleX,  int iScaleY,
+                                 int iAddX,    int iAddY,    int iDeltaX,  int iDeltaY )
+{
+  const int filter16[8][16][12] =
+  {
+    { // D = 1
+      {   0,   0,   0,   0,   0, 128,   0,   0,   0,   0,   0,   0 },
+      {   0,   0,   0,   2,  -6, 127,   7,  -2,   0,   0,   0,   0 },
+      {   0,   0,   0,   3, -12, 125,  16,  -5,   1,   0,   0,   0 },
+      {   0,   0,   0,   4, -16, 120,  26,  -7,   1,   0,   0,   0 },
+      {   0,   0,   0,   5, -18, 114,  36, -10,   1,   0,   0,   0 },
+      {   0,   0,   0,   5, -20, 107,  46, -12,   2,   0,   0,   0 },
+      {   0,   0,   0,   5, -21,  99,  57, -15,   3,   0,   0,   0 },
+      {   0,   0,   0,   5, -20,  89,  68, -18,   4,   0,   0,   0 },
+      {   0,   0,   0,   4, -19,  79,  79, -19,   4,   0,   0,   0 },
+      {   0,   0,   0,   4, -18,  68,  89, -20,   5,   0,   0,   0 },
+      {   0,   0,   0,   3, -15,  57,  99, -21,   5,   0,   0,   0 },
+      {   0,   0,   0,   2, -12,  46, 107, -20,   5,   0,   0,   0 },
+      {   0,   0,   0,   1, -10,  36, 114, -18,   5,   0,   0,   0 },
+      {   0,   0,   0,   1,  -7,  26, 120, -16,   4,   0,   0,   0 },
+      {   0,   0,   0,   1,  -5,  16, 125, -12,   3,   0,   0,   0 },
+      {   0,   0,   0,   0,  -2,   7, 127,  -6,   2,   0,   0,   0 }
+    },
+    { // D = 1.5
+      {   0,   2,   0, -14,  33,  86,  33, -14,   0,   2,   0,   0 },
+      {   0,   1,   1, -14,  29,  85,  38, -13,  -1,   2,   0,   0 },
+      {   0,   1,   2, -14,  24,  84,  43, -12,  -2,   2,   0,   0 },
+      {   0,   1,   2, -13,  19,  83,  48, -11,  -3,   2,   0,   0 },
+      {   0,   0,   3, -13,  15,  81,  53, -10,  -4,   3,   0,   0 },
+      {   0,   0,   3, -12,  11,  79,  57,  -8,  -5,   3,   0,   0 },
+      {   0,   0,   3, -11,   7,  76,  62,  -5,  -7,   3,   0,   0 },
+      {   0,   0,   3, -10,   3,  73,  65,  -2,  -7,   3,   0,   0 },
+      {   0,   0,   3,  -9,   0,  70,  70,   0,  -9,   3,   0,   0 },
+      {   0,   0,   3,  -7,  -2,  65,  73,   3, -10,   3,   0,   0 },
+      {   0,   0,   3,  -7,  -5,  62,  76,   7, -11,   3,   0,   0 },
+      {   0,   0,   3,  -5,  -8,  57,  79,  11, -12,   3,   0,   0 },
+      {   0,   0,   3,  -4, -10,  53,  81,  15, -13,   3,   0,   0 },
+      {   0,   0,   2,  -3, -11,  48,  83,  19, -13,   2,   1,   0 },
+      {   0,   0,   2,  -2, -12,  43,  84,  24, -14,   2,   1,   0 },
+      {   0,   0,   2,  -1, -13,  38,  85,  29, -14,   1,   1,   0 }
+    },
+    { // D = 2
+      {   0,   5,   -6,  -10,  37,  76,   37,  -10,  -6,    5,  0,   0}, //0
+      {   0,   5,   -4,  -11,  33,  76,   40,  -9,    -7,    5,  0,   0}, //1
+      //{   0,   5,   -3,  -12,  28,  75,   44,  -7,    -8,    5,  1,   0}, //2
+      {  -1,   5,   -3,  -12,  29,  75,   45,  -7,    -8,   5,  0,   0}, //2 new coefficients in m24499
+      {  -1,   4,   -2,  -13,  25,  75,   48,  -5,    -9,    5,  1,   0}, //3
+      {  -1,   4,   -1,  -13,  22,  73,   52,  -3,    -10,  4,  1,   0}, //4
+      {  -1,   4,   0,    -13,  18,  72,   55,  -1,    -11,  4,  2,  -1}, //5
+      {  -1,   4,   1,    -13,  14,  70,   59,  2,    -12,  3,  2,  -1}, //6
+      {  -1,   3,   1,    -13,  11,  68,   62,  5,    -12,  3,  2,  -1}, //7
+      {  -1,   3,   2,    -13,  8,  65,   65,  8,    -13,  2,  3,  -1}, //8
+      {  -1,   2,   3,    -12,  5,  62,   68,  11,    -13,  1,  3,  -1}, //9
+      {  -1,   2,   3,    -12,  2,  59,   70,  14,    -13,  1,  4,  -1}, //10
+      {  -1,   2,   4,    -11,  -1,  55,   72,  18,    -13,  0,  4,  -1}, //11
+      {   0,   1,   4,    -10,  -3,  52,   73,  22,    -13,  -1,  4,  -1}, //12
+      {   0,   1,   5,    -9,    -5,  48,   75,  25,    -13,  -2,  4,  -1}, //13
+      //{   0,   1,   5,    -8,    -7,  44,   75,  28,    -12,  -3,  5,   0}, //14
+      {    0,   0,   5,    -8,   -7,  45,   75,  29,    -12,  -3,  5,  -1}  , //14 new coefficients in m24499  
+      {   0,   0,   5,    -7,    -9,  40,   76,  33,    -11,  -4,  5,   0}, //15
+    },
+    { // D = 2.5
+      {   2,  -3,   -9,  6,   39,  58,   39,  6,   -9,  -3,    2,    0}, // 0
+      {   2,  -3,   -9,  4,   38,  58,   43,  7,   -9,  -4,    1,    0}, // 1
+      {   2,  -2,   -9,  2,   35,  58,   44,  9,   -8,  -4,    1,    0}, // 2
+      {   1,  -2,   -9,  1,   34,  58,   46,  11,   -8,  -5,    1,    0}, // 3
+      //{   1,  -1,   -8,  -1,   31,  57,   48,  13,   -8,  -5,    1,    0}, // 4
+      {   1,  -1,   -8,  -1,   31,  57,   47,  13,   -7,  -5,    1,    0},  // 4 new coefficients in m24499  
+      {   1,  -1,   -8,  -2,   29,  56,   49,  15,   -7,  -6,    1,    1}, // 5
+      {   1,  0,   -8,  -3,   26,  55,   51,  17,   -7,  -6,    1,    1}, // 6
+      {   1,  0,   -7,  -4,   24,  54,   52,  19,   -6,  -7,    1,    1}, // 7
+      {   1,  0,   -7,  -5,   22,  53,   53,  22,   -5,  -7,    0,    1}, // 8
+      {   1,  1,   -7,  -6,   19,  52,   54,  24,   -4,  -7,    0,    1}, // 9
+      {   1,  1,   -6,  -7,   17,  51,   55,  26,   -3,  -8,    0,    1}, // 10
+      {   1,  1,   -6,  -7,   15,  49,   56,  29,   -2,  -8,    -1,    1}, // 11
+      //{   0,  1,   -5,  -8,   13,  48,   57,  31,   -1,  -8,    -1,    1}, // 12 new coefficients in m24499
+      {   0,  1,   -5,  -7,   13,  47,  57,  31,  -1,    -8,   -1,    1}, // 12   
+      {   0,  1,   -5,  -8,   11,  46,   58,  34,   1,    -9,    -2,    1}, // 13
+      {   0,  1,   -4,  -8,   9,    44,   58,  35,   2,    -9,    -2,    2}, // 14
+      {   0,  1,   -4,  -9,   7,    43,   58,  38,   4,    -9,    -3,    2}, // 15
+    },
+    { // D = 3
+      {  -2,  -7,   0,  17,  35,  43,  35,  17,   0,  -7,  -5,   2 },
+      {  -2,  -7,  -1,  16,  34,  43,  36,  18,   1,  -7,  -5,   2 },
+      {  -1,  -7,  -1,  14,  33,  43,  36,  19,   1,  -6,  -5,   2 },
+      {  -1,  -7,  -2,  13,  32,  42,  37,  20,   3,  -6,  -5,   2 },
+      {   0,  -7,  -3,  12,  31,  42,  38,  21,   3,  -6,  -5,   2 },
+      {   0,  -7,  -3,  11,  30,  42,  39,  23,   4,  -6,  -6,   1 },
+      {   0,  -7,  -4,  10,  29,  42,  40,  24,   5,  -6,  -6,   1 },
+      {   1,  -7,  -4,   9,  27,  41,  40,  25,   6,  -5,  -6,   1 },
+      {   1,  -6,  -5,   7,  26,  41,  41,  26,   7,  -5,  -6,   1 },
+      {   1,  -6,  -5,   6,  25,  40,  41,  27,   9,  -4,  -7,   1 },
+      {   1,  -6,  -6,   5,  24,  40,  42,  29,  10,  -4,  -7,   0 },
+      {   1,  -6,  -6,   4,  23,  39,  42,  30,  11,  -3,  -7,   0 },
+      {   2,  -5,  -6,   3,  21,  38,  42,  31,  12,  -3,  -7,   0 },
+      {   2,  -5,  -6,   3,  20,  37,  42,  32,  13,  -2,  -7,  -1 },
+      {   2,  -5,  -6,   1,  19,  36,  43,  33,  14,  -1,  -7,  -1 },
+      {   2,  -5,  -7,   1,  18,  36,  43,  34,  16,  -1,  -7,  -2 }
+    },
+    { // D = 3.5
+      {  -6,  -3,   5,  19,  31,  36,  31,  19,   5,  -3,  -6,   0 },
+      {  -6,  -4,   4,  18,  31,  37,  32,  20,   6,  -3,  -6,  -1 },
+      {  -6,  -4,   4,  17,  30,  36,  33,  21,   7,  -3,  -6,  -1 },
+      {  -5,  -5,   3,  16,  30,  36,  33,  22,   8,  -2,  -6,  -2 },
+      {  -5,  -5,   2,  15,  29,  36,  34,  23,   9,  -2,  -6,  -2 },
+      {  -5,  -5,   2,  15,  28,  36,  34,  24,  10,  -2,  -6,  -3 },
+      {  -4,  -5,   1,  14,  27,  36,  35,  24,  10,  -1,  -6,  -3 },
+      {  -4,  -5,   0,  13,  26,  35,  35,  25,  11,   0,  -5,  -3 },
+      {  -4,  -6,   0,  12,  26,  36,  36,  26,  12,   0,  -6,  -4 },
+      {  -3,  -5,   0,  11,  25,  35,  35,  26,  13,   0,  -5,  -4 },
+      {  -3,  -6,  -1,  10,  24,  35,  36,  27,  14,   1,  -5,  -4 },
+      {  -3,  -6,  -2,  10,  24,  34,  36,  28,  15,   2,  -5,  -5 },
+      {  -2,  -6,  -2,   9,  23,  34,  36,  29,  15,   2,  -5,  -5 },
+      {  -2,  -6,  -2,   8,  22,  33,  36,  30,  16,   3,  -5,  -5 },
+      {  -1,  -6,  -3,   7,  21,  33,  36,  30,  17,   4,  -4,  -6 },
+      {  -1,  -6,  -3,   6,  20,  32,  37,  31,  18,   4,  -4,  -6 }
+    },
+    { // D = 4
+      {  -9,   0,   9,  20,  28,  32,  28,  20,   9,   0,  -9,   0 },
+      {  -9,   0,   8,  19,  28,  32,  29,  20,  10,   0,  -4,  -5 },
+      {  -9,  -1,   8,  18,  28,  32,  29,  21,  10,   1,  -4,  -5 },
+      {  -9,  -1,   7,  18,  27,  32,  30,  22,  11,   1,  -4,  -6 },
+      {  -8,  -2,   6,  17,  27,  32,  30,  22,  12,   2,  -4,  -6 },
+      {  -8,  -2,   6,  16,  26,  32,  31,  23,  12,   2,  -4,  -6 },
+      {  -8,  -2,   5,  16,  26,  31,  31,  23,  13,   3,  -3,  -7 },
+      {  -8,  -3,   5,  15,  25,  31,  31,  24,  14,   4,  -3,  -7 },
+      {  -7,  -3,   4,  14,  25,  31,  31,  25,  14,   4,  -3,  -7 },
+      {  -7,  -3,   4,  14,  24,  31,  31,  25,  15,   5,  -3,  -8 },
+      {  -7,  -3,   3,  13,  23,  31,  31,  26,  16,   5,  -2,  -8 },
+      {  -6,  -4,   2,  12,  23,  31,  32,  26,  16,   6,  -2,  -8 },
+      {  -6,  -4,   2,  12,  22,  30,  32,  27,  17,   6,  -2,  -8 },
+      {  -6,  -4,   1,  11,  22,  30,  32,  27,  18,   7,  -1,  -9 },
+      {  -5,  -4,   1,  10,  21,  29,  32,  28,  18,   8,  -1,  -9 },
+      {  -5,  -4,   0,  10,  20,  29,  32,  28,  19,   8,   0,  -9 }
+    },
+    { // D = 5.5
+      {  -8,   7,  13,  18,  22,  24,  22,  18,  13,   7,   2, -10 },
+      {  -8,   7,  13,  18,  22,  23,  22,  19,  13,   7,   2, -10 },
+      {  -8,   6,  12,  18,  22,  23,  22,  19,  14,   8,   2, -10 },
+      {  -9,   6,  12,  17,  22,  23,  23,  19,  14,   8,   3, -10 },
+      {  -9,   6,  12,  17,  21,  23,  23,  19,  14,   9,   3, -10 },
+      {  -9,   5,  11,  17,  21,  23,  23,  20,  15,   9,   3, -10 },
+      {  -9,   5,  11,  16,  21,  23,  23,  20,  15,   9,   4, -10 },
+      {  -9,   5,  10,  16,  21,  23,  23,  20,  15,  10,   4, -10 },
+      { -10,   5,  10,  16,  20,  23,  23,  20,  16,  10,   5, -10 },
+      { -10,   4,  10,  15,  20,  23,  23,  21,  16,  10,   5,  -9 },
+      { -10,   4,   9,  15,  20,  23,  23,  21,  16,  11,   5,  -9 },
+      { -10,   3,   9,  15,  20,  23,  23,  21,  17,  11,   5,  -9 },
+      { -10,   3,   9,  14,  19,  23,  23,  21,  17,  12,   6,  -9 },
+      { -10,   3,   8,  14,  19,  23,  23,  22,  17,  12,   6,  -9 },
+      { -10,   2,   8,  14,  19,  22,  23,  22,  18,  12,   6,  -8 },
+      { -10,   2,   7,  13,  19,  22,  23,  22,  18,  13,   7,  -8 }
+    }
+  };
+
+  //===== determine filter sets =====
+  int iCropW      = iCurrW - iLOffset - iROffset;
+  int iCropH      = iCurrH - iTOffset - iBOffset;
+  int iVerFilter  = 0;
+  int iHorFilter  = 0;
+  if      (  4 * iCropH > 15 * iBaseH )   iVerFilter  = 7;
+  else if (  7 * iCropH > 20 * iBaseH )   iVerFilter  = 6;
+  else if (  2 * iCropH >  5 * iBaseH )   iVerFilter  = 5;
+  else if (  1 * iCropH >  2 * iBaseH )   iVerFilter  = 4;
+  else if (  3 * iCropH >  5 * iBaseH )   iVerFilter  = 3;
+  else if (  4 * iCropH >  5 * iBaseH )   iVerFilter  = 2;
+  else if ( 19 * iCropH > 20 * iBaseH )   iVerFilter  = 1;
+  if      (  4 * iCropW > 15 * iBaseW )   iHorFilter  = 7;
+  else if (  7 * iCropW > 20 * iBaseW )   iHorFilter  = 6;
+  else if (  2 * iCropW >  5 * iBaseW )   iHorFilter  = 5;
+  else if (  1 * iCropW >  2 * iBaseW )   iHorFilter  = 4;
+  else if (  3 * iCropW >  5 * iBaseW )   iHorFilter  = 3;
+  else if (  4 * iCropW >  5 * iBaseW )   iHorFilter  = 2;
+  else if ( 19 * iCropW > 20 * iBaseW )   iHorFilter  = 1;
+
+  int iShiftXM4 = iShiftX - 4;
+  int iShiftYM4 = iShiftY - 4;
+
+  //===== horizontal downsampling =====
+  {
+    for( int j = 0; j < iCurrH; j++ )
+    {
+      int* piSrc = &m_paiImageBuffer[j*m_iImageStride];
+      for( int i = 0; i < iBaseW; i++ )
+      {
+        int iRefPos16 = (int)( (unsigned int)( i * iScaleX + iAddX ) >> iShiftXM4 ) - iDeltaX;
+        int iPhase    = iRefPos16  & 15;
+        int iRefPos   = iRefPos16 >>  4;
+
+        m_paiTmp1dBuffer[i] = 0;
+        for( int k = 0; k < 12; k++ )
+        {
+          int m = xClip( iRefPos + k - 5, 0, iCurrW - 1 );
+          m_paiTmp1dBuffer[i] += filter16[iHorFilter][iPhase][k] * piSrc[m];
+        }
+      }
+      //--- copy row back to image buffer ---
+      memcpy( piSrc, m_paiTmp1dBuffer, iBaseW*sizeof(int) );
+    }
+  }
+
+  //===== vertical downsampling =====
+  {
+    for( int i = 0; i < iBaseW; i++ )
+    {
+      int* piSrc = &m_paiImageBuffer[i];
+      for( int j = 0; j < iBaseH; j++ )
+      {
+        int iRefPos16 = (int)( (unsigned int)( j * iScaleY + iAddY ) >> iShiftYM4 ) - iDeltaY;
+        int iPhase    = iRefPos16  & 15;
+        int iRefPos   = iRefPos16 >>  4;
+
+        m_paiTmp1dBuffer[j] = 0;
+        for( int k = 0; k < 12; k++ )
+        {
+          int m = xClip( iRefPos + k - 5, 0, iCurrH - 1 );
+          m_paiTmp1dBuffer[j] += filter16[iVerFilter][iPhase][k] * piSrc[m*m_iImageStride];
+        }
+        m_paiTmp1dBuffer[j] = ( m_paiTmp1dBuffer[j] + 8192 ) >> 14;
+      }
+      //--- clip and copy back to image buffer ---
+      for( int n = 0; n < iBaseH; n++ )
+      {
+        piSrc[n*m_iImageStride] = xClip( m_paiTmp1dBuffer[n], 0, 255 );
+      }
+    }
+  }
+}
+
+
+
+
Index: /tags/SHM-9.0/source/App/TAppDownConvert/DownConvert.h
===================================================================
--- /tags/SHM-9.0/source/App/TAppDownConvert/DownConvert.h	(revision 1088)
+++ /tags/SHM-9.0/source/App/TAppDownConvert/DownConvert.h	(revision 1088)
@@ -0,0 +1,208 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef _DOWN_CONVERT_
+#define _DOWN_CONVERT_
+
+#define ZERO_PHASE        1
+
+#define ESS_NONE      0
+
+#include <cassert>
+#include "../../Lib/TLibCommon/TypeDef.h"
+
+#ifndef  gMax
+#define  gMax(x,y)   ((x)>(y)?(x):(y))
+#define  gMin(x,y)   ((x)<(y)?(x):(y))
+
+#define ROFRS( exp, retVal )  \
+{                             \
+  if( !( exp ) )              \
+  {                           \
+  return retVal;            \
+  }                           \
+}
+
+#define ROTRS( exp, retVal )  \
+{                             \
+  if( ( exp ) )               \
+  {                           \
+  return retVal;            \
+  }                           \
+}
+
+#endif
+
+class ResizeParameters 
+{
+public:
+  ResizeParameters()
+    : m_iExtendedSpatialScalability ( ESS_NONE )
+    , m_iLevelIdc                   ( 0 )
+    , m_bFrameMbsOnlyFlag           ( true )
+    , m_bFieldPicFlag               ( false )
+    , m_bBotFieldFlag               ( false )
+    , m_bIsMbAffFrame               ( false )
+    , m_iFrameWidth                 ( 0 )
+    , m_iFrameHeight                ( 0 )
+    , m_iWidthInSamples             ( 0 )
+    , m_iHeightInSamples            ( 0 )
+    , m_iChromaPhaseX               ( 0 )
+    , m_iChromaPhaseY               ( 0 )
+    , m_iScaledRefFrmWidth          ( 0 )
+    , m_iScaledRefFrmHeight         ( 0 )
+    , m_iLeftFrmOffset              ( 0 )
+    , m_iTopFrmOffset               ( 0 )
+    , m_iRefLayerChromaPhaseX       ( 0 )
+    , m_iRefLayerChromaPhaseY       ( 0 )
+    , m_bRefLayerFrameMbsOnlyFlag   ( true )
+    , m_bRefLayerFieldPicFlag       ( false )
+    , m_bRefLayerBotFieldFlag       ( false )
+    , m_bRefLayerIsMbAffFrame       ( false )
+    , m_iRefLayerFrmWidth           ( 0 )
+    , m_iRefLayerFrmHeight          ( 0 )
+    , m_iRefLayerWidthInSamples     ( 0 )
+    , m_iRefLayerHeightInSamples    ( 0 )
+  { 
+  };
+
+
+
+public:
+  //===== parameters of current layer =====
+  Int   m_iExtendedSpatialScalability;
+  Int   m_iLevelIdc;
+  Bool  m_bFrameMbsOnlyFlag;
+  Bool  m_bFieldPicFlag;
+  Bool  m_bBotFieldFlag;
+  Bool  m_bIsMbAffFrame;
+  Int   m_iFrameWidth;
+  Int   m_iFrameHeight;
+  Int   m_iWidthInSamples;
+  Int   m_iHeightInSamples;
+  Int   m_iChromaPhaseX;
+  Int   m_iChromaPhaseY;
+  Int   m_iScaledRefFrmWidth;     // also in PictureParameters
+  Int   m_iScaledRefFrmHeight;    // also in PictureParameters
+  Int   m_iLeftFrmOffset;         // also in PictureParameters
+  Int   m_iTopFrmOffset;          // also in PictureParameters
+  Int   m_iRefLayerChromaPhaseX;  // also in PictureParameters
+  Int   m_iRefLayerChromaPhaseY;  // also in PictureParameters
+
+  //===== parameters for base layer =====
+  Bool  m_bRefLayerFrameMbsOnlyFlag;
+  Bool  m_bRefLayerFieldPicFlag;
+  Bool  m_bRefLayerBotFieldFlag;
+  Bool  m_bRefLayerIsMbAffFrame;
+  Int   m_iRefLayerFrmWidth;
+  Int   m_iRefLayerFrmHeight;
+  Int   m_iRefLayerWidthInSamples;
+  Int   m_iRefLayerHeightInSamples;
+};
+
+
+class DownConvert
+{
+public:
+  //========================
+  // general main functions
+  //========================
+  DownConvert   ();
+  ~DownConvert  ();
+  bool  init    ( int iMaxWidth, int iMaxHeight, int iMaxMargin = 0 );
+  void  destroy ();
+
+  //=====================================
+  // main functions for DownConvert Tool
+  //=====================================
+  void  downsamplingSVC             ( unsigned char*          pucBufferY,    int   iStrideY,
+                                      unsigned char*          pucBufferU,    int   iStrideU,
+                                      unsigned char*          pucBufferV,    int   iStrideV,
+                                      ResizeParameters*       pcParameters,  bool  bBotCoincided = false );
+
+  //==========================
+  // general helper functions
+  //==========================
+  //--- delete buffers ---
+  void  xDestroy                    ();
+  //--- general clipping ---
+  int   xClip                       ( int                     iValue,
+                                      int                     imin,
+                                      int                     imax );
+  //=======================================
+  // helper functions for DownConvert Tool
+  //=======================================
+  //--- place to and get from image buffer ---
+  void  xCopyToImageBuffer          ( unsigned char*        pucSrc,
+                                      int                   iWidth,
+                                      int                   iHeight,
+                                      int                   iStride );
+  void  xCopyFromImageBuffer        ( unsigned char*        pucDes,
+                                      int                   iWidth,
+                                      int                   iHeight,
+                                      int                   iStride );
+  //--- SVC non-normative downsampling ---
+  void  xCompDownsampling           ( ResizeParameters*     pcParameters,
+                                      bool                  bChroma,
+                                      bool                  bBotFlag,
+                                      bool                  bVerticalDownsampling );
+  void  xVertDownsampling           ( int                   iBaseW,
+                                      int                   iBaseH,
+                                      bool                  bBotFlag );
+  void  xBasicDownsampling          ( int  iBaseW,   int  iBaseH,   int  iCurrW,   int  iCurrH,
+                                      int  iLOffset, int  iTOffset, int  iROffset, int  iBOffset,
+                                      int  iShiftX,  int  iShiftY,  int  iScaleX,  int  iScaleY,
+                                      int  iAddX,    int  iAddY,    int  iDeltaX,  int  iDeltaY );
+private:
+  //===== member variables =====
+  int         m_iImageStride;
+  int*        m_paiImageBuffer;
+  int*        m_paiTmp1dBuffer;
+};
+
+
+__inline Int CeilLog2( Int i )
+{
+  Int s = 0; i--;
+  while( i > 0 )
+  {
+    s++;
+    i >>= 1;
+  }
+  return s;
+}
+
+
+#endif // _DOWN_CONVERT_
+
+
Index: /tags/SHM-9.0/source/App/TAppDownConvert/TAppDownConvert.cpp
===================================================================
--- /tags/SHM-9.0/source/App/TAppDownConvert/TAppDownConvert.cpp	(revision 1088)
+++ /tags/SHM-9.0/source/App/TAppDownConvert/TAppDownConvert.cpp	(revision 1088)
@@ -0,0 +1,592 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TAppDownConvert.cpp
+    \brief    Down convert application main
+*/
+
+#include <cmath>
+#include <cstdio>
+#include <cstdlib>
+#include <cstring>
+#include <ctime>
+
+#include "DownConvert.h"
+
+typedef struct
+{
+  int            stride;
+  int            lines;
+  unsigned char* data;
+  unsigned char* data2;
+} ColorComponent;
+
+typedef struct
+{
+  ColorComponent y;
+  ColorComponent u;
+  ColorComponent v;
+} YuvFrame;
+
+
+void
+  createColorComponent( ColorComponent& c, int maxwidth, int maxheight )
+{
+  maxwidth  = ( ( maxwidth  + 15 ) >> 4 ) << 4;
+  maxheight = ( ( maxheight + 15 ) >> 4 ) << 4;
+  int size  = maxwidth * maxheight;
+  c.stride  = maxwidth;
+  c.lines   = maxheight;
+  c.data    = new unsigned char [ size ];
+  c.data2   = new unsigned char [ size ];
+
+  if( ! c.data || ! c.data2 )
+  {
+    fprintf(stderr, "\nERROR: memory allocation failed!\n\n");
+    exit(1);
+  }
+}
+
+void
+  deleteColorComponent( ColorComponent& c )
+{
+  delete[] c.data;
+  delete[] c.data2;
+  c.stride  = 0;
+  c.lines   = 0;
+  c.data    = 0;
+  c.data2   = 0;
+}
+
+int
+  readColorComponent( ColorComponent& c, FILE* file, int width, int height, bool second )
+{
+  assert( width  <= c.stride );
+  assert( height <= c.lines  );
+
+  int iMaxPadWidth  = gMin( c.stride, ( ( width  + 15 ) >> 4 ) << 4 );
+  int iMaxPadHeight = gMin( c.lines,  ( ( height + 31 ) >> 5 ) << 5 );
+
+  for( int i = 0; i < height; i++ )
+  {
+    unsigned char* buffer = ( second ? c.data2 : c.data ) + i * c.stride;
+    int            rsize  = (int)fread( buffer, sizeof(unsigned char), width, file );
+    if( rsize != width )
+    {
+      return 1;
+    }
+    for( int xp = width; xp < iMaxPadWidth; xp++ )
+    {
+      buffer[xp] = buffer[xp-1];
+    }
+  }
+  for( int yp = height; yp < iMaxPadHeight; yp++ )
+  {
+    unsigned char* buffer  = ( second ? c.data2 : c.data ) + yp * c.stride;
+    unsigned char* bufferX = buffer - c.stride;
+    for( int xp = 0; xp < c.stride; xp++ )
+    {
+      buffer[xp] = bufferX[xp];
+    }
+  }
+  return 0;
+}
+
+void
+  duplicateColorComponent( ColorComponent& c )
+{
+  memcpy( c.data2, c.data, c.stride * c.lines * sizeof(unsigned char) );
+}
+
+void
+  combineTopAndBottomInColorComponent( ColorComponent& c, Bool bBotField )
+{
+  int            offs = ( bBotField ? c.stride : 0 );
+  unsigned char* pDes = c.data  + offs;
+  unsigned char* pSrc = c.data2 + offs;
+  for( int i = 0; i < c.lines / 2; i++, pDes += 2*c.stride, pSrc += 2*c.stride )
+  {
+    memcpy( pDes, pSrc, c.stride * sizeof(unsigned char) );
+  }
+}
+
+void
+  writeColorComponent( ColorComponent& c, FILE* file, int width, int height, bool second )
+{
+  assert( width  <= c.stride );
+  assert( height <= c.lines  );
+
+  for( int i = 0; i < height; i++ )
+  {
+    unsigned char* buffer = ( second ? c.data2 : c.data ) + i * c.stride;
+    int            wsize  = (int)fwrite( buffer, sizeof(unsigned char), width, file );
+
+    if( wsize != width )
+    {
+      fprintf(stderr, "\nERROR: while writing to output file!\n\n");
+      exit(1);
+    }
+  }
+}
+
+
+void
+  createFrame( YuvFrame& f, int width, int height )
+{
+  createColorComponent( f.y, width,      height      );
+  createColorComponent( f.u, width >> 1, height >> 1 );
+  createColorComponent( f.v, width >> 1, height >> 1 );
+}
+
+void
+  deleteFrame( YuvFrame& f )
+{
+  deleteColorComponent( f.y );
+  deleteColorComponent( f.u );
+  deleteColorComponent( f.v );
+}
+
+int
+  readFrame( YuvFrame& f, FILE* file, int width, int height, bool second = false )
+{
+  ROTRS( readColorComponent( f.y, file, width,      height,      second ), 1 );
+  ROTRS( readColorComponent( f.u, file, width >> 1, height >> 1, second ), 1 );
+  ROTRS( readColorComponent( f.v, file, width >> 1, height >> 1, second ), 1 );
+  return 0;
+}
+
+void
+  duplicateFrame( YuvFrame& f )
+{
+  duplicateColorComponent( f.y );
+  duplicateColorComponent( f.u );
+  duplicateColorComponent( f.v );
+}
+
+void
+  combineTopAndBottomInFrame( YuvFrame& f, Bool botField )
+{
+  combineTopAndBottomInColorComponent( f.y, botField );
+  combineTopAndBottomInColorComponent( f.u, botField );
+  combineTopAndBottomInColorComponent( f.v, botField );
+}
+
+void
+  writeFrame( YuvFrame& f, FILE* file, int width, int height, bool both = false )
+{
+  writeColorComponent( f.y, file, width,      height,      false );
+  writeColorComponent( f.u, file, width >> 1, height >> 1, false );
+  writeColorComponent( f.v, file, width >> 1, height >> 1, false );
+
+  if( both )
+  {
+    writeColorComponent( f.y, file, width,      height,      true );
+    writeColorComponent( f.u, file, width >> 1, height >> 1, true );
+    writeColorComponent( f.v, file, width >> 1, height >> 1, true );
+  }
+}
+
+
+void
+  print_usage_and_exit( int test, const char* name, const char* message = 0 )
+{
+  if( test )
+  {
+    if( message )
+    {
+      fprintf ( stderr, "\nERROR: %s\n", message );
+    }
+    fprintf (   stderr, "\nUsage: %s <win> <hin> <in> <wout> <hout> <out> [<t> [<skip> [<frms>]]] [[-phase <args>] ]\n\n", name );
+    fprintf (   stderr, "  win     : input width  (luma samples)\n" );
+    fprintf (   stderr, "  hin     : input height (luma samples)\n" );
+    fprintf (   stderr, "  in      : input file\n" );
+    fprintf (   stderr, "  wout    : output width  (luma samples)\n" );
+    fprintf (   stderr, "  hout    : output height (luma samples)\n" );
+    fprintf (   stderr, "  out     : output file\n" );
+    fprintf (   stderr, "\n--------------------------- OPTIONAL ---------------------------\n\n" );
+    fprintf (   stderr, "  t       : number of temporal downsampling stages (default: 0)\n" );
+    fprintf (   stderr, "  skip    : number of frames to skip at start (default: 0)\n" );
+    fprintf (   stderr, "  frms    : number of frames wanted in output file (default: max)\n" );
+    fprintf (   stderr, "\n-------------------------- OVERLOADED --------------------------\n\n" );
+    fprintf (   stderr, " -phase <in_uv_ph_x> <in_uv_ph_y> <out_uv_ph_x> <out_uv_ph_y>\n");
+    fprintf (   stderr, "   in_uv_ph_x : input  chroma phase shift in horizontal direction (default:-1)\n" );
+    fprintf (   stderr, "   in_uv_ph_y : input  chroma phase shift in vertical   direction (default: 0)\n" );
+    fprintf (   stderr, "   out_uv_ph_x: output chroma phase shift in horizontal direction (default:-1)\n" );
+    fprintf (   stderr, "   out_uv_ph_y: output chroma phase shift in vertical   direction (default: 0)\n" );
+    fprintf (   stderr, "\n\n");
+    exit    (   1 );
+  }
+}
+
+
+void
+  updateCropParametersFromFile( ResizeParameters& cRP, FILE* cropFile, int resamplingMethod, char* name )
+{
+  int crop_x0 = 0;
+  int crop_y0 = 0;
+  int crop_w  = 0;
+  int crop_h  = 0;
+  if( fscanf( cropFile, "%d,%d,%d,%d\n", &crop_x0, &crop_y0, &crop_w, &crop_h ) == 4 )
+  {
+    cRP.m_iLeftFrmOffset      = crop_x0;
+    cRP.m_iTopFrmOffset       = crop_y0;
+    cRP.m_iScaledRefFrmWidth  = crop_w;
+    cRP.m_iScaledRefFrmHeight = crop_h;
+  }
+  print_usage_and_exit( cRP.m_iLeftFrmOffset     & 1 || cRP.m_iTopFrmOffset       & 1,                                              name, "cropping parameters must be even values" );
+  print_usage_and_exit( cRP.m_iScaledRefFrmWidth & 1 || cRP.m_iScaledRefFrmHeight & 1,                                              name, "cropping parameters must be even values" );
+  print_usage_and_exit( resamplingMethod == 2 && cRP.m_iScaledRefFrmWidth  != gMin( cRP.m_iRefLayerFrmWidth,  cRP.m_iFrameWidth  ),  name, "crop dimensions must be the same as the minimal dimensions" );
+  print_usage_and_exit( resamplingMethod == 2 && cRP.m_iScaledRefFrmHeight != gMin( cRP.m_iRefLayerFrmHeight, cRP.m_iFrameHeight ),  name, "crop dimensions must be the same as the minimal dimensions" );
+  print_usage_and_exit( cRP.m_iScaledRefFrmWidth  > gMax( cRP.m_iRefLayerFrmWidth,  cRP.m_iFrameWidth  ),                            name, "wrong crop window size" );
+  print_usage_and_exit( cRP.m_iScaledRefFrmHeight > gMax( cRP.m_iRefLayerFrmHeight, cRP.m_iFrameHeight ),                            name, "wrong crop window size" );
+  print_usage_and_exit( cRP.m_iScaledRefFrmWidth  < gMin( cRP.m_iRefLayerFrmWidth,  cRP.m_iFrameWidth  ),                            name, "wrong crop window size" );
+  print_usage_and_exit( cRP.m_iScaledRefFrmHeight < gMin( cRP.m_iRefLayerFrmHeight, cRP.m_iFrameHeight ),                            name, "wrong crop window size" );
+  print_usage_and_exit( cRP.m_iLeftFrmOffset + cRP.m_iScaledRefFrmWidth  > gMax( cRP.m_iRefLayerFrmWidth,  cRP.m_iFrameWidth  ),     name, "wrong crop window size and origin" );
+  print_usage_and_exit( cRP.m_iTopFrmOffset  + cRP.m_iScaledRefFrmHeight > gMax( cRP.m_iRefLayerFrmHeight, cRP.m_iFrameHeight ),     name, "wrong crop window size and origin" );
+}
+
+
+void
+  resampleFrame( YuvFrame&          rcFrame,
+  DownConvert&       rcDownConvert,
+  ResizeParameters&  rcRP,
+  int                resamplingMethod,
+  int                resamplingMode,
+  bool               resampling,
+  bool               upsampling,
+  bool               bSecondInputFrame )
+{
+  assert( upsampling == 0 );
+
+  //===== downsampling =====
+  ResizeParameters cRP = rcRP;
+  {
+    Int iRefVerMbShift        = ( cRP.m_bRefLayerFrameMbsOnlyFlag ? 4 : 5 );
+    Int iScaledVerShift       = ( cRP.m_bFrameMbsOnlyFlag         ? 1 : 2 );
+    Int iHorDiv               = ( cRP.m_iFrameWidth    <<               1 );
+    Int iVerDiv               = ( cRP.m_iFrameHeight   << iScaledVerShift );
+    Int iRefFrmW              = ( ( cRP.m_iFrameWidth   + ( 1 <<               4 ) - 1 ) >>               4 ) <<               4;        // round to next multiple of 16
+    Int iRefFrmH              = ( ( cRP.m_iFrameHeight  + ( 1 <<  iRefVerMbShift ) - 1 ) >>  iRefVerMbShift ) <<  iRefVerMbShift;        // round to next multiple of 16 or 32 (for interlaced)
+    Int iScaledRefFrmW        = ( ( cRP.m_iScaledRefFrmWidth  * iRefFrmW + ( iHorDiv >> 1 ) ) / iHorDiv ) <<               1;  // scale and round to next multiple of  2
+    Int iScaledRefFrmH        = ( ( cRP.m_iScaledRefFrmHeight * iRefFrmH + ( iVerDiv >> 1 ) ) / iVerDiv ) << iScaledVerShift;  // scale and round to next multiple of  2 or  4 (for interlaced)
+    cRP.m_iFrameWidth         = iRefFrmW;
+    cRP.m_iFrameHeight        = iRefFrmH;
+    cRP.m_iScaledRefFrmWidth  = iScaledRefFrmW;
+    cRP.m_iScaledRefFrmHeight = iScaledRefFrmH;
+  }
+  assert( resamplingMethod == 0 );
+  if( resamplingMode < 4 )
+  {
+    rcDownConvert.downsamplingSVC       ( rcFrame.y.data,  rcFrame.y.stride, rcFrame.u.data,  rcFrame.u.stride, rcFrame.v.data,  rcFrame.v.stride, &cRP, resamplingMode == 3 );
+    return;
+  }
+}
+
+
+
+int
+  main( int argc, char *argv[] )
+{
+  //===== set standard resize parameters =====
+  ResizeParameters cRP;
+  cRP.m_bRefLayerFrameMbsOnlyFlag   = true;
+  cRP.m_bFrameMbsOnlyFlag           = true;
+  cRP.m_bRefLayerFieldPicFlag       = false;
+  cRP.m_bFieldPicFlag               = false;
+  cRP.m_bRefLayerBotFieldFlag       = false;
+  cRP.m_bBotFieldFlag               = false;
+  cRP.m_bRefLayerIsMbAffFrame       = false;
+  cRP.m_bIsMbAffFrame               = false;
+#if ZERO_PHASE
+  cRP.m_iRefLayerChromaPhaseX       = 0;
+  cRP.m_iRefLayerChromaPhaseY       = 1;
+  cRP.m_iChromaPhaseX               = 0;
+  cRP.m_iChromaPhaseY               = 1;
+#else
+  cRP.m_iRefLayerChromaPhaseX       = -1;
+  cRP.m_iRefLayerChromaPhaseY       = 0;
+  cRP.m_iChromaPhaseX               = -1;
+  cRP.m_iChromaPhaseY               = 0;
+#endif
+  cRP.m_iRefLayerFrmWidth           = 0;
+  cRP.m_iRefLayerFrmHeight          = 0;
+  cRP.m_iScaledRefFrmWidth          = 0;
+  cRP.m_iScaledRefFrmHeight         = 0;
+  cRP.m_iFrameWidth                 = 0;
+  cRP.m_iFrameHeight                = 0;
+  cRP.m_iLeftFrmOffset              = 0;
+  cRP.m_iTopFrmOffset               = 0;
+  //cRP.m_iExtendedSpatialScalability = 0;
+  cRP.m_iLevelIdc                   = 0;
+
+  //===== init parameters =====
+  FILE* inputFile                   = 0;
+  FILE* outputFile                  = 0;
+  FILE* croppingParametersFile      = 0;
+  int   resamplingMethod            = 0;
+  int   resamplingMode              = 0;
+  bool  croppingInitialized         = false;
+  bool  phaseInitialized            = false;
+  bool  methodInitialized           = false;
+  bool  resampling                  = false;
+  bool  upsampling                  = false;
+  int   numSpatialDyadicStages      = 0;
+  int   skipBetween                 = 0;
+  int   skipAtStart                 = 0;
+  int   maxNumOutputFrames          = 0;
+
+
+  //===== read input parameters =====
+  print_usage_and_exit( ( argc < 7 || argc > 24 ), argv[0], "wrong number of arguments" );
+  cRP.m_iRefLayerFrmWidth   = atoi  ( argv[1] );
+  cRP.m_iRefLayerFrmHeight  = atoi  ( argv[2] );
+  inputFile                 = fopen ( argv[3], "rb" );
+  cRP.m_iFrameWidth         = atoi  ( argv[4] );
+  cRP.m_iFrameHeight        = atoi  ( argv[5] );
+  outputFile                = fopen ( argv[6], "wb" );
+  print_usage_and_exit( ! inputFile,  argv[0], "failed to open input file" );
+  print_usage_and_exit( ! outputFile, argv[0], "failed to open input file" );
+  print_usage_and_exit( cRP.m_iRefLayerFrmWidth > cRP.m_iFrameWidth && cRP.m_iRefLayerFrmHeight < cRP.m_iFrameHeight, argv[0], "mixed upsampling and downsampling not supported" );
+  print_usage_and_exit( cRP.m_iRefLayerFrmWidth < cRP.m_iFrameWidth && cRP.m_iRefLayerFrmHeight > cRP.m_iFrameHeight, argv[0], "mixed upsampling and downsampling not supported" );
+  for( int i = 7; i < argc; )
+  {
+    if( ! strcmp( argv[i], "-phase" ) )
+    {
+      print_usage_and_exit( resamplingMethod != 0,          argv[0], "phases only supported in normative resampling" );
+      print_usage_and_exit( phaseInitialized || argc < i+5, argv[0], "wrong number of phase parameters" );
+      phaseInitialized = true;
+      i++;
+      cRP.m_iRefLayerChromaPhaseX = atoi( argv[i++] );
+      cRP.m_iRefLayerChromaPhaseY = atoi( argv[i++] );
+      cRP.m_iChromaPhaseX         = atoi( argv[i++] );
+      cRP.m_iChromaPhaseY         = atoi( argv[i++] );
+      print_usage_and_exit( cRP.m_iRefLayerChromaPhaseX > 0 || cRP.m_iRefLayerChromaPhaseX < -1, argv[0], "wrong phase x parameters (range : [-1, 0])");
+      print_usage_and_exit( cRP.m_iRefLayerChromaPhaseY > 1 || cRP.m_iRefLayerChromaPhaseY < -1, argv[0], "wrong phase x parameters (range : [-1, 1])");
+      print_usage_and_exit( cRP.m_iChromaPhaseX         > 0 || cRP.m_iChromaPhaseX         < -1, argv[0], "wrong phase x parameters (range : [-1, 0])");
+      print_usage_and_exit( cRP.m_iChromaPhaseY         > 1 || cRP.m_iChromaPhaseY         < -1, argv[0], "wrong phase x parameters (range : [-1, 1])");
+    }
+    else if (i == 7)
+    {
+      methodInitialized = true;
+      resamplingMethod  = atoi( argv[i++] );
+      print_usage_and_exit( resamplingMethod < 0 || resamplingMethod > 4, argv[0], "unsupported method" );
+      if( resamplingMethod > 2 )
+      {
+        print_usage_and_exit( cRP.m_iRefLayerFrmWidth  > cRP.m_iFrameWidth,  argv[0], "method 3 and 4 are not supported for downsampling" );
+        print_usage_and_exit( cRP.m_iRefLayerFrmHeight > cRP.m_iFrameHeight, argv[0], "method 3 and 4 are not supported for downsampling" );
+      }
+      if( resamplingMethod != 2 )
+      {
+        resampling  = true;
+        upsampling  = ( cRP.m_iRefLayerFrmWidth < cRP.m_iFrameWidth ) || ( cRP.m_iRefLayerFrmHeight < cRP.m_iFrameHeight );
+      }
+      if( resamplingMethod == 1 )
+      {
+        if( upsampling )
+        {
+          int      div  = cRP.m_iFrameWidth / cRP.m_iRefLayerFrmWidth;
+          if     ( div == 1) numSpatialDyadicStages =  0;
+          else if( div == 2) numSpatialDyadicStages =  1;
+          else if( div == 4) numSpatialDyadicStages =  2;
+          else if( div == 8) numSpatialDyadicStages =  3;
+          else               numSpatialDyadicStages = -1;
+          print_usage_and_exit( numSpatialDyadicStages < 0,                           argv[0], "ratio not supported for dyadic upsampling method" );
+          print_usage_and_exit( div * cRP.m_iRefLayerFrmWidth  != cRP.m_iFrameWidth,  argv[0], "ratio is not dyadic in dyadic mode" );
+          print_usage_and_exit( div * cRP.m_iRefLayerFrmHeight != cRP.m_iFrameHeight, argv[0], "different horizontal and vertical ratio in dyadic mode" );
+        }
+        else
+        {
+          int      div  = cRP.m_iRefLayerFrmWidth / cRP.m_iFrameWidth;
+          if     ( div == 1) numSpatialDyadicStages =  0;
+          else if( div == 2) numSpatialDyadicStages =  1;
+          else if( div == 4) numSpatialDyadicStages =  2;
+          else if( div == 8) numSpatialDyadicStages =  3;
+          else               numSpatialDyadicStages = -1;
+          print_usage_and_exit( numSpatialDyadicStages < 0,                           argv[0], "ratio not supported for dyadic downsampling method" );
+          print_usage_and_exit( div * cRP.m_iFrameWidth  != cRP.m_iRefLayerFrmWidth,  argv[0], "ratio is not dyadic in dyadic mode" );
+          print_usage_and_exit( div * cRP.m_iFrameHeight != cRP.m_iRefLayerFrmHeight, argv[0], "different horizontal and vertical ratio in dyadic mode" );
+        }
+      }
+    }
+    else if( i == 8 )
+    {
+      int TStages = atoi( argv[i++] );
+      skipBetween = ( 1 << TStages ) - 1;
+      print_usage_and_exit( TStages < 0,              argv[0], "negative number of temporal stages" );
+    }
+    else if( i == 9 )
+    {
+      skipAtStart = atoi( argv[i++] );
+      print_usage_and_exit( skipAtStart < 0,          argv[0], "negative number of skipped frames at start" );
+    }
+    else if( i == 10 )
+    {
+      maxNumOutputFrames = atoi( argv[i++] );
+      print_usage_and_exit( maxNumOutputFrames < 0 ,  argv[0], "negative number of output frames" );
+    }
+    else
+    {
+      print_usage_and_exit( true, argv[0], "error in command line parameters" );
+    }
+  }
+  if( ! methodInitialized )
+  {
+    resampling  = true;
+    upsampling  = ( cRP.m_iRefLayerFrmWidth < cRP.m_iFrameWidth ) || ( cRP.m_iRefLayerFrmHeight < cRP.m_iFrameHeight );
+  }
+  if( ! croppingInitialized )
+  {
+    if( resamplingMethod == 2 )
+    {
+      cRP.m_iScaledRefFrmWidth  = gMin( cRP.m_iRefLayerFrmWidth,  cRP.m_iFrameWidth  );
+      cRP.m_iScaledRefFrmHeight = gMin( cRP.m_iRefLayerFrmHeight, cRP.m_iFrameHeight );
+    }
+    else
+    {
+      cRP.m_iScaledRefFrmWidth  = gMax( cRP.m_iRefLayerFrmWidth,  cRP.m_iFrameWidth  );
+      cRP.m_iScaledRefFrmHeight = gMax( cRP.m_iRefLayerFrmHeight, cRP.m_iFrameHeight );
+    }
+  }
+
+  //===== set basic parameters for resampling control =====
+  if( resamplingMethod == 0 )
+  {
+    if( resamplingMode == 1 )
+    {
+      cRP.m_bRefLayerFrameMbsOnlyFlag = false;
+      cRP.m_bFrameMbsOnlyFlag         = false;
+    }
+    else if( resamplingMode == 2 || resamplingMode == 3 )
+    {
+      cRP.m_bFrameMbsOnlyFlag     = false;
+      if( ! upsampling )
+      {
+        cRP.m_bFieldPicFlag       = true;
+        cRP.m_bBotFieldFlag       = ( resamplingMode == 3 );
+      }
+    }
+    else if( resamplingMode == 4 || resamplingMode == 5 )
+    {
+      cRP.m_bRefLayerFrameMbsOnlyFlag = false;
+      cRP.m_bRefLayerFieldPicFlag     = true;
+    }
+  }
+
+  //===== initialize classes =====
+  YuvFrame    cFrame;
+  DownConvert cDownConvert;
+  {
+    int maxWidth  = gMax( cRP.m_iRefLayerFrmWidth,  cRP.m_iFrameWidth  );
+    int maxHeight = gMax( cRP.m_iRefLayerFrmHeight, cRP.m_iFrameHeight );
+    int minWidth  = gMin( cRP.m_iRefLayerFrmWidth,  cRP.m_iFrameWidth  );
+    int minHeight = gMin( cRP.m_iRefLayerFrmHeight, cRP.m_iFrameHeight );
+    int minWRnd16 = ( ( minWidth  + 15 ) >> 4 ) << 4;
+    int minHRnd32 = ( ( minHeight + 31 ) >> 5 ) << 5;
+    maxWidth      = ( ( maxWidth  * minWRnd16 + ( minWidth  << 4 ) - 1 ) / ( minWidth  << 4 ) ) << 4;
+    maxHeight     = ( ( maxHeight * minHRnd32 + ( minHeight << 4 ) - 1 ) / ( minHeight << 4 ) ) << 4;
+    createFrame( cFrame, maxWidth, maxHeight );
+    cDownConvert.init(   maxWidth, maxHeight );
+  }
+
+  printf("Resampler\n\n");
+
+  //===== loop over frames =====
+  int   skip              = skipAtStart;
+  int   writtenFrames     = 0;
+  int   numInputFrames    = ( resamplingMode >= 4 && ! upsampling ? 2 : 1 );
+  int   numOutputFrames   = ( resamplingMode >= 4 &&   upsampling ? 2 : 1 );
+  bool  bFinished         = false;
+  long  startTime         = clock();
+  while( ! bFinished )
+  {
+    for( int inputFrame = 0; inputFrame < numInputFrames && ! bFinished; inputFrame++ )
+    {
+      //===== read input frame =====
+      for( int numToRead = skip + 1; numToRead > 0 && ! bFinished; numToRead-- )
+      {
+        bFinished = ( readFrame( cFrame, inputFile, cRP.m_iRefLayerFrmWidth, cRP.m_iRefLayerFrmHeight, inputFrame != 0 ) != 0 );
+      }
+      skip = skipBetween;
+      if( cRP.m_iExtendedSpatialScalability == 2 && ! bFinished )
+      {
+        updateCropParametersFromFile( cRP, croppingParametersFile, resamplingMethod, argv[0] );
+      }
+
+      //===== set resampling parameter =====
+      if( resamplingMethod != 0 &&
+        cRP.m_iScaledRefFrmWidth  == gMin( cRP.m_iRefLayerFrmWidth,  cRP.m_iFrameWidth  ) &&
+        cRP.m_iScaledRefFrmHeight == gMin( cRP.m_iRefLayerFrmHeight, cRP.m_iFrameHeight )   )
+      {
+        resampling = false;
+      }
+      else
+      {
+        resampling = true;
+      }
+
+      //===== resample input frame =====
+      if( ! bFinished )
+      {
+        resampleFrame( cFrame, cDownConvert, cRP, resamplingMethod, resamplingMode, resampling, upsampling, inputFrame != 0 );
+      }
+    }
+
+    //===== write output frame =====
+    if( ! bFinished )
+    {
+      Bool bWriteTwoFrames = ( numOutputFrames == 2 && ( maxNumOutputFrames == 0 || writtenFrames + 1 < maxNumOutputFrames ) );
+      writeFrame( cFrame, outputFile, cRP.m_iFrameWidth, cRP.m_iFrameHeight, bWriteTwoFrames );
+      writtenFrames += ( bWriteTwoFrames ? 2 : 1 );
+      bFinished      = ( maxNumOutputFrames != 0 && writtenFrames == maxNumOutputFrames );
+      fprintf( stderr, "\r%6d frames converted", writtenFrames );
+    }
+  }
+  long  endTime           = clock();
+
+  deleteFrame( cFrame );
+  fclose     ( inputFile );
+  fclose     ( outputFile );
+  if( croppingParametersFile )
+  {
+    fclose   ( croppingParametersFile );
+  }
+
+  fprintf( stderr, "\n" );
+  double deltaInSecond = (double)( endTime - startTime) / (double)CLOCKS_PER_SEC;
+  fprintf( stderr, "in %.2lf seconds => %.0lf ms/frame\n", deltaInSecond, deltaInSecond / (double)writtenFrames * 1000.0 );
+  if( writtenFrames < maxNumOutputFrames )
+  {
+    fprintf( stderr, "\nNOTE: less output frames generated than specified!!!\n\n" );
+  }
+  return 0;
+}
Index: /tags/SHM-9.0/source/App/TAppEncoder/TAppEncCfg.cpp
===================================================================
--- /tags/SHM-9.0/source/App/TAppEncoder/TAppEncCfg.cpp	(revision 1088)
+++ /tags/SHM-9.0/source/App/TAppEncoder/TAppEncCfg.cpp	(revision 1088)
@@ -0,0 +1,5218 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TAppEncCfg.cpp
+    \brief    Handle encoder configuration parameters
+*/
+
+#include <stdlib.h>
+#include <cassert>
+#include <cstring>
+#include <string>
+#include <limits>
+#include "TLibCommon/TComRom.h"
+#include "TAppEncCfg.h"
+#include "TAppCommon/program_options_lite.h"
+#include "TLibEncoder/TEncRateCtrl.h"
+#ifdef WIN32
+#define strdup _strdup
+#endif
+
+#define MACRO_TO_STRING_HELPER(val) #val
+#define MACRO_TO_STRING(val) MACRO_TO_STRING_HELPER(val)
+
+using namespace std;
+namespace po = df::program_options_lite;
+
+
+
+enum ExtendedProfileName // this is used for determining profile strings, where multiple profiles map to a single profile idc with various constraint flag combinations
+{
+  NONE = 0,
+  MAIN = 1,
+  MAIN10 = 2,
+  MAINSTILLPICTURE = 3,
+  MAINREXT = 4,
+  HIGHTHROUGHPUTREXT = 5, // Placeholder profile for development
+#if MULTIPLE_PTL_SUPPORT
+  MULTIVIEWMAIN = 6,
+  SCALABLEMAIN = 7,
+  SCALABLEMAIN10 = 8,
+#endif
+  // The following are RExt profiles, which would map to the MAINREXT profile idc.
+  // The enumeration indicates the bit-depth constraint in the bottom 2 digits
+  //                           the chroma format in the next digit
+  //                           the intra constraint in the top digit
+  MONOCHROME_8      = 1008,
+  MONOCHROME_12     = 1012,
+  MONOCHROME_16     = 1016,
+  MAIN_12           = 1112,
+  MAIN_422_10       = 1210,
+  MAIN_422_12       = 1212,
+  MAIN_444          = 1308,
+  MAIN_444_10       = 1310,
+  MAIN_444_12       = 1312,
+  MAIN_444_16       = 1316, // non-standard profile definition, used for development purposes
+  MAIN_INTRA        = 2108,
+  MAIN_10_INTRA     = 2110,
+  MAIN_12_INTRA     = 2112,
+  MAIN_422_10_INTRA = 2210,
+  MAIN_422_12_INTRA = 2212,
+  MAIN_444_INTRA    = 2308,
+  MAIN_444_10_INTRA = 2310,
+  MAIN_444_12_INTRA = 2312,
+  MAIN_444_16_INTRA = 2316,
+
+};
+
+
+//! \ingroup TAppEncoder
+//! \{
+
+// ====================================================================================================================
+// Constructor / destructor / initialization / destroy
+// ====================================================================================================================
+
+#if SVC_EXTENSION
+TAppEncCfg::TAppEncCfg()
+: m_pBitstreamFile()
+#if AVC_BASE
+#if VPS_AVC_BL_FLAG_REMOVAL
+, m_nonHEVCBaseLayerFlag(0)
+#else
+, m_avcBaseLayerFlag(0)
+#endif
+#endif
+, m_maxTidRefPresentFlag(1)
+#if OUTPUT_LAYER_SETS_CONFIG
+, m_defaultTargetOutputLayerIdc (-1)
+, m_numOutputLayerSets          (-1)
+#endif
+, m_inputColourSpaceConvert(IPCOLOURSPACE_UNCHANGED)
+, m_snrInternalColourSpace(false)
+, m_outputInternalColourSpace(false)
+, m_scalingListFile()
+, m_elRapSliceBEnabled(0)
+{
+  for(UInt layer=0; layer<MAX_LAYERS; layer++)
+  {
+    m_acLayerCfg[layer].setAppEncCfg(this);
+  }
+  memset( m_scalabilityMask, 0, sizeof(m_scalabilityMask) );
+}
+#else
+TAppEncCfg::TAppEncCfg()
+: m_pchInputFile()
+, m_pchBitstreamFile()
+, m_pchReconFile()
+, m_inputColourSpaceConvert(IPCOLOURSPACE_UNCHANGED)
+, m_snrInternalColourSpace(false)
+, m_outputInternalColourSpace(false)
+, m_pchdQPFile()
+, m_scalingListFile()
+{
+  m_aidQP = NULL;
+  m_startOfCodedInterval = NULL;
+  m_codedPivotValue = NULL;
+  m_targetPivotValue = NULL;
+#if Q0074_COLOUR_REMAPPING_SEI
+  for( Int c=0 ; c<3 ; c++)
+  {
+    m_colourRemapSEIPreLutCodedValue[c]   = NULL;
+    m_colourRemapSEIPreLutTargetValue[c]  = NULL;
+    m_colourRemapSEIPostLutCodedValue[c]  = NULL;
+    m_colourRemapSEIPostLutTargetValue[c] = NULL;
+  }
+#endif
+}
+#endif
+
+TAppEncCfg::~TAppEncCfg()
+{
+#if SVC_EXTENSION
+  if( m_pBitstreamFile )
+  {
+    free(m_pBitstreamFile);
+    m_pBitstreamFile = NULL;
+  }
+#else  
+  if ( m_aidQP )
+  {
+    delete[] m_aidQP;
+  }
+  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;
+  }
+
+  free(m_pchInputFile);
+  free(m_pchBitstreamFile);
+#endif
+#if !SVC_EXTENSION  
+  free(m_pchReconFile);
+  free(m_pchdQPFile);
+#if Q0074_COLOUR_REMAPPING_SEI
+  for( Int c=0 ; c<3 ; c++)
+  {
+    if ( m_colourRemapSEIPreLutCodedValue[c] )
+    {
+      delete[] m_colourRemapSEIPreLutCodedValue[c];
+    }
+    if ( m_colourRemapSEIPreLutTargetValue[c] )
+    {
+      delete[] m_colourRemapSEIPreLutTargetValue[c];
+    }
+    if ( m_colourRemapSEIPostLutCodedValue[c] )
+    {
+      delete[] m_colourRemapSEIPostLutCodedValue[c];
+    }
+    if ( m_colourRemapSEIPostLutTargetValue[c] )
+    {
+      delete[] m_colourRemapSEIPostLutTargetValue[c];
+    }
+  }
+#endif
+#endif
+  free(m_scalingListFile);
+}
+
+Void TAppEncCfg::create()
+{
+}
+
+Void TAppEncCfg::destroy()
+{
+#if VPS_EXTN_DIRECT_REF_LAYERS
+  for(Int layer = 0; layer < MAX_LAYERS; layer++)
+  {
+    if( m_acLayerCfg[layer].m_numSamplePredRefLayers > 0 )
+    {
+      delete [] m_acLayerCfg[layer].m_samplePredRefLayerIds;
+      m_acLayerCfg[layer].m_samplePredRefLayerIds = NULL;
+    }
+    if( m_acLayerCfg[layer].m_numMotionPredRefLayers > 0 )
+    {
+      delete [] m_acLayerCfg[layer].m_motionPredRefLayerIds;
+      m_acLayerCfg[layer].m_motionPredRefLayerIds = NULL;
+    }
+    if( m_acLayerCfg[layer].m_numActiveRefLayers > 0 )
+    {
+      delete [] m_acLayerCfg[layer].m_predLayerIds;
+      m_acLayerCfg[layer].m_predLayerIds = NULL;
+    }
+  }
+#endif
+}
+
+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
+  return in;
+}
+
+Bool confirmPara(Bool bflag, const Char* message);
+
+static inline ChromaFormat numberToChromaFormat(const Int val)
+{
+  switch (val)
+  {
+    case 400: return CHROMA_400; break;
+    case 420: return CHROMA_420; break;
+    case 422: return CHROMA_422; break;
+    case 444: return CHROMA_444; break;
+    default:  return NUM_CHROMA_FORMAT;
+  }
+}
+
+#if SVC_EXTENSION
+void TAppEncCfg::getDirFilename(string& filename, string& dir, const string path)
+{
+  size_t pos = path.find_last_of("\\");
+  if(pos != std::string::npos)
+  {
+    filename.assign(path.begin() + pos + 1, path.end());
+    dir.assign(path.begin(), path.begin() + pos + 1);
+  }
+  else
+  {
+    pos = path.find_last_of("/");
+    if(pos != std::string::npos)
+    {
+      filename.assign(path.begin() + pos + 1, path.end());
+      dir.assign(path.begin(), path.begin() + pos + 1);
+    }
+    else
+    {
+      filename = path;
+      dir.assign("");
+    }
+  }
+}
+#endif
+
+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   },
+  {"main-RExt",            Profile::MAINREXT           },
+  {"high-throughput-RExt", Profile::HIGHTHROUGHPUTREXT },
+#if MULTIPLE_PTL_SUPPORT
+  {"multiview-main",       Profile::MULTIVIEWMAIN      },       //This is not used in this software
+  {"scalable-main",        Profile::SCALABLEMAIN       },
+  {"scalable-main10",      Profile::SCALABLEMAIN10     },
+#endif
+};
+
+static const struct MapStrToExtendedProfile
+{
+  const Char* str;
+  ExtendedProfileName value;
+}
+strToExtendedProfile[] =
+{
+    {"none",               NONE             },
+    {"main",               MAIN             },
+    {"main10",             MAIN10           },
+    {"main-still-picture", MAINSTILLPICTURE },
+    {"main-RExt",          MAINREXT         },
+    {"high-throughput-RExt", HIGHTHROUGHPUTREXT },
+    {"monochrome",         MONOCHROME_8     },
+    {"monochrome12",       MONOCHROME_12    },
+    {"monochrome16",       MONOCHROME_16    },
+    {"main12",             MAIN_12          },
+    {"main_422_10",        MAIN_422_10      },
+    {"main_422_12",        MAIN_422_12      },
+    {"main_444",           MAIN_444         },
+    {"main_444_10",        MAIN_444_10      },
+    {"main_444_12",        MAIN_444_12      },
+    {"main_444_16",        MAIN_444_16      },
+    {"main_intra",         MAIN_INTRA       },
+    {"main_10_intra",      MAIN_10_INTRA    },
+    {"main_12_intra",      MAIN_12_INTRA    },
+    {"main_422_10_intra",  MAIN_422_10_INTRA},
+    {"main_422_12_intra",  MAIN_422_12_INTRA},
+    {"main_444_intra",     MAIN_444_INTRA   },
+    {"main_444_10_intra",  MAIN_444_10_INTRA},
+    {"main_444_12_intra",  MAIN_444_12_INTRA},
+    {"main_444_16_intra",  MAIN_444_16_INTRA},
+#if MULTIPLE_PTL_SUPPORT
+    {"multiview-main",     MULTIVIEWMAIN    },
+    {"scalable-main",      SCALABLEMAIN     },
+    {"scalable-main10",    SCALABLEMAIN10   },
+#endif
+};
+
+static const ExtendedProfileName validRExtProfileNames[2/* intraConstraintFlag*/][4/* bit depth constraint 8=0, 10=1, 12=2, 16=3*/][4/*chroma format*/]=
+{
+    {
+        { MONOCHROME_8,  NONE,          NONE,              MAIN_444          }, // 8-bit  inter for 400, 420, 422 and 444
+        { NONE,          NONE,          MAIN_422_10,       MAIN_444_10       }, // 10-bit inter for 400, 420, 422 and 444
+        { MONOCHROME_12, MAIN_12,       MAIN_422_12,       MAIN_444_12       }, // 12-bit inter for 400, 420, 422 and 444
+        { MONOCHROME_16, NONE,          NONE,              MAIN_444_16       }  // 16-bit inter for 400, 420, 422 and 444 (the latter is non standard used for development)
+    },
+    {
+        { NONE,          MAIN_INTRA,    NONE,              MAIN_444_INTRA    }, // 8-bit  intra for 400, 420, 422 and 444
+        { NONE,          MAIN_10_INTRA, MAIN_422_10_INTRA, MAIN_444_10_INTRA }, // 10-bit intra for 400, 420, 422 and 444
+        { NONE,          MAIN_12_INTRA, MAIN_422_12_INTRA, MAIN_444_12_INTRA }, // 12-bit intra for 400, 420, 422 and 444
+        { NONE,          NONE,          NONE,              MAIN_444_16_INTRA }  // 16-bit intra for 400, 420, 422 and 444
+    }
+};
+
+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},
+  {"8.5", Level::LEVEL8_5},
+};
+
+static const struct MapStrToCostMode
+{
+  const Char* str;
+  CostMode    value;
+}
+strToCostMode[] =
+{
+  {"lossy",                     COST_STANDARD_LOSSY},
+  {"sequence_level_lossless",   COST_SEQUENCE_LEVEL_LOSSLESS},
+  {"lossless",                  COST_LOSSLESS_CODING},
+  {"mixed_lossless_lossy",      COST_MIXED_LOSSLESS_LOSSY_CODING}
+};
+
+static const struct MapStrToScalingListMode
+{
+  const Char* str;
+  ScalingListMode value;
+}
+strToScalingListMode[] =
+{
+  {"0",       SCALING_LIST_OFF},
+  {"1",       SCALING_LIST_DEFAULT},
+  {"2",       SCALING_LIST_FILE_READ},
+  {"off",     SCALING_LIST_OFF},
+  {"default", SCALING_LIST_DEFAULT},
+  {"file",    SCALING_LIST_FILE_READ}
+};
+
+template<typename T, typename P>
+static std::string enumToString(P map[], UInt mapLen, const T val)
+{
+  for (UInt i = 0; i < mapLen; i++)
+  {
+    if (val == map[i].value)
+    {
+      return map[i].str;
+    }
+  }
+  return std::string();
+}
+
+template<typename T, typename P>
+static istream& readStrToEnum(P map[], UInt mapLen, istream &in, T &val)
+{
+  string str;
+  in >> str;
+
+  for (UInt 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;
+}
+
+//inline to prevent compiler warnings for "unused static function"
+
+static inline istream& operator >> (istream &in, ExtendedProfileName &profile)
+{
+  return readStrToEnum(strToExtendedProfile, sizeof(strToExtendedProfile)/sizeof(*strToExtendedProfile), in, profile);
+}
+
+namespace Level
+{
+  static inline istream& operator >> (istream &in, Tier &tier)
+  {
+    return readStrToEnum(strToTier, sizeof(strToTier)/sizeof(*strToTier), in, tier);
+  }
+
+  static inline istream& operator >> (istream &in, Name &level)
+  {
+    return readStrToEnum(strToLevel, sizeof(strToLevel)/sizeof(*strToLevel), in, level);
+  }
+}
+
+static inline istream& operator >> (istream &in, CostMode &mode)
+{
+  return readStrToEnum(strToCostMode, sizeof(strToCostMode)/sizeof(*strToCostMode), in, mode);
+}
+
+static inline istream& operator >> (istream &in, ScalingListMode &mode)
+{
+  return readStrToEnum(strToScalingListMode, sizeof(strToScalingListMode)/sizeof(*strToScalingListMode), in, mode);
+}
+
+#if MULTIPLE_PTL_SUPPORT
+namespace Profile
+{
+  static inline istream& operator >> (istream &in, Name &profile)
+  {
+    return readStrToEnum(strToProfile, sizeof(strToProfile)/sizeof(*strToProfile), in, profile);
+  }
+}
+#endif
+
+template <class T>
+struct SMultiValueInput
+{
+  const T              minValIncl;
+  const T              maxValIncl; // Use 0 for unlimited
+  const std::size_t    minNumValuesIncl;
+  const std::size_t    maxNumValuesIncl; // Use 0 for unlimited
+        std::vector<T> values;
+  SMultiValueInput() : minValIncl(0), maxValIncl(0), minNumValuesIncl(0), maxNumValuesIncl(0), values() { }
+  SMultiValueInput(std::vector<T> &defaults) : minValIncl(0), maxValIncl(0), minNumValuesIncl(0), maxNumValuesIncl(0), values(defaults) { }
+  SMultiValueInput(const T &minValue, const T &maxValue, std::size_t minNumberValues=0, std::size_t maxNumberValues=0)
+    : minValIncl(minValue), maxValIncl(maxValue), minNumValuesIncl(minNumberValues), maxNumValuesIncl(maxNumberValues), values()  { }
+  SMultiValueInput(const T &minValue, const T &maxValue, std::size_t minNumberValues, std::size_t maxNumberValues, const T* defValues, const UInt numDefValues)
+    : minValIncl(minValue), maxValIncl(maxValue), minNumValuesIncl(minNumberValues), maxNumValuesIncl(maxNumberValues), values(defValues, defValues+numDefValues)  { }
+  SMultiValueInput<T> &operator=(const std::vector<T> &userValues) { values=userValues; return *this; }
+  SMultiValueInput<T> &operator=(const SMultiValueInput<T> &userValues) { values=userValues.values; return *this; }
+};
+
+static inline istream& operator >> (istream &in, SMultiValueInput<UInt> &values)
+{
+  values.values.clear();
+  string str;
+  in >> str;
+  if (!str.empty())
+  {
+    const Char *pStr=str.c_str();
+    // soak up any whitespace
+    for(;isspace(*pStr);pStr++);
+
+    while (*pStr != 0)
+    {
+      Char *eptr;
+      UInt val=strtoul(pStr, &eptr, 0);
+      if (*eptr!=0 && !isspace(*eptr) && *eptr!=',')
+      {
+        in.setstate(ios::failbit);
+        break;
+      }
+      if (val<values.minValIncl || val>values.maxValIncl)
+      {
+        in.setstate(ios::failbit);
+        break;
+      }
+
+      if (values.maxNumValuesIncl != 0 && values.values.size() >= values.maxNumValuesIncl)
+      {
+        in.setstate(ios::failbit);
+        break;
+      }
+      values.values.push_back(val);
+      // soak up any whitespace and up to 1 comma.
+      pStr=eptr;
+      for(;isspace(*pStr);pStr++);
+      if (*pStr == ',') pStr++;
+      for(;isspace(*pStr);pStr++);
+    }
+  }
+  if (values.values.size() < values.minNumValuesIncl)
+  {
+    in.setstate(ios::failbit);
+  }
+  return in;
+}
+
+static inline istream& operator >> (istream &in, SMultiValueInput<Int> &values)
+{
+  values.values.clear();
+  string str;
+  in >> str;
+  if (!str.empty())
+  {
+    const Char *pStr=str.c_str();
+    // soak up any whitespace
+    for(;isspace(*pStr);pStr++);
+
+    while (*pStr != 0)
+    {
+      Char *eptr;
+      Int val=strtol(pStr, &eptr, 0);
+      if (*eptr!=0 && !isspace(*eptr) && *eptr!=',')
+      {
+        in.setstate(ios::failbit);
+        break;
+      }
+      if (val<values.minValIncl || val>values.maxValIncl)
+      {
+        in.setstate(ios::failbit);
+        break;
+      }
+
+      if (values.maxNumValuesIncl != 0 && values.values.size() >= values.maxNumValuesIncl)
+      {
+        in.setstate(ios::failbit);
+        break;
+      }
+      values.values.push_back(val);
+      // soak up any whitespace and up to 1 comma.
+      pStr=eptr;
+      for(;isspace(*pStr);pStr++);
+      if (*pStr == ',') pStr++;
+      for(;isspace(*pStr);pStr++);
+    }
+  }
+  if (values.values.size() < values.minNumValuesIncl)
+  {
+    in.setstate(ios::failbit);
+  }
+  return in;
+}
+
+static inline istream& operator >> (istream &in, SMultiValueInput<Bool> &values)
+{
+  values.values.clear();
+  string str;
+  in >> str;
+  if (!str.empty())
+  {
+    const Char *pStr=str.c_str();
+    // soak up any whitespace
+    for(;isspace(*pStr);pStr++);
+
+    while (*pStr != 0)
+    {
+      Char *eptr;
+      Int val=strtol(pStr, &eptr, 0);
+      if (*eptr!=0 && !isspace(*eptr) && *eptr!=',')
+      {
+        in.setstate(ios::failbit);
+        break;
+      }
+      if (val<Int(values.minValIncl) || val>Int(values.maxValIncl))
+      {
+        in.setstate(ios::failbit);
+        break;
+      }
+
+      if (values.maxNumValuesIncl != 0 && values.values.size() >= values.maxNumValuesIncl)
+      {
+        in.setstate(ios::failbit);
+        break;
+      }
+      values.values.push_back(val!=0);
+      // soak up any whitespace and up to 1 comma.
+      pStr=eptr;
+      for(;isspace(*pStr);pStr++);
+      if (*pStr == ',') pStr++;
+      for(;isspace(*pStr);pStr++);
+    }
+  }
+  if (values.values.size() < values.minNumValuesIncl)
+  {
+    in.setstate(ios::failbit);
+  }
+  return in;
+}
+
+static Void
+automaticallySelectRExtProfile(const Bool bUsingGeneralRExtTools,
+                               const Bool bUsingChromaQPAdjustment,
+                               const Bool bUsingExtendedPrecision,
+                               const Bool bIntraConstraintFlag,
+                               UInt &bitDepthConstraint,
+                               ChromaFormat &chromaFormatConstraint,
+                               const Int  maxBitDepth,
+                               const ChromaFormat chromaFormat)
+{
+  // Try to choose profile, according to table in Q1013.
+  UInt trialBitDepthConstraint=maxBitDepth;
+  if (trialBitDepthConstraint<8) trialBitDepthConstraint=8;
+  else if (trialBitDepthConstraint==9 || trialBitDepthConstraint==11) trialBitDepthConstraint++;
+  else if (trialBitDepthConstraint>12) trialBitDepthConstraint=16;
+
+  // both format and bit depth constraints are unspecified
+  if (bUsingExtendedPrecision || trialBitDepthConstraint==16)
+  {
+    bitDepthConstraint = 16;
+    chromaFormatConstraint = (!bIntraConstraintFlag && chromaFormat==CHROMA_400) ? CHROMA_400 : CHROMA_444;
+  }
+  else if (bUsingGeneralRExtTools)
+  {
+    if (chromaFormat == CHROMA_400 && !bIntraConstraintFlag)
+    {
+      bitDepthConstraint = 16;
+      chromaFormatConstraint = CHROMA_400;
+    }
+    else
+    {
+      bitDepthConstraint = trialBitDepthConstraint;
+      chromaFormatConstraint = CHROMA_444;
+    }
+  }
+  else if (chromaFormat == CHROMA_400)
+  {
+    if (bIntraConstraintFlag)
+    {
+      chromaFormatConstraint = CHROMA_420; // there is no intra 4:0:0 profile.
+      bitDepthConstraint     = trialBitDepthConstraint;
+    }
+    else
+    {
+      chromaFormatConstraint = CHROMA_400;
+      bitDepthConstraint     = trialBitDepthConstraint == 8 ? 8 : 12;
+    }
+  }
+  else
+  {
+    bitDepthConstraint = trialBitDepthConstraint;
+    chromaFormatConstraint = chromaFormat;
+    if (bUsingChromaQPAdjustment && chromaFormat == CHROMA_420) chromaFormatConstraint = CHROMA_422; // 4:2:0 cannot use the chroma qp tool.
+    if (chromaFormatConstraint == CHROMA_422 && bitDepthConstraint == 8) bitDepthConstraint = 10; // there is no 8-bit 4:2:2 profile.
+    if (chromaFormatConstraint == CHROMA_420 && !bIntraConstraintFlag) bitDepthConstraint = 12; // there is no 8 or 10-bit 4:2:0 inter RExt profile.
+  }
+}
+// ====================================================================================================================
+// 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 SVC_EXTENSION
+  string  cfg_LayerCfgFile   [MAX_LAYERS];
+  string  cfg_BitstreamFile;
+  string* cfg_InputFile      [MAX_LAYERS];
+  string* cfg_ReconFile      [MAX_LAYERS];
+  Double* cfg_fQP            [MAX_LAYERS];
+  Int*    cfg_layerId        [MAX_LAYERS];
+#if REPN_FORMAT_IN_VPS
+  Int*    cfg_repFormatIdx  [MAX_LAYERS];
+#endif
+  Int*    cfg_SourceWidth   [MAX_LAYERS]; 
+  Int*    cfg_SourceHeight  [MAX_LAYERS];
+  Int*    cfg_FrameRate     [MAX_LAYERS];
+  Int*    cfg_IntraPeriod   [MAX_LAYERS];
+  Int*    cfg_confWinLeft   [MAX_LAYERS];
+  Int*    cfg_confWinRight  [MAX_LAYERS];
+  Int*    cfg_confWinTop    [MAX_LAYERS];
+  Int*    cfg_confWinBottom [MAX_LAYERS];
+  Int*    cfg_aiPadX        [MAX_LAYERS];
+  Int*    cfg_aiPadY        [MAX_LAYERS];
+  Int*    cfg_conformanceMode  [MAX_LAYERS];
+  Bool*   cfg_useExtendedPrecision [MAX_LAYERS];
+#if LAYER_CTB
+  // coding unit (CU) definition
+  UInt*      cfg_uiMaxCUWidth[MAX_LAYERS];                                   ///< max. CU width in pixel
+  UInt*      cfg_uiMaxCUHeight[MAX_LAYERS];                                  ///< max. CU height in pixel
+  UInt*      cfg_uiMaxCUDepth[MAX_LAYERS];                                   ///< max. CU depth
+  
+  // transfom unit (TU) definition
+  UInt*      cfg_uiQuadtreeTULog2MaxSize[MAX_LAYERS];
+  UInt*      cfg_uiQuadtreeTULog2MinSize[MAX_LAYERS];
+  
+  UInt*      cfg_uiQuadtreeTUMaxDepthInter[MAX_LAYERS];
+  UInt*      cfg_uiQuadtreeTUMaxDepthIntra[MAX_LAYERS];
+#endif
+#if AUXILIARY_PICTURES
+  Int*     cfg_auxId               [MAX_LAYERS];
+#endif
+#if VPS_EXTN_DIRECT_REF_LAYERS
+  Int*    cfg_numSamplePredRefLayers  [MAX_LAYERS];
+  string  cfg_samplePredRefLayerIds   [MAX_LAYERS];
+  string* cfg_samplePredRefLayerIdsPtr[MAX_LAYERS];
+  Int*    cfg_numMotionPredRefLayers  [MAX_LAYERS];
+  string  cfg_motionPredRefLayerIds   [MAX_LAYERS];
+  string* cfg_motionPredRefLayerIdsPtr[MAX_LAYERS];
+  Int*    cfg_numActiveRefLayers [MAX_LAYERS];
+  string  cfg_predLayerIds       [MAX_LAYERS];
+  string* cfg_predLayerIdsPtr    [MAX_LAYERS];
+#endif
+#if O0098_SCALED_REF_LAYER_ID
+  string    cfg_refLocationOffsetLayerId [MAX_LAYERS];
+#endif
+  string    cfg_scaledRefLayerLeftOffset [MAX_LAYERS];
+  string    cfg_scaledRefLayerTopOffset [MAX_LAYERS];
+  string    cfg_scaledRefLayerRightOffset [MAX_LAYERS];
+  string    cfg_scaledRefLayerBottomOffset [MAX_LAYERS];
+  Int*      cfg_numRefLayerLocationOffsets[MAX_LAYERS];
+#if REF_REGION_OFFSET
+  string    cfg_scaledRefLayerOffsetPresentFlag [MAX_LAYERS];
+  string    cfg_refRegionOffsetPresentFlag      [MAX_LAYERS];
+  string    cfg_refRegionLeftOffset   [MAX_LAYERS];
+  string    cfg_refRegionTopOffset    [MAX_LAYERS];
+  string    cfg_refRegionRightOffset  [MAX_LAYERS];
+  string    cfg_refRegionBottomOffset [MAX_LAYERS];
+#endif
+#if R0209_GENERIC_PHASE
+  string    cfg_resamplePhaseSetPresentFlag [MAX_LAYERS];
+  string    cfg_phaseHorLuma   [MAX_LAYERS];
+  string    cfg_phaseVerLuma   [MAX_LAYERS];
+  string    cfg_phaseHorChroma [MAX_LAYERS];
+  string    cfg_phaseVerChroma [MAX_LAYERS];
+#else
+#if P0312_VERT_PHASE_ADJ
+  string    cfg_vertPhasePositionEnableFlag[MAX_LAYERS];
+#endif
+#endif
+
+#if O0098_SCALED_REF_LAYER_ID
+  string*    cfg_refLocationOffsetLayerIdPtr   [MAX_LAYERS];
+#endif
+  string*    cfg_scaledRefLayerLeftOffsetPtr   [MAX_LAYERS];
+  string*    cfg_scaledRefLayerTopOffsetPtr    [MAX_LAYERS];
+  string*    cfg_scaledRefLayerRightOffsetPtr  [MAX_LAYERS];
+  string*    cfg_scaledRefLayerBottomOffsetPtr [MAX_LAYERS];
+#if REF_REGION_OFFSET
+  string*    cfg_scaledRefLayerOffsetPresentFlagPtr [MAX_LAYERS];
+  string*    cfg_refRegionOffsetPresentFlagPtr      [MAX_LAYERS];
+  string*    cfg_refRegionLeftOffsetPtr   [MAX_LAYERS];
+  string*    cfg_refRegionTopOffsetPtr    [MAX_LAYERS];
+  string*    cfg_refRegionRightOffsetPtr  [MAX_LAYERS];
+  string*    cfg_refRegionBottomOffsetPtr [MAX_LAYERS];
+#endif
+#if R0209_GENERIC_PHASE
+  string*    cfg_resamplePhaseSetPresentFlagPtr [MAX_LAYERS];
+  string*    cfg_phaseHorLumaPtr   [MAX_LAYERS];
+  string*    cfg_phaseVerLumaPtr   [MAX_LAYERS];
+  string*    cfg_phaseHorChromaPtr [MAX_LAYERS];
+  string*    cfg_phaseVerChromaPtr [MAX_LAYERS];
+#endif
+#if P0312_VERT_PHASE_ADJ
+  string*    cfg_vertPhasePositionEnableFlagPtr[MAX_LAYERS];
+#endif
+
+#if RC_SHVC_HARMONIZATION
+  Bool*   cfg_RCEnableRateControl  [MAX_LAYERS];
+  Int*    cfg_RCTargetBitRate      [MAX_LAYERS];
+  Bool*   cfg_RCKeepHierarchicalBit[MAX_LAYERS];
+  Bool*   cfg_RCLCULevelRC         [MAX_LAYERS];
+  Bool*   cfg_RCUseLCUSeparateModel[MAX_LAYERS];
+  Int*    cfg_RCInitialQP          [MAX_LAYERS];
+  Bool*   cfg_RCForceIntraQP       [MAX_LAYERS];
+#endif
+#if O0194_DIFFERENT_BITDEPTH_EL_BL
+  Int*    cfg_InputBitDepth    [MAX_NUM_CHANNEL_TYPE][MAX_LAYERS];
+  Int*    cfg_InternalBitDepth [MAX_NUM_CHANNEL_TYPE][MAX_LAYERS];
+  Int*    cfg_OutputBitDepth   [MAX_NUM_CHANNEL_TYPE][MAX_LAYERS];
+#endif
+  Int*    cfg_maxTidIlRefPicsPlus1[MAX_LAYERS]; 
+#if Q0074_COLOUR_REMAPPING_SEI
+  string* cfg_colourRemapSEIFile[MAX_LAYERS];
+#endif
+  Int*    cfg_waveFrontSynchro[MAX_LAYERS];
+
+#if R0071_IRAP_EOS_CROSS_LAYER_IMPACTS
+  Int*    cfg_layerSwitchOffBegin[MAX_LAYERS];
+  Int*    cfg_layerSwitchOffEnd[MAX_LAYERS];
+#endif
+
+#if MULTIPLE_PTL_SUPPORT
+  Bool    tmpIntraConstraintFlag;
+  Bool    tmpLowerBitRateConstraintFlag;
+  UInt    tmpBitDepthConstraint;
+  Int*    cfg_layerPTLIdx[MAX_VPS_LAYER_IDX_PLUS1];
+#endif
+
+  for(UInt layer = 0; layer < MAX_LAYERS; layer++)
+  {
+    cfg_InputFile[layer]    = &m_acLayerCfg[layer].m_cInputFile;
+    cfg_ReconFile[layer]    = &m_acLayerCfg[layer].m_cReconFile;
+    cfg_fQP[layer]          = &m_acLayerCfg[layer].m_fQP;
+#if Q0074_COLOUR_REMAPPING_SEI
+    cfg_colourRemapSEIFile[layer] = &m_acLayerCfg[layer].m_colourRemapSEIFile;
+#endif
+#if REPN_FORMAT_IN_VPS
+    cfg_repFormatIdx[layer] = &m_acLayerCfg[layer].m_repFormatIdx;
+#endif
+    cfg_layerId[layer]              = &m_acLayerCfg[layer].m_layerId;
+    cfg_SourceWidth[layer]          = &m_acLayerCfg[layer].m_iSourceWidth;
+    cfg_SourceHeight[layer]         = &m_acLayerCfg[layer].m_iSourceHeight;
+    cfg_FrameRate[layer]            = &m_acLayerCfg[layer].m_iFrameRate; 
+    cfg_IntraPeriod[layer]          = &m_acLayerCfg[layer].m_iIntraPeriod; 
+    cfg_conformanceMode[layer]      = &m_acLayerCfg[layer].m_conformanceMode;
+    cfg_confWinLeft[layer]          = &m_acLayerCfg[layer].m_confWinLeft;
+    cfg_confWinRight[layer]         = &m_acLayerCfg[layer].m_confWinRight;
+    cfg_confWinTop[layer]           = &m_acLayerCfg[layer].m_confWinTop;
+    cfg_confWinBottom[layer]        = &m_acLayerCfg[layer].m_confWinBottom;
+    cfg_aiPadX[layer]               = &m_acLayerCfg[layer].m_aiPad[0];
+    cfg_aiPadY[layer]               = &m_acLayerCfg[layer].m_aiPad[1];
+    cfg_useExtendedPrecision[layer] = &m_acLayerCfg[layer].m_useExtendedPrecision;
+#if LAYER_CTB
+    // coding unit (CU) definition
+    cfg_uiMaxCUWidth[layer]  = &m_acLayerCfg[layer].m_uiMaxCUWidth;
+    cfg_uiMaxCUHeight[layer] = &m_acLayerCfg[layer].m_uiMaxCUHeight;
+    cfg_uiMaxCUDepth[layer]  = &m_acLayerCfg[layer].m_uiMaxCUDepth;
+
+    // transfom unit (TU) definition.
+    cfg_uiQuadtreeTULog2MaxSize[layer] = &m_acLayerCfg[layer].m_uiQuadtreeTULog2MaxSize;
+    cfg_uiQuadtreeTULog2MinSize[layer] = &m_acLayerCfg[layer].m_uiQuadtreeTULog2MinSize;
+
+    cfg_uiQuadtreeTUMaxDepthInter[layer] = &m_acLayerCfg[layer].m_uiQuadtreeTUMaxDepthInter;
+    cfg_uiQuadtreeTUMaxDepthIntra[layer] = &m_acLayerCfg[layer].m_uiQuadtreeTUMaxDepthIntra;
+#endif
+#if VPS_EXTN_DIRECT_REF_LAYERS
+    cfg_numSamplePredRefLayers  [layer] = &m_acLayerCfg[layer].m_numSamplePredRefLayers;
+    cfg_samplePredRefLayerIdsPtr[layer] = &cfg_samplePredRefLayerIds[layer];
+    cfg_numMotionPredRefLayers  [layer] = &m_acLayerCfg[layer].m_numMotionPredRefLayers;
+    cfg_motionPredRefLayerIdsPtr[layer] = &cfg_motionPredRefLayerIds[layer];
+    cfg_numActiveRefLayers  [layer] = &m_acLayerCfg[layer].m_numActiveRefLayers;
+    cfg_predLayerIdsPtr     [layer]  = &cfg_predLayerIds[layer];
+#endif
+    cfg_numRefLayerLocationOffsets [layer] = &m_acLayerCfg[layer].m_numRefLayerLocationOffsets;
+    cfg_waveFrontSynchro[layer]  = &m_acLayerCfg[layer].m_waveFrontSynchro;
+    for(Int i = 0; i < MAX_LAYERS; i++)
+    {
+#if O0098_SCALED_REF_LAYER_ID
+      cfg_refLocationOffsetLayerIdPtr  [layer] = &cfg_refLocationOffsetLayerId[layer];
+#endif
+      cfg_scaledRefLayerLeftOffsetPtr  [layer] = &cfg_scaledRefLayerLeftOffset[layer];
+      cfg_scaledRefLayerTopOffsetPtr   [layer] = &cfg_scaledRefLayerTopOffset[layer];
+      cfg_scaledRefLayerRightOffsetPtr [layer] = &cfg_scaledRefLayerRightOffset[layer];
+      cfg_scaledRefLayerBottomOffsetPtr[layer] = &cfg_scaledRefLayerBottomOffset[layer];
+#if P0312_VERT_PHASE_ADJ
+      cfg_vertPhasePositionEnableFlagPtr[layer] = &cfg_vertPhasePositionEnableFlag[layer];
+#endif
+#if REF_REGION_OFFSET
+      cfg_scaledRefLayerOffsetPresentFlagPtr [layer] = &cfg_scaledRefLayerOffsetPresentFlag [layer];
+      cfg_refRegionOffsetPresentFlagPtr      [layer] = &cfg_refRegionOffsetPresentFlag      [layer];
+      cfg_refRegionLeftOffsetPtr  [layer] = &cfg_refRegionLeftOffset  [layer];
+      cfg_refRegionTopOffsetPtr   [layer] = &cfg_refRegionTopOffset   [layer];
+      cfg_refRegionRightOffsetPtr [layer] = &cfg_refRegionRightOffset [layer];
+      cfg_refRegionBottomOffsetPtr[layer] = &cfg_refRegionBottomOffset[layer];
+#endif
+#if R0209_GENERIC_PHASE
+      cfg_resamplePhaseSetPresentFlagPtr [layer] = &cfg_resamplePhaseSetPresentFlag [layer];
+      cfg_phaseHorLumaPtr   [layer] = &cfg_phaseHorLuma   [layer];
+      cfg_phaseVerLumaPtr   [layer] = &cfg_phaseVerLuma   [layer];
+      cfg_phaseHorChromaPtr [layer] = &cfg_phaseHorChroma [layer];
+      cfg_phaseVerChromaPtr [layer] = &cfg_phaseVerChroma [layer];
+#endif
+    }
+#if RC_SHVC_HARMONIZATION
+    cfg_RCEnableRateControl[layer]   = &m_acLayerCfg[layer].m_RCEnableRateControl;
+    cfg_RCTargetBitRate[layer]       = &m_acLayerCfg[layer].m_RCTargetBitrate;
+    cfg_RCKeepHierarchicalBit[layer] = &m_acLayerCfg[layer].m_RCKeepHierarchicalBit;
+    cfg_RCLCULevelRC[layer]          = &m_acLayerCfg[layer].m_RCLCULevelRC;
+    cfg_RCUseLCUSeparateModel[layer] = &m_acLayerCfg[layer].m_RCUseLCUSeparateModel;
+    cfg_RCInitialQP[layer]           = &m_acLayerCfg[layer].m_RCInitialQP;
+    cfg_RCForceIntraQP[layer]        = &m_acLayerCfg[layer].m_RCForceIntraQP;
+#endif
+#if O0194_DIFFERENT_BITDEPTH_EL_BL
+    cfg_InputBitDepth   [CHANNEL_TYPE_LUMA][layer] = &m_acLayerCfg[layer].m_inputBitDepth[CHANNEL_TYPE_LUMA];
+    cfg_InternalBitDepth[CHANNEL_TYPE_LUMA][layer] = &m_acLayerCfg[layer].m_internalBitDepth[CHANNEL_TYPE_LUMA];
+    cfg_OutputBitDepth  [CHANNEL_TYPE_LUMA][layer] = &m_acLayerCfg[layer].m_outputBitDepth[CHANNEL_TYPE_LUMA];
+    cfg_InternalBitDepth[CHANNEL_TYPE_CHROMA][layer] = &m_acLayerCfg[layer].m_internalBitDepth[CHANNEL_TYPE_CHROMA];
+    cfg_InputBitDepth   [CHANNEL_TYPE_CHROMA][layer] = &m_acLayerCfg[layer].m_inputBitDepth[CHANNEL_TYPE_CHROMA];
+    cfg_OutputBitDepth  [CHANNEL_TYPE_CHROMA][layer] = &m_acLayerCfg[layer].m_outputBitDepth[CHANNEL_TYPE_CHROMA];
+#endif
+    cfg_maxTidIlRefPicsPlus1[layer] = &m_acLayerCfg[layer].m_maxTidIlRefPicsPlus1;
+#if AUXILIARY_PICTURES
+    cfg_auxId[layer]                = &m_acLayerCfg[layer].m_auxId; 
+#endif
+#if R0071_IRAP_EOS_CROSS_LAYER_IMPACTS
+    cfg_layerSwitchOffBegin[layer] = &m_acLayerCfg[layer].m_layerSwitchOffBegin;
+    cfg_layerSwitchOffEnd[layer]   = &m_acLayerCfg[layer].m_layerSwitchOffEnd;
+#endif
+#if MULTIPLE_PTL_SUPPORT
+    cfg_layerPTLIdx[layer]          = &m_acLayerCfg[layer].m_layerPTLIdx; 
+#endif
+  }
+#if Q0078_ADD_LAYER_SETS
+  Int* cfg_numLayerInIdList[MAX_VPS_LAYER_SETS_PLUS1];
+  string cfg_layerSetLayerIdList[MAX_VPS_LAYER_SETS_PLUS1];
+  string* cfg_layerSetLayerIdListPtr[MAX_VPS_LAYER_SETS_PLUS1];
+  Int* cfg_numHighestLayerIdx[MAX_VPS_LAYER_SETS_PLUS1];
+  string cfg_highestLayerIdx[MAX_VPS_LAYER_SETS_PLUS1];
+  string* cfg_highestLayerIdxPtr[MAX_VPS_LAYER_SETS_PLUS1];
+  for (UInt i = 0; i < MAX_VPS_LAYER_SETS_PLUS1; i++)
+  {
+    cfg_numLayerInIdList[i] = &m_numLayerInIdList[i];
+    cfg_layerSetLayerIdListPtr[i] = &cfg_layerSetLayerIdList[i];
+    cfg_highestLayerIdxPtr[i] = &cfg_highestLayerIdx[i];
+    cfg_numHighestLayerIdx[i] = &m_numHighestLayerIdx[i];
+  }
+#endif
+#if OUTPUT_LAYER_SETS_CONFIG
+  string* cfg_numOutputLayersInOutputLayerSet = new string;
+  string* cfg_listOfOutputLayers     = new string[MAX_VPS_OUTPUT_LAYER_SETS_PLUS1];
+  string* cfg_outputLayerSetIdx      = new string;
+#endif
+#if MULTIPLE_PTL_SUPPORT
+  string* cfg_listOfLayerPTLOfOlss   = new string[MAX_VPS_OUTPUT_LAYER_SETS_PLUS1];
+#endif
+#if AVC_BASE
+  string  cfg_BLInputFile;
+#endif
+#if N0383_IL_CONSTRAINED_TILE_SETS_SEI
+  string  cfg_tileSets;
+#endif
+#else //SVC_EXTENSION
+  string cfg_InputFile;
+  string cfg_BitstreamFile;
+  string cfg_ReconFile;
+  string cfg_dQPFile;
+#if Q0074_COLOUR_REMAPPING_SEI
+  string cfg_colourRemapSEIFile;
+#endif
+#endif //SVC_EXTENSION
+  string cfg_ScalingListFile;
+
+  Int tmpChromaFormat;
+  Int tmpInputChromaFormat;
+  Int tmpConstraintChromaFormat;
+  string inputColourSpaceConvert;
+#if MULTIPLE_PTL_SUPPORT
+  ExtendedProfileName extendedProfile[MAX_NUM_LAYER_IDS + 1];
+#else
+  ExtendedProfileName extendedProfile;
+#endif
+  Int saoOffsetBitShift[MAX_NUM_CHANNEL_TYPE];
+
+  // Multi-value input fields:                                // minval, maxval (incl), min_entries, max_entries (incl) [, default values, number of default values]
+  SMultiValueInput<UInt> cfg_ColumnWidth                     (0, std::numeric_limits<UInt>::max(), 0, std::numeric_limits<UInt>::max());
+  SMultiValueInput<UInt> cfg_RowHeight                       (0, std::numeric_limits<UInt>::max(), 0, std::numeric_limits<UInt>::max());
+  SMultiValueInput<Int>  cfg_startOfCodedInterval            (std::numeric_limits<Int>::min(), std::numeric_limits<Int>::max(), 0, 1<<16);
+  SMultiValueInput<Int>  cfg_codedPivotValue                 (std::numeric_limits<Int>::min(), std::numeric_limits<Int>::max(), 0, 1<<16);
+  SMultiValueInput<Int>  cfg_targetPivotValue                (std::numeric_limits<Int>::min(), std::numeric_limits<Int>::max(), 0, 1<<16);
+
+  const UInt defaultInputKneeCodes[3]  = { 600, 800, 900 };
+  const UInt defaultOutputKneeCodes[3] = { 100, 250, 450 };
+  SMultiValueInput<UInt> cfg_kneeSEIInputKneePointValue      (1,  999, 0, 999, defaultInputKneeCodes,  sizeof(defaultInputKneeCodes )/sizeof(UInt));
+  SMultiValueInput<UInt> cfg_kneeSEIOutputKneePointValue     (0, 1000, 0, 999, defaultOutputKneeCodes, sizeof(defaultOutputKneeCodes)/sizeof(UInt));
+  const Int defaultPrimaryCodes[6]     = { 0,50000, 0,0, 50000,0 };
+  const Int defaultWhitePointCode[2]   = { 16667, 16667 };
+  SMultiValueInput<Int>  cfg_DisplayPrimariesCode            (0, 50000, 3, 3, defaultPrimaryCodes,   sizeof(defaultPrimaryCodes  )/sizeof(Int));
+  SMultiValueInput<Int>  cfg_DisplayWhitePointCode           (0, 50000, 2, 2, defaultWhitePointCode, sizeof(defaultWhitePointCode)/sizeof(Int));
+
+  SMultiValueInput<Bool> cfg_timeCodeSeiTimeStampFlag        (0,  1, 0, MAX_TIMECODE_SEI_SETS);
+  SMultiValueInput<Bool> cfg_timeCodeSeiNumUnitFieldBasedFlag(0,  1, 0, MAX_TIMECODE_SEI_SETS);
+  SMultiValueInput<Int>  cfg_timeCodeSeiCountingType         (0,  6, 0, MAX_TIMECODE_SEI_SETS);
+  SMultiValueInput<Bool> cfg_timeCodeSeiFullTimeStampFlag    (0,  1, 0, MAX_TIMECODE_SEI_SETS);
+  SMultiValueInput<Bool> cfg_timeCodeSeiDiscontinuityFlag    (0,  1, 0, MAX_TIMECODE_SEI_SETS);
+  SMultiValueInput<Bool> cfg_timeCodeSeiCntDroppedFlag       (0,  1, 0, MAX_TIMECODE_SEI_SETS);
+  SMultiValueInput<Int>  cfg_timeCodeSeiNumberOfFrames       (0,511, 0, MAX_TIMECODE_SEI_SETS);
+  SMultiValueInput<Int>  cfg_timeCodeSeiSecondsValue         (0, 59, 0, MAX_TIMECODE_SEI_SETS);
+  SMultiValueInput<Int>  cfg_timeCodeSeiMinutesValue         (0, 59, 0, MAX_TIMECODE_SEI_SETS);
+  SMultiValueInput<Int>  cfg_timeCodeSeiHoursValue           (0, 23, 0, MAX_TIMECODE_SEI_SETS);
+  SMultiValueInput<Bool> cfg_timeCodeSeiSecondsFlag          (0,  1, 0, MAX_TIMECODE_SEI_SETS);
+  SMultiValueInput<Bool> cfg_timeCodeSeiMinutesFlag          (0,  1, 0, MAX_TIMECODE_SEI_SETS);
+  SMultiValueInput<Bool> cfg_timeCodeSeiHoursFlag            (0,  1, 0, MAX_TIMECODE_SEI_SETS);
+  SMultiValueInput<Int>  cfg_timeCodeSeiTimeOffsetLength     (0, 31, 0, MAX_TIMECODE_SEI_SETS);
+  SMultiValueInput<Int>  cfg_timeCodeSeiTimeOffsetValue      (std::numeric_limits<Int>::min(), std::numeric_limits<Int>::max(), 0, MAX_TIMECODE_SEI_SETS);
+
+#if Q0096_OVERLAY_SEI
+  const Int CFG_MAX_OVERLAYS = 3;
+  UInt   cfg_overlaySEIIdx[CFG_MAX_OVERLAYS];  
+  Bool   cfg_overlaySEILanguagePresentFlag[CFG_MAX_OVERLAYS];  
+  UInt   cfg_overlaySEIContentLayerId[CFG_MAX_OVERLAYS];
+  Bool   cfg_overlaySEILabelPresentFlag[CFG_MAX_OVERLAYS];
+  UInt   cfg_overlaySEILabelLayerId[CFG_MAX_OVERLAYS];
+  Bool   cfg_overlaySEIAlphaPresentFlag[CFG_MAX_OVERLAYS];
+  UInt   cfg_overlaySEIAlphaLayerId[CFG_MAX_OVERLAYS];
+  UInt   cfg_overlaySEINumElementsMinus1[CFG_MAX_OVERLAYS];
+  string cfg_overlaySEIElementLabelRanges[CFG_MAX_OVERLAYS];  
+  string cfg_overlaySEILanguage[CFG_MAX_OVERLAYS];  
+  string cfg_overlaySEIName[CFG_MAX_OVERLAYS];  
+  string cfg_overlaySEIElementNames[CFG_MAX_OVERLAYS];  
+#endif
+
+  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 SVC_EXTENSION
+  ("InputFile%d,-i%d",                              cfg_InputFile,                      string(""), MAX_LAYERS, "original YUV input file name for layer %d")
+  ("ReconFile%d,-o%d",                              cfg_ReconFile,                      string(""), MAX_LAYERS, "reconstruction YUV input file name for layer %d")
+  ("LayerConfig%d,-lc%d",                           cfg_LayerCfgFile,                   string(""), MAX_LAYERS, "layer %d configuration file name")
+  ("SourceWidth%d,-wdt%d",                          cfg_SourceWidth,                             0, MAX_LAYERS, "Source picture width for layer %d")
+  ("SourceHeight%d,-hgt%d",                         cfg_SourceHeight,                            0, MAX_LAYERS, "Source picture height for layer %d")
+  ("FrameRate%d,-fr%d",                             cfg_FrameRate,                               0, MAX_LAYERS, "Frame rate for layer %d")
+  ("LambdaModifier%d,-LM%d",                        m_adLambdaModifier,                Double(1.0), MAX_TLAYER, "Lambda modifier for temporal layer %d")
+#if O0215_PHASE_ALIGNMENT
+  ("PhaseAlignment",                                m_phaseAlignFlag,                                    false, "indicate the sample location alignment between layers (0: zero position aligned, 1: central position aligned)")
+#endif
+#if REPN_FORMAT_IN_VPS
+  ("RepFormatIdx%d",                                cfg_repFormatIdx,                           -1, MAX_LAYERS, "Index to the representation format structure used from the VPS")
+#endif
+  ("LayerId%d",                                     cfg_layerId,                                -1, MAX_LAYERS,  "Layer id")
+#if VPS_EXTN_DIRECT_REF_LAYERS
+  ("NumSamplePredRefLayers%d",                      cfg_numSamplePredRefLayers,                 -1, MAX_LAYERS, "Number of sample prediction reference layers")
+  ("SamplePredRefLayerIds%d",                       cfg_samplePredRefLayerIdsPtr,       string(""), MAX_LAYERS, "sample pred reference layer IDs")
+  ("NumMotionPredRefLayers%d",                      cfg_numMotionPredRefLayers,                 -1, MAX_LAYERS, "Number of motion prediction reference layers")
+  ("MotionPredRefLayerIds%d",                       cfg_motionPredRefLayerIdsPtr,       string(""), MAX_LAYERS, "motion pred reference layer IDs")
+  ("NumActiveRefLayers%d",                          cfg_numActiveRefLayers,                     -1, MAX_LAYERS, "Number of active reference layers")
+  ("PredLayerIds%d",                                cfg_predLayerIdsPtr,                string(""), MAX_LAYERS, "inter-layer prediction layer IDs")
+#endif
+  ("NumLayers",                                     m_numLayers,                                             1, "Number of layers to code")  
+#if Q0078_ADD_LAYER_SETS
+#if OUTPUT_LAYER_SETS_CONFIG
+  ("NumLayerSets",                                  m_numLayerSets,                                          1, "Number of layer sets")
+#else
+  ("NumLayerSets",                                  m_numLayerSets,                                          0, "Number of layer sets")
+#endif
+  ("NumLayerInIdList%d",                            cfg_numLayerInIdList,            0, MAX_VPS_LAYER_IDX_PLUS1, "Number of layers in the set")
+  ("LayerSetLayerIdList%d",                         cfg_layerSetLayerIdListPtr, string(""), MAX_VPS_LAYER_IDX_PLUS1, "Layer IDs for the set")
+  ("NumAddLayerSets",                               m_numAddLayerSets,                                       0, "Number of additional layer sets")
+  ("NumHighestLayerIdx%d",                          cfg_numHighestLayerIdx,          0, MAX_VPS_LAYER_IDX_PLUS1, "Number of highest layer idx")
+  ("HighestLayerIdx%d",                             cfg_highestLayerIdxPtr, string(""), MAX_VPS_LAYER_IDX_PLUS1, "Highest layer idx for an additional layer set")
+#endif
+#if OUTPUT_LAYER_SETS_CONFIG
+  ("DefaultTargetOutputLayerIdc",                   m_defaultTargetOutputLayerIdc,                           1, "Default target output layers. 0: All layers are output layer, 1: Only highest layer is output layer, 2 or 3: No default output layers")
+  ("NumOutputLayerSets",                            m_numOutputLayerSets,                                    1, "Number of output layer sets excluding the 0-th output layer set")
+  ("NumOutputLayersInOutputLayerSet",               cfg_numOutputLayersInOutputLayerSet,         string(""), 1, "List containing number of output layers in the output layer sets")
+  ("ListOfOutputLayers%d",                          cfg_listOfOutputLayers, string(""), MAX_VPS_LAYER_IDX_PLUS1, "Layer IDs for the set, in terms of layer ID in the output layer set Range: [0..NumLayersInOutputLayerSet-1]")
+  ("OutputLayerSetIdx",                             cfg_outputLayerSetIdx,                       string(""), 1, "Corresponding layer set index, only for non-default output layer sets")
+#endif
+#if AUXILIARY_PICTURES
+  ("AuxId%d",                                       cfg_auxId,                                   0, MAX_LAYERS, "Auxilary picture ID for layer %d (0: Not aux pic, 1: Alpha plane, 2: Depth picture, 3: Cb enh, 4: Cr enh")
+#endif
+  ("ExtendedPrecision%d",                           cfg_useExtendedPrecision,                false, MAX_LAYERS, "Increased internal accuracies to support high bit depths (not valid in V1 profiles)")
+  ("ConformanceMode%d",                             cfg_conformanceMode,                         0, MAX_LAYERS, "Window conformance mode (0: no cropping, 1:automatic padding, 2: padding, 3:cropping")
+  ("ConfLeft%d",                                    cfg_confWinLeft,                             0, MAX_LAYERS, "Deprecated alias of ConfWinLeft")
+  ("ConfRight%d",                                   cfg_confWinRight,                            0, MAX_LAYERS, "Deprecated alias of ConfWinRight")
+  ("ConfTop%d",                                     cfg_confWinTop,                              0, MAX_LAYERS, "Deprecated alias of ConfWinTop")
+  ("ConfBottom%d",                                  cfg_confWinBottom,                           0, MAX_LAYERS, "Deprecated alias of ConfWinBottom")
+  ("ConfWinLeft%d",                                 cfg_confWinLeft,                             0, MAX_LAYERS, "Left offset for window conformance mode 3")
+  ("ConfWinRight%d",                                cfg_confWinRight,                            0, MAX_LAYERS, "Right offset for window conformance mode 3")
+  ("ConfWinTop%d",                                  cfg_confWinTop,                              0, MAX_LAYERS, "Top offset for window conformance mode 3")
+  ("ConfWinBottom%d",                               cfg_confWinBottom,                           0, MAX_LAYERS, "Bottom offset for window conformance mode 3")
+  ("HorizontalPadding%d,-pdx%d",                    cfg_aiPadX,                                  0, MAX_LAYERS, "Horizontal source padding for conformance window mode 2")
+  ("VerticalPadding%d,-pdy%d",                      cfg_aiPadY,                                  0, MAX_LAYERS, "Vertical source padding for conformance window mode 2")
+  ("ScalabilityMask1",                              m_scalabilityMask[VIEW_ORDER_INDEX],                     0, "scalability_mask[1] (multiview)")
+  ("ScalabilityMask2",                              m_scalabilityMask[SCALABILITY_ID],                       1, "scalability_mask[2] (scalable)" )
+#if AUXILIARY_PICTURES
+  ("ScalabilityMask3",                              m_scalabilityMask[AUX_ID],                               0, "scalability_mask[3] (auxiliary pictures)" )
+#endif
+  ("BitstreamFile,b",                               cfg_BitstreamFile, string(""), "Bitstream output file name")
+#if !O0194_DIFFERENT_BITDEPTH_EL_BL
+  ("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)")
+#endif
+  ("NumRefLocationOffsets%d",                       cfg_numRefLayerLocationOffsets,              0, MAX_LAYERS,  "Number of reference layer offset sets ")
+#if O0098_SCALED_REF_LAYER_ID
+  ("RefLocationOffsetLayerId%d",                    cfg_refLocationOffsetLayerIdPtr,    string(""), MAX_LAYERS, "Layer ID of reference location offset")
+#endif                                             
+  ("ScaledRefLayerLeftOffset%d",                    cfg_scaledRefLayerLeftOffsetPtr,    string(""), MAX_LAYERS, "Horizontal offset of top-left luma sample of scaled base layer picture with respect to"
+                                                                                                                " top-left luma sample of the EL picture, in units of two luma samples")
+  ("ScaledRefLayerTopOffset%d",                     cfg_scaledRefLayerTopOffsetPtr,     string(""), MAX_LAYERS, "Vertical offset of top-left luma sample of scaled base layer picture with respect to"
+                                                                                                                " top-left luma sample of the EL picture, in units of two luma samples")
+  ("ScaledRefLayerRightOffset%d",                   cfg_scaledRefLayerRightOffsetPtr,   string(""), MAX_LAYERS, "Horizontal offset of bottom-right luma sample of scaled base layer picture with respect to"
+                                                                                                                " bottom-right luma sample of the EL picture, in units of two luma samples")
+  ("ScaledRefLayerBottomOffset%d",                  cfg_scaledRefLayerBottomOffsetPtr,  string(""), MAX_LAYERS, "Vertical offset of bottom-right luma sample of scaled base layer picture with respect to"
+                                                                                                                "  bottom-right luma sample of the EL picture, in units of two luma samples")
+#if REF_REGION_OFFSET
+  ("ScaledRefLayerOffsetPresentFlag%d",         cfg_scaledRefLayerOffsetPresentFlagPtr, string(""), MAX_LAYERS, "presense flag of scaled reference layer offsets")
+  ("RefRegionOffsetPresentFlag%d",                  cfg_refRegionOffsetPresentFlagPtr,  string(""), MAX_LAYERS, "presense flag of reference region offsets")
+  ("RefRegionLeftOffset%d",                         cfg_refRegionLeftOffsetPtr,         string(""), MAX_LAYERS, "Horizontal offset of top-left luma sample of ref region with respect to"
+                                                                                                                "  top-left luma sample of the BL picture, in units of two luma samples")
+  ("RefRegionTopOffset%d",                          cfg_refRegionTopOffsetPtr,          string(""), MAX_LAYERS, "Vertical offset of top-left luma sample of ref region with respect to"
+                                                                                                                "  top-left luma sample of the BL picture, in units of two luma samples")
+  ("RefRegionRightOffset%d",                        cfg_refRegionRightOffsetPtr,        string(""), MAX_LAYERS, "Horizontal offset of bottom-right luma sample of ref region with respect to"
+                                                                                                                "  bottom-right luma sample of the BL picture, in units of two luma samples")
+  ("RefRegionBottomOffset%d",                       cfg_refRegionBottomOffsetPtr,       string(""), MAX_LAYERS, "Vertical offset of bottom-right luma sample of ref region with respect to"
+                                                                                                                "  bottom-right luma sample of the BL picture, in units of two luma samples")
+#endif
+#if R0209_GENERIC_PHASE
+  ("ResamplePhaseSetPresentFlag%d",                 cfg_resamplePhaseSetPresentFlagPtr, string(""), MAX_LAYERS, "presense flag of resample phase set")
+  ("PhaseHorLuma%d",                                cfg_phaseHorLumaPtr,                string(""), MAX_LAYERS, "luma shift in the horizontal direction used in resampling proces")
+  ("PhaseVerLuma%d",                                cfg_phaseVerLumaPtr,                string(""), MAX_LAYERS, "luma shift in the vertical   direction used in resampling proces")
+  ("PhaseHorChroma%d",                              cfg_phaseHorChromaPtr,              string(""), MAX_LAYERS, "chroma shift in the horizontal direction used in resampling proces")
+  ("PhaseVerChroma%d",                              cfg_phaseVerChromaPtr,              string(""), MAX_LAYERS, "chroma shift in the vertical   direction used in resampling proces")
+#endif
+#if P0312_VERT_PHASE_ADJ
+  ("VertPhasePositionEnableFlag%d",                 cfg _vertPhasePositionEnableFlagPtr,string(""), MAX_LAYERS, "VertPhasePositionEnableFlag for layer %d")
+#endif
+#if Q0074_COLOUR_REMAPPING_SEI
+  ("SEIColourRemappingInfoFile%d",                   cfg_colourRemapSEIFile,           string(""), MAX_LAYERS, "Colour Remapping Information SEI parameters file name for layer %d")
+#endif
+#if O0194_DIFFERENT_BITDEPTH_EL_BL
+  ("InputBitDepth%d",                                cfg_InputBitDepth[CHANNEL_TYPE_LUMA],      8, MAX_LAYERS, "Bit-depth of input file for layer %d")
+  ("InternalBitDepth%d",                             cfg_InternalBitDepth[CHANNEL_TYPE_LUMA],   0, MAX_LAYERS, "Bit-depth the codec operates at. (default:InputBitDepth) for layer %d "
+                                                                                                               " If different to InputBitDepth, source data will be converted")
+  ("OutputBitDepth%d",                               cfg_OutputBitDepth[CHANNEL_TYPE_LUMA],     0, MAX_LAYERS, "Bit-depth of output file (default:InternalBitDepth)")
+  ("InputBitDepthC%d",                               cfg_InputBitDepth[CHANNEL_TYPE_CHROMA],    0, MAX_LAYERS, "As per InputBitDepth but for chroma component. (default:InputBitDepth) for layer %d")
+  ("InternalBitDepthC%d",                            cfg_InternalBitDepth[CHANNEL_TYPE_CHROMA], 0, MAX_LAYERS, "As per InternalBitDepth but for chroma component. (default:IntrenalBitDepth) for layer %d")
+  ("OutputBitDepthC%d",                              cfg_OutputBitDepth[CHANNEL_TYPE_CHROMA],   0, MAX_LAYERS, "As per OutputBitDepth but for chroma component. (default:InternalBitDepthC)")
+#endif
+  ("MaxTidRefPresentFlag",                           m_maxTidRefPresentFlag,                            false, "max_tid_ref_present_flag (0: not present, 1: present) " )
+  ("MaxTidIlRefPicsPlus1%d",                         cfg_maxTidIlRefPicsPlus1,                  7, MAX_LAYERS, "allowed maximum temporal_id for inter-layer prediction")
+#if O0223_PICTURE_TYPES_ALIGN_FLAG
+  ("CrossLayerPictureTypeAlignFlag",                 m_crossLayerPictureTypeAlignFlag,                   true, "align picture type across layers" )  
+#endif
+  ("CrossLayerIrapAlignFlag",                        m_crossLayerIrapAlignFlag,                          true, "align IRAP across layers" )  
+#if P0068_CROSS_LAYER_ALIGNED_IDR_ONLY_FOR_IRAP_FLAG
+  ("CrossLayerAlignedIdrOnlyFlag",                   m_crossLayerAlignedIdrOnlyFlag,                     true, "only idr for IRAP across layers" )  
+#endif
+#if O0194_WEIGHTED_PREDICTION_CGS
+  ("InterLayerWeightedPred",                          m_useInterLayerWeightedPred,                       false, "enable IL WP parameters estimation at encoder" )  
+#endif
+#if AVC_BASE
+#if VPS_AVC_BL_FLAG_REMOVAL
+  ("NonHEVCBase,-nonhevc",                            m_nonHEVCBaseLayerFlag,                                0, "BL is available but not internal")
+#else
+  ("AvcBase,-avc",                                    m_avcBaseLayerFlag,                                    0, "avc_base_layer_flag")
+#endif
+  ("InputBLFile,-ibl",                                cfg_BLInputFile,                              string(""), "Base layer rec YUV input file name")
+#endif
+  ("EnableElRapB,-use-rap-b",                         m_elRapSliceBEnabled,                                 0, "Set ILP over base-layer I picture to B picture (default is P picture)")
+  ("InputChromaFormat",                               tmpInputChromaFormat,                               420, "InputChromaFormatIDC")
+  ("ChromaFormatIDC,-cf",                             tmpChromaFormat,                                      0, "ChromaFormatIDC (400|420|422|444 or set 0 (default) for same as InputChromaFormat)")
+#else //SVC_EXTENSION
+  ("InputFile,i",                                     cfg_InputFile,                               string(""), "Original YUV input file name")
+  ("BitstreamFile,b",                                 cfg_BitstreamFile,                           string(""), "Bitstream output file name")
+  ("ReconFile,o",                                     cfg_ReconFile,                               string(""), "Reconstructed YUV output file name")
+  ("SourceWidth,-wdt",                                m_iSourceWidth,                                       0, "Source picture width")
+  ("SourceHeight,-hgt",                               m_iSourceHeight,                                      0, "Source picture height")
+  ("InputBitDepth",                                   m_inputBitDepth[CHANNEL_TYPE_LUMA],                   8, "Bit-depth of input file")
+  ("OutputBitDepth",                                  m_outputBitDepth[CHANNEL_TYPE_LUMA],                  0, "Bit-depth of output file (default:InternalBitDepth)")
+  ("MSBExtendedBitDepth",                             m_MSBExtendedBitDepth[CHANNEL_TYPE_LUMA],             0, "bit depth of luma component after addition of MSBs of value 0 (used for synthesising High Dynamic Range source material). (default:InputBitDepth)")
+  ("InternalBitDepth",                                m_internalBitDepth[CHANNEL_TYPE_LUMA],                0, "Bit-depth the codec operates at. (default:MSBExtendedBitDepth). If different to MSBExtendedBitDepth, source data will be converted")
+  ("InputBitDepthC",                                  m_inputBitDepth[CHANNEL_TYPE_CHROMA],                 0, "As per InputBitDepth but for chroma component. (default:InputBitDepth)")
+  ("OutputBitDepthC",                                 m_outputBitDepth[CHANNEL_TYPE_CHROMA],                0, "As per OutputBitDepth but for chroma component. (default:InternalBitDepthC)")
+  ("MSBExtendedBitDepthC",                            m_MSBExtendedBitDepth[CHANNEL_TYPE_CHROMA],           0, "As per MSBExtendedBitDepth but for chroma component. (default:MSBExtendedBitDepth)")
+  ("InternalBitDepthC",                               m_internalBitDepth[CHANNEL_TYPE_CHROMA],              0, "As per InternalBitDepth but for chroma component. (default:InternalBitDepth)")
+  ("ExtendedPrecision",                               m_useExtendedPrecision,                           false, "Increased internal accuracies to support high bit depths (not valid in V1 profiles)")
+  ("HighPrecisionPredictionWeighting",                m_useHighPrecisionPredictionWeighting,            false, "Use high precision option for weighted prediction (not valid in V1 profiles)")
+  ("InputColourSpaceConvert",                         inputColourSpaceConvert,                     string(""), "Colour space conversion to apply to input video. Permitted values are (empty string=UNCHANGED) " + getListOfColourSpaceConverts(true))
+  ("SNRInternalColourSpace",                          m_snrInternalColourSpace,                         false, "If true, then no colour space conversion is applied prior to SNR, otherwise inverse of input is applied.")
+  ("OutputInternalColourSpace",                       m_outputInternalColourSpace,                      false, "If true, then no colour space conversion is applied for reconstructed video, otherwise inverse of input is applied.")
+  ("InputChromaFormat",                               tmpInputChromaFormat,                               420, "InputChromaFormatIDC")
+#endif //SVC_EXTENSION
+  ("MSEBasedSequencePSNR",                            m_printMSEBasedSequencePSNR,                      false, "0 (default) emit sequence PSNR only as a linear average of the frame PSNRs, 1 = also emit a sequence PSNR based on an average of the frame MSEs")
+  ("PrintFrameMSE",                                   m_printFrameMSE,                                  false, "0 (default) emit only bit count and PSNRs for each frame, 1 = also emit MSE values")
+  ("PrintSequenceMSE",                                m_printSequenceMSE,                               false, "0 (default) emit only bit rate and PSNRs for the whole sequence, 1 = also emit MSE values")
+  ("CabacZeroWordPaddingEnabled",                     m_cabacZeroWordPaddingEnabled,                    false, "0 (default) do not add conforming cabac-zero-words to bit streams, 1 = add cabac-zero-words")
+#if !SVC_EXTENSION
+  ("ChromaFormatIDC,-cf",                             tmpChromaFormat,                                      0, "ChromaFormatIDC (400|420|422|444 or set 0 (default) for same as InputChromaFormat)")
+  ("ConformanceMode",                                 m_conformanceWindowMode,                              0, "Deprecated alias of ConformanceWindowMode")
+  ("ConformanceWindowMode",                           m_conformanceWindowMode,                              0, "Window conformance mode (0: no window, 1:automatic padding, 2:padding, 3:conformance")
+  ("HorizontalPadding,-pdx",                          m_aiPad[0],                                           0, "Horizontal source padding for conformance window mode 2")
+  ("VerticalPadding,-pdy",                            m_aiPad[1],                                           0, "Vertical source padding for conformance window mode 2")
+  ("ConfLeft",                                        m_confWinLeft,                                        0, "Deprecated alias of ConfWinLeft")
+  ("ConfRight",                                       m_confWinRight,                                       0, "Deprecated alias of ConfWinRight")
+  ("ConfTop",                                         m_confWinTop,                                         0, "Deprecated alias of ConfWinTop")
+  ("ConfBottom",                                      m_confWinBottom,                                      0, "Deprecated alias of ConfWinBottom")
+  ("ConfWinLeft",                                     m_confWinLeft,                                        0, "Left offset for window conformance mode 3")
+  ("ConfWinRight",                                    m_confWinRight,                                       0, "Right offset for window conformance mode 3")
+  ("ConfWinTop",                                      m_confWinTop,                                         0, "Top offset for window conformance mode 3")
+  ("ConfWinBottom",                                   m_confWinBottom,                                      0, "Bottom offset for window conformance mode 3")
+  ("FrameRate,-fr",                                   m_iFrameRate,                                         0, "Frame rate")
+#if Q0074_COLOUR_REMAPPING_SEI
+  ("SEIColourRemappingInfoFile",                      cfg_colourRemapSEIFile, string(""), "Colour Remapping Information SEI parameters file name")
+#endif
+#endif //SVC_EXTENSION
+  ("FrameSkip,-fs",                                   m_FrameSkip,                                         0u, "Number of frames to skip at start of input YUV")
+  ("FramesToBeEncoded,f",                             m_framesToBeEncoded,                                  0, "Number of frames to be encoded (default=all)")
+
+  //Field coding parameters
+  ("FieldCoding",                                     m_isField,                                        false, "Signals if it's a field based coding")
+  ("TopFieldFirst, Tff",                              m_isTopFieldFirst,                                false, "In case of field based coding, signals whether if it's a top field first or not")
+
+  // Profile and level
+#if MULTIPLE_PTL_SUPPORT
+  ("NumProfileTierLevel",                             m_numPTLInfo,                                         1, "Number of Profile, Tier and Level information")
+  ("Profile%d",                                       extendedProfile,          NONE, (MAX_NUM_LAYER_IDS + 1),  "Profile name to use for encoding. Use main (for main), main10 (for main10), main-still-picture, main-RExt (for Range Extensions profile), any of the RExt specific profile names, or none")
+  ("Level%d",                                         m_levelList,       Level::NONE, (MAX_NUM_LAYER_IDS + 1), "Level limit to be used, eg 5.1, or none")
+  ("Tier%d",                                          m_levelTierList,   Level::MAIN, (MAX_NUM_LAYER_IDS + 1), "Tier to use for interpretation of --Level (main or high only)")
+  ("MaxBitDepthConstraint",                           tmpBitDepthConstraint,                               0u, "Bit depth to use for profile-constraint for RExt profiles. 0=automatically choose based upon other parameters")
+  ("MaxChromaFormatConstraint",                       tmpConstraintChromaFormat,                            0, "Chroma-format to use for the profile-constraint for RExt profiles. 0=automatically choose based upon other parameters")
+  ("IntraConstraintFlag",                             tmpIntraConstraintFlag,                           false, "Value of general_intra_constraint_flag to use for RExt profiles (not used if an explicit RExt sub-profile is specified)")
+  ("LowerBitRateConstraintFlag",                      tmpLowerBitRateConstraintFlag,                     true, "Value of general_lower_bit_rate_constraint_flag to use for RExt profiles")
+
+  ("ProfileCompatibility%d",                          m_profileCompatibility, Profile::NONE, (MAX_NUM_LAYER_IDS + 1), "Compatible profile to be used when encoding")
+  ("ProgressiveSource%d",                             m_progressiveSourceFlagList,   false, (MAX_NUM_LAYER_IDS + 1), "Indicate that source is progressive")
+  ("InterlacedSource%d",                              m_interlacedSourceFlagList,    false, (MAX_NUM_LAYER_IDS + 1), "Indicate that source is interlaced")
+  ("NonPackedSource%d",                               m_nonPackedConstraintFlagList, false, (MAX_NUM_LAYER_IDS + 1), "Indicate that source does not contain frame packing")
+  ("FrameOnly%d",                                     m_frameOnlyConstraintFlagList, false, (MAX_NUM_LAYER_IDS + 1), "Indicate that the bitstream contains only frames")
+  
+  ("LayerPTLIndex%d",                                 cfg_layerPTLIdx,               0, MAX_VPS_LAYER_IDX_PLUS1, "Index of PTL for each layer")
+  ("ListOfProfileTierLevelOls%d",                     cfg_listOfLayerPTLOfOlss, string(""), MAX_VPS_OUTPUT_LAYER_SETS_PLUS1, "PTL Index for each layer in each OLS except the first OLS. The PTL index for layer in the first OLS is set to 1")
+#else
+  ("Profile",                                         extendedProfile,                                   NONE, "Profile name to use for encoding. Use main (for main), main10 (for main10), main-still-picture, main-RExt (for Range Extensions profile), any of the RExt specific profile names, or none")
+  ("Level",                                           m_level,                                    Level::NONE, "Level limit to be used, eg 5.1, or none")
+  ("Tier",                                            m_levelTier,                                Level::MAIN, "Tier to use for interpretation of --Level (main or high only)")
+  ("MaxBitDepthConstraint",                           m_bitDepthConstraint,                                0u, "Bit depth to use for profile-constraint for RExt profiles. 0=automatically choose based upon other parameters")
+  ("MaxChromaFormatConstraint",                       tmpConstraintChromaFormat,                            0, "Chroma-format to use for the profile-constraint for RExt profiles. 0=automatically choose based upon other parameters")
+  ("IntraConstraintFlag",                             m_intraConstraintFlag,                            false, "Value of general_intra_constraint_flag to use for RExt profiles (not used if an explicit RExt sub-profile is specified)")
+  ("LowerBitRateConstraintFlag",                      m_lowerBitRateConstraintFlag,                      true, "Value of general_lower_bit_rate_constraint_flag to use for RExt profiles")
+
+  ("ProgressiveSource",                               m_progressiveSourceFlag,                          false, "Indicate that source is progressive")
+  ("InterlacedSource",                                m_interlacedSourceFlag,                           false, "Indicate that source is interlaced")
+  ("NonPackedSource",                                 m_nonPackedConstraintFlag,                        false, "Indicate that source does not contain frame packing")
+  ("FrameOnly",                                       m_frameOnlyConstraintFlag,                        false, "Indicate that the bitstream contains only frames")
+#endif
+
+#if LAYER_CTB
+  // Unit definition parameters
+  ("MaxCUWidth%d",                                    cfg_uiMaxCUWidth,             64u, MAX_LAYERS, "Maximum CU width")
+  ("MaxCUHeight%d",                                   cfg_uiMaxCUHeight,            64u, MAX_LAYERS, "Maximum CU height")
+  // todo: remove defaults from MaxCUSize
+  ("MaxCUSize%d,s%d",                                 cfg_uiMaxCUWidth,             64u, MAX_LAYERS, "Maximum CU size")
+  ("MaxCUSize%d,s%d",                                 cfg_uiMaxCUHeight,            64u, MAX_LAYERS, "Maximum CU size")
+  ("MaxPartitionDepth%d,h%d",                         cfg_uiMaxCUDepth,              4u, MAX_LAYERS, "CU depth")
+  
+  ("QuadtreeTULog2MaxSize%d",                         cfg_uiQuadtreeTULog2MaxSize,   6u, MAX_LAYERS, "Maximum TU size in logarithm base 2")
+  ("QuadtreeTULog2MinSize%d",                         cfg_uiQuadtreeTULog2MinSize,   2u, MAX_LAYERS, "Minimum TU size in logarithm base 2")
+  
+  ("QuadtreeTUMaxDepthIntra%d",                       cfg_uiQuadtreeTUMaxDepthIntra, 1u, MAX_LAYERS, "Depth of TU tree for intra CUs")
+  ("QuadtreeTUMaxDepthInter%d",                       cfg_uiQuadtreeTUMaxDepthInter, 2u, MAX_LAYERS, "Depth of TU tree for inter CUs")
+
+
+  // set the same CU realted settings across all the layers if config file parameters are not layer specific
+  ("MaxCUWidth",                                      cfg_uiMaxCUWidth,             64u, MAX_LAYERS, "Maximum CU width")
+  ("MaxCUHeight",                                     cfg_uiMaxCUHeight,            64u, MAX_LAYERS, "Maximum CU height")
+  // todo: remove defaults from MaxCUSize
+  ("MaxCUSize,s",                                     cfg_uiMaxCUWidth,             64u, MAX_LAYERS, "Maximum CU size")
+  ("MaxCUSize,s",                                     cfg_uiMaxCUHeight,            64u, MAX_LAYERS, "Maximum CU size")
+  ("MaxPartitionDepth,h",                             cfg_uiMaxCUDepth,              4u, MAX_LAYERS, "CU depth")
+  
+  ("QuadtreeTULog2MaxSize",                           cfg_uiQuadtreeTULog2MaxSize,   6u, MAX_LAYERS, "Maximum TU size in logarithm base 2")
+  ("QuadtreeTULog2MinSize",                           cfg_uiQuadtreeTULog2MinSize,   2u, MAX_LAYERS, "Minimum TU size in logarithm base 2")
+  
+  ("QuadtreeTUMaxDepthIntra",                         cfg_uiQuadtreeTUMaxDepthIntra, 1u, MAX_LAYERS, "Depth of TU tree for intra CUs")
+  ("QuadtreeTUMaxDepthInter",                         cfg_uiQuadtreeTUMaxDepthInter, 2u, MAX_LAYERS, "Depth of TU tree for inter CUs")
+#else
+  // 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")
+#endif
+  
+  // Coding structure paramters
+#if SVC_EXTENSION
+  ("IntraPeriod%d,-ip%d",                             cfg_IntraPeriod, -1, MAX_LAYERS, "intra period in frames for layer %d, (-1: only first frame)")
+#else
+  ("IntraPeriod,-ip",                                 m_iIntraPeriod,                                      -1, "Intra period in frames, (-1: only first frame)")
+#endif
+#if ALLOW_RECOVERY_POINT_AS_RAP
+  ("DecodingRefreshType,-dr",                         m_iDecodingRefreshType,                               0, "Intra refresh type (0:none 1:CRA 2:IDR 3:RecPointSEI)")
+#else
+  ("DecodingRefreshType,-dr",                         m_iDecodingRefreshType,                               0, "Intra refresh type (0:none 1:CRA 2:IDR)")
+#endif
+  ("GOPSize,g",                                       m_iGOPSize,                                           1, "GOP size of temporal structure")
+
+  // motion search 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")
+
+#if SVC_EXTENSION
+  ("LambdaModifier%d,-LM%d",                          m_adLambdaModifier, ( double )1.0, MAX_TLAYER, "Lambda modifier for temporal layer %d")
+#else
+  // Mode decision parameters
+  // 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")
+#endif
+
+  /* Quantization parameters */
+#if SVC_EXTENSION
+  ("QP%d,-q%d",                                       cfg_fQP,  30.0, MAX_LAYERS, "Qp value for layer %d, 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")
+  ("MaxCUChromaQpAdjustmentDepth",                    m_maxCUChromaQpAdjustmentDepth,                      -1, "Maximum depth for CU chroma Qp adjustment - set less than 0 to disable")
+
+  ("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")
+#if !SVC_EXTENSION
+  ("dQPFile,m",                                       cfg_dQPFile,                                 string(""), "dQP file name")
+#endif
+  ("RDOQ",                                            m_useRDOQ,                                         true)
+  ("RDOQTS",                                          m_useRDOQTS,                                       true)
+  ("RDpenalty",                                       m_rdPenalty,                                          0,  "RD-penalty for 32x32 TU for intra in non-intra slices. 0:disabled  1:RD-penalty  2:maximum RD-penalty")
+
+  // Deblocking filter parameters
+  ("LoopFilterDisable",                               m_bLoopFilterDisable,                             false)
+  ("LoopFilterOffsetInPPS",                           m_loopFilterOffsetInPPS,                          false)
+  ("LoopFilterBetaOffset_div2",                       m_loopFilterBetaOffsetDiv2,                           0)
+  ("LoopFilterTcOffset_div2",                         m_loopFilterTcOffsetDiv2,                             0)
+  ("DeblockingFilterControlPresent",                  m_DeblockingFilterControlPresent,                 false)
+  ("DeblockingFilterMetric",                          m_DeblockingFilterMetric,                         false)
+
+  // Coding tools
+  ("AMP",                                             m_enableAMP,                                       true, "Enable asymmetric motion partitions")
+  ("CrossComponentPrediction",                        m_useCrossComponentPrediction,                    false, "Enable the use of cross-component prediction (not valid in V1 profiles)")
+  ("ReconBasedCrossCPredictionEstimate",              m_reconBasedCrossCPredictionEstimate,             false, "When determining the alpha value for cross-component prediction, use the decoded residual rather than the pre-transform encoder-side residual")
+  ("SaoLumaOffsetBitShift",                           saoOffsetBitShift[CHANNEL_TYPE_LUMA],                 0, "Specify the luma SAO bit-shift. If negative, automatically calculate a suitable value based upon bit depth and initial QP")
+  ("SaoChromaOffsetBitShift",                         saoOffsetBitShift[CHANNEL_TYPE_CHROMA],               0, "Specify the chroma SAO bit-shift. If negative, automatically calculate a suitable value based upon bit depth and initial QP")
+  ("TransformSkip",                                   m_useTransformSkip,                               false, "Intra transform skipping")
+  ("TransformSkipFast",                               m_useTransformSkipFast,                           false, "Fast intra transform skipping")
+  ("TransformSkipLog2MaxSize",                        m_transformSkipLog2MaxSize,                          2U, "Specify transform-skip maximum size. Minimum 2. (not valid in V1 profiles)")
+  ("ImplicitResidualDPCM",                            m_useResidualDPCM[RDPCM_SIGNAL_IMPLICIT],         false, "Enable implicitly signalled residual DPCM for intra (also known as sample-adaptive intra predict) (not valid in V1 profiles)")
+  ("ExplicitResidualDPCM",                            m_useResidualDPCM[RDPCM_SIGNAL_EXPLICIT],         false, "Enable explicitly signalled residual DPCM for inter (not valid in V1 profiles)")
+  ("ResidualRotation",                                m_useResidualRotation,                            false, "Enable rotation of transform-skipped and transquant-bypassed TUs through 180 degrees prior to entropy coding (not valid in V1 profiles)")
+  ("SingleSignificanceMapContext",                    m_useSingleSignificanceMapContext,                false, "Enable, for transform-skipped and transquant-bypassed TUs, the selection of a single significance map context variable for all coefficients (not valid in V1 profiles)")
+  ("GolombRiceParameterAdaptation",                   m_useGolombRiceParameterAdaptation,               false, "Enable the adaptation of the Golomb-Rice parameter over the course of each slice")
+  ("AlignCABACBeforeBypass",                          m_alignCABACBeforeBypass,                         false, "Align the CABAC engine to a defined fraction of a bit prior to coding bypass data. Must be 1 in high bit rate profile, 0 otherwise" )
+  ("SAO",                                             m_bUseSAO,                                         true, "Enable Sample Adaptive Offset")
+  ("MaxNumOffsetsPerPic",                             m_maxNumOffsetsPerPic,                             2048, "Max number of SAO offset per picture (Default: 2048)")
+  ("SAOLcuBoundary",                                  m_saoCtuBoundary,                                 false, "0: right/bottom CTU boundary areas skipped from SAO parameter estimation, 1: non-deblocked pixels are used for those areas")
+  ("SliceMode",                                       m_sliceMode,                                          0, "0: Disable all Recon slice limits, 1: Enforce max # of CTUs, 2: Enforce max # of bytes, 3:specify tiles per dependent slice")
+  ("SliceArgument",                                   m_sliceArgument,                                      0, "Depending on SliceMode being:"
+                                                                                                               "\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 CTUs, 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)
+  ("IntraReferenceSmoothing",                         m_enableIntraReferenceSmoothing,                   true, "0: Disable use of intra reference smoothing. 1: Enable use of intra reference smoothing (not valid in V1 profiles)")
+  ("WeightedPredP,-wpP",                              m_useWeightedPred,                                false, "Use weighted prediction in P slices")
+  ("WeightedPredB,-wpB",                              m_useWeightedBiPred,                              false, "Use weighted (bidirectional) prediction in B slices")
+  ("Log2ParallelMergeLevel",                          m_log2ParallelMergeLevel,                            2u, "Parallel merge estimation region")
+    //deprecated copies of renamed tile parameters
+  ("UniformSpacingIdc",                               m_tileUniformSpacingFlag,                         false,      "deprecated alias of TileUniformSpacing")
+  ("ColumnWidthArray",                                cfg_ColumnWidth,                        cfg_ColumnWidth, "deprecated alias of TileColumnWidthArray")
+  ("RowHeightArray",                                  cfg_RowHeight,                            cfg_RowHeight, "deprecated alias of TileRowHeightArray")
+
+  ("TileUniformSpacing",                              m_tileUniformSpacingFlag,                         false,      "Indicates that tile columns and rows are distributed uniformly")
+  ("NumTileColumnsMinus1",                            m_numTileColumnsMinus1,                               0,          "Number of tile columns in a picture minus 1")
+  ("NumTileRowsMinus1",                               m_numTileRowsMinus1,                                  0,          "Number of rows in a picture minus 1")
+  ("TileColumnWidthArray",                            cfg_ColumnWidth,                        cfg_ColumnWidth, "Array containing tile column width values in units of CTU")
+  ("TileRowHeightArray",                              cfg_RowHeight,                            cfg_RowHeight, "Array containing tile row height values in units of CTU")
+  ("LFCrossTileBoundaryFlag",                         m_bLFCrossTileBoundaryFlag,                        true, "1: cross-tile-boundary loop filtering. 0:non-cross-tile-boundary loop filtering")
+#if SVC_EXTENSION
+  ("WaveFrontSynchro%d",                              cfg_waveFrontSynchro,             0,  MAX_LAYERS,          "0: no synchro; 1 synchro with TR; 2 TRR etc")
+#else
+  ("WaveFrontSynchro",                                m_iWaveFrontSynchro,                                  0, "0: no synchro; 1 synchro with top-right-right")
+#endif
+  ("ScalingList",                                     m_useScalingListId,                    SCALING_LIST_OFF, "0/off: no scaling list, 1/default: default scaling lists, 2/file: scaling lists specified in ScalingListFile")
+  ("ScalingListFile",                                 cfg_ScalingListFile,                         string(""), "Scaling list file name. Use an empty string to produce help.")
+  ("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 FAST_INTRA_SHVC
+  ("FIS",                                             m_useFastIntraScalable, false, "Fast Intra Decision for Scalable HEVC")
+#endif
+#if RC_SHVC_HARMONIZATION
+  ("RateControl%d",                                   cfg_RCEnableRateControl, false, MAX_LAYERS, "Rate control: enable rate control for layer %d")
+  ("TargetBitrate%d",                                 cfg_RCTargetBitRate, 0, MAX_LAYERS, "Rate control: target bitrate for layer %d")
+  ("KeepHierarchicalBit%d",                           cfg_RCKeepHierarchicalBit, false, MAX_LAYERS, "Rate control: keep hierarchical bit allocation for layer %d")
+  ("LCULevelRateControl%d",                           cfg_RCLCULevelRC, true, MAX_LAYERS, "Rate control: LCU level RC")
+  ("RCLCUSeparateModel%d",                            cfg_RCUseLCUSeparateModel, true, MAX_LAYERS, "Rate control: Use LCU level separate R-lambda model")
+  ("InitialQP%d",                                     cfg_RCInitialQP, 0, MAX_LAYERS, "Rate control: initial QP")
+  ("RCForceIntraQP%d",                                cfg_RCForceIntraQP, false, MAX_LAYERS, "Rate control: force intra QP to be equal to initial QP")
+#else
+  ( "RateControl",                                    m_RCEnableRateControl,                            false, "Rate control: enable rate control" )
+  ( "TargetBitrate",                                  m_RCTargetBitrate,                                    0, "Rate control: target bit-rate" )
+  ( "KeepHierarchicalBit",                            m_RCKeepHierarchicalBit,                              0, "Rate control: 0: equal bit allocation; 1: fixed ratio bit allocation; 2: adaptive ratio bit allocation" )
+  ( "LCULevelRateControl",                            m_RCLCULevelRC,                                    true, "Rate control: true: CTU level RC; false: picture level RC" )
+  ( "RCLCUSeparateModel",                             m_RCUseLCUSeparateModel,                           true, "Rate control: use CTU 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" )
+#endif
+
+  ("TransquantBypassEnableFlag",                      m_TransquantBypassEnableFlag,                     false, "transquant_bypass_enable_flag indicator in PPS")
+  ("CUTransquantBypassFlagForce",                     m_CUTransquantBypassFlagForce,                    false, "Force transquant bypass mode, when transquant_bypass_enable_flag is enabled")
+  ("CostMode",                                        m_costMode,                         COST_STANDARD_LOSSY, "Use alternative cost functions: choose between 'lossy', 'sequence_level_lossless', 'lossless' (which forces QP to " MACRO_TO_STRING(LOSSLESS_AND_MIXED_LOSSLESS_RD_COST_TEST_QP) ") and 'mixed_lossless_lossy' (which used QP'=" MACRO_TO_STRING(LOSSLESS_AND_MIXED_LOSSLESS_RD_COST_TEST_QP_PRIME) " for pre-estimates of transquant-bypass blocks).")
+  ("RecalculateQPAccordingToLambda",                  m_recalculateQPAccordingToLambda,                 false, "Recalculate QP values according to lambda values. Do not suggest to be enabled in all intra case")
+  ("StrongIntraSmoothing,-sis",                       m_useStrongIntraSmoothing,                         true, "Enable strong intra smoothing for 32x32 blocks")
+  ("SEIActiveParameterSets",                          m_activeParameterSetsSEIEnabled,                      0, "Enable generation of active parameter sets SEI messages")
+  ("VuiParametersPresent,-vui",                       m_vuiParametersPresentFlag,                       false, "Enable generation of vui_parameters()")
+  ("AspectRatioInfoPresent",                          m_aspectRatioInfoPresentFlag,                     false, "Signals whether aspect_ratio_idc is present")
+  ("AspectRatioIdc",                                  m_aspectRatioIdc,                                     0, "aspect_ratio_idc")
+  ("SarWidth",                                        m_sarWidth,                                           0, "horizontal size of the sample aspect ratio")
+  ("SarHeight",                                       m_sarHeight,                                          0, "vertical size of the sample aspect ratio")
+  ("OverscanInfoPresent",                             m_overscanInfoPresentFlag,                        false, "Indicates whether conformant decoded pictures are suitable for display using overscan\n")
+  ("OverscanAppropriate",                             m_overscanAppropriateFlag,                        false, "Indicates whether conformant decoded pictures are suitable for display using overscan\n")
+  ("VideoSignalTypePresent",                          m_videoSignalTypePresentFlag,                     false, "Signals whether video_format, video_full_range_flag, and colour_description_present_flag are present")
+  ("VideoFormat",                                     m_videoFormat,                                        5, "Indicates representation of pictures")
+  ("VideoFullRange",                                  m_videoFullRangeFlag,                             false, "Indicates the black level and range of luma and chroma signals")
+  ("ColourDescriptionPresent",                        m_colourDescriptionPresentFlag,                   false, "Signals whether colour_primaries, transfer_characteristics and matrix_coefficients are present")
+  ("ColourPrimaries",                                 m_colourPrimaries,                                    2, "Indicates chromaticity coordinates of the source primaries")
+  ("TransferCharacteristics",                         m_transferCharacteristics,                            2, "Indicates the opto-electronic transfer characteristics of the source")
+  ("MatrixCoefficients",                              m_matrixCoefficients,                                 2, "Describes the matrix coefficients used in deriving luma and chroma from RGB primaries")
+  ("ChromaLocInfoPresent",                            m_chromaLocInfoPresentFlag,                       false, "Signals whether chroma_sample_loc_type_top_field and chroma_sample_loc_type_bottom_field are present")
+  ("ChromaSampleLocTypeTopField",                     m_chromaSampleLocTypeTopField,                        0, "Specifies the location of chroma samples for top field")
+  ("ChromaSampleLocTypeBottomField",                  m_chromaSampleLocTypeBottomField,                     0, "Specifies the location of chroma samples for bottom field")
+  ("NeutralChromaIndication",                         m_neutralChromaIndicationFlag,                    false, "Indicates that the value of all decoded chroma samples is equal to 1<<(BitDepthCr-1)")
+  ("DefaultDisplayWindowFlag",                        m_defaultDisplayWindowFlag,                       false, "Indicates the presence of the Default Window parameters")
+  ("DefDispWinLeftOffset",                            m_defDispWinLeftOffset,                               0, "Specifies the left offset of the default display window from the conformance window")
+  ("DefDispWinRightOffset",                           m_defDispWinRightOffset,                              0, "Specifies the right offset of the default display window from the conformance window")
+  ("DefDispWinTopOffset",                             m_defDispWinTopOffset,                                0, "Specifies the top offset of the default display window from the conformance window")
+  ("DefDispWinBottomOffset",                          m_defDispWinBottomOffset,                             0, "Specifies the bottom offset of the default display window from the conformance window")
+  ("FrameFieldInfoPresentFlag",                       m_frameFieldInfoPresentFlag,                      false, "Indicates that pic_struct and field coding related values are present in picture timing SEI messages")
+  ("PocProportionalToTimingFlag",                     m_pocProportionalToTimingFlag,                    false, "Indicates that the POC value is proportional to the output time w.r.t. first picture in CVS")
+  ("NumTicksPocDiffOneMinus1",                        m_numTicksPocDiffOneMinus1,                           0, "Number of ticks minus 1 that for a POC difference of one")
+  ("BitstreamRestriction",                            m_bitstreamRestrictionFlag,                       false, "Signals whether bitstream restriction parameters are present")
+  ("TilesFixedStructure",                             m_tilesFixedStructureFlag,                        false, "Indicates that each active picture parameter set has the same values of the syntax elements related to tiles")
+  ("MotionVectorsOverPicBoundaries",                  m_motionVectorsOverPicBoundariesFlag,             false, "Indicates that no samples outside the picture boundaries are used for inter prediction")
+  ("MaxBytesPerPicDenom",                             m_maxBytesPerPicDenom,                                2, "Indicates a number of bytes not exceeded by the sum of the sizes of the VCL NAL units associated with any coded picture")
+  ("MaxBitsPerMinCuDenom",                            m_maxBitsPerMinCuDenom,                               1, "Indicates an upper bound for the number of bits of coding_unit() data")
+  ("Log2MaxMvLengthHorizontal",                       m_log2MaxMvLengthHorizontal,                         15, "Indicate the maximum absolute value of a decoded horizontal MV component in quarter-pel luma units")
+  ("Log2MaxMvLengthVertical",                         m_log2MaxMvLengthVertical,                           15, "Indicate the maximum absolute value of a decoded vertical MV component in quarter-pel luma units")
+  ("SEIRecoveryPoint",                                m_recoveryPointSEIEnabled,                            0, "Control generation of recovery point SEI messages")
+  ("SEIBufferingPeriod",                              m_bufferingPeriodSEIEnabled,                          0, "Control generation of buffering period SEI messages")
+  ("SEIPictureTiming",                                m_pictureTimingSEIEnabled,                            0, "Control generation of picture timing SEI messages")
+  ("SEIToneMappingInfo",                              m_toneMappingInfoSEIEnabled,                      false, "Control generation of Tone Mapping SEI messages")
+  ("SEIToneMapId",                                    m_toneMapId,                                          0, "Specifies Id of Tone Mapping SEI message for a given session")
+  ("SEIToneMapCancelFlag",                            m_toneMapCancelFlag,                              false, "Indicates that Tone Mapping SEI message cancels the persistence 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 Tone 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 maximum 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,      cfg_startOfCodedInterval, "Array of user-defined mapping table")
+  ("SEIToneMapNumPivots",                             m_numPivots,                                          0, "Specifies the number of pivot points in mode 3")
+  ("SEIToneMapCodedPivotValue",                       cfg_codedPivotValue,                cfg_codedPivotValue, "Array of pivot point")
+  ("SEIToneMapTargetPivotValue",                      cfg_targetPivotValue,              cfg_targetPivotValue, "Array of pivot point")
+  ("SEIToneMapCameraIsoSpeedIdc",                     m_cameraIsoSpeedIdc,                                  0, "Indicates the camera ISO speed for daylight illumination")
+  ("SEIToneMapCameraIsoSpeedValue",                   m_cameraIsoSpeedValue,                              400, "Specifies the camera ISO speed for daylight illumination of Extended_ISO")
+  ("SEIToneMapExposureIndexIdc",                      m_exposureIndexIdc,                                   0, "Indicates the exposure index setting of the camera")
+  ("SEIToneMapExposureIndexValue",                    m_exposureIndexValue,                               400, "Specifies the exposure index setting of the camera 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")
+  ("SEIChromaSamplingFilterHint",                     m_chromaSamplingFilterSEIenabled,                 false, "Control generation of the chroma sampling filter hint SEI message")
+  ("SEIChromaSamplingHorizontalFilterType",           m_chromaSamplingHorFilterIdc,                         2, "Defines the Index of the chroma sampling horizontal filter\n"
+                                                                                                               "\t0: unspecified  - Chroma filter is unknown or is determined by the application"
+                                                                                                               "\t1: User-defined - Filter coefficients are specified in the chroma sampling filter hint SEI message"
+                                                                                                               "\t2: Standards-defined - ITU-T Rec. T.800 | ISO/IEC15444-1, 5/3 filter")
+  ("SEIChromaSamplingVerticalFilterType",             m_chromaSamplingVerFilterIdc,                         2, "Defines the Index of the chroma sampling vertical filter\n"
+                                                                                                               "\t0: unspecified  - Chroma filter is unknown or is determined by the application"
+                                                                                                               "\t1: User-defined - Filter coefficients are specified in the chroma sampling filter hint SEI message"
+                                                                                                               "\t2: Standards-defined - ITU-T Rec. T.800 | ISO/IEC15444-1, 5/3 filter")
+  ("SEIFramePacking",                                 m_framePackingSEIEnabled,                             0, "Control generation of frame packing SEI messages")
+  ("SEIFramePackingType",                             m_framePackingSEIType,                                0, "Define frame packing arrangement\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")
+  ("SEISegmentedRectFramePacking",                    m_segmentedRectFramePackingSEIEnabled,                0, "Controls generation of segmented rectangular frame packing SEI messages")
+  ("SEISegmentedRectFramePackingCancel",              m_segmentedRectFramePackingSEICancel,             false, "If equal to 1, cancels the persistence of any previous SRFPA SEI message")
+  ("SEISegmentedRectFramePackingType",                m_segmentedRectFramePackingSEIType,                   0, "Specifies the arrangement of the frames in the reconstructed picture")
+  ("SEISegmentedRectFramePackingPersistence",         m_segmentedRectFramePackingSEIPersistence,        false, "If equal to 0, the SEI applies to the current frame only")
+  ("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")
+  ("SEINoDisplay",                                    m_noDisplaySEITLayer,                                 0, "Control generation of no display SEI message\n"
+                                                                                                               "\tN: 0 < N enable no display SEI message for temporal layer N or higher\n"
+                                                                                                               "\t0: disable")
+  ("SEIDecodingUnitInfo",                             m_decodingUnitInfoSEIEnabled,                         0, "Control generation of decoding unit information SEI message.")
+#if LAYERS_NOT_PRESENT_SEI
+  ("SEILayersNotPresent",                             m_layersNotPresentSEIEnabled,             0, "Control generation of layers not present SEI message")
+#endif
+  ("SEISOPDescription",                               m_SOPDescriptionSEIEnabled,                           0, "Control generation of SOP description SEI messages")
+  ("SEIScalableNesting",                              m_scalableNestingSEIEnabled,                          0, "Control generation of scalable nesting SEI messages")
+  ("SEITempMotionConstrainedTileSets",                m_tmctsSEIEnabled,                                false, "Control generation of temporal motion constrained tile sets SEI message")
+  ("SEITimeCodeEnabled",                              m_timeCodeSEIEnabled,                             false, "Control generation of time code information SEI message")
+  ("SEITimeCodeNumClockTs",                           m_timeCodeSEINumTs,                                   0, "Number of clock time sets [0..3]")
+  ("SEITimeCodeTimeStampFlag",                        cfg_timeCodeSeiTimeStampFlag,          cfg_timeCodeSeiTimeStampFlag,         "Time stamp flag associated to each time set")
+  ("SEITimeCodeFieldBasedFlag",                       cfg_timeCodeSeiNumUnitFieldBasedFlag,  cfg_timeCodeSeiNumUnitFieldBasedFlag, "Field based flag associated to each time set")
+  ("SEITimeCodeCountingType",                         cfg_timeCodeSeiCountingType,           cfg_timeCodeSeiCountingType,          "Counting type associated to each time set")
+  ("SEITimeCodeFullTsFlag",                           cfg_timeCodeSeiFullTimeStampFlag,      cfg_timeCodeSeiFullTimeStampFlag,     "Full time stamp flag associated to each time set")
+  ("SEITimeCodeDiscontinuityFlag",                    cfg_timeCodeSeiDiscontinuityFlag,      cfg_timeCodeSeiDiscontinuityFlag,     "Discontinuity flag associated to each time set")
+  ("SEITimeCodeCntDroppedFlag",                       cfg_timeCodeSeiCntDroppedFlag,         cfg_timeCodeSeiCntDroppedFlag,        "Counter dropped flag associated to each time set")
+  ("SEITimeCodeNumFrames",                            cfg_timeCodeSeiNumberOfFrames,         cfg_timeCodeSeiNumberOfFrames,        "Number of frames associated to each time set")
+  ("SEITimeCodeSecondsValue",                         cfg_timeCodeSeiSecondsValue,           cfg_timeCodeSeiSecondsValue,          "Seconds value for each time set")
+  ("SEITimeCodeMinutesValue",                         cfg_timeCodeSeiMinutesValue,           cfg_timeCodeSeiMinutesValue,          "Minutes value for each time set")
+  ("SEITimeCodeHoursValue",                           cfg_timeCodeSeiHoursValue,             cfg_timeCodeSeiHoursValue,            "Hours value for each time set")
+  ("SEITimeCodeSecondsFlag",                          cfg_timeCodeSeiSecondsFlag,            cfg_timeCodeSeiSecondsFlag,           "Flag to signal seconds value presence in each time set")
+  ("SEITimeCodeMinutesFlag",                          cfg_timeCodeSeiMinutesFlag,            cfg_timeCodeSeiMinutesFlag,           "Flag to signal minutes value presence in each time set")
+  ("SEITimeCodeHoursFlag",                            cfg_timeCodeSeiHoursFlag,              cfg_timeCodeSeiHoursFlag,             "Flag to signal hours value presence in each time set")
+  ("SEITimeCodeOffsetLength",                         cfg_timeCodeSeiTimeOffsetLength,       cfg_timeCodeSeiTimeOffsetLength,      "Time offset length associated to each time set")
+  ("SEITimeCodeTimeOffset",                           cfg_timeCodeSeiTimeOffsetValue,        cfg_timeCodeSeiTimeOffsetValue,       "Time offset associated to each time set")
+  ("SEIKneeFunctionInfo",                             m_kneeSEIEnabled,                                 false, "Control generation of Knee function SEI messages")
+  ("SEIKneeFunctionId",                               m_kneeSEIId,                                          0, "Specifies Id of Knee function SEI message for a given session")
+  ("SEIKneeFunctionCancelFlag",                       m_kneeSEICancelFlag,                              false, "Indicates that Knee function SEI message cancels the persistence or follows")
+  ("SEIKneeFunctionPersistenceFlag",                  m_kneeSEIPersistenceFlag,                          true, "Specifies the persistence of the Knee function SEI message")
+  ("SEIKneeFunctionInputDrange",                      m_kneeSEIInputDrange,                              1000, "Specifies the peak luminance level for the input picture of Knee function SEI messages")
+  ("SEIKneeFunctionInputDispLuminance",               m_kneeSEIInputDispLuminance,                        100, "Specifies the expected display brightness for the input picture of Knee function SEI messages")
+  ("SEIKneeFunctionOutputDrange",                     m_kneeSEIOutputDrange,                             4000, "Specifies the peak luminance level for the output picture of Knee function SEI messages")
+  ("SEIKneeFunctionOutputDispLuminance",              m_kneeSEIOutputDispLuminance,                       800, "Specifies the expected display brightness for the output picture of Knee function SEI messages")
+  ("SEIKneeFunctionNumKneePointsMinus1",              m_kneeSEINumKneePointsMinus1,                         2, "Specifies the number of knee points - 1")
+  ("SEIKneeFunctionInputKneePointValue",              cfg_kneeSEIInputKneePointValue,   cfg_kneeSEIInputKneePointValue, "Array of input knee point")
+  ("SEIKneeFunctionOutputKneePointValue",             cfg_kneeSEIOutputKneePointValue, cfg_kneeSEIOutputKneePointValue, "Array of output knee point")
+  ("SEIMasteringDisplayColourVolume",                 m_masteringDisplay.colourVolumeSEIEnabled,         false, "Control generation of mastering display colour volume SEI messages")
+  ("SEIMasteringDisplayMaxLuminance",                 m_masteringDisplay.maxLuminance,                  10000u, "Specifies the mastering display maximum luminance value in units of 1/10000 candela per square metre (32-bit code value)")
+  ("SEIMasteringDisplayMinLuminance",                 m_masteringDisplay.minLuminance,                      0u, "Specifies the mastering display minimum luminance value in units of 1/10000 candela per square metre (32-bit code value)")
+  ("SEIMasteringDisplayPrimaries",                    cfg_DisplayPrimariesCode,       cfg_DisplayPrimariesCode, "Mastering display primaries for all three colour planes in CIE xy coordinates in increments of 1/50000 (results in the ranges 0 to 50000 inclusive)")
+  ("SEIMasteringDisplayWhitePoint",                   cfg_DisplayWhitePointCode,     cfg_DisplayWhitePointCode, "Mastering display white point CIE xy coordinates in normalised increments of 1/50000 (e.g. 0.333 = 16667)")
+    
+#if P0123_ALPHA_CHANNEL_SEI
+  ("SEIAlphaChannelInfo",                     m_alphaSEIEnabled,                        false, "Enables transmission of information associated with alpha channel (default : 0)")
+  ("SEIAlphaCancelFlag",                      m_alphaCancelFlag,                         true, "Denotes that this SEI message cancels the persistence of any previously received alpha channel SEI message (default : 1)")
+  ("SEIAlphaUseIdc",                          m_alphaUseIdc,                                2, "Denotes the use of the received alpha channel in final picture composition (e.g. pre-multiplied alpha, default : 2)")
+  ("SEIAlphaBitDepthMinus8",                  m_alphaBitDepthMinus8,                        0, "Denotes the bit depth associated with the received alpha channel (default : 0)")
+  ("SEIAlphaTransparentValue",                m_alphaTransparentValue,                      0, "Denotes the sample value which is considered transparent for alpha blending purposes (default : 0)")
+  ("SEIAlphaOpaqueValue",                     m_alphaOpaqueValue,                         255, "Denotes the sample value which is considered opaque for alpha blending purposes (default : 255)")
+  ("SEIAlphaIncrementFlag",                   m_alphaIncrementFlag,                     false, "Denotes whether the sample values should be incremented by one for the purposes of alpha blending (default : 0)")
+  ("SEIAlphaClipFlag",                        m_alphaClipFlag,                          false, "Denotes whether clipping is applied to the sample values (default : 0)")
+  ("SEIAlphaClipType",                        m_alphaClipTypeFlag,                      false, "Denotes the type of clipping applied to the sample values (0 = binary, 1 = linear, default : 0)")
+#endif
+#if Q0096_OVERLAY_SEI
+  ("SEIOverlayInfo",                          m_overlaySEIEnabled,                      false, "Control generation of Selectable Overlays SEI messages")
+  ("SEIOverlayCancelFlag",                    m_overlayInfoCancelFlag,                   true, "Indicates that Selectable Overlay SEI message cancels the persistance or follows (default: 1)")
+  ("SEIOverlayContentAuxIdMinus128",          m_overlayContentAuxIdMinus128,          UInt(0), "Indicates the AuxId value of auxiliary pictures containing overlay content - 128")
+  ("SEIOverlayLabelAuxIdMinus128",            m_overlayLabelAuxIdMinus128,            UInt(1), "Indicates the AuxId value of auxiliary pictures containing label content - 128")
+  ("SEIOverlayAlphaAuxIdMinus128",            m_overlayAlphaAuxIdMinus128,            UInt(2), "Indicates the AuxId value of auxiliary pictures containing alpha content - 128")
+  ("SEIOverlayElementLabelValueLengthMinus8", m_overlayElementLabelValueLengthMinus8, UInt(0), "Indicates the number of bits used for coding min and max label values - 8")
+  ("SEIOverlayNumOverlaysMinus1",             m_numOverlaysMinus1,                    UInt(0), "Specifies the number of overlays described by this SEI message - 1")
+  ("SEIOverlayIdx0",                          cfg_overlaySEIIdx[0],                   UInt(0), "Indicates the index of overlay 0")
+  ("SEIOverlayIdx1",                          cfg_overlaySEIIdx[1],                   UInt(1), "Indicates the index of overlay 1")
+  ("SEIOverlayIdx2",                          cfg_overlaySEIIdx[2],                   UInt(2), "Indicates the index of overlay 2")
+  ("SEIOverlayLanguagePresentFlag0",          cfg_overlaySEILanguagePresentFlag[0],     false, "Indicates if the language for overlay 0 is specified")
+  ("SEIOverlayLanguagePresentFlag1",          cfg_overlaySEILanguagePresentFlag[1],     false, "Indicates if the language for overlay 1 is specified")
+  ("SEIOverlayLanguagePresentFlag2",          cfg_overlaySEILanguagePresentFlag[2],     false, "Indicates if the language for overlay 2 is specified")
+  ("SEIOverlayContentLayerId0",               cfg_overlaySEIContentLayerId[0],        UInt(0), "Indicates the nuh_layer_id value of the overlay content of overlay 0")  
+  ("SEIOverlayContentLayerId1",               cfg_overlaySEIContentLayerId[1],        UInt(0), "Indicates the nuh_layer_id value of the overlay content of overlay 1")  
+  ("SEIOverlayContentLayerId2",               cfg_overlaySEIContentLayerId[2],        UInt(0), "Indicates the nuh_layer_id value of the overlay content of overlay 2")  
+  ("SEIOverlayLabelPresentFlag0",             cfg_overlaySEILabelPresentFlag[0],        false, "Specifies if label content 0 is present")  
+  ("SEIOverlayLabelPresentFlag1",             cfg_overlaySEILabelPresentFlag[1],        false, "Specifies if label content 1 is present")  
+  ("SEIOverlayLabelPresentFlag2",             cfg_overlaySEILabelPresentFlag[2],        false, "Specifies if label content 2 is present")  
+  ("SEIOverlayLabelLayerId0",                 cfg_overlaySEILabelLayerId[0],          UInt(0), "Specifies the nuh_layer_id value of the label content of overlay 0")  
+  ("SEIOverlayLabelLayerId1",                 cfg_overlaySEILabelLayerId[1],          UInt(0), "Specifies the nuh_layer_id value of the label content of overlay 1")  
+  ("SEIOverlayLabelLayerId2",                 cfg_overlaySEILabelLayerId[2],          UInt(0), "Specifies the nuh_layer_id value of the label content of overlay 2")  
+  ("SEIOverlayAlphaPresentFlag0",             cfg_overlaySEIAlphaPresentFlag[0],        false, "Specifies if alpha content 0 is present")  
+  ("SEIOverlayAlphaPresentFlag1",             cfg_overlaySEIAlphaPresentFlag[1],        false, "Specifies if alpha content 1 is present")  
+  ("SEIOverlayAlphaPresentFlag2",             cfg_overlaySEIAlphaPresentFlag[2],        false, "Specifies if alpha content 2 is present")  
+  ("SEIOverlayAlphaLayerId0",                 cfg_overlaySEIAlphaLayerId[0],          UInt(0), "Specifies the nuh_layer_id value of the alpha content of overlay 0")  
+  ("SEIOverlayAlphaLayerId1",                 cfg_overlaySEIAlphaLayerId[1],          UInt(0), "Specifies the nuh_layer_id value of the alpha content of overlay 1")  
+  ("SEIOverlayAlphaLayerId2",                 cfg_overlaySEIAlphaLayerId[2],          UInt(0), "Specifies the nuh_layer_id value of the alpha content of overlay 2")  
+  ("SEIOverlayNumElementsMinus1_0",           cfg_overlaySEINumElementsMinus1[0],     UInt(0), "Specifies the number of overlay elements in overlay 0")  
+  ("SEIOverlayNumElementsMinus1_1",           cfg_overlaySEINumElementsMinus1[1],     UInt(0), "Specifies the number of overlay elements in overlay 1")  
+  ("SEIOverlayNumElementsMinus1_2",           cfg_overlaySEINumElementsMinus1[2],     UInt(0), "Specifies the number of overlay elements in overlay 2")  
+  ("SEIOverlayElementLabelRange0",            cfg_overlaySEIElementLabelRanges[0], string(""), "Array of minimum and maximum values in order min0, max0, min1, max1, etc.\n"""
+                                                                                               "indicating the range of sample values corresponding to overlay elements of overlay 0")    
+  ("SEIOverlayElementLabelRange1",            cfg_overlaySEIElementLabelRanges[1], string(""), "Array of minimum and maximum values in order min0, max0, min1, max1, etc.\n"""
+                                                                                               "indicating the range of sample values corresponding to overlay elements of overlay 1")    
+  ("SEIOverlayElementLabelRange2",            cfg_overlaySEIElementLabelRanges[2], string(""), "Array of minimum and maximum values in order min0, max0, min1, max1, etc.\n"""
+                                                                                               "indicating the range of sample values corresponding to overlay elements of overlay 2")  
+  ("SEIOverlayLanguage0",                     cfg_overlaySEILanguage[0],           string(""), "Indicates the language of overlay 0 by a language tag according to RFC 5646")
+  ("SEIOverlayLanguage1",                     cfg_overlaySEILanguage[1],           string(""), "Indicates the language of overlay 1 by a language tag according to RFC 5646")
+  ("SEIOverlayLanguage2",                     cfg_overlaySEILanguage[2],           string(""), "Indicates the language of overlay 2 by a language tag according to RFC 5646")
+  ("SEIOverlayName0",                         cfg_overlaySEIName[0],       string("Overlay0"), "Indicates the name of overlay 0")
+  ("SEIOverlayName1",                         cfg_overlaySEIName[1],       string("Overlay1"), "Indicates the name of overlay 1")
+  ("SEIOverlayName2",                         cfg_overlaySEIName[2],       string("Overlay2"), "Indicates the name of overlay 2")
+  ("SEIOverlayElementNames0",                 cfg_overlaySEIElementNames[0],       string(""), "Indicates the names of all overlay elements of overlay 0 in the format name1|name2|name3|...")                                                                                       
+  ("SEIOverlayElementNames1",                 cfg_overlaySEIElementNames[1],       string(""), "Indicates the names of all overlay elements of overlay 1 in the format name1|name2|name3|...")                                                                                       
+  ("SEIOverlayElementNames2",                 cfg_overlaySEIElementNames[2],       string(""), "Indicates the names of all overlay elements of overlay 2 in the format name1|name2|name3|...")                                                                                       
+  ("SEIOverlayPersistenceFlag",               m_overlayInfoPersistenceFlag,              true, "Indicates if the SEI message applies to the current picture only (0) or also to following pictures (1)")
+#endif
+#if Q0189_TMVP_CONSTRAINTS
+  ("SEITemporalMotionVectorPredictionConstraints",             m_TMVPConstraintsSEIEnabled,              0, "Control generation of TMVP constrants SEI message")
+#endif
+#if M0040_ADAPTIVE_RESOLUTION_CHANGE
+  ("AdaptiveResolutionChange",     m_adaptiveResolutionChange, 0, "Adaptive resolution change frame number. Should coincide with EL RAP picture. (0: disable)")
+#endif
+#if R0071_IRAP_EOS_CROSS_LAYER_IMPACTS
+  ("LayerSwitchOffBegin%d", cfg_layerSwitchOffBegin, 0, MAX_LAYERS, "Switch layer %d off after given poc")
+  ("LayerSwitchOffEnd%d", cfg_layerSwitchOffEnd, 0, MAX_LAYERS, "Switch layer %d on at given poc")
+#endif
+#if HIGHER_LAYER_IRAP_SKIP_FLAG
+  ("SkipPictureAtArcSwitch",     m_skipPictureAtArcSwitch, false, "Code the higher layer picture in ARC up-switching as a skip picture. (0: disable)")
+#endif
+#if N0383_IL_CONSTRAINED_TILE_SETS_SEI
+  ("SEIInterLayerConstrainedTileSets", m_interLayerConstrainedTileSetsSEIEnabled, false, "Control generation of inter layer constrained tile sets SEI message")
+  ("IlNumSetsInMessage",               m_ilNumSetsInMessage,                         0u, "Number of inter layer constrained tile sets")
+  ("TileSetsArray",                    cfg_tileSets,                         string(""), "Array containing tile sets params (TopLeftTileIndex, BottonRightTileIndex and ilcIdc for each set) ")
+#endif
+#if O0153_ALT_OUTPUT_LAYER_FLAG
+  ("AltOutputLayerFlag",               m_altOutputLayerFlag,                      false, "Specifies the value of alt_output_layer_flag in VPS extension")
+#endif
+#if O0149_CROSS_LAYER_BLA_FLAG
+  ("CrossLayerBLAFlag",                m_crossLayerBLAFlag,                       false, "Specifies the value of cross_layer_bla_flag in VPS")
+#endif
+#if Q0048_CGS_3D_ASYMLUT
+  ("CGS",     m_nCGSFlag , 0, "whether CGS is enabled")
+  ("CGSMaxOctantDepth", m_nCGSMaxOctantDepth , 1, "max octant depth")
+  ("CGSMaxYPartNumLog",  m_nCGSMaxYPartNumLog2 , 2, "max Y part number ")
+  ("CGSLUTBit",     m_nCGSLUTBit , 12, "bit depth of CGS LUT")
+#if R0151_CGS_3D_ASYMLUT_IMPROVE
+  ("CGSAdaptC",     m_nCGSAdaptiveChroma , 1, "adaptive chroma partition (only for the case of two chroma partitions)")
+#endif
+#if R0179_ENC_OPT_3DLUT_SIZE
+  ("CGSSizeRDO",     m_nCGSLutSizeRDO , 0, "RDOpt selection of best table size (effective when large maximum table size such as 8x8x8 is used)")
+#endif
+#endif
+#if Q0108_TSA_STSA
+  ("InheritCodingStruct%d",m_inheritCodingStruct, 0, MAX_LAYERS, "Predicts the GOP structure of one layer for another layer")
+#endif
+  ;
+
+  for(Int i=1; i<MAX_GOP+1; i++) {
+    std::ostringstream cOSS;
+    cOSS<<"Frame"<<i;
+    opts.addOptions()(cOSS.str(), m_GOPList[i-1], GOPEntry());
+  }
+
+#if Q0108_TSA_STSA
+  for (Int i=1; i<MAX_LAYERS; i++)
+  {
+    for(Int j=1; j<MAX_GOP+1; j++)
+    { 
+      std::ostringstream cOSS;
+      cOSS<<"Layer"<<i<<"Frame"<<j;
+      opts.addOptions()(cOSS.str(), m_EhGOPList[i][j-1], GOPEntry());
+    }
+  }
+#endif 
+
+  po::setDefaults(opts);
+  const list<const Char*>& argv_unhandled = po::scanArgv(opts, argc, (const Char**) argv);
+
+#if Q0108_TSA_STSA
+  for (Int i=1; i<MAX_LAYERS; i++)
+  {
+    if(m_inheritCodingStruct[i] == 0)
+    {
+      for(Int j=1; j<MAX_GOP+1; j++)
+      { 
+        m_EhGOPList[i][j-1] = m_GOPList[j-1];
+      }
+    }
+    else if( m_inheritCodingStruct[i] > 0)
+    {
+      for(Int j=1; j<MAX_GOP+1; j++)
+      {
+        m_EhGOPList[i][j-1] = m_EhGOPList[m_inheritCodingStruct[i]][j-1];
+      }
+    }
+  }
+#endif 
+  
+  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 SVC_EXTENSION
+#if AVC_BASE
+#if VPS_AVC_BL_FLAG_REMOVAL
+  if( m_nonHEVCBaseLayerFlag )
+#else
+  if( m_avcBaseLayerFlag )
+#endif
+  {
+    *cfg_InputFile[0] = cfg_BLInputFile;
+  }
+#endif
+  m_pBitstreamFile = cfg_BitstreamFile.empty() ? NULL : strdup(cfg_BitstreamFile.c_str());
+#else //SVC_EXTENSION
+  m_pchInputFile = cfg_InputFile.empty() ? NULL : strdup(cfg_InputFile.c_str());
+  m_pchBitstreamFile = cfg_BitstreamFile.empty() ? NULL : strdup(cfg_BitstreamFile.c_str());
+  m_pchReconFile = cfg_ReconFile.empty() ? NULL : strdup(cfg_ReconFile.c_str());
+  m_pchdQPFile = cfg_dQPFile.empty() ? NULL : strdup(cfg_dQPFile.c_str());
+#if Q0074_COLOUR_REMAPPING_SEI
+  m_colourRemapSEIFile = cfg_colourRemapSEIFile.empty() ? NULL : strdup(cfg_colourRemapSEIFile.c_str());
+#endif
+#endif //SVC_EXTENSION
+
+
+  if(m_isField)
+  {
+#if SVC_EXTENSION
+    for(Int layer = 0; layer < MAX_LAYERS; layer++)
+    {
+      //Frame height
+      m_acLayerCfg[layer].m_iSourceHeightOrg = m_acLayerCfg[layer].m_iSourceHeight;
+      //Field height
+      m_acLayerCfg[layer].m_iSourceHeight = m_acLayerCfg[layer].m_iSourceHeight >> 1;
+    }
+#else
+    //Frame height
+    m_iSourceHeightOrg = m_iSourceHeight;
+    //Field height
+    m_iSourceHeight = m_iSourceHeight >> 1;
+#endif
+    //number of fields to encode
+    m_framesToBeEncoded *= 2;
+  }
+
+  if( !m_tileUniformSpacingFlag && m_numTileColumnsMinus1 > 0 )
+  {
+    if (cfg_ColumnWidth.values.size() > m_numTileColumnsMinus1)
+    {
+      printf( "The number of columns whose width are defined is larger than the allowed number of columns.\n" );
+      exit( EXIT_FAILURE );
+    }
+    else if (cfg_ColumnWidth.values.size() < m_numTileColumnsMinus1)
+    {
+      printf( "The width of some columns is not defined.\n" );
+      exit( EXIT_FAILURE );
+    }
+    else
+    {
+      m_tileColumnWidth.resize(m_numTileColumnsMinus1);
+      for(UInt i=0; i<cfg_ColumnWidth.values.size(); i++)
+        m_tileColumnWidth[i]=cfg_ColumnWidth.values[i];
+    }
+  }
+  else
+  {
+    m_tileColumnWidth.clear();
+  }
+
+  if( !m_tileUniformSpacingFlag && m_numTileRowsMinus1 > 0 )
+  {
+    if (cfg_RowHeight.values.size() > m_numTileRowsMinus1)
+    {
+      printf( "The number of rows whose height are defined is larger than the allowed number of rows.\n" );
+      exit( EXIT_FAILURE );
+    }
+    else if (cfg_RowHeight.values.size() < m_numTileRowsMinus1)
+    {
+      printf( "The height of some rows is not defined.\n" );
+      exit( EXIT_FAILURE );
+    }
+    else
+    {
+      m_tileRowHeight.resize(m_numTileRowsMinus1);
+      for(UInt i=0; i<cfg_RowHeight.values.size(); i++)
+        m_tileRowHeight[i]=cfg_RowHeight.values[i];
+    }
+  }
+  else
+  {
+    m_tileRowHeight.clear();
+  }
+
+  m_scalingListFile = cfg_ScalingListFile.empty() ? NULL : strdup(cfg_ScalingListFile.c_str());
+
+
+  
+  /* rules for input, output and internal bitdepths as per help text */
+#if O0194_DIFFERENT_BITDEPTH_EL_BL
+  for(Int layer = 0; layer < MAX_LAYERS; layer++)
+  {
+    if( m_acLayerCfg[layer].m_layerId < 0 )
+    {
+      m_acLayerCfg[layer].m_layerId = layer;
+    }
+
+    m_acLayerCfg[layer].m_MSBExtendedBitDepth[CHANNEL_TYPE_LUMA  ] = m_acLayerCfg[layer].m_inputBitDepth      [CHANNEL_TYPE_LUMA  ];
+    m_acLayerCfg[layer].m_MSBExtendedBitDepth[CHANNEL_TYPE_CHROMA] = m_acLayerCfg[layer].m_MSBExtendedBitDepth[CHANNEL_TYPE_LUMA  ];
+
+    if (m_acLayerCfg[layer].m_internalBitDepth   [CHANNEL_TYPE_LUMA  ] == 0) { m_acLayerCfg[layer].m_internalBitDepth   [CHANNEL_TYPE_LUMA  ] = m_acLayerCfg[layer].m_MSBExtendedBitDepth[CHANNEL_TYPE_LUMA  ]; }
+    if (m_acLayerCfg[layer].m_internalBitDepth   [CHANNEL_TYPE_CHROMA] == 0) { m_acLayerCfg[layer].m_internalBitDepth   [CHANNEL_TYPE_CHROMA] = m_acLayerCfg[layer].m_internalBitDepth   [CHANNEL_TYPE_LUMA  ]; }
+    if (m_acLayerCfg[layer].m_inputBitDepth      [CHANNEL_TYPE_CHROMA] == 0) { m_acLayerCfg[layer].m_inputBitDepth      [CHANNEL_TYPE_CHROMA] = m_acLayerCfg[layer].m_inputBitDepth      [CHANNEL_TYPE_LUMA  ]; }
+    if (m_acLayerCfg[layer].m_outputBitDepth     [CHANNEL_TYPE_LUMA  ] == 0) { m_acLayerCfg[layer].m_outputBitDepth     [CHANNEL_TYPE_LUMA  ] = m_acLayerCfg[layer].m_internalBitDepth   [CHANNEL_TYPE_LUMA  ]; }
+    if (m_acLayerCfg[layer].m_outputBitDepth     [CHANNEL_TYPE_CHROMA] == 0) { m_acLayerCfg[layer].m_outputBitDepth     [CHANNEL_TYPE_CHROMA] = m_acLayerCfg[layer].m_internalBitDepth   [CHANNEL_TYPE_CHROMA]; }
+
+    m_acLayerCfg[layer].m_InputChromaFormatIDC = numberToChromaFormat(tmpInputChromaFormat);
+    m_acLayerCfg[layer].m_chromaFormatIDC      = ((tmpChromaFormat == 0) ? (m_acLayerCfg[layer].m_InputChromaFormatIDC) : (numberToChromaFormat(tmpChromaFormat)));
+
+    m_acLayerCfg[layer].m_useHighPrecisionPredictionWeighting = false;
+    m_acLayerCfg[layer].m_useExtendedPrecision = false;
+  }
+#else
+  /* rules for input, output and internal bitdepths as per help text */
+  if (m_MSBExtendedBitDepth[CHANNEL_TYPE_LUMA  ] == 0) { m_MSBExtendedBitDepth[CHANNEL_TYPE_LUMA  ] = m_inputBitDepth      [CHANNEL_TYPE_LUMA  ]; }
+  if (m_MSBExtendedBitDepth[CHANNEL_TYPE_CHROMA] == 0) { m_MSBExtendedBitDepth[CHANNEL_TYPE_CHROMA] = m_MSBExtendedBitDepth[CHANNEL_TYPE_LUMA  ]; }
+  if (m_internalBitDepth   [CHANNEL_TYPE_LUMA  ] == 0) { m_internalBitDepth   [CHANNEL_TYPE_LUMA  ] = m_MSBExtendedBitDepth[CHANNEL_TYPE_LUMA  ]; }
+  if (m_internalBitDepth   [CHANNEL_TYPE_CHROMA] == 0) { m_internalBitDepth   [CHANNEL_TYPE_CHROMA] = m_internalBitDepth   [CHANNEL_TYPE_LUMA  ]; }
+  if (m_inputBitDepth      [CHANNEL_TYPE_CHROMA] == 0) { m_inputBitDepth      [CHANNEL_TYPE_CHROMA] = m_inputBitDepth      [CHANNEL_TYPE_LUMA  ]; }
+  if (m_outputBitDepth     [CHANNEL_TYPE_LUMA  ] == 0) { m_outputBitDepth     [CHANNEL_TYPE_LUMA  ] = m_internalBitDepth   [CHANNEL_TYPE_LUMA  ]; }
+  if (m_outputBitDepth     [CHANNEL_TYPE_CHROMA] == 0) { m_outputBitDepth     [CHANNEL_TYPE_CHROMA] = m_internalBitDepth   [CHANNEL_TYPE_CHROMA]; }
+
+  m_InputChromaFormatIDC = numberToChromaFormat(tmpInputChromaFormat);
+  m_chromaFormatIDC      = ((tmpChromaFormat == 0) ? (m_InputChromaFormatIDC) : (numberToChromaFormat(tmpChromaFormat)));
+#endif
+
+#if R0071_IRAP_EOS_CROSS_LAYER_IMPACTS
+  for (Int layer = 0; layer < MAX_LAYERS; layer++)
+  {
+    if (m_acLayerCfg[layer].m_layerSwitchOffBegin < m_acLayerCfg[layer].m_layerSwitchOffEnd)
+    {
+      if (m_iGOPSize > 0 && (m_acLayerCfg[layer].m_layerSwitchOffBegin % m_iGOPSize) != 0)
+      {
+        printf("LayerSwitchOffBegin%d: Must be multiple of GOP size.\n", layer);
+        exit(EXIT_FAILURE);
+      }
+      if (m_acLayerCfg[layer].m_iIntraPeriod > 0 && (m_acLayerCfg[layer].m_layerSwitchOffEnd % m_acLayerCfg[layer].m_iIntraPeriod) != 0)
+      {
+        printf("LayerSwitchOffEnd%d: Must be IRAP picture.\n", layer);
+        exit(EXIT_FAILURE);
+      }
+    }
+  }
+#endif
+
+#if MULTIPLE_PTL_SUPPORT
+  for( Int layer = 0; layer < MAX_LAYERS; layer++ )
+  {
+    m_acLayerCfg[layer].m_bitDepthConstraint = tmpBitDepthConstraint;
+    m_acLayerCfg[layer].m_intraConstraintFlag = tmpIntraConstraintFlag;
+    m_acLayerCfg[layer].m_lowerBitRateConstraintFlag = tmpLowerBitRateConstraintFlag;    
+
+    for (UInt channelType = 0; channelType < MAX_NUM_CHANNEL_TYPE; channelType++)
+    {
+      m_acLayerCfg[layer].m_saoOffsetBitShift[channelType] = 0;
+    }
+        
+    Int layerPTLIdx = m_acLayerCfg[layer].m_layerPTLIdx;
+
+    if( extendedProfile[layerPTLIdx] >= 1000 && extendedProfile[layerPTLIdx] <= 2316 )
+    {
+      m_profileList[layerPTLIdx] = Profile::MAINREXT;            
+
+      if( m_acLayerCfg[layer].m_bitDepthConstraint != 0 || tmpConstraintChromaFormat != 0)
+      {
+        fprintf(stderr, "Error: The bit depth and chroma format constraints are not used when an explicit RExt profile is specified\n");
+        exit(EXIT_FAILURE);
+      }
+      m_acLayerCfg[layer].m_bitDepthConstraint  = (extendedProfile[layerPTLIdx]%100);
+      m_acLayerCfg[layer].m_intraConstraintFlag = (extendedProfile[layerPTLIdx]>=2000);
+      switch ((extendedProfile[layerPTLIdx]/100)%10)
+      {
+      case 0:  tmpConstraintChromaFormat=400; break;
+      case 1:  tmpConstraintChromaFormat=420; break;
+      case 2:  tmpConstraintChromaFormat=422; break;
+      default: tmpConstraintChromaFormat=444; break;
+      }
+    }
+    else
+    {
+      if( layer == 0 )
+      {
+        m_profileList[0] = Profile::Name(extendedProfile[0]);
+      }
+
+      m_profileList[layerPTLIdx] = Profile::Name(extendedProfile[layerPTLIdx]);
+    }
+
+    if( m_profileList[layerPTLIdx] == Profile::HIGHTHROUGHPUTREXT )
+    {
+      if( m_acLayerCfg[layer].m_bitDepthConstraint == 0 ) m_acLayerCfg[layer].m_bitDepthConstraint = 16;
+      m_acLayerCfg[layer].m_chromaFormatConstraint = (tmpConstraintChromaFormat == 0) ? CHROMA_444 : numberToChromaFormat(tmpConstraintChromaFormat);
+    }
+    else if( m_profileList[layerPTLIdx] == Profile::MAINREXT )
+    {
+      if( m_acLayerCfg[layer].m_bitDepthConstraint == 0 && tmpConstraintChromaFormat == 0 )
+      {
+        // produce a valid combination, if possible.
+        const Bool bUsingGeneralRExtTools  = m_useResidualRotation                    ||
+          m_useSingleSignificanceMapContext        ||
+          m_useResidualDPCM[RDPCM_SIGNAL_IMPLICIT] ||
+          m_useResidualDPCM[RDPCM_SIGNAL_EXPLICIT] ||
+          !m_enableIntraReferenceSmoothing         ||
+          m_useGolombRiceParameterAdaptation       ||
+          m_transformSkipLog2MaxSize!=2;
+        const Bool bUsingChromaQPAdjustment= m_maxCUChromaQpAdjustmentDepth >= 0;
+        const Bool bUsingExtendedPrecision = m_acLayerCfg[layer].m_useExtendedPrecision;
+        m_acLayerCfg[layer].m_chromaFormatConstraint = NUM_CHROMA_FORMAT;
+        automaticallySelectRExtProfile(bUsingGeneralRExtTools,
+          bUsingChromaQPAdjustment,
+          bUsingExtendedPrecision,
+          m_acLayerCfg[layer].m_intraConstraintFlag,
+          m_acLayerCfg[layer].m_bitDepthConstraint,
+          m_acLayerCfg[layer].m_chromaFormatConstraint,
+          m_acLayerCfg[layer].m_chromaFormatIDC==CHROMA_400 ? m_acLayerCfg[layer].m_internalBitDepth[CHANNEL_TYPE_LUMA] : std::max(m_acLayerCfg[layer].m_internalBitDepth[CHANNEL_TYPE_LUMA], m_acLayerCfg[layer].m_internalBitDepth[CHANNEL_TYPE_CHROMA]),
+          m_acLayerCfg[layer].m_chromaFormatIDC);
+      }
+      else if( m_acLayerCfg[layer].m_bitDepthConstraint == 0 || tmpConstraintChromaFormat == 0)
+      {
+        fprintf(stderr, "Error: The bit depth and chroma format constraints must either both be specified or both be configured automatically\n");
+        exit(EXIT_FAILURE);
+      }
+      else
+      {
+        m_acLayerCfg[layer].m_chromaFormatConstraint = numberToChromaFormat(tmpConstraintChromaFormat);
+      }
+    }
+    else
+    {
+      m_acLayerCfg[layer].m_chromaFormatConstraint = (tmpConstraintChromaFormat == 0) ? m_acLayerCfg[layer].m_chromaFormatIDC : numberToChromaFormat(tmpConstraintChromaFormat);
+      m_acLayerCfg[layer].m_bitDepthConstraint = (m_profileList[layerPTLIdx] == Profile::MAIN10 || m_profileList[layerPTLIdx] == Profile::SCALABLEMAIN10) ? 10 : 8;
+    }
+  }
+#else
+  if (extendedProfile >= 1000 && extendedProfile <= 2316)
+  {
+    m_profile = Profile::MAINREXT;
+    if (m_bitDepthConstraint != 0 || tmpConstraintChromaFormat != 0)
+    {
+      fprintf(stderr, "Error: The bit depth and chroma format constraints are not used when an explicit RExt profile is specified\n");
+      exit(EXIT_FAILURE);
+    }
+    m_bitDepthConstraint     = (extendedProfile%100);
+    m_intraConstraintFlag    = (extendedProfile>=2000);
+    switch ((extendedProfile/100)%10)
+    {
+      case 0:  tmpConstraintChromaFormat=400; break;
+      case 1:  tmpConstraintChromaFormat=420; break;
+      case 2:  tmpConstraintChromaFormat=422; break;
+      default: tmpConstraintChromaFormat=444; break;
+    }
+  }
+  else
+  {
+    m_profile = Profile::Name(extendedProfile);
+  }
+
+#if SVC_EXTENSION
+  ChromaFormat m_chromaFormatIDC = m_acLayerCfg[0].m_chromaFormatIDC;
+#endif
+
+  if (m_profile == Profile::HIGHTHROUGHPUTREXT )
+  {
+    if (m_bitDepthConstraint == 0) m_bitDepthConstraint = 16;
+    m_chromaFormatConstraint = (tmpConstraintChromaFormat == 0) ? CHROMA_444 : numberToChromaFormat(tmpConstraintChromaFormat);
+  }
+  else if (m_profile == Profile::MAINREXT)
+  {
+    if (m_bitDepthConstraint == 0 && tmpConstraintChromaFormat == 0)
+    {
+#if SVC_EXTENSION
+      Bool m_useExtendedPrecision    = m_acLayerCfg[0].m_useExtendedPrecision;
+      Int  m_internalBitDepth[]      = {m_acLayerCfg[0].m_internalBitDepth[CHANNEL_TYPE_LUMA], m_acLayerCfg[0].m_internalBitDepth[CHANNEL_TYPE_CHROMA]};
+      ChromaFormat m_chromaFormatIDC = m_acLayerCfg[0].m_chromaFormatIDC;
+#endif
+      // produce a valid combination, if possible.
+      const Bool bUsingGeneralRExtTools  = m_useResidualRotation                    ||
+                                           m_useSingleSignificanceMapContext        ||
+                                           m_useResidualDPCM[RDPCM_SIGNAL_IMPLICIT] ||
+                                           m_useResidualDPCM[RDPCM_SIGNAL_EXPLICIT] ||
+                                           !m_enableIntraReferenceSmoothing         ||
+                                           m_useGolombRiceParameterAdaptation       ||
+                                           m_transformSkipLog2MaxSize!=2;
+      const Bool bUsingChromaQPAdjustment= m_maxCUChromaQpAdjustmentDepth >= 0;
+      const Bool bUsingExtendedPrecision = m_useExtendedPrecision;
+      m_chromaFormatConstraint = NUM_CHROMA_FORMAT;
+      automaticallySelectRExtProfile(bUsingGeneralRExtTools,
+                                     bUsingChromaQPAdjustment,
+                                     bUsingExtendedPrecision,
+                                     m_intraConstraintFlag,
+                                     m_bitDepthConstraint,
+                                     m_chromaFormatConstraint,
+                                     m_chromaFormatIDC==CHROMA_400 ? m_internalBitDepth[CHANNEL_TYPE_LUMA] : std::max(m_internalBitDepth[CHANNEL_TYPE_LUMA], m_internalBitDepth[CHANNEL_TYPE_CHROMA]),
+                                     m_chromaFormatIDC);
+    }
+    else if (m_bitDepthConstraint == 0 || tmpConstraintChromaFormat == 0)
+    {
+      fprintf(stderr, "Error: The bit depth and chroma format constraints must either both be specified or both be configured automatically\n");
+      exit(EXIT_FAILURE);
+    }
+    else
+    {
+      m_chromaFormatConstraint = numberToChromaFormat(tmpConstraintChromaFormat);
+    }
+  }
+  else
+  {
+    m_chromaFormatConstraint = (tmpConstraintChromaFormat == 0) ? m_chromaFormatIDC : numberToChromaFormat(tmpConstraintChromaFormat);
+    m_bitDepthConstraint = (m_profile == Profile::MAIN10?10:8);
+  }
+#endif
+
+  m_inputColourSpaceConvert = stringToInputColourSpaceConvert(inputColourSpaceConvert, true);
+
+#if SVC_EXTENSION
+  for(Int layer = 0; layer < MAX_LAYERS; layer++)
+  {
+#if !MULTIPLE_PTL_SUPPORT
+    m_acLayerCfg[layer].m_chromaFormatConstraint = m_chromaFormatConstraint;
+    m_acLayerCfg[layer].m_bitDepthConstraint = m_bitDepthConstraint;
+#endif
+
+    // If number of scaled ref. layer offsets is non-zero, at least one of the offsets should be specified
+    if(m_acLayerCfg[layer].m_numRefLayerLocationOffsets)
+    {
+#if O0098_SCALED_REF_LAYER_ID
+      assert( strcmp(cfg_refLocationOffsetLayerId[layer].c_str(),  ""));
+#endif
+#if REF_REGION_OFFSET
+      Bool srloFlag =
+        strcmp(cfg_scaledRefLayerLeftOffset   [layer].c_str(), "") ||
+        strcmp(cfg_scaledRefLayerRightOffset  [layer].c_str(), "") ||
+        strcmp(cfg_scaledRefLayerTopOffset    [layer].c_str(), "") ||
+        strcmp(cfg_scaledRefLayerBottomOffset [layer].c_str(), "");
+      Bool rroFlag =
+        strcmp(cfg_refRegionLeftOffset   [layer].c_str(), "") ||
+        strcmp(cfg_refRegionRightOffset  [layer].c_str(), "") ||
+        strcmp(cfg_refRegionTopOffset    [layer].c_str(), "") ||
+        strcmp(cfg_refRegionBottomOffset [layer].c_str(), "");
+#if R0209_GENERIC_PHASE
+      Bool phaseSetFlag =
+        strcmp(cfg_phaseHorLuma   [layer].c_str(), "") ||
+        strcmp(cfg_phaseVerLuma   [layer].c_str(), "") ||
+        strcmp(cfg_phaseHorChroma [layer].c_str(), "") ||
+        strcmp(cfg_phaseVerChroma [layer].c_str(), "");
+      assert( srloFlag || rroFlag || phaseSetFlag);
+#else
+      assert( srloFlag || rroFlag );
+#endif
+#else
+#if P0312_VERT_PHASE_ADJ
+      assert( strcmp(cfg_scaledRefLayerLeftOffset[layer].c_str(),  "") ||
+              strcmp(cfg_scaledRefLayerRightOffset[layer].c_str(), "") ||
+              strcmp(cfg_scaledRefLayerTopOffset[layer].c_str(),   "") ||
+              strcmp(cfg_scaledRefLayerBottomOffset[layer].c_str(),"") ||
+              strcmp(cfg_vertPhasePositionEnableFlag[layer].c_str(),"") ); 
+#else
+      assert( strcmp(cfg_scaledRefLayerLeftOffset[layer].c_str(),  "") ||
+              strcmp(cfg_scaledRefLayerRightOffset[layer].c_str(), "") ||
+              strcmp(cfg_scaledRefLayerTopOffset[layer].c_str(),   "") ||
+              strcmp(cfg_scaledRefLayerBottomOffset[layer].c_str(),"") ); 
+#endif
+#endif
+    }
+
+    Int *tempArray = NULL;   // Contain the value 
+
+#if O0098_SCALED_REF_LAYER_ID
+    // ID //
+    if(strcmp(cfg_refLocationOffsetLayerId[layer].c_str(),  ""))
+    {
+      cfgStringToArray( &tempArray, cfg_refLocationOffsetLayerId[layer], m_acLayerCfg[layer].m_numRefLayerLocationOffsets, "RefLocationOffsetLayerId");
+      if(tempArray)
+      {
+        for(Int i = 0; i < m_acLayerCfg[layer].m_numRefLayerLocationOffsets; i++)
+        {
+          m_acLayerCfg[layer].m_refLocationOffsetLayerId[i] = tempArray[i];
+        }
+        delete [] tempArray; tempArray = NULL;
+      }
+    }
+#endif
+
+#if REF_REGION_OFFSET
+    // Presense Flag //
+    if(strcmp(cfg_scaledRefLayerOffsetPresentFlag[layer].c_str(),  ""))
+    {
+      cfgStringToArray( &tempArray, cfg_scaledRefLayerOffsetPresentFlag[layer], m_acLayerCfg[layer].m_numRefLayerLocationOffsets, "ScaledRefLayerOffsetPresentFlag");
+      if(tempArray)
+      {
+        for(Int i = 0; i < m_acLayerCfg[layer].m_numRefLayerLocationOffsets; i++)
+        {
+          m_acLayerCfg[layer].m_scaledRefLayerOffsetPresentFlag[i] = tempArray[i];
+        }
+        delete [] tempArray; tempArray = NULL;
+      }
+    }
+#endif
+
+    // Left offset //
+    if(strcmp(cfg_scaledRefLayerLeftOffset[layer].c_str(),  ""))
+    {
+      cfgStringToArray( &tempArray, cfg_scaledRefLayerLeftOffset[layer], m_acLayerCfg[layer].m_numRefLayerLocationOffsets, "LeftOffset");
+      if(tempArray)
+      {
+        for(Int i = 0; i < m_acLayerCfg[layer].m_numRefLayerLocationOffsets; i++)
+        {
+          m_acLayerCfg[layer].m_scaledRefLayerLeftOffset[i] = tempArray[i];
+        }
+        delete [] tempArray; tempArray = NULL;
+      }
+    }
+
+    // Top offset //
+    if(strcmp(cfg_scaledRefLayerTopOffset[layer].c_str(),  ""))
+    {
+      cfgStringToArray( &tempArray, cfg_scaledRefLayerTopOffset[layer], m_acLayerCfg[layer].m_numRefLayerLocationOffsets, "TopOffset");
+      if(tempArray)
+      {
+        for(Int i = 0; i < m_acLayerCfg[layer].m_numRefLayerLocationOffsets; i++)
+        {
+          m_acLayerCfg[layer].m_scaledRefLayerTopOffset[i] = tempArray[i];
+        }
+        delete [] tempArray; tempArray = NULL;
+      }
+    }
+
+    // Right offset //
+    if(strcmp(cfg_scaledRefLayerRightOffset[layer].c_str(),  ""))
+    {
+      cfgStringToArray( &tempArray, cfg_scaledRefLayerRightOffset[layer], m_acLayerCfg[layer].m_numRefLayerLocationOffsets, "RightOffset");
+      if(tempArray)
+      {
+        for(Int i = 0; i < m_acLayerCfg[layer].m_numRefLayerLocationOffsets; i++)
+        {
+          m_acLayerCfg[layer].m_scaledRefLayerRightOffset[i] = tempArray[i];
+        }
+        delete [] tempArray; tempArray = NULL;
+      }
+    }
+
+    // Bottom offset //
+    if(strcmp(cfg_scaledRefLayerBottomOffset[layer].c_str(),  ""))
+    {
+      cfgStringToArray( &tempArray, cfg_scaledRefLayerBottomOffset[layer], m_acLayerCfg[layer].m_numRefLayerLocationOffsets, "BottomOffset");
+      if(tempArray)
+      {
+        for(Int i = 0; i < m_acLayerCfg[layer].m_numRefLayerLocationOffsets; i++)
+        {
+          m_acLayerCfg[layer].m_scaledRefLayerBottomOffset[i] = tempArray[i];
+        }
+        delete [] tempArray; tempArray = NULL;
+      }
+    }
+#if P0312_VERT_PHASE_ADJ
+   // VertPhasePositionEnableFlag //
+    if(strcmp(cfg_vertPhasePositionEnableFlag[layer].c_str(),  ""))
+    {
+      cfgStringToArray( &tempArray, cfg_vertPhasePositionEnableFlag[layer], m_acLayerCfg[layer].m_numScaledRefLayerOffsets, "VertPhasePositionEnableFlag");
+      if(tempArray)
+      {
+        for(Int i = 0; i < m_acLayerCfg[layer].m_numScaledRefLayerOffsets; i++)
+        {
+          m_acLayerCfg[layer].m_vertPhasePositionEnableFlag[i] = tempArray[i];
+        }
+        delete [] tempArray; tempArray = NULL;
+      }
+    }
+#endif
+#if REF_REGION_OFFSET
+    // Presense Flag //
+    if(strcmp(cfg_refRegionOffsetPresentFlag[layer].c_str(),  ""))
+    {
+      cfgStringToArray( &tempArray, cfg_refRegionOffsetPresentFlag[layer], m_acLayerCfg[layer].m_numRefLayerLocationOffsets, "RefRegionOffsetPresentFlag");
+      if(tempArray)
+      {
+        for(Int i = 0; i < m_acLayerCfg[layer].m_numRefLayerLocationOffsets; i++)
+        {
+          m_acLayerCfg[layer].m_refRegionOffsetPresentFlag[i] = tempArray[i];
+        }
+        delete [] tempArray; tempArray = NULL;
+      }
+    }
+
+    // Left offset //
+    if(strcmp(cfg_refRegionLeftOffset[layer].c_str(),  ""))
+    {
+      cfgStringToArray( &tempArray, cfg_refRegionLeftOffset[layer], m_acLayerCfg[layer].m_numRefLayerLocationOffsets, "RefRegionLeftOffset");
+      if(tempArray)
+      {
+        for(Int i = 0; i < m_acLayerCfg[layer].m_numRefLayerLocationOffsets; i++)
+        {
+          m_acLayerCfg[layer].m_refRegionLeftOffset[i] = tempArray[i];
+        }
+        delete [] tempArray; tempArray = NULL;
+      }
+    }
+
+    // Top offset //
+    if(strcmp(cfg_refRegionTopOffset[layer].c_str(),  ""))
+    {
+      cfgStringToArray( &tempArray, cfg_refRegionTopOffset[layer], m_acLayerCfg[layer].m_numRefLayerLocationOffsets, "RefRegionTopOffset");
+      if(tempArray)
+      {
+        for(Int i = 0; i < m_acLayerCfg[layer].m_numRefLayerLocationOffsets; i++)
+        {
+          m_acLayerCfg[layer].m_refRegionTopOffset[i] = tempArray[i];
+        }
+        delete [] tempArray; tempArray = NULL;
+      }
+    }
+
+    // Right offset //
+    if(strcmp(cfg_refRegionRightOffset[layer].c_str(),  ""))
+    {
+      cfgStringToArray( &tempArray, cfg_refRegionRightOffset[layer], m_acLayerCfg[layer].m_numRefLayerLocationOffsets, "RefRegionRightOffset");
+      if(tempArray)
+      {
+        for(Int i = 0; i < m_acLayerCfg[layer].m_numRefLayerLocationOffsets; i++)
+        {
+          m_acLayerCfg[layer].m_refRegionRightOffset[i] = tempArray[i];
+        }
+        delete [] tempArray; tempArray = NULL;
+      }
+    }
+
+    // Bottom offset //
+    if(strcmp(cfg_refRegionBottomOffset[layer].c_str(),  ""))
+    {
+      cfgStringToArray( &tempArray, cfg_refRegionBottomOffset[layer], m_acLayerCfg[layer].m_numRefLayerLocationOffsets, "RefRegionBottomOffset");
+      if(tempArray)
+      {
+        for(Int i = 0; i < m_acLayerCfg[layer].m_numRefLayerLocationOffsets; i++)
+        {
+          m_acLayerCfg[layer].m_refRegionBottomOffset[i] = tempArray[i];
+        }
+        delete [] tempArray; tempArray = NULL;
+      }
+    }
+#endif
+#if R0209_GENERIC_PHASE
+    Int numPhaseSet = m_acLayerCfg[layer].m_numRefLayerLocationOffsets;
+
+    // Presense Flag //
+    if(strcmp(cfg_resamplePhaseSetPresentFlag[layer].c_str(),  ""))
+    {
+      cfgStringToArray( &tempArray, cfg_resamplePhaseSetPresentFlag[layer], numPhaseSet, "resamplePhaseSetPresentFlag");
+      if(tempArray)
+      {
+        for(Int i = 0; i < numPhaseSet; i++)
+        {
+          m_acLayerCfg[layer].m_resamplePhaseSetPresentFlag[i] = tempArray[i];
+        }
+        delete [] tempArray; tempArray = NULL;
+      }
+    }
+
+    // Luma horizontal phase //
+    if(strcmp(cfg_phaseHorLuma[layer].c_str(),  ""))
+    {
+      cfgStringToArray( &tempArray, cfg_phaseHorLuma[layer], numPhaseSet, "phaseHorLuma");
+      if(tempArray)
+      {
+        for(Int i = 0; i < numPhaseSet; i++)
+        {
+          m_acLayerCfg[layer].m_phaseHorLuma[i] = tempArray[i];
+        }
+        delete [] tempArray; tempArray = NULL;
+      }
+    }
+
+    // Luma vertical phase //
+    if(strcmp(cfg_phaseVerLuma[layer].c_str(),  ""))
+    {
+      cfgStringToArray( &tempArray, cfg_phaseVerLuma[layer], numPhaseSet, "phaseVerLuma");
+      if(tempArray)
+      {
+        for(Int i = 0; i < numPhaseSet; i++)
+        {
+          m_acLayerCfg[layer].m_phaseVerLuma[i] = tempArray[i];
+        }
+        delete [] tempArray; tempArray = NULL;
+      }
+    }
+
+    // Chroma horizontal phase //
+    if(strcmp(cfg_phaseHorChroma[layer].c_str(),  ""))
+    {
+      cfgStringToArray( &tempArray, cfg_phaseHorChroma[layer], numPhaseSet, "phaseHorChroma");
+      if(tempArray)
+      {
+        for(Int i = 0; i < numPhaseSet; i++)
+        {
+          m_acLayerCfg[layer].m_phaseHorChroma[i] = tempArray[i];
+        }
+        delete [] tempArray; tempArray = NULL;
+      }
+    }
+
+    // Chroma vertical phase //
+    if(strcmp(cfg_phaseVerChroma[layer].c_str(),  ""))
+    {
+      cfgStringToArray( &tempArray, cfg_phaseVerChroma[layer], numPhaseSet, "phaseVerChroma");
+      if(tempArray)
+      {
+        for(Int i = 0; i < numPhaseSet; i++)
+        {
+          m_acLayerCfg[layer].m_phaseVerChroma[i] = tempArray[i];
+        }
+        delete [] tempArray; tempArray = NULL;
+      }
+    }
+#endif
+  }
+
+#if VPS_EXTN_DIRECT_REF_LAYERS
+  for(Int layer = 0; layer < MAX_LAYERS; layer++)
+  {
+    Char* pSamplePredRefLayerIds = cfg_samplePredRefLayerIds[layer].empty() ? NULL: strdup(cfg_samplePredRefLayerIds[layer].c_str());
+    if( m_acLayerCfg[layer].m_numSamplePredRefLayers > 0 )
+    {
+      char *samplePredRefLayerId;
+      int  i=0;
+      m_acLayerCfg[layer].m_samplePredRefLayerIds = new Int[m_acLayerCfg[layer].m_numSamplePredRefLayers];
+      samplePredRefLayerId = strtok(pSamplePredRefLayerIds, " ,-");
+      while(samplePredRefLayerId != NULL)
+      {
+        if( i >= m_acLayerCfg[layer].m_numSamplePredRefLayers )
+        {
+          printf( "NumSamplePredRefLayers%d: The number of columns whose width are defined is larger than the allowed number of columns.\n", layer );
+          exit( EXIT_FAILURE );
+        }
+        *( m_acLayerCfg[layer].m_samplePredRefLayerIds + i ) = atoi( samplePredRefLayerId );
+        samplePredRefLayerId = strtok(NULL, " ,-");
+        i++;
+      }
+      if( i < m_acLayerCfg[layer].m_numSamplePredRefLayers )
+      {
+        printf( "NumSamplePredRefLayers%d: The width of some columns is not defined.\n", layer );
+        exit( EXIT_FAILURE );
+      }
+    }
+    else
+    {
+      m_acLayerCfg[layer].m_samplePredRefLayerIds = NULL;
+    }
+
+    if( pSamplePredRefLayerIds )
+    {
+      free( pSamplePredRefLayerIds );
+      pSamplePredRefLayerIds = NULL;
+    }
+  }
+  for(Int layer = 0; layer < MAX_LAYERS; layer++)
+  {
+    Char* pMotionPredRefLayerIds = cfg_motionPredRefLayerIds[layer].empty() ? NULL: strdup(cfg_motionPredRefLayerIds[layer].c_str());
+    if( m_acLayerCfg[layer].m_numMotionPredRefLayers > 0 )
+    {
+      char *motionPredRefLayerId;
+      int  i=0;
+      m_acLayerCfg[layer].m_motionPredRefLayerIds = new Int[m_acLayerCfg[layer].m_numMotionPredRefLayers];
+      motionPredRefLayerId = strtok(pMotionPredRefLayerIds, " ,-");
+      while(motionPredRefLayerId != NULL)
+      {
+        if( i >= m_acLayerCfg[layer].m_numMotionPredRefLayers )
+        {
+          printf( "NumMotionPredRefLayers%d: The number of columns whose width are defined is larger than the allowed number of columns.\n", layer );
+          exit( EXIT_FAILURE );
+        }
+        *( m_acLayerCfg[layer].m_motionPredRefLayerIds + i ) = atoi( motionPredRefLayerId );
+        motionPredRefLayerId = strtok(NULL, " ,-");
+        i++;
+      }
+      if( i < m_acLayerCfg[layer].m_numMotionPredRefLayers )
+      {
+        printf( "NumMotionPredRefLayers%d: The width of some columns is not defined.\n", layer );
+        exit( EXIT_FAILURE );
+      }
+    }
+    else
+    {
+      m_acLayerCfg[layer].m_motionPredRefLayerIds = NULL;
+    }
+
+    if( pMotionPredRefLayerIds )
+    {
+      free( pMotionPredRefLayerIds );
+      pMotionPredRefLayerIds = NULL;
+    }
+  }
+
+  for(Int layer = 0; layer < MAX_LAYERS; layer++)
+  {
+    Char* pPredLayerIds = cfg_predLayerIds[layer].empty() ? NULL: strdup(cfg_predLayerIds[layer].c_str());
+    if( m_acLayerCfg[layer].m_numActiveRefLayers > 0 )
+    {
+      char *refLayerId;
+      int  i=0;
+      m_acLayerCfg[layer].m_predLayerIds = new Int[m_acLayerCfg[layer].m_numActiveRefLayers];
+      refLayerId = strtok(pPredLayerIds, " ,-");
+      while(refLayerId != NULL)
+      {
+        if( i >= m_acLayerCfg[layer].m_numActiveRefLayers )
+        {
+          printf( "NumActiveRefLayers%d: The number of columns whose width are defined is larger than the allowed number of columns.\n", layer );
+          exit( EXIT_FAILURE );
+        }
+        *( m_acLayerCfg[layer].m_predLayerIds + i ) = atoi( refLayerId );
+        refLayerId = strtok(NULL, " ,-");
+        i++;
+      }
+      if( i < m_acLayerCfg[layer].m_numActiveRefLayers )
+      {
+        printf( "NumActiveRefLayers%d: The width of some columns is not defined.\n", layer );
+        exit( EXIT_FAILURE );
+      }
+    }
+    else
+    {
+      m_acLayerCfg[layer].m_predLayerIds = NULL;
+    }
+
+    if( pPredLayerIds )
+    {
+      free( pPredLayerIds );
+      pPredLayerIds = NULL;
+    }
+  }
+#endif
+#if Q0078_ADD_LAYER_SETS
+#if OUTPUT_LAYER_SETS_CONFIG
+  for (Int layerSet = 1; layerSet < m_numLayerSets; layerSet++)
+  {
+    // Simplifying the code in the #else section, and allowing 0-th layer set t
+    assert( scanStringToArray( cfg_layerSetLayerIdList[layerSet], m_numLayerInIdList[layerSet], "NumLayerInIdList", m_layerSetLayerIdList[layerSet] ) );
+#else
+  for (Int layerSet = 0; layerSet < m_numLayerSets; layerSet++)
+  {
+    if (m_numLayerInIdList[layerSet] > 0)
+    {
+      Char* layerSetLayerIdListDup = cfg_layerSetLayerIdList[layerSet].empty() ? NULL : strdup(cfg_layerSetLayerIdList[layerSet].c_str());
+      Int  i = 0;
+      char *layerId = strtok(layerSetLayerIdListDup, " ,-");
+      while (layerId != NULL)
+      {
+        if (i >= m_numLayerInIdList[layerSet])
+        {
+          printf("NumLayerInIdList%d: The number of layers in the set is larger than the allowed number of layers.\n", layerSet);
+          exit(EXIT_FAILURE);
+        }
+        m_layerSetLayerIdList[layerSet][i] = atoi(layerId);
+        layerId = strtok(NULL, " ,-");
+        i++;
+      }
+
+      if( layerSetLayerIdListDup )
+      {
+        free( layerSetLayerIdListDup );
+        layerSetLayerIdListDup = NULL;
+      }
+    }
+#endif
+  }
+  for (Int addLayerSet = 0; addLayerSet < m_numAddLayerSets; addLayerSet++)
+  {
+#if OUTPUT_LAYER_SETS_CONFIG
+    // Simplifying the code in the #else section
+#if FIX_LAYER_ID_INIT
+    assert( scanStringToArray( cfg_highestLayerIdx[addLayerSet], m_numHighestLayerIdx[addLayerSet], "HighestLayerIdx", m_highestLayerIdx[addLayerSet] ) );
+#else
+    assert( scanStringToArray( cfg_layerSetLayerIdList[addLayerSet], m_numLayerInIdList[addLayerSet], "NumLayerInIdList",  m_highestLayerIdx[addLayerSet] ) );
+#endif
+#else
+    if (m_numHighestLayerIdx[addLayerSet] > 0)
+    {
+      Char* highestLayrIdxListDup = cfg_highestLayerIdx[addLayerSet].empty() ? NULL : strdup(cfg_highestLayerIdx[addLayerSet].c_str());
+      Int  i = 0;
+      char *layerIdx = strtok(highestLayrIdxListDup, " ,-");
+      while (layerIdx != NULL)
+      {
+        if (i >= m_numLayerInIdList[addLayerSet])
+        {
+          printf("NumLayerInIdList%d: The number of layer idx's in the highest layer idx list is larger than the allowed number of idx's.\n", addLayerSet);
+          exit(EXIT_FAILURE);
+        }
+        m_highestLayerIdx[addLayerSet][i] = atoi(layerIdx);
+        layerIdx = strtok(NULL, " ,-");
+        i++;
+      }
+
+      if( highestLayrIdxListDup )
+      {
+        free( highestLayrIdxListDup );
+        highestLayrIdxListDup = NULL;
+      }
+    }
+#endif
+  }
+#endif
+#if OUTPUT_LAYER_SETS_CONFIG
+  if( m_defaultTargetOutputLayerIdc != -1 )
+  {
+    assert( m_defaultTargetOutputLayerIdc >= 0 && m_defaultTargetOutputLayerIdc <= 3 );
+  }
+  assert( m_numOutputLayerSets != 0 );
+  assert( m_numOutputLayerSets >= m_numLayerSets + m_numAddLayerSets ); // Number of output layer sets must be at least as many as layer sets.
+
+  // If output layer Set Idx is specified, only specify it for the non-default output layer sets
+  Int numNonDefaultOls = m_numOutputLayerSets - (m_numLayerSets + m_numAddLayerSets);
+  if( numNonDefaultOls )
+  {
+    assert( scanStringToArray( *cfg_outputLayerSetIdx, numNonDefaultOls, "OutputLayerSetIdx", m_outputLayerSetIdx ) ); 
+    for(Int i = 0; i < numNonDefaultOls; i++)
+    {
+      assert( m_outputLayerSetIdx[i] >= 0 && m_outputLayerSetIdx[i] < (m_numLayerSets + m_numAddLayerSets) );
+    }
+  }
+
+  // Number of output layers in output layer sets
+  scanStringToArray( *cfg_numOutputLayersInOutputLayerSet, m_numOutputLayerSets - 1, "NumOutputLayersInOutputLayerSets", m_numOutputLayersInOutputLayerSet );
+  m_numOutputLayersInOutputLayerSet.insert(m_numOutputLayersInOutputLayerSet.begin(), 1);
+  // Layers in the output layer set
+  m_listOfOutputLayers.resize(m_numOutputLayerSets);
+
+#if MULTIPLE_PTL_SUPPORT
+  m_listOfLayerPTLofOlss.resize(m_numOutputLayerSets);
+#endif
+
+  Int startOlsCtr = 1;
+  if( m_defaultTargetOutputLayerIdc == 0 || m_defaultTargetOutputLayerIdc == 1 )
+  {
+    // Default output layer sets defined
+    startOlsCtr = m_numLayerSets;
+  }
+  for( Int olsCtr = 1; olsCtr < m_numOutputLayerSets; olsCtr++ )
+  {
+    if( olsCtr < startOlsCtr )
+    {
+      if(scanStringToArray( cfg_listOfOutputLayers[olsCtr], m_numOutputLayersInOutputLayerSet[olsCtr], "ListOfOutputLayers", m_listOfOutputLayers[olsCtr] ) )
+      {
+        std::cout << "Default OLS defined. Ignoring ListOfOutputLayers" << olsCtr << endl;
+      }
+    }
+    else
+    {
+      assert( scanStringToArray( cfg_listOfOutputLayers[olsCtr], m_numOutputLayersInOutputLayerSet[olsCtr], "ListOfOutputLayers", m_listOfOutputLayers[olsCtr] ) );
+    }
+#if MULTIPLE_PTL_SUPPORT
+    Int olsToLsIndex = (olsCtr >= (m_numLayerSets + m_numAddLayerSets)) ? m_outputLayerSetIdx[olsCtr - (m_numLayerSets + m_numAddLayerSets)] : olsCtr;
+#if R0235_SMALLEST_LAYER_ID
+    // This is a fix to allow setting of PTL for additional layer sets
+    if (olsCtr >= m_numLayerSets && olsCtr < (m_numLayerSets + m_numAddLayerSets))
+    {
+      scanStringToArrayNumEntries(cfg_listOfLayerPTLOfOlss[olsCtr], m_numLayerInIdList[olsToLsIndex], "List of PTL for each layers in OLS", m_listOfLayerPTLofOlss[olsCtr]);
+    }
+    else
+    {
+      scanStringToArray(cfg_listOfLayerPTLOfOlss[olsCtr], m_numLayerInIdList[olsToLsIndex], "List of PTL for each layers in OLS", m_listOfLayerPTLofOlss[olsCtr]);
+    }
+#else
+    scanStringToArray( cfg_listOfLayerPTLOfOlss[olsCtr], m_numLayerInIdList[olsToLsIndex], "List of PTL for each layers in OLS", m_listOfLayerPTLofOlss[olsCtr] );
+#endif
+    //For conformance checking
+    //Conformance of a layer in an output operation point associated with an OLS in a bitstream to the Scalable Main profile is indicated as follows:
+    //If OpTid of the output operation point is equal to vps_max_sub_layer_minus1, the conformance is indicated by general_profile_idc being equal to 7 or general_profile_compatibility_flag[ 7 ] being equal to 1
+    //Conformance of a layer in an output operation point associated with an OLS in a bitstream to the Scalable Main 10 profile is indicated as follows:
+    //If OpTid of the output operation point is equal to vps_max_sub_layer_minus1, the conformance is indicated by general_profile_idc being equal to 7 or general_profile_compatibility_flag[ 7 ] being equal to 1
+    //The following assert may be updated / upgraded to take care of general_profile_compatibility_flag.
+#if R0235_SMALLEST_LAYER_ID
+    if (m_numAddLayerSets == 0)
+    {
+#endif
+    for ( Int ii = 1; ii < m_numLayerInIdList[olsToLsIndex]; ii++)
+    {
+      if (m_layerSetLayerIdList[olsToLsIndex][ii - 1] != 0 && m_layerSetLayerIdList[olsToLsIndex][ii] != 0)  //Profile / profile compatibility of enhancement layers must indicate the same profile.
+      {
+        assert( (m_profileList[m_listOfLayerPTLofOlss[olsCtr][ii]] == m_profileList[m_listOfLayerPTLofOlss[olsCtr][ii - 1]]) ||
+                (m_profileList[m_listOfLayerPTLofOlss[olsCtr][ii]] == m_profileCompatibility[m_listOfLayerPTLofOlss[olsCtr][ii - 1]]) ||   
+                (m_profileCompatibility[m_listOfLayerPTLofOlss[olsCtr][ii]] == m_profileList[m_listOfLayerPTLofOlss[olsCtr][ii - 1]]) );
+      }
+    }
+#if R0235_SMALLEST_LAYER_ID
+    }
+#endif
+#endif
+  }
+#if MULTIPLE_PTL_SUPPORT
+  m_listOfLayerPTLofOlss[0].push_back(*cfg_layerPTLIdx[0]);
+  delete [] cfg_listOfLayerPTLOfOlss;
+#endif
+  delete cfg_numOutputLayersInOutputLayerSet;
+  delete [] cfg_listOfOutputLayers;
+  delete cfg_outputLayerSetIdx;
+#endif
+#else //SVC_EXTENSION
+  switch (m_conformanceWindowMode)
+  {
+  case 0:
+    {
+      // no conformance or padding
+      m_confWinLeft = m_confWinRight = m_confWinTop = m_confWinBottom = 0;
+      m_aiPad[1] = m_aiPad[0] = 0;
+      break;
+    }
+  case 1:
+    {
+      // automatic padding to minimum CU size
+      Int minCuSize = m_uiMaxCUHeight >> (m_uiMaxCUDepth - 1);
+      if (m_iSourceWidth % minCuSize)
+      {
+        m_aiPad[0] = m_confWinRight  = ((m_iSourceWidth / minCuSize) + 1) * minCuSize - m_iSourceWidth;
+        m_iSourceWidth  += m_confWinRight;
+      }
+      if (m_iSourceHeight % minCuSize)
+      {
+        m_aiPad[1] = m_confWinBottom = ((m_iSourceHeight / minCuSize) + 1) * minCuSize - m_iSourceHeight;
+        m_iSourceHeight += m_confWinBottom;
+        if ( m_isField )
+        {
+          m_iSourceHeightOrg += m_confWinBottom << 1;
+          m_aiPad[1] = m_confWinBottom << 1;
+        }
+      }
+      if (m_aiPad[0] % TComSPS::getWinUnitX(m_chromaFormatIDC) != 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(m_chromaFormatIDC) != 0)
+      {
+        fprintf(stderr, "Error: picture height is not an integer multiple of the specified chroma subsampling\n");
+        exit(EXIT_FAILURE);
+      }
+      break;
+    }
+  case 2:
+    {
+      //padding
+      m_iSourceWidth  += m_aiPad[0];
+      m_iSourceHeight += m_aiPad[1];
+      m_confWinRight  = m_aiPad[0];
+      m_confWinBottom = m_aiPad[1];
+      break;
+    }
+  case 3:
+    {
+      // conformance
+      if ((m_confWinLeft == 0) && (m_confWinRight == 0) && (m_confWinTop == 0) && (m_confWinBottom == 0))
+      {
+        fprintf(stderr, "Warning: Conformance window enabled, but all conformance window parameters set to zero\n");
+      }
+      if ((m_aiPad[1] != 0) || (m_aiPad[0]!=0))
+      {
+        fprintf(stderr, "Warning: Conformance window enabled, padding parameters will be ignored\n");
+      }
+      m_aiPad[1] = m_aiPad[0] = 0;
+      break;
+    }
+  }
+
+  // allocate slice-based dQP values
+  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;
+    }
+  }
+
+  for(UInt ch=0; ch<MAX_NUM_CHANNEL_TYPE; ch++)
+  {
+    if (saoOffsetBitShift[ch]<0)
+    {
+      if (m_internalBitDepth[ch]>10)
+      {
+        m_saoOffsetBitShift[ch]=UInt(Clip3<Int>(0, m_internalBitDepth[ch]-10, Int(m_internalBitDepth[ch]-10 + 0.165*m_iQP - 3.22 + 0.5) ) );
+      }
+      else
+      {
+        m_saoOffsetBitShift[ch]=0;
+      }
+    }
+    else
+    {
+      m_saoOffsetBitShift[ch]=UInt(saoOffsetBitShift[ch]);
+    }
+  }
+
+  // reading external dQP description from file
+  if ( m_pchdQPFile )
+  {
+    FILE* fpt=fopen( m_pchdQPFile, "r" );
+    if ( fpt )
+    {
+      Int iValue;
+      Int iPOC = 0;
+      while ( iPOC < m_framesToBeEncoded )
+      {
+        if ( fscanf(fpt, "%d", &iValue ) == EOF ) break;
+        m_aidQP[ iPOC ] = iValue;
+        iPOC++;
+      }
+      fclose(fpt);
+    }
+  }
+  m_iWaveFrontSubstreams = m_iWaveFrontSynchro ? (m_iSourceHeight + m_uiMaxCUHeight - 1) / m_uiMaxCUHeight : 1;
+#endif
+  if( m_masteringDisplay.colourVolumeSEIEnabled )
+  {
+    for(UInt idx=0; idx<6; idx++)
+    {
+      m_masteringDisplay.primaries[idx/2][idx%2] = UShort((cfg_DisplayPrimariesCode.values.size() > idx) ? cfg_DisplayPrimariesCode.values[idx] : 0);
+    }
+    for(UInt idx=0; idx<2; idx++)
+    {
+      m_masteringDisplay.whitePoint[idx] = UShort((cfg_DisplayWhitePointCode.values.size() > idx) ? cfg_DisplayWhitePointCode.values[idx] : 0);
+    }
+  }
+    
+  if( m_toneMappingInfoSEIEnabled && !m_toneMapCancelFlag )
+  {
+    if( m_toneMapModelId == 2 && !cfg_startOfCodedInterval.values.empty() )
+    {
+      const UInt num = 1u<< m_toneMapTargetBitDepth;
+      m_startOfCodedInterval = new Int[num];
+      for(UInt i=0; i<num; i++)
+      {
+        m_startOfCodedInterval[i] = cfg_startOfCodedInterval.values.size() > i ? cfg_startOfCodedInterval.values[i] : 0;
+      }
+    }
+    else
+    {
+      m_startOfCodedInterval = NULL;
+    }
+    if( ( m_toneMapModelId == 3 ) && ( m_numPivots > 0 ) )
+    {
+      if( !cfg_codedPivotValue.values.empty() && !cfg_targetPivotValue.values.empty() )
+      {
+        m_codedPivotValue  = new Int[m_numPivots];
+        m_targetPivotValue = new Int[m_numPivots];
+        for(UInt i=0; i<m_numPivots; i++)
+        {
+          m_codedPivotValue[i]  = cfg_codedPivotValue.values.size()  > i ? cfg_codedPivotValue.values [i] : 0;
+          m_targetPivotValue[i] = cfg_targetPivotValue.values.size() > i ? cfg_targetPivotValue.values[i] : 0;
+        }
+      }
+    }
+    else
+    {
+      m_codedPivotValue = NULL;
+      m_targetPivotValue = NULL;
+    }
+  }
+
+  if( m_kneeSEIEnabled && !m_kneeSEICancelFlag )
+  {
+    assert ( m_kneeSEINumKneePointsMinus1 >= 0 && m_kneeSEINumKneePointsMinus1 < 999 );
+    m_kneeSEIInputKneePoint  = new Int[m_kneeSEINumKneePointsMinus1+1];
+    m_kneeSEIOutputKneePoint = new Int[m_kneeSEINumKneePointsMinus1+1];
+    for(Int i=0; i<(m_kneeSEINumKneePointsMinus1+1); i++)
+    {
+      m_kneeSEIInputKneePoint[i]  = cfg_kneeSEIInputKneePointValue.values.size()  > i ? cfg_kneeSEIInputKneePointValue.values[i]  : 1;
+      m_kneeSEIOutputKneePoint[i] = cfg_kneeSEIOutputKneePointValue.values.size() > i ? cfg_kneeSEIOutputKneePointValue.values[i] : 0;
+    }
+  }
+
+  if(m_timeCodeSEIEnabled)
+  {
+    for(Int i = 0; i < m_timeCodeSEINumTs && i < MAX_TIMECODE_SEI_SETS; i++)
+    {
+      m_timeSetArray[i].clockTimeStampFlag    = cfg_timeCodeSeiTimeStampFlag        .values.size()>i ? cfg_timeCodeSeiTimeStampFlag        .values [i] : false;
+      m_timeSetArray[i].numUnitFieldBasedFlag = cfg_timeCodeSeiNumUnitFieldBasedFlag.values.size()>i ? cfg_timeCodeSeiNumUnitFieldBasedFlag.values [i] : 0;
+      m_timeSetArray[i].countingType          = cfg_timeCodeSeiCountingType         .values.size()>i ? cfg_timeCodeSeiCountingType         .values [i] : 0;
+      m_timeSetArray[i].fullTimeStampFlag     = cfg_timeCodeSeiFullTimeStampFlag    .values.size()>i ? cfg_timeCodeSeiFullTimeStampFlag    .values [i] : 0;
+      m_timeSetArray[i].discontinuityFlag     = cfg_timeCodeSeiDiscontinuityFlag    .values.size()>i ? cfg_timeCodeSeiDiscontinuityFlag    .values [i] : 0;
+      m_timeSetArray[i].cntDroppedFlag        = cfg_timeCodeSeiCntDroppedFlag       .values.size()>i ? cfg_timeCodeSeiCntDroppedFlag       .values [i] : 0;
+      m_timeSetArray[i].numberOfFrames        = cfg_timeCodeSeiNumberOfFrames       .values.size()>i ? cfg_timeCodeSeiNumberOfFrames       .values [i] : 0;
+      m_timeSetArray[i].secondsValue          = cfg_timeCodeSeiSecondsValue         .values.size()>i ? cfg_timeCodeSeiSecondsValue         .values [i] : 0;
+      m_timeSetArray[i].minutesValue          = cfg_timeCodeSeiMinutesValue         .values.size()>i ? cfg_timeCodeSeiMinutesValue         .values [i] : 0;
+      m_timeSetArray[i].hoursValue            = cfg_timeCodeSeiHoursValue           .values.size()>i ? cfg_timeCodeSeiHoursValue           .values [i] : 0;
+      m_timeSetArray[i].secondsFlag           = cfg_timeCodeSeiSecondsFlag          .values.size()>i ? cfg_timeCodeSeiSecondsFlag          .values [i] : 0;
+      m_timeSetArray[i].minutesFlag           = cfg_timeCodeSeiMinutesFlag          .values.size()>i ? cfg_timeCodeSeiMinutesFlag          .values [i] : 0;
+      m_timeSetArray[i].hoursFlag             = cfg_timeCodeSeiHoursFlag            .values.size()>i ? cfg_timeCodeSeiHoursFlag            .values [i] : 0;
+      m_timeSetArray[i].timeOffsetLength      = cfg_timeCodeSeiTimeOffsetLength     .values.size()>i ? cfg_timeCodeSeiTimeOffsetLength     .values [i] : 0;
+      m_timeSetArray[i].timeOffsetValue       = cfg_timeCodeSeiTimeOffsetValue      .values.size()>i ? cfg_timeCodeSeiTimeOffsetValue      .values [i] : 0;
+    }
+  }
+#if Q0096_OVERLAY_SEI
+  if( m_overlaySEIEnabled && !m_overlayInfoCancelFlag )
+  {
+    m_overlayIdx.resize                 ( m_numOverlaysMinus1+1 );  
+    m_overlayLanguagePresentFlag.resize ( m_numOverlaysMinus1+1 );
+    m_overlayContentLayerId.resize      ( m_numOverlaysMinus1+1 );
+    m_overlayLabelPresentFlag.resize    ( m_numOverlaysMinus1+1 );
+    m_overlayLabelLayerId.resize        ( m_numOverlaysMinus1+1 );
+    m_overlayAlphaPresentFlag.resize    ( m_numOverlaysMinus1+1 );
+    m_overlayAlphaLayerId.resize        ( m_numOverlaysMinus1+1 );
+    m_numOverlayElementsMinus1.resize   ( m_numOverlaysMinus1+1 );
+    m_overlayElementLabelMin.resize     ( m_numOverlaysMinus1+1 );
+    m_overlayElementLabelMax.resize     ( m_numOverlaysMinus1+1 );  
+    m_overlayLanguage.resize            ( m_numOverlaysMinus1+1 );     
+    m_overlayName.resize                ( m_numOverlaysMinus1+1 );     
+    m_overlayElementName.resize         ( m_numOverlaysMinus1+1 );     
+    for (Int i=0 ; i<=m_numOverlaysMinus1 ; i++)
+    {
+      m_overlayIdx[i]                  = cfg_overlaySEIIdx[i];
+      m_overlayLanguagePresentFlag[i]  = cfg_overlaySEILanguagePresentFlag[i];
+      m_overlayContentLayerId[i]       = cfg_overlaySEIContentLayerId[i];
+      m_overlayLabelPresentFlag[i]     = cfg_overlaySEILabelPresentFlag[i];
+      m_overlayLabelLayerId[i]         = cfg_overlaySEILabelLayerId[i];
+      m_overlayAlphaPresentFlag[i]     = cfg_overlaySEIAlphaPresentFlag[i];
+      m_overlayAlphaLayerId[i]         = cfg_overlaySEIAlphaLayerId[i];
+      m_numOverlayElementsMinus1[i]    = cfg_overlaySEINumElementsMinus1[i];
+      m_overlayLanguage[i]             = cfg_overlaySEILanguage[i];
+      m_overlayName[i]                 = cfg_overlaySEIName[i];
+      
+      //parse min and max values of label elements
+      istringstream ranges(cfg_overlaySEIElementLabelRanges[i]);
+      string range;          
+      UInt val;        
+      vector<UInt> vRanges;
+      while ( getline(ranges, range, ' ') ) 
+      {        
+        istringstream(range) >> val;        
+        vRanges.push_back(val);
+      }      
+      assert( vRanges.size()%2==0 );
+      assert( vRanges.size()==2*(m_numOverlayElementsMinus1[i]+1) );
+      m_overlayElementLabelMin[i].resize( m_numOverlayElementsMinus1[i]+1 );
+      m_overlayElementLabelMax[i].resize( m_numOverlayElementsMinus1[i]+1 );
+      for (Int j=0 ; j<=m_numOverlayElementsMinus1[i] ; j++)
+      {
+        m_overlayElementLabelMin[i][j] = vRanges[2*j];
+        m_overlayElementLabelMax[i][j] = vRanges[2*j+1];
+      }
+      
+      //parse overlay element names
+      istringstream elementNames(cfg_overlaySEIElementNames[i]);
+      string elementName;                
+      vector<string> vElementName;                
+      while ( getline(elementNames, elementName, '|') ) 
+      {        
+        vElementName.push_back(elementName);         
+      }      
+      if ( m_overlayLabelPresentFlag[i] )
+      {
+        m_overlayElementName[i].resize( m_numOverlayElementsMinus1[i]+1 );     
+        for (Int j=0 ; j<=m_numOverlayElementsMinus1[i] ; j++)
+        {
+          if (j < vElementName.size())
+          {
+            m_overlayElementName[i][j] = vElementName[j];
+          }
+          else
+          {
+            m_overlayElementName[i][j] = string("NoElementName");
+          }
+        }
+      }            
+    }        
+  }
+#endif
+#if Q0074_COLOUR_REMAPPING_SEI
+#if !SVC_EXTENSION
+  // reading external Colour Remapping Information SEI message parameters from file
+  if( m_colourRemapSEIFile )
+  {
+    FILE* fic;
+    Int retval;
+    if((fic = fopen(m_colourRemapSEIFile,"r")) == (FILE*)NULL)
+    {
+      fprintf(stderr, "Can't open Colour Remapping Information SEI parameters file %s\n", m_colourRemapSEIFile);
+      exit(EXIT_FAILURE);
+    }
+
+    retval = fscanf( fic, "%d", &m_colourRemapSEIId );
+    retval = fscanf( fic, "%d", &m_colourRemapSEICancelFlag );
+    if( !m_colourRemapSEICancelFlag )
+    {
+      retval = fscanf( fic, "%d", &m_colourRemapSEIPersistenceFlag );
+      retval = fscanf( fic, "%d", &m_colourRemapSEIVideoSignalInfoPresentFlag);
+      if( m_colourRemapSEIVideoSignalInfoPresentFlag )
+      {
+        retval = fscanf( fic, "%d", &m_colourRemapSEIFullRangeFlag  );
+        retval = fscanf( fic, "%d", &m_colourRemapSEIPrimaries );
+        retval = fscanf( fic, "%d", &m_colourRemapSEITransferFunction );
+        retval = fscanf( fic, "%d", &m_colourRemapSEIMatrixCoefficients );
+      }
+
+      retval = fscanf( fic, "%d", &m_colourRemapSEIInputBitDepth );
+      retval = fscanf( fic, "%d", &m_colourRemapSEIBitDepth );
+  
+      for( Int c=0 ; c<3 ; c++ )
+      {
+        retval = fscanf( fic, "%d", &m_colourRemapSEIPreLutNumValMinus1[c] );
+        if( m_colourRemapSEIPreLutNumValMinus1[c]>0 )
+        {
+          m_colourRemapSEIPreLutCodedValue[c]  = new Int[m_colourRemapSEIPreLutNumValMinus1[c]+1];
+          m_colourRemapSEIPreLutTargetValue[c] = new Int[m_colourRemapSEIPreLutNumValMinus1[c]+1];
+          for( Int i=0 ; i<=m_colourRemapSEIPreLutNumValMinus1[c] ; i++ )
+          {
+            retval = fscanf( fic, "%d", &m_colourRemapSEIPreLutCodedValue[c][i] );
+            retval = fscanf( fic, "%d", &m_colourRemapSEIPreLutTargetValue[c][i] );
+          }
+        }
+      }
+
+      retval = fscanf( fic, "%d", &m_colourRemapSEIMatrixPresentFlag );
+      if( m_colourRemapSEIMatrixPresentFlag )
+      {
+        retval = fscanf( fic, "%d", &m_colourRemapSEILog2MatrixDenom );
+        for( Int c=0 ; c<3 ; c++ )
+          for( Int i=0 ; i<3 ; i++ )
+            retval = fscanf( fic, "%d", &m_colourRemapSEICoeffs[c][i] );
+      }
+
+      for( Int c=0 ; c<3 ; c++ )
+      {
+        retval = fscanf( fic, "%d", &m_colourRemapSEIPostLutNumValMinus1[c] );
+        if( m_colourRemapSEIPostLutNumValMinus1[c]>0 )
+        {
+          m_colourRemapSEIPostLutCodedValue[c]  = new Int[m_colourRemapSEIPostLutNumValMinus1[c]+1];
+          m_colourRemapSEIPostLutTargetValue[c] = new Int[m_colourRemapSEIPostLutNumValMinus1[c]+1];
+          for( Int i=0 ; i<=m_colourRemapSEIPostLutNumValMinus1[c] ; i++ )
+          {
+            retval = fscanf( fic, "%d", &m_colourRemapSEIPostLutCodedValue[c][i] );
+            retval = fscanf( fic, "%d", &m_colourRemapSEIPostLutTargetValue[c][i] );
+          }
+        }
+      }
+    }
+
+    fclose( fic );
+    if( retval != 1 )
+    {
+      fprintf(stderr, "Error while reading Colour Remapping Information SEI parameters file\n");
+      exit(EXIT_FAILURE);
+    }
+  }
+#else
+   // Reading external Colour Remapping Information SEI message parameters from file
+  // It seems that TAppEncLayerCfg::parseCfg is not used
+  for(UInt layer = 0; layer < m_numLayers; layer++)
+  {
+    if( cfg_colourRemapSEIFile[layer]->length() )
+    {
+      FILE* fic;
+      Int retval;
+      if((fic = fopen(cfg_colourRemapSEIFile[layer]->c_str(),"r")) == (FILE*)NULL)
+      {
+        fprintf(stderr, "Can't open Colour Remapping Information SEI parameters file %s\n", cfg_colourRemapSEIFile[layer]->c_str());
+        exit(EXIT_FAILURE);
+      }
+      Int tempCode;
+      retval = fscanf( fic, "%d", &m_acLayerCfg[layer].m_colourRemapSEIId );
+      retval = fscanf( fic, "%d", &tempCode ); m_acLayerCfg[layer].m_colourRemapSEICancelFlag = tempCode ? 1 : 0;
+      if( !m_acLayerCfg[layer].m_colourRemapSEICancelFlag )
+      {
+        retval = fscanf( fic, "%d", &tempCode ); m_acLayerCfg[layer].m_colourRemapSEIPersistenceFlag = tempCode ? 1 : 0;
+        retval = fscanf( fic, "%d", &tempCode ); m_acLayerCfg[layer].m_colourRemapSEIVideoSignalInfoPresentFlag = tempCode ? 1 : 0;
+        if( m_acLayerCfg[layer].m_colourRemapSEIVideoSignalInfoPresentFlag )
+        {
+          retval = fscanf( fic, "%d", &tempCode ); m_acLayerCfg[layer].m_colourRemapSEIFullRangeFlag = tempCode ? 1 : 0;
+          retval = fscanf( fic, "%d", &m_acLayerCfg[layer].m_colourRemapSEIPrimaries );
+          retval = fscanf( fic, "%d", &m_acLayerCfg[layer].m_colourRemapSEITransferFunction );
+          retval = fscanf( fic, "%d", &m_acLayerCfg[layer].m_colourRemapSEIMatrixCoefficients );
+        }
+
+        retval = fscanf( fic, "%d", &m_acLayerCfg[layer].m_colourRemapSEIInputBitDepth );
+        retval = fscanf( fic, "%d", &m_acLayerCfg[layer].m_colourRemapSEIBitDepth );
+  
+        for( Int c=0 ; c<3 ; c++ )
+        {
+          retval = fscanf( fic, "%d", &m_acLayerCfg[layer].m_colourRemapSEIPreLutNumValMinus1[c] );
+          if( m_acLayerCfg[layer].m_colourRemapSEIPreLutNumValMinus1[c]>0 )
+          {
+            m_acLayerCfg[layer].m_colourRemapSEIPreLutCodedValue[c]  = new Int[m_acLayerCfg[layer].m_colourRemapSEIPreLutNumValMinus1[c]+1];
+            m_acLayerCfg[layer].m_colourRemapSEIPreLutTargetValue[c] = new Int[m_acLayerCfg[layer].m_colourRemapSEIPreLutNumValMinus1[c]+1];
+            for( Int i=0 ; i<=m_acLayerCfg[layer].m_colourRemapSEIPreLutNumValMinus1[c] ; i++ )
+            {
+              retval = fscanf( fic, "%d", &m_acLayerCfg[layer].m_colourRemapSEIPreLutCodedValue[c][i] );
+              retval = fscanf( fic, "%d", &m_acLayerCfg[layer].m_colourRemapSEIPreLutTargetValue[c][i] );
+            }
+          }
+        }
+
+        retval = fscanf( fic, "%d", &tempCode ); m_acLayerCfg[layer].m_colourRemapSEIMatrixPresentFlag = tempCode ? 1 : 0;
+        if( m_acLayerCfg[layer].m_colourRemapSEIMatrixPresentFlag )
+        {
+          retval = fscanf( fic, "%d", &m_acLayerCfg[layer].m_colourRemapSEILog2MatrixDenom );
+          for( Int c=0 ; c<3 ; c++ )
+            for( Int i=0 ; i<3 ; i++ )
+              retval = fscanf( fic, "%d", &m_acLayerCfg[layer].m_colourRemapSEICoeffs[c][i] );
+        }
+
+        for( Int c=0 ; c<3 ; c++ )
+        {
+          retval = fscanf( fic, "%d", &m_acLayerCfg[layer].m_colourRemapSEIPostLutNumValMinus1[c] );
+          if( m_acLayerCfg[layer].m_colourRemapSEIPostLutNumValMinus1[c]>0 )
+          {
+            m_acLayerCfg[layer].m_colourRemapSEIPostLutCodedValue[c]  = new Int[m_acLayerCfg[layer].m_colourRemapSEIPostLutNumValMinus1[c]+1];
+            m_acLayerCfg[layer].m_colourRemapSEIPostLutTargetValue[c] = new Int[m_acLayerCfg[layer].m_colourRemapSEIPostLutNumValMinus1[c]+1];
+            for( Int i=0 ; i<=m_acLayerCfg[layer].m_colourRemapSEIPostLutNumValMinus1[c] ; i++ )
+            {
+              retval = fscanf( fic, "%d", &m_acLayerCfg[layer].m_colourRemapSEIPostLutCodedValue[c][i] );
+              retval = fscanf( fic, "%d", &m_acLayerCfg[layer].m_colourRemapSEIPostLutTargetValue[c][i] );
+            }
+          }
+        }
+      }
+
+      fclose( fic );
+      if( retval != 1 )
+      {
+        fprintf(stderr, "Error while reading Colour Remapping Information SEI parameters file\n");
+        exit(EXIT_FAILURE);
+      }
+    }
+  }
+#endif
+#endif
+#if N0383_IL_CONSTRAINED_TILE_SETS_SEI
+  if (m_interLayerConstrainedTileSetsSEIEnabled)
+  {
+    if (m_numTileColumnsMinus1 == 0 && m_numTileRowsMinus1 == 0)
+    {
+      printf( "Tiles are not defined (needed for inter-layer comnstrained tile sets SEI).\n" );
+      exit( EXIT_FAILURE );
+    }
+    Char* pTileSets = cfg_tileSets.empty() ? NULL : strdup(cfg_tileSets.c_str());
+    int i = 0;
+    char *topLeftTileIndex = strtok(pTileSets, " ,");
+    while(topLeftTileIndex != NULL)
+    {
+      if( i >= m_ilNumSetsInMessage )
+      {
+        printf( "The number of tile sets is larger than defined by IlNumSetsInMessage.\n" );
+        exit( EXIT_FAILURE );
+      }
+      *( m_topLeftTileIndex + i ) = atoi( topLeftTileIndex );
+      char *bottonRightTileIndex = strtok(NULL, " ,");
+      if( bottonRightTileIndex == NULL )
+      {
+        printf( "BottonRightTileIndex is missing in the tile sets.\n" );
+        exit( EXIT_FAILURE );
+      }
+      *( m_bottomRightTileIndex + i ) = atoi( bottonRightTileIndex );
+      char *ilcIdc = strtok(NULL, " ,");
+      if( ilcIdc == NULL )
+      {
+        printf( "IlcIdc is missing in the tile sets.\n" );
+        exit( EXIT_FAILURE );
+      }
+      *( m_ilcIdc + i ) = atoi( ilcIdc );
+      topLeftTileIndex = strtok(NULL, " ,");
+      i++;
+    }
+    if( i < m_ilNumSetsInMessage )
+    {
+      printf( "The number of tile sets is smaller than defined by IlNumSetsInMessage.\n" );
+      exit( EXIT_FAILURE );
+    }
+    m_skippedTileSetPresentFlag = false;
+
+    if( pTileSets )
+    {
+      free( pTileSets );
+      pTileSets = NULL;
+    }
+  }
+#endif
+  // check validity of input parameters
+#if SVC_EXTENSION
+  for( UInt layerIdx = 0; layerIdx < m_numLayers; layerIdx++ )
+  {
+    xCheckParameter(layerIdx);
+  }
+#else
+  xCheckParameter();
+#endif
+
+  // set global varibles
+#if LAYER_CTB
+  for(Int layer = 0; layer < MAX_LAYERS; layer++)
+  {
+    xSetGlobal(layer);
+  }
+#else
+  xSetGlobal();
+#endif
+  
+  // print-out parameters
+  xPrintParameter();
+
+  return true;
+}
+
+
+// ====================================================================================================================
+// Private member functions
+// ====================================================================================================================
+
+#if SVC_EXTENSION
+Void TAppEncCfg::xCheckParameter(UInt layerIdx)
+{
+  Bool m_useExtendedPrecision                = m_acLayerCfg[layerIdx].m_useExtendedPrecision;
+  Bool m_useHighPrecisionPredictionWeighting = m_acLayerCfg[layerIdx].m_useHighPrecisionPredictionWeighting;
+  ChromaFormat m_chromaFormatIDC             = m_acLayerCfg[layerIdx].m_chromaFormatIDC;
+  ChromaFormat m_chromaFormatConstraint      = m_acLayerCfg[layerIdx].m_chromaFormatConstraint;
+  ChromaFormat m_InputChromaFormatIDC        = m_acLayerCfg[layerIdx].m_InputChromaFormatIDC;
+
+  Int m_inputBitDepth[]       = {m_acLayerCfg[layerIdx].m_inputBitDepth[CHANNEL_TYPE_LUMA],       m_acLayerCfg[layerIdx].m_inputBitDepth[CHANNEL_TYPE_CHROMA]};
+  Int m_internalBitDepth[]    = {m_acLayerCfg[layerIdx].m_internalBitDepth[CHANNEL_TYPE_LUMA],    m_acLayerCfg[layerIdx].m_internalBitDepth[CHANNEL_TYPE_CHROMA]};
+  Int m_MSBExtendedBitDepth[] = {m_acLayerCfg[layerIdx].m_MSBExtendedBitDepth[CHANNEL_TYPE_LUMA], m_acLayerCfg[layerIdx].m_MSBExtendedBitDepth[CHANNEL_TYPE_CHROMA]};  
+
+  m_saoOffsetBitShift[CHANNEL_TYPE_LUMA]   = m_acLayerCfg[layerIdx].m_saoOffsetBitShift[CHANNEL_TYPE_LUMA];
+  m_saoOffsetBitShift[CHANNEL_TYPE_CHROMA] = m_acLayerCfg[layerIdx].m_saoOffsetBitShift[CHANNEL_TYPE_CHROMA];
+
+#if MULTIPLE_PTL_SUPPORT
+  Int layerPTLIdx = m_acLayerCfg[layerIdx].m_layerPTLIdx;
+  Profile::Name m_profile           = m_profileList[layerPTLIdx];
+  UInt m_bitDepthConstraint         = m_acLayerCfg[layerIdx].m_bitDepthConstraint;
+  Bool m_intraConstraintFlag        = m_acLayerCfg[layerIdx].m_intraConstraintFlag;
+  Bool m_lowerBitRateConstraintFlag = m_acLayerCfg[layerIdx].m_lowerBitRateConstraintFlag;
+#endif
+#else
+Void TAppEncCfg::xCheckParameter()
+{
+#endif
+
+  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 SVC_EXTENSION && MULTIPLE_PTL_SUPPORT
+  Int ii = 0;
+  while( ii < m_numPTLInfo )
+  {
+    if( m_profileList[ii] == Profile::NONE )
+    {
+      fprintf(stderr, "***************************************************************************\n");
+      fprintf(stderr, "** WARNING: For conforming bitstreams a valid Profile value must be set! **\n");
+      fprintf(stderr, "***************************************************************************\n");
+    }
+    if( m_levelList[ii] == Level::NONE )
+    {
+      fprintf(stderr, "***************************************************************************\n");
+      fprintf(stderr, "** WARNING: For conforming bitstreams a valid Level value must be set!   **\n");
+      fprintf(stderr, "***************************************************************************\n");
+    }
+    ii++;
+  }
+  if( m_numLayers > 1 && m_numPTLInfo > 1 && !m_nonHEVCBaseLayerFlag )
+  {
+    assert(m_profileList[0] <= Profile::MULTIVIEWMAIN);  //Profile IDC of PTL in VPS shall be one of single-layer profile IDCs
+    assert(m_profileList[0] == m_profileList[1]);        //Profile IDC of VpsProfileTierLevel[ 0 ] and VpsProfileTierLevel[ 1 ] shall be the same when BL is HEVC compatible
+    assert(m_levelList[0] >= m_levelList[1]);            //Level IDC of VpsProfileTierLevel[ 0 ] should not be less than level IDC of VpsProfileTierLevel[ 1 ]. 
+                                                         //NOTE that this is not conformance constraint but it would be nice if our encoder can prevent inefficient level IDC assignment
+    if (m_levelList[0] == m_levelList[1])
+    {
+      printf("Warning: Level0 is set the same as Level1\n");
+    }
+  }
+#else
+  if( m_profile==Profile::NONE )
+  {
+    fprintf(stderr, "***************************************************************************\n");
+    fprintf(stderr, "** WARNING: For conforming bitstreams a valid Profile value must be set! **\n");
+    fprintf(stderr, "***************************************************************************\n");
+  }
+  if( m_level==Level::NONE )
+  {
+    fprintf(stderr, "***************************************************************************\n");
+    fprintf(stderr, "** WARNING: For conforming bitstreams a valid Level value must be set!   **\n");
+    fprintf(stderr, "***************************************************************************\n");
+  }
+#endif
+
+  Bool check_failed = false; /* abort if there is a fatal configuration problem */
+#define xConfirmPara(a,b) check_failed |= confirmPara(a,b)
+
+  const UInt maxBitDepth=(m_chromaFormatIDC==CHROMA_400) ? m_internalBitDepth[CHANNEL_TYPE_LUMA] : std::max(m_internalBitDepth[CHANNEL_TYPE_LUMA], m_internalBitDepth[CHANNEL_TYPE_CHROMA]);
+  xConfirmPara(m_bitDepthConstraint<maxBitDepth, "The internalBitDepth must not be greater than the bitDepthConstraint value");
+  xConfirmPara(m_chromaFormatConstraint<m_chromaFormatIDC, "The chroma format used must not be greater than the chromaFormatConstraint value");
+
+  if (m_profile==Profile::MAINREXT || m_profile==Profile::HIGHTHROUGHPUTREXT)
+  {
+    xConfirmPara(m_lowerBitRateConstraintFlag==false && m_intraConstraintFlag==false, "The lowerBitRateConstraint flag cannot be false when intraConstraintFlag is false");
+    xConfirmPara(m_alignCABACBeforeBypass && m_profile!=Profile::HIGHTHROUGHPUTREXT, "AlignCABACBeforeBypass must not be enabled unless the high throughput profile is being used.");
+    if (m_profile == Profile::MAINREXT)
+    {
+      const UInt intraIdx = m_intraConstraintFlag ? 1:0;
+      const UInt bitDepthIdx = (m_bitDepthConstraint == 8 ? 0 : (m_bitDepthConstraint ==10 ? 1 : (m_bitDepthConstraint == 12 ? 2 : (m_bitDepthConstraint == 16 ? 3 : 4 ))));
+      const UInt chromaFormatIdx = UInt(m_chromaFormatConstraint);
+      const Bool bValidProfile = (bitDepthIdx > 3 || chromaFormatIdx>3) ? false : (validRExtProfileNames[intraIdx][bitDepthIdx][chromaFormatIdx] != NONE);
+      xConfirmPara(!bValidProfile, "Invalid intra constraint flag, bit depth constraint flag and chroma format constraint flag combination for a RExt profile");
+      const Bool bUsingGeneralRExtTools  = m_useResidualRotation                    ||
+                                           m_useSingleSignificanceMapContext        ||
+                                           m_useResidualDPCM[RDPCM_SIGNAL_IMPLICIT] ||
+                                           m_useResidualDPCM[RDPCM_SIGNAL_EXPLICIT] ||
+                                           !m_enableIntraReferenceSmoothing         ||
+                                           m_useGolombRiceParameterAdaptation       ||
+                                           m_transformSkipLog2MaxSize!=2;
+      const Bool bUsingChromaQPTool      = m_maxCUChromaQpAdjustmentDepth >= 0;
+      const Bool bUsingExtendedPrecision = m_useExtendedPrecision;
+
+      xConfirmPara((m_chromaFormatConstraint==CHROMA_420 || m_chromaFormatConstraint==CHROMA_400) && bUsingChromaQPTool, "CU Chroma QP adjustment cannot be used for 4:0:0 or 4:2:0 RExt profiles");
+      xConfirmPara(m_bitDepthConstraint != 16 && bUsingExtendedPrecision, "Extended precision can only be used in 16-bit RExt profiles");
+      if (!(m_chromaFormatConstraint == CHROMA_400 && m_bitDepthConstraint == 16) && m_chromaFormatConstraint!=CHROMA_444)
+      {
+        xConfirmPara(bUsingGeneralRExtTools, "Combination of tools and profiles are not possible in the specified RExt profile.");
+      }
+      if (!m_intraConstraintFlag && m_bitDepthConstraint==16 && m_chromaFormatConstraint==CHROMA_444)
+      {
+        fprintf(stderr, "********************************************************************************************************\n");
+        fprintf(stderr, "** WARNING: The RExt constraint flags describe a non standard combination (used for development only) **\n");
+        fprintf(stderr, "********************************************************************************************************\n");
+      }
+    }
+    else
+    {
+      xConfirmPara( m_chromaFormatConstraint != CHROMA_444, "chroma format constraint must be 4:4:4 in the High Throughput 4:4:4 16-bit Intra profile.");
+      xConfirmPara( m_bitDepthConstraint     != 16,         "bit depth constraint must be 4:4:4 in the High Throughput 4:4:4 16-bit Intra profile.");
+      xConfirmPara( m_intraConstraintFlag    != 1,          "intra constraint flag must be 1 in the High Throughput 4:4:4 16-bit Intra profile.");
+    }
+  }
+  else
+  {
+#if MULTIPLE_PTL_SUPPORT
+    xConfirmPara(m_bitDepthConstraint!=((m_profile==Profile::MAIN10 || m_profile==Profile::SCALABLEMAIN10)?10:8), "BitDepthConstraint must be 8 for MAIN profile and 10 for MAIN10 or Scalable-main10 profile.");
+#else
+    xConfirmPara(m_bitDepthConstraint!=((m_profile==Profile::MAIN10)?10:8), "BitDepthConstraint must be 8 for MAIN profile and 10 for MAIN10 profile.");
+#endif
+    xConfirmPara(m_chromaFormatConstraint!=CHROMA_420, "ChromaFormatConstraint must be 420 for non main-RExt profiles.");
+    xConfirmPara(m_intraConstraintFlag==true, "IntraConstraintFlag must be false for non main_RExt profiles.");
+    xConfirmPara(m_lowerBitRateConstraintFlag==false, "LowerBitrateConstraintFlag must be true for non main-RExt profiles.");
+
+    xConfirmPara(m_useCrossComponentPrediction==true, "CrossComponentPrediction must not be used for non main-RExt profiles.");
+    xConfirmPara(m_transformSkipLog2MaxSize!=2, "Transform Skip Log2 Max Size must be 2 for V1 profiles.");
+    xConfirmPara(m_useResidualRotation==true, "UseResidualRotation must not be enabled for non main-RExt profiles.");
+    xConfirmPara(m_useSingleSignificanceMapContext==true, "UseSingleSignificanceMapContext must not be enabled for non main-RExt profiles.");
+    xConfirmPara(m_useResidualDPCM[RDPCM_SIGNAL_IMPLICIT]==true, "ImplicitResidualDPCM must not be enabled for non main-RExt profiles.");
+    xConfirmPara(m_useResidualDPCM[RDPCM_SIGNAL_EXPLICIT]==true, "ExplicitResidualDPCM must not be enabled for non main-RExt profiles.");
+    xConfirmPara(m_useGolombRiceParameterAdaptation==true, "GolombRiceParameterAdaption must not be enabled for non main-RExt profiles.");
+    xConfirmPara(m_useExtendedPrecision==true, "UseExtendedPrecision must not be enabled for non main-RExt profiles.");
+    xConfirmPara(m_useHighPrecisionPredictionWeighting==true, "UseHighPrecisionPredictionWeighting must not be enabled for non main-RExt profiles.");
+    xConfirmPara(m_enableIntraReferenceSmoothing==false, "EnableIntraReferenceSmoothing must be enabled for non main-RExt profiles.");
+    xConfirmPara(m_alignCABACBeforeBypass, "AlignCABACBeforeBypass cannot be enabled for non main-RExt profiles.");
+  }
+
+  // check range of parameters
+  xConfirmPara( m_inputBitDepth[CHANNEL_TYPE_LUMA  ] < 8,                                   "InputBitDepth must be at least 8" );
+  xConfirmPara( m_inputBitDepth[CHANNEL_TYPE_CHROMA] < 8,                                   "InputBitDepthC must be at least 8" );
+
+#if !RExt__HIGH_BIT_DEPTH_SUPPORT
+  if (m_useExtendedPrecision)
+  {
+    for (UInt channelType = 0; channelType < MAX_NUM_CHANNEL_TYPE; channelType++)
+    {
+      xConfirmPara((m_internalBitDepth[channelType] > 8) , "Model is not configured to support high enough internal accuracies - enable RExt__HIGH_BIT_DEPTH_SUPPORT to use increased precision internal data types etc...");
+    }
+  }
+  else
+  {
+    for (UInt channelType = 0; channelType < MAX_NUM_CHANNEL_TYPE; channelType++)
+    {
+      xConfirmPara((m_internalBitDepth[channelType] > 12) , "Model is not configured to support high enough internal accuracies - enable RExt__HIGH_BIT_DEPTH_SUPPORT to use increased precision internal data types etc...");
+    }
+  }
+#endif
+
+  xConfirmPara( (m_MSBExtendedBitDepth[CHANNEL_TYPE_LUMA  ] < m_inputBitDepth[CHANNEL_TYPE_LUMA  ]), "MSB-extended bit depth for luma channel (--MSBExtendedBitDepth) must be greater than or equal to input bit depth for luma channel (--InputBitDepth)" );
+  xConfirmPara( (m_MSBExtendedBitDepth[CHANNEL_TYPE_CHROMA] < m_inputBitDepth[CHANNEL_TYPE_CHROMA]), "MSB-extended bit depth for chroma channel (--MSBExtendedBitDepthC) must be greater than or equal to input bit depth for chroma channel (--InputBitDepthC)" );
+
+  xConfirmPara( m_saoOffsetBitShift[CHANNEL_TYPE_LUMA]   > (m_internalBitDepth[CHANNEL_TYPE_LUMA  ]<10?0:(m_internalBitDepth[CHANNEL_TYPE_LUMA  ]-10)), "SaoLumaOffsetBitShift must be in the range of 0 to InternalBitDepth-10, inclusive");
+  xConfirmPara( m_saoOffsetBitShift[CHANNEL_TYPE_CHROMA] > (m_internalBitDepth[CHANNEL_TYPE_CHROMA]<10?0:(m_internalBitDepth[CHANNEL_TYPE_CHROMA]-10)), "SaoChromaOffsetBitShift must be in the range of 0 to InternalBitDepthC-10, inclusive");
+
+  xConfirmPara( m_chromaFormatIDC >= NUM_CHROMA_FORMAT,                                     "ChromaFormatIDC must be either 400, 420, 422 or 444" );
+  std::string sTempIPCSC="InputColourSpaceConvert must be empty, "+getListOfColourSpaceConverts(true);
+  xConfirmPara( m_inputColourSpaceConvert >= NUMBER_INPUT_COLOUR_SPACE_CONVERSIONS,         sTempIPCSC.c_str() );
+  xConfirmPara( m_InputChromaFormatIDC >= NUM_CHROMA_FORMAT,                                "InputChromaFormatIDC must be either 400, 420, 422 or 444" );
+
+#if !SVC_EXTENSION  
+  xConfirmPara( m_iFrameRate <= 0,                                                          "Frame rate must be more than 1" );
+#endif
+  xConfirmPara( m_framesToBeEncoded <= 0,                                                   "Total Number Of Frames encoded must be more than 0" );
+  xConfirmPara( m_iGOPSize < 1 ,                                                            "GOP Size must be greater or equal to 1" );
+  xConfirmPara( m_iGOPSize > 1 &&  m_iGOPSize % 2,                                          "GOP Size must be a multiple of 2, if GOP Size is greater than 1" );
+#if !SVC_EXTENSION 
+  xConfirmPara( (m_iIntraPeriod > 0 && m_iIntraPeriod < m_iGOPSize) || m_iIntraPeriod == 0, "Intra period must be more than GOP size, or -1 , not 0" );
+#endif
+#if ALLOW_RECOVERY_POINT_AS_RAP
+  xConfirmPara( m_iDecodingRefreshType < 0 || m_iDecodingRefreshType > 3,                   "Decoding Refresh Type must be comprised between 0 and 3 included" );
+  if(m_iDecodingRefreshType == 3)
+  {
+    xConfirmPara( !m_recoveryPointSEIEnabled,                                               "When using RecoveryPointSEI messages as RA points, recoveryPointSEI must be enabled" );
+  }
+#else
+  xConfirmPara( m_iDecodingRefreshType < 0 || m_iDecodingRefreshType > 2,                   "Decoding Refresh Type must be equal to 0, 1 or 2" );
+#endif
+
+  if (m_isField)
+  {
+    if (!m_pictureTimingSEIEnabled)
+    {
+      fprintf(stderr, "****************************************************************************\n");
+      fprintf(stderr, "** WARNING: Picture Timing SEI should be enabled for field coding!        **\n");
+      fprintf(stderr, "****************************************************************************\n");
+    }
+  }
+  if ( m_bufferingPeriodSEIEnabled && !m_activeParameterSetsSEIEnabled)
+  {
+    fprintf(stderr, "****************************************************************************\n");
+    fprintf(stderr, "** WARNING: using buffering period SEI requires SPS activation with       **\n"); 
+    fprintf(stderr, "**          active parameter sets SEI. Enabling active parameter sets SEI **\n");
+    fprintf(stderr, "****************************************************************************\n");
+    m_activeParameterSetsSEIEnabled = 1;
+  }
+  if ( m_pictureTimingSEIEnabled && !m_activeParameterSetsSEIEnabled)
+  {
+    fprintf(stderr, "****************************************************************************\n");
+    fprintf(stderr, "** WARNING: using picture timing SEI requires SPS activation with active  **\n"); 
+    fprintf(stderr, "**          parameter sets SEI. Enabling active parameter sets SEI.       **\n");
+    fprintf(stderr, "****************************************************************************\n");
+    m_activeParameterSetsSEIEnabled = 1;
+  }
+
+  if(m_useCrossComponentPrediction && (m_chromaFormatIDC != CHROMA_444))
+  {
+    fprintf(stderr, "****************************************************************************\n");
+    fprintf(stderr, "** WARNING: Cross-component prediction is specified for 4:4:4 format only **\n");
+    fprintf(stderr, "****************************************************************************\n");
+
+    m_useCrossComponentPrediction = false;
+  }
+
+  if ( m_CUTransquantBypassFlagForce && m_bUseHADME )
+  {
+    fprintf(stderr, "****************************************************************************\n");
+    fprintf(stderr, "** WARNING: --HadamardME has been disabled due to the enabling of         **\n");
+    fprintf(stderr, "**          --CUTransquantBypassFlagForce                                 **\n");
+    fprintf(stderr, "****************************************************************************\n");
+
+    m_bUseHADME = false; // this has been disabled so that the lambda is calculated slightly differently for lossless modes (as a result of JCTVC-R0104).
+  }
+
+  xConfirmPara (m_transformSkipLog2MaxSize < 2, "Transform Skip Log2 Max Size must be at least 2 (4x4)");
+
+  if (m_transformSkipLog2MaxSize!=2 && m_useTransformSkipFast)
+  {
+    fprintf(stderr, "***************************************************************************\n");
+    fprintf(stderr, "** WARNING: Transform skip fast is enabled (which only tests NxN splits),**\n");
+    fprintf(stderr, "**          but transform skip log2 max size is not 2 (4x4)              **\n");
+    fprintf(stderr, "**          It may be better to disable transform skip fast mode         **\n");
+    fprintf(stderr, "***************************************************************************\n");
+  }
+
+#if !SVC_EXTENSION
+  xConfirmPara( m_iQP <  -6 * (m_internalBitDepth[CHANNEL_TYPE_LUMA] - 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)" );
+#if LAYER_CTB
+  for(UInt layer = 0; layer < MAX_LAYERS; layer++)
+  {
+    xConfirmPara( m_iMaxCuDQPDepth > m_acLayerCfg[layer].m_uiMaxCUDepth - 1,                "Absolute depth for a minimum CuDQP exceeds maximum coding unit depth" );
+  }
+#else
+  xConfirmPara( m_iMaxCuDQPDepth > m_uiMaxCUDepth - 1,                                          "Absolute depth for a minimum CuDQP exceeds maximum coding unit depth" );
+#endif
+
+  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 !SVC_EXTENSION
+  if (m_iDecodingRefreshType == 2)
+  {
+    xConfirmPara( m_iIntraPeriod > 0 && m_iIntraPeriod <= m_iGOPSize ,                      "Intra period must be larger than GOP size for periodic IDR pictures");
+  }
+#endif
+#if !LAYER_CTB
+  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");
+#endif
+#if !SVC_EXTENSION
+  xConfirmPara( (m_iSourceWidth  % (m_uiMaxCUWidth  >> (m_uiMaxCUDepth-1)))!=0,             "Resulting coded frame width must be a multiple of the minimum CU size");
+  xConfirmPara( (m_iSourceHeight % (m_uiMaxCUHeight >> (m_uiMaxCUDepth-1)))!=0,             "Resulting coded frame height must be a multiple of the minimum CU size");
+#endif
+  
+#if !LAYER_CTB
+  xConfirmPara( m_uiQuadtreeTULog2MinSize < 2,                                        "QuadtreeTULog2MinSize must be 2 or greater.");
+  xConfirmPara( m_uiQuadtreeTULog2MaxSize > 5,                                        "QuadtreeTULog2MaxSize must be 5 or smaller.");
+  xConfirmPara( m_uiQuadtreeTULog2MaxSize < m_uiQuadtreeTULog2MinSize,                "QuadtreeTULog2MaxSize must be greater than or equal to m_uiQuadtreeTULog2MinSize.");
+  xConfirmPara( (1<<m_uiQuadtreeTULog2MaxSize) > m_uiMaxCUWidth,                      "QuadtreeTULog2MaxSize must be log2(maxCUSize) or smaller.");
+  xConfirmPara( ( 1 << m_uiQuadtreeTULog2MinSize ) >= ( m_uiMaxCUWidth  >> (m_uiMaxCUDepth-1)), "QuadtreeTULog2MinSize must not be greater than or equal to minimum CU size" );
+  xConfirmPara( ( 1 << m_uiQuadtreeTULog2MinSize ) >= ( m_uiMaxCUHeight >> (m_uiMaxCUDepth-1)), "QuadtreeTULog2MinSize must not be greater than or equal to minimum CU 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" );
+#endif
+  
+  xConfirmPara(  m_maxNumMergeCand < 1,  "MaxNumMergeCand must be 1 or greater.");
+  xConfirmPara(  m_maxNumMergeCand > 5,  "MaxNumMergeCand must be 5 or smaller.");
+
+#if !SVC_EXTENSION
+#if ADAPTIVE_QP_SELECTION
+  xConfirmPara( m_bUseAdaptQpSelect == true && m_iQP < 0,                                              "AdaptiveQpSelection must be disabled when QP < 0.");
+  xConfirmPara( m_bUseAdaptQpSelect == true && (m_cbQpOffset !=0 || m_crQpOffset != 0 ),               "AdaptiveQpSelection must be disabled when ChromaQpOffset is not equal to 0.");
+#endif
+#endif
+
+  if( m_usePCM)
+  {
+    for (UInt channelType = 0; channelType < MAX_NUM_CHANNEL_TYPE; channelType++)
+    {
+      xConfirmPara(((m_MSBExtendedBitDepth[channelType] > m_internalBitDepth[channelType]) && m_bPCMInputBitDepthFlag), "PCM bit depth cannot be greater than internal bit depth (PCMInputBitDepthFlag cannot be used when InputBitDepth or MSBExtendedBitDepth > InternalBitDepth)");
+    }
+    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" );
+  }
+  
+#if !SVC_EXTENSION
+  Bool tileFlag = (m_numTileColumnsMinus1 > 0 || m_numTileRowsMinus1 > 0 );
+  if (m_profile!=Profile::HIGHTHROUGHPUTREXT)
+  {
+    xConfirmPara( tileFlag && m_iWaveFrontSynchro,            "Tile and Wavefront can not be applied together, except in the High Throughput Intra 4:4:4 16 profile");
+  }
+
+  xConfirmPara( m_iSourceWidth  % TComSPS::getWinUnitX(m_chromaFormatIDC) != 0, "Picture width must be an integer multiple of the specified chroma subsampling");
+  xConfirmPara( m_iSourceHeight % TComSPS::getWinUnitY(m_chromaFormatIDC) != 0, "Picture height must be an integer multiple of the specified chroma subsampling");
+
+  xConfirmPara( m_aiPad[0] % TComSPS::getWinUnitX(m_chromaFormatIDC) != 0, "Horizontal padding must be an integer multiple of the specified chroma subsampling");
+  xConfirmPara( m_aiPad[1] % TComSPS::getWinUnitY(m_chromaFormatIDC) != 0, "Vertical padding must be an integer multiple of the specified chroma subsampling");
+
+  xConfirmPara( m_confWinLeft   % TComSPS::getWinUnitX(m_chromaFormatIDC) != 0, "Left conformance window offset must be an integer multiple of the specified chroma subsampling");
+  xConfirmPara( m_confWinRight  % TComSPS::getWinUnitX(m_chromaFormatIDC) != 0, "Right conformance window offset must be an integer multiple of the specified chroma subsampling");
+  xConfirmPara( m_confWinTop    % TComSPS::getWinUnitY(m_chromaFormatIDC) != 0, "Top conformance window offset must be an integer multiple of the specified chroma subsampling");
+  xConfirmPara( m_confWinBottom % TComSPS::getWinUnitY(m_chromaFormatIDC) != 0, "Bottom conformance window offset must be an integer multiple of the specified chroma subsampling");
+
+  xConfirmPara( m_defaultDisplayWindowFlag && !m_vuiParametersPresentFlag, "VUI needs to be enabled for default display window");
+
+  if (m_defaultDisplayWindowFlag)
+  {
+    xConfirmPara( m_defDispWinLeftOffset   % TComSPS::getWinUnitX(m_chromaFormatIDC) != 0, "Left default display window offset must be an integer multiple of the specified chroma subsampling");
+    xConfirmPara( m_defDispWinRightOffset  % TComSPS::getWinUnitX(m_chromaFormatIDC) != 0, "Right default display window offset must be an integer multiple of the specified chroma subsampling");
+    xConfirmPara( m_defDispWinTopOffset    % TComSPS::getWinUnitY(m_chromaFormatIDC) != 0, "Top default display window offset must be an integer multiple of the specified chroma subsampling");
+    xConfirmPara( m_defDispWinBottomOffset % TComSPS::getWinUnitY(m_chromaFormatIDC) != 0, "Bottom default display window offset must be an integer multiple of the specified chroma subsampling");
+  }
+#endif
+
+#if !LAYER_CTB
+  // 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");
+  }
+#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 SVC_EXTENSION
+#if Q0108_TSA_STSA
+  if( m_acLayerCfg[0].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;
+  }
+  else
+  {
+    xConfirmPara( m_intraConstraintFlag, "IntraConstraintFlag cannot be 1 for inter sequences");
+  }
+
+  if (m_acLayerCfg[layerIdx].m_iIntraPeriod == 1 && m_EhGOPList[layerIdx][0].m_POC == -1) {
+    m_EhGOPList[layerIdx][0] = GOPEntry();
+    m_EhGOPList[layerIdx][0].m_QPFactor = 1;
+    m_EhGOPList[layerIdx][0].m_betaOffsetDiv2 = 0;
+    m_EhGOPList[layerIdx][0].m_tcOffsetDiv2 = 0;
+    m_EhGOPList[layerIdx][0].m_POC = 1;
+    m_EhGOPList[layerIdx][0].m_numRefPicsActive = 4;
+  }
+  else
+  {
+    xConfirmPara( m_intraConstraintFlag, "IntraConstraintFlag cannot be 1 for inter sequences");
+  }
+#else
+  for(UInt layer = 0; layer < MAX_LAYERS; layer++)
+  {
+    Int m_iIntraPeriod = m_acLayerCfg[layer].m_iIntraPeriod;
+    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;
+    }
+    else
+    {
+      xConfirmPara( m_intraConstraintFlag, "IntraConstraintFlag cannot be 1 for inter sequences");
+    }
+  }
+#endif
+#else
+  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;
+  }
+  else
+  {
+    xConfirmPara( m_intraConstraintFlag, "IntraConstraintFlag cannot be 1 for inter sequences");
+  }
+#endif
+
+  Bool verifiedGOP=false;
+  Bool errorGOP=false;
+  Int checkGOP=1;
+  Int numRefs = m_isField ? 2 : 1;
+  Int refList[MAX_NUM_REF_PICS+1];
+  refList[0]=0;
+  if(m_isField)
+  {
+    refList[1] = 1;
+  }
+  Bool isOK[MAX_GOP];
+  for(Int i=0; i<MAX_GOP; i++)
+  {
+    isOK[i]=false;
+  }
+  Int numOK=0;
+#if !SVC_EXTENSION
+  xConfirmPara( m_iIntraPeriod >=0&&(m_iIntraPeriod%m_iGOPSize!=0), "Intra period must be a multiple of GOPSize, or -1" );
+#endif
+
+  for(Int i=0; i<m_iGOPSize; i++)
+  {
+    if(m_GOPList[i].m_POC==m_iGOPSize)
+    {
+      xConfirmPara( m_GOPList[i].m_temporalId!=0 , "The last frame in each GOP must have temporal ID = 0 " );
+    }
+  }
+
+#if SVC_EXTENSION
+  xConfirmPara( m_numLayers > MAX_LAYERS , "Number of layers in config file is greater than MAX_LAYERS" );
+  m_numLayers = m_numLayers > MAX_LAYERS ? MAX_LAYERS : m_numLayers;
+  
+  // it can be updated after AVC BL support will be added to the WD
+#if VPS_AVC_BL_FLAG_REMOVAL
+  if( m_nonHEVCBaseLayerFlag )
+#else
+  if( m_avcBaseLayerFlag )
+#endif
+  {
+    m_crossLayerIrapAlignFlag = false;
+    m_crossLayerPictureTypeAlignFlag = false;
+    m_crossLayerAlignedIdrOnlyFlag = false;
+  }
+
+  // verify layer configuration parameters
+  if(m_acLayerCfg[layerIdx].xCheckParameter(m_isField))
+  {
+    printf("\nError: invalid configuration parameter found in layer %d \n", layerIdx);
+    check_failed = true;
+  }
+
+  // verify layer configuration parameters
+  Int m_iIntraPeriod = m_acLayerCfg[layerIdx].m_iIntraPeriod;
+#endif
+  if ( (m_iIntraPeriod != 1) && !m_loopFilterOffsetInPPS && m_DeblockingFilterControlPresent && (!m_bLoopFilterDisable) )
+  {
+    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)" );
+    }
+  }
+
+#if !Q0108_TSA_STSA
+  m_extraRPSs=0;                                     
+#else
+  memset( m_extraRPSs, 0, sizeof( m_extraRPSs ) );
+#endif
+  //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)
+    {
+      printf("\nError: found fewer Reference Picture Sets than GOPSize\n");
+      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)
+          {
+            printf("\nError: ref pic %d is not available for GOP frame %d\n",m_GOPList[curGOP].m_referencePics[i],curGOP+1);
+            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)
+#if !Q0108_TSA_STSA
+        m_GOPList[m_iGOPSize+m_extraRPSs]=m_GOPList[curGOP];
+#else
+        m_GOPList[m_iGOPSize+m_extraRPSs[0]]=m_GOPList[curGOP];
+#endif
+        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)
+          {
+#if !Q0108_TSA_STSA
+            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];
+#else
+            m_GOPList[m_iGOPSize+m_extraRPSs[0]].m_referencePics[newRefs]=m_GOPList[curGOP].m_referencePics[i];
+            m_GOPList[m_iGOPSize+m_extraRPSs[0]].m_usedByCurrPic[newRefs]=m_GOPList[curGOP].m_usedByCurrPic[i];
+#endif
+            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 !Q0108_TSA_STSA
+              if(m_GOPList[m_iGOPSize+m_extraRPSs].m_referencePics[i]==offPOC-curPOC)
+#else
+              if(m_GOPList[m_iGOPSize+m_extraRPSs[0]].m_referencePics[i]==offPOC-curPOC)
+#endif
+              {
+                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 !Q0108_TSA_STSA
+                if(m_GOPList[m_iGOPSize+m_extraRPSs].m_referencePics[j]<offPOC-curPOC||m_GOPList[m_iGOPSize+m_extraRPSs].m_referencePics[j]>0)
+#else
+                if(m_GOPList[m_iGOPSize+m_extraRPSs[0]].m_referencePics[j]<offPOC-curPOC||m_GOPList[m_iGOPSize+m_extraRPSs[0]].m_referencePics[j]>0)
+#endif
+                {
+                  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++)
+              {
+#if !Q0108_TSA_STSA
+                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;
+#else
+                Int newPrev = m_GOPList[m_iGOPSize+m_extraRPSs[0]].m_referencePics[j];
+                Int newUsed = m_GOPList[m_iGOPSize+m_extraRPSs[0]].m_usedByCurrPic[j];
+                m_GOPList[m_iGOPSize+m_extraRPSs[0]].m_referencePics[j]=prev;
+                m_GOPList[m_iGOPSize+m_extraRPSs[0]].m_usedByCurrPic[j]=prevUsed;
+#endif
+
+                prevUsed=newUsed;
+                prev=newPrev;
+              }
+              newRefs++;
+            }
+          }
+          if(newRefs>=numPrefRefs)
+          {
+            break;
+          }
+        }
+#if !Q0108_TSA_STSA
+        m_GOPList[m_iGOPSize+m_extraRPSs].m_numRefPics=newRefs;
+        m_GOPList[m_iGOPSize+m_extraRPSs].m_POC = curPOC;
+#else
+        m_GOPList[m_iGOPSize+m_extraRPSs[0]].m_numRefPics=newRefs;
+        m_GOPList[m_iGOPSize+m_extraRPSs[0]].m_POC = curPOC;
+#endif
+#if !Q0108_TSA_STSA
+        if (m_extraRPSs == 0)
+#else
+        if (m_extraRPSs[0] == 0)
+#endif
+        {
+#if !Q0108_TSA_STSA
+          m_GOPList[m_iGOPSize+m_extraRPSs].m_interRPSPrediction = 0;
+          m_GOPList[m_iGOPSize+m_extraRPSs].m_numRefIdc = 0;
+#else
+          m_GOPList[m_iGOPSize+m_extraRPSs[0]].m_interRPSPrediction = 0;
+          m_GOPList[m_iGOPSize+m_extraRPSs[0]].m_numRefIdc = 0;
+#endif
+        }
+        else
+        {
+#if !Q0108_TSA_STSA
+          Int rIdx =  m_iGOPSize + m_extraRPSs - 1;
+#else
+          Int rIdx =  m_iGOPSize + m_extraRPSs[0] - 1;
+#endif
+          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;
+#if !Q0108_TSA_STSA
+            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++;
+      }
+#else
+            for (Int j = 0; j < m_GOPList[m_iGOPSize+m_extraRPSs[0]].m_numRefPics; j++)
+            {
+              if ( (absPOCref - curPOC) == m_GOPList[m_iGOPSize+m_extraRPSs[0]].m_referencePics[j])
+              {
+                if (m_GOPList[m_iGOPSize+m_extraRPSs[0]].m_usedByCurrPic[j])
+                {
+                  refIdc = 1;
+                }
+                else
+                {
+                  refIdc = 2;
+                }
+              }
+            }
+            m_GOPList[m_iGOPSize+m_extraRPSs[0]].m_refIdc[newIdc]=refIdc;
+            newIdc++;
+          }
+          m_GOPList[m_iGOPSize+m_extraRPSs[0]].m_interRPSPrediction = 1;  
+          m_GOPList[m_iGOPSize+m_extraRPSs[0]].m_numRefIdc = newIdc;
+          m_GOPList[m_iGOPSize+m_extraRPSs[0]].m_deltaRPS = refPOC - m_GOPList[m_iGOPSize+m_extraRPSs[0]].m_POC; 
+        }
+        curGOP=m_iGOPSize+m_extraRPSs[0];
+        m_extraRPSs[0]++;
+      }
+#endif
+
+      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");
+
+#if SVC_EXTENSION && Q0108_TSA_STSA
+  if( layerIdx > 0 )
+  {
+    verifiedGOP=false;
+    errorGOP=false;
+    checkGOP=1;
+    numRefs = m_isField ? 2 : 1;
+    refList[0]=0;
+
+    if(m_isField)
+    {
+      refList[1] = 1;
+    }
+
+    memset( isOK, 0, sizeof( isOK ) );
+    numOK=0;
+
+    for(Int i=0; i<m_iGOPSize; i++)
+    {
+      if(m_EhGOPList[layerIdx][i].m_POC==m_iGOPSize)
+      {
+        xConfirmPara( m_EhGOPList[layerIdx][i].m_temporalId!=0 , "The last frame in each GOP must have temporal ID = 0 " );
+      }
+    }
+
+    xConfirmPara( m_numLayers > MAX_LAYERS , "Number of layers in config file is greater than MAX_LAYERS" );
+    m_numLayers = m_numLayers > MAX_LAYERS ? MAX_LAYERS : m_numLayers;
+
+    // verify layer configuration parameters
+    for(UInt layer=0; layer<m_numLayers; layer++)
+    {
+      if ( (m_acLayerCfg[layer].m_iIntraPeriod != 1) && !m_loopFilterOffsetInPPS && m_DeblockingFilterControlPresent && (!m_bLoopFilterDisable) )
+      {
+        for(Int i=0; i<m_iGOPSize; i++)
+        {
+          xConfirmPara( (m_EhGOPList[layerIdx][i].m_betaOffsetDiv2 + m_loopFilterBetaOffsetDiv2) < -6 || (m_EhGOPList[layerIdx][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_EhGOPList[layerIdx][i].m_tcOffsetDiv2 + m_loopFilterTcOffsetDiv2) < -6 || (m_EhGOPList[layerIdx][i].m_tcOffsetDiv2 + m_loopFilterTcOffsetDiv2) > 6, "Loop Filter Tc Offset div. 2 for one of the GOP entries exceeds supported range (-6 to 6)" );
+        }
+      }
+    }
+
+    //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_EhGOPList[layerIdx][curGOP].m_POC;    
+      if(m_EhGOPList[layerIdx][curGOP].m_POC<0) 
+      {
+        printf("\nError: found fewer Reference Picture Sets than GOPSize\n");
+        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_EhGOPList[layerIdx][curGOP].m_numRefPics; i++) 
+        {
+          Int absPOC = curPOC+m_EhGOPList[layerIdx][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_EhGOPList[layerIdx][k].m_POC%m_iGOPSize)
+                  {
+                    if(m_EhGOPList[layerIdx][k].m_temporalId==m_EhGOPList[layerIdx][curGOP].m_temporalId)
+                    {
+                      m_EhGOPList[layerIdx][k].m_refPic = true;
+                    }
+                    m_EhGOPList[layerIdx][curGOP].m_usedByCurrPic[i]=m_EhGOPList[layerIdx][k].m_temporalId<=m_EhGOPList[layerIdx][curGOP].m_temporalId;
+                  }
+                }
+              }
+            }
+            if(!found)
+            {
+              printf("\nError: ref pic %d is not available for GOP frame %d\n",m_EhGOPList[layerIdx][curGOP].m_referencePics[i],curGOP+1);
+              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_EhGOPList[layerIdx][m_iGOPSize+m_extraRPSs[layerIdx]]=m_EhGOPList[layerIdx][curGOP];
+          Int newRefs=0;
+          for(Int i = 0; i< m_EhGOPList[layerIdx][curGOP].m_numRefPics; i++) 
+          {
+            Int absPOC = curPOC+m_EhGOPList[layerIdx][curGOP].m_referencePics[i];
+            if(absPOC>=0)
+            {
+              m_EhGOPList[layerIdx][m_iGOPSize+m_extraRPSs[layerIdx]].m_referencePics[newRefs]=m_EhGOPList[layerIdx][curGOP].m_referencePics[i];
+              m_EhGOPList[layerIdx][m_iGOPSize+m_extraRPSs[layerIdx]].m_usedByCurrPic[newRefs]=m_EhGOPList[layerIdx][curGOP].m_usedByCurrPic[i];
+              newRefs++;
+            }
+          }
+          Int numPrefRefs = m_EhGOPList[layerIdx][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_EhGOPList[layerIdx][offGOP].m_POC;
+            if(offPOC>=0&&m_EhGOPList[layerIdx][offGOP].m_temporalId<=m_EhGOPList[layerIdx][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_EhGOPList[layerIdx][m_iGOPSize+m_extraRPSs[layerIdx]].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_EhGOPList[layerIdx][offGOP].m_temporalId==m_EhGOPList[layerIdx][curGOP].m_temporalId)
+                {
+                  m_EhGOPList[layerIdx][offGOP].m_refPic = true;
+                }
+                for(Int j=0; j<newRefs; j++)
+                {
+                  if(m_EhGOPList[layerIdx][m_iGOPSize+m_extraRPSs[layerIdx]].m_referencePics[j]<offPOC-curPOC||m_EhGOPList[layerIdx][m_iGOPSize+m_extraRPSs[layerIdx]].m_referencePics[j]>0)
+                  {
+                    insertPoint = j;
+                    break;
+                  }
+                }
+                Int prev = offPOC-curPOC;
+                Int prevUsed = m_EhGOPList[layerIdx][offGOP].m_temporalId<=m_EhGOPList[layerIdx][curGOP].m_temporalId;
+                for(Int j=insertPoint; j<newRefs+1; j++)
+                {
+                  Int newPrev = m_EhGOPList[layerIdx][m_iGOPSize+m_extraRPSs[layerIdx]].m_referencePics[j];
+                  Int newUsed = m_EhGOPList[layerIdx][m_iGOPSize+m_extraRPSs[layerIdx]].m_usedByCurrPic[j];
+                  m_EhGOPList[layerIdx][m_iGOPSize+m_extraRPSs[layerIdx]].m_referencePics[j]=prev;
+                  m_EhGOPList[layerIdx][m_iGOPSize+m_extraRPSs[layerIdx]].m_usedByCurrPic[j]=prevUsed;
+                  prevUsed=newUsed;
+                  prev=newPrev;
+                }
+                newRefs++;
+              }
+            }
+            if(newRefs>=numPrefRefs)
+            {
+              break;
+            }
+          }
+          m_EhGOPList[layerIdx][m_iGOPSize+m_extraRPSs[layerIdx]].m_numRefPics=newRefs;
+          m_EhGOPList[layerIdx][m_iGOPSize+m_extraRPSs[layerIdx]].m_POC = curPOC;
+          if (m_extraRPSs[layerIdx] == 0)
+          {
+            m_EhGOPList[layerIdx][m_iGOPSize+m_extraRPSs[layerIdx]].m_interRPSPrediction = 0;
+            m_EhGOPList[layerIdx][m_iGOPSize+m_extraRPSs[layerIdx]].m_numRefIdc = 0;
+          }
+          else
+          {
+            Int rIdx =  m_iGOPSize + m_extraRPSs[layerIdx] - 1;
+            Int refPOC = m_EhGOPList[layerIdx][rIdx].m_POC;
+            Int refPics = m_EhGOPList[layerIdx][rIdx].m_numRefPics;
+            Int newIdc=0;
+            for(Int i = 0; i<= refPics; i++) 
+            {
+              Int deltaPOC = ((i != refPics)? m_EhGOPList[layerIdx][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_EhGOPList[layerIdx][m_iGOPSize+m_extraRPSs[layerIdx]].m_numRefPics; j++)
+              {
+                if ( (absPOCref - curPOC) == m_EhGOPList[layerIdx][m_iGOPSize+m_extraRPSs[layerIdx]].m_referencePics[j])
+                {
+                  if (m_EhGOPList[layerIdx][m_iGOPSize+m_extraRPSs[layerIdx]].m_usedByCurrPic[j])
+                  {
+                    refIdc = 1;
+                  }
+                  else
+                  {
+                    refIdc = 2;
+                  }
+                }
+              }
+              m_EhGOPList[layerIdx][m_iGOPSize+m_extraRPSs[layerIdx]].m_refIdc[newIdc]=refIdc;
+              newIdc++;
+            }
+            m_EhGOPList[layerIdx][m_iGOPSize+m_extraRPSs[layerIdx]].m_interRPSPrediction = 1;  
+            m_EhGOPList[layerIdx][m_iGOPSize+m_extraRPSs[layerIdx]].m_numRefIdc = newIdc;
+            m_EhGOPList[layerIdx][m_iGOPSize+m_extraRPSs[layerIdx]].m_deltaRPS = refPOC - m_EhGOPList[layerIdx][m_iGOPSize+m_extraRPSs[layerIdx]].m_POC; 
+          }
+          curGOP=m_iGOPSize+m_extraRPSs[layerIdx];
+          m_extraRPSs[layerIdx]++;
+        }
+        numRefs=0;
+        for(Int i = 0; i< m_EhGOPList[layerIdx][curGOP].m_numRefPics; i++) 
+        {
+          Int absPOC = curPOC+m_EhGOPList[layerIdx][curGOP].m_referencePics[i];
+          if(absPOC >= 0) 
+          {
+            refList[numRefs]=absPOC;
+            numRefs++;
+          }
+        }
+        refList[numRefs]=curPOC;
+        numRefs++;
+      }
+      checkGOP++;
+    }
+    xConfirmPara(errorGOP,"Invalid GOP structure given");
+  }
+#endif 
+
+  m_maxTempLayer = 1;
+  for(Int i=0; i<m_iGOPSize; i++) 
+  {
+    if(m_GOPList[i].m_temporalId >= m_maxTempLayer)
+    {
+      m_maxTempLayer = m_GOPList[i].m_temporalId+1;
+    }
+    xConfirmPara(m_GOPList[i].m_sliceType!='B' && m_GOPList[i].m_sliceType!='P' && m_GOPList[i].m_sliceType!='I', "Slice type must be equal to B or P or I");
+  }
+
+#if Q0108_TSA_STSA
+  if( layerIdx > 0 )
+  {
+    m_EhMaxTempLayer[layerIdx] = 1;
+    for(Int i=0; i<m_iGOPSize; i++) 
+    {
+      if(m_EhGOPList[layerIdx][i].m_temporalId >= m_EhMaxTempLayer[layerIdx] )
+      {
+        m_EhMaxTempLayer[layerIdx] = m_EhGOPList[layerIdx][i].m_temporalId;
+      }
+      xConfirmPara(m_GOPList[i].m_sliceType!='B'&&m_GOPList[i].m_sliceType!='P'&&m_GOPList[i].m_sliceType!='I', "Slice type must be equal to B or P or I");
+    }
+  }
+#endif
+
+  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 SVC_EXTENSION // ToDo: it should be checked for the case when parameters are different for the layers
+  Int m_iSourceWidth = m_acLayerCfg[layerIdx].m_iSourceWidth;
+  Int m_iSourceHeight = m_acLayerCfg[layerIdx].m_iSourceHeight;
+#if LAYER_CTB
+  Int m_uiMaxCUWidth = m_acLayerCfg[layerIdx].m_uiMaxCUWidth;
+  Int m_uiMaxCUHeight = m_acLayerCfg[layerIdx].m_uiMaxCUHeight;
+#endif
+
+  Bool tileFlag = (m_numTileColumnsMinus1 > 0 || m_numTileRowsMinus1 > 0 );
+  Int m_iWaveFrontSynchro = m_acLayerCfg[layerIdx].m_waveFrontSynchro;
+  xConfirmPara( tileFlag && m_iWaveFrontSynchro,            "Tile and Wavefront can not be applied together");
+#endif
+
+  if(m_vuiParametersPresentFlag && m_bitstreamRestrictionFlag)
+  {
+    Int PicSizeInSamplesY =  m_iSourceWidth * m_iSourceHeight;
+    if(tileFlag)
+    {
+      Int maxTileWidth = 0;
+      Int maxTileHeight = 0;
+      Int widthInCU = (m_iSourceWidth % m_uiMaxCUWidth) ? m_iSourceWidth/m_uiMaxCUWidth + 1: m_iSourceWidth/m_uiMaxCUWidth;
+      Int heightInCU = (m_iSourceHeight % m_uiMaxCUHeight) ? m_iSourceHeight/m_uiMaxCUHeight + 1: m_iSourceHeight/m_uiMaxCUHeight;
+      if(m_tileUniformSpacingFlag)
+      {
+        maxTileWidth = m_uiMaxCUWidth*((widthInCU+m_numTileColumnsMinus1)/(m_numTileColumnsMinus1+1));
+        maxTileHeight = m_uiMaxCUHeight*((heightInCU+m_numTileRowsMinus1)/(m_numTileRowsMinus1+1));
+        // if only the last tile-row is one treeblock higher than the others
+        // the maxTileHeight becomes smaller if the last row of treeblocks has lower height than the others
+        if(!((heightInCU-1)%(m_numTileRowsMinus1+1)))
+        {
+          maxTileHeight = maxTileHeight - m_uiMaxCUHeight + (m_iSourceHeight % m_uiMaxCUHeight);
+        }
+        // if only the last tile-column is one treeblock wider than the others
+        // the maxTileWidth becomes smaller if the last column of treeblocks has lower width than the others
+        if(!((widthInCU-1)%(m_numTileColumnsMinus1+1)))
+        {
+          maxTileWidth = maxTileWidth - m_uiMaxCUWidth + (m_iSourceWidth % m_uiMaxCUWidth);
+        }
+      }
+      else // not uniform spacing
+      {
+        if(m_numTileColumnsMinus1<1)
+        {
+          maxTileWidth = m_iSourceWidth;
+        }
+        else
+        {
+          Int accColumnWidth = 0;
+          for(Int col=0; col<(m_numTileColumnsMinus1); col++)
+          {
+            maxTileWidth = m_tileColumnWidth[col]>maxTileWidth ? m_tileColumnWidth[col]:maxTileWidth;
+            accColumnWidth += m_tileColumnWidth[col];
+          }
+          maxTileWidth = (widthInCU-accColumnWidth)>maxTileWidth ? m_uiMaxCUWidth*(widthInCU-accColumnWidth):m_uiMaxCUWidth*maxTileWidth;
+        }
+        if(m_numTileRowsMinus1<1)
+        {
+          maxTileHeight = m_iSourceHeight;
+        }
+        else
+        {
+          Int accRowHeight = 0;
+          for(Int row=0; row<(m_numTileRowsMinus1); row++)
+          {
+            maxTileHeight = m_tileRowHeight[row]>maxTileHeight ? m_tileRowHeight[row]:maxTileHeight;
+            accRowHeight += m_tileRowHeight[row];
+          }
+          maxTileHeight = (heightInCU-accRowHeight)>maxTileHeight ? m_uiMaxCUHeight*(heightInCU-accRowHeight):m_uiMaxCUHeight*maxTileHeight;
+        }
+      }
+      Int maxSizeInSamplesY = maxTileWidth*maxTileHeight;
+      m_minSpatialSegmentationIdc = 4*PicSizeInSamplesY/maxSizeInSamplesY-4;
+    }
+    else if(m_iWaveFrontSynchro)
+    {
+      m_minSpatialSegmentationIdc = 4*PicSizeInSamplesY/((2*m_iSourceHeight+m_iSourceWidth)*m_uiMaxCUHeight)-4;
+    }
+    else if(m_sliceMode == FIXED_NUMBER_OF_CTU)
+    {
+      m_minSpatialSegmentationIdc = 4*PicSizeInSamplesY/(m_sliceArgument*m_uiMaxCUWidth*m_uiMaxCUHeight)-4;
+    }
+    else
+    {
+      m_minSpatialSegmentationIdc = 0;
+    }
+  }
+#if !SVC_EXTENSION
+  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" );
+#endif
+
+  xConfirmPara( m_decodedPictureHashSEIEnabled<0 || m_decodedPictureHashSEIEnabled>3, "this hash type is not correct!\n");
+
+  if (m_toneMappingInfoSEIEnabled)
+  {
+    xConfirmPara( m_toneMapCodedDataBitDepth < 8 || m_toneMapCodedDataBitDepth > 14 , "SEIToneMapCodedDataBitDepth must be in rage 8 to 14");
+    xConfirmPara( m_toneMapTargetBitDepth < 1 || (m_toneMapTargetBitDepth > 16 && m_toneMapTargetBitDepth < 255) , "SEIToneMapTargetBitDepth must be in rage 1 to 16 or equal to 255");
+    xConfirmPara( m_toneMapModelId < 0 || m_toneMapModelId > 4 , "SEIToneMapModelId must be in rage 0 to 4");
+    xConfirmPara( m_cameraIsoSpeedValue == 0, "SEIToneMapCameraIsoSpeedValue shall not be equal to 0");
+    xConfirmPara( m_exposureIndexValue  == 0, "SEIToneMapExposureIndexValue shall not be equal to 0");
+    xConfirmPara( m_extendedRangeWhiteLevel < 100, "SEIToneMapExtendedRangeWhiteLevel should be greater than or equal to 100");
+    xConfirmPara( m_nominalBlackLevelLumaCodeValue >= m_nominalWhiteLevelLumaCodeValue, "SEIToneMapNominalWhiteLevelLumaCodeValue shall be greater than SEIToneMapNominalBlackLevelLumaCodeValue");
+    xConfirmPara( m_extendedWhiteLevelLumaCodeValue < m_nominalWhiteLevelLumaCodeValue, "SEIToneMapExtendedWhiteLevelLumaCodeValue shall be greater than or equal to SEIToneMapNominalWhiteLevelLumaCodeValue");
+  }
+
+  if (m_kneeSEIEnabled && !m_kneeSEICancelFlag)
+  {
+    xConfirmPara( m_kneeSEINumKneePointsMinus1 < 0 || m_kneeSEINumKneePointsMinus1 > 998, "SEIKneeFunctionNumKneePointsMinus1 must be in the range of 0 to 998");
+    for ( UInt i=0; i<=m_kneeSEINumKneePointsMinus1; i++ ){
+      xConfirmPara( m_kneeSEIInputKneePoint[i] < 1 || m_kneeSEIInputKneePoint[i] > 999, "SEIKneeFunctionInputKneePointValue must be in the range of 1 to 999");
+      xConfirmPara( m_kneeSEIOutputKneePoint[i] < 0 || m_kneeSEIOutputKneePoint[i] > 1000, "SEIKneeFunctionInputKneePointValue must be in the range of 0 to 1000");
+      if ( i > 0 )
+      {
+        xConfirmPara( m_kneeSEIInputKneePoint[i-1] >= m_kneeSEIInputKneePoint[i],  "The i-th SEIKneeFunctionInputKneePointValue must be greater than the (i-1)-th value");
+        xConfirmPara( m_kneeSEIOutputKneePoint[i-1] > m_kneeSEIOutputKneePoint[i],  "The i-th SEIKneeFunctionOutputKneePointValue must be greater than or equal to the (i-1)-th value");
+      }
+    }
+  }
+
+#if P0123_ALPHA_CHANNEL_SEI
+  if( m_alphaSEIEnabled && !m_alphaCancelFlag )
+  {
+    xConfirmPara(0 < m_alphaUseIdc || m_alphaUseIdc > 2, "SEIAlphaUseIdc greater than 2 is reserved for future use by ITU-T | ISO/IEC");
+    xConfirmPara(m_alphaBitDepthMinus8 < 0 || m_alphaBitDepthMinus8 > 7, "SEIAlphaBitDepthMinus8 shall be in the range 0 to 7 inclusive");
+  }
+#endif
+#if Q0096_OVERLAY_SEI
+  if( m_overlaySEIEnabled && !m_overlayInfoCancelFlag )
+  {
+    xConfirmPara( m_overlayContentAuxIdMinus128 < 0 || m_overlayContentAuxIdMinus128 > 31, "SEIOverlayContentAuxIdMinus128 must be in the range of 0 to 31");
+    xConfirmPara( m_overlayLabelAuxIdMinus128 < 0 || m_overlayLabelAuxIdMinus128 > 31, "SEIOverlayLabelAuxIdMinus128 must be in the range of 0 to 31");
+    xConfirmPara( m_overlayAlphaAuxIdMinus128 < 0 || m_overlayAlphaAuxIdMinus128 > 31, "SEIOverlayAlphaAuxIdMinus128 must be in the range of 0 to 31");
+    xConfirmPara( m_numOverlaysMinus1 < 0 || m_numOverlaysMinus1 > 15, "SEIOverlayNumOverlaysMinus1 must be in the range of 0 to 15");
+    for (Int i=0 ; i<=m_numOverlaysMinus1 ; i++ )
+    {
+      xConfirmPara( m_overlayIdx[i] < 0 || m_overlayIdx[i] > 255, "SEIOverlayIdx must be in the range of 0 to 255");
+      xConfirmPara( m_numOverlayElementsMinus1[i] < 0 || m_numOverlayElementsMinus1[i] > 255, "SEIOverlayNumElementsMinus1 must be in the range of 0 to 255");
+    }
+  }
+#endif
+#if Q0074_COLOUR_REMAPPING_SEI
+#if !SVC_EXTENSION
+  if ( m_colourRemapSEIFile && !m_colourRemapSEICancelFlag )
+  {
+    xConfirmPara( m_colourRemapSEIInputBitDepth < 8 || m_colourRemapSEIInputBitDepth > 16 , "colour_remap_input_bit_depth shall be in the range of 8 to 16, inclusive");
+    xConfirmPara( m_colourRemapSEIBitDepth < 8 || m_colourRemapSEIBitDepth > 16, "colour_remap_bit_depth shall be in the range of 8 to 16, inclusive");
+    for( Int c=0 ; c<3 ; c++)
+    {
+      xConfirmPara( m_colourRemapSEIPreLutNumValMinus1[c] < 0 || m_colourRemapSEIPreLutNumValMinus1[c] > 32, "pre_lut_num_val_minus1[c] shall be in the range of 0 to 32, inclusive");
+      if( m_colourRemapSEIPreLutNumValMinus1[c]>0 )
+        for( Int i=0 ; i<=m_colourRemapSEIPreLutNumValMinus1[c] ; i++)
+        {
+          xConfirmPara( m_colourRemapSEIPreLutCodedValue[c][i] < 0 || m_colourRemapSEIPreLutCodedValue[c][i] > ((1<<m_colourRemapSEIInputBitDepth)-1), "pre_lut_coded_value[c][i] shall be in the range of 0 to (1<<colour_remap_input_bit_depth)-1, inclusive");
+          xConfirmPara( m_colourRemapSEIPreLutTargetValue[c][i] < 0 || m_colourRemapSEIPreLutTargetValue[c][i] > ((1<<m_colourRemapSEIBitDepth)-1), "pre_lut_target_value[c][i] shall be in the range of 0 to (1<<colour_remap_bit_depth)-1, inclusive");
+        }
+      xConfirmPara( m_colourRemapSEIPostLutNumValMinus1[c] < 0 || m_colourRemapSEIPostLutNumValMinus1[c] > 32, "post_lut_num_val_minus1[c] shall be in the range of 0 to 32, inclusive");
+      if( m_colourRemapSEIPostLutNumValMinus1[c]>0 )
+        for( Int i=0 ; i<=m_colourRemapSEIPostLutNumValMinus1[c] ; i++)
+        {
+          xConfirmPara( m_colourRemapSEIPostLutCodedValue[c][i] < 0 || m_colourRemapSEIPostLutCodedValue[c][i] > ((1<<m_colourRemapSEIBitDepth)-1), "post_lut_coded_value[c][i] shall be in the range of 0 to (1<<colour_remap_bit_depth)-1, inclusive");
+          xConfirmPara( m_colourRemapSEIPostLutTargetValue[c][i] < 0 || m_colourRemapSEIPostLutTargetValue[c][i] > ((1<<m_colourRemapSEIBitDepth)-1), "post_lut_target_value[c][i] shall be in the range of 0 to (1<<colour_remap_bit_depth)-1, inclusive");
+        }
+    }
+    if ( m_colourRemapSEIMatrixPresentFlag )
+    {
+      xConfirmPara( m_colourRemapSEILog2MatrixDenom < 0 || m_colourRemapSEILog2MatrixDenom > 15, "log2_matrix_denom shall be in the range of 0 to 15, inclusive");
+      for( Int c=0 ; c<3 ; c++)
+        for( Int i=0 ; i<3 ; i++)
+          xConfirmPara( m_colourRemapSEICoeffs[c][i] < -32768 || m_colourRemapSEICoeffs[c][i] > 32767, "colour_remap_coeffs[c][i] shall be in the range of -32768 and 32767, inclusive");
+    }
+  }
+#endif
+#endif
+
+#if RC_SHVC_HARMONIZATION
+  if ( m_acLayerCfg[layerIdx].m_RCEnableRateControl )
+  {
+    if ( m_acLayerCfg[layerIdx].m_RCForceIntraQP )
+    {
+      if ( m_acLayerCfg[layerIdx].m_RCInitialQP == 0 )
+      {
+        printf( "\nInitial QP for rate control is not specified. Reset not to use force intra QP!" );
+        m_acLayerCfg[layerIdx].m_RCForceIntraQP = false;
+      }
+    }
+  }
+  xConfirmPara( m_uiDeltaQpRD > 0, "Rate control cannot be used together with slice level multiple-QP optimization!\n" );
+#else
+  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" );
+  }
+#endif
+
+  xConfirmPara(!m_TransquantBypassEnableFlag && m_CUTransquantBypassFlagForce, "CUTransquantBypassFlagForce cannot be 1 when TransquantBypassEnableFlag is 0");
+
+  xConfirmPara(m_log2ParallelMergeLevel < 2, "Log2ParallelMergeLevel should be larger than or equal to 2");
+
+  if (m_framePackingSEIEnabled)
+  {
+    xConfirmPara(m_framePackingSEIType < 3 || m_framePackingSEIType > 5 , "SEIFramePackingType must be in rage 3 to 5");
+  }
+
+  if (m_segmentedRectFramePackingSEIEnabled)
+  {
+    xConfirmPara(m_framePackingSEIEnabled > 0 , "SEISegmentedRectFramePacking must be 0 when SEIFramePacking is 1");
+  }
+
+  if((m_numTileColumnsMinus1 <= 0) && (m_numTileRowsMinus1 <= 0) && m_tmctsSEIEnabled)
+  {
+    printf("SEITempMotionConstrainedTileSets is set to false to disable 'temporal_motion_constrained_tile_sets' SEI because there are no tiles enabled\n");
+    m_tmctsSEIEnabled = false;
+  }
+
+  if(m_timeCodeSEIEnabled)
+  {
+    xConfirmPara(m_timeCodeSEINumTs > MAX_TIMECODE_SEI_SETS, "Number of time sets cannot exceed 3");
+  }
+
+#if SVC_EXTENSION
+#if VPS_EXTN_DIRECT_REF_LAYERS
+  xConfirmPara( (m_acLayerCfg[0].m_numSamplePredRefLayers != 0) && (m_acLayerCfg[0].m_numSamplePredRefLayers != -1), "Layer 0 cannot have any reference layers" );
+  // NOTE: m_numSamplePredRefLayers  (for any layer) could be -1 (not signalled in cfg), in which case only the "previous layer" would be taken for reference
+  if( layerIdx > 0 )
+  {
+    xConfirmPara(m_acLayerCfg[layerIdx].m_numSamplePredRefLayers > layerIdx, "Cannot reference more layers than before current layer");
+    for(Int i = 0; i < m_acLayerCfg[layerIdx].m_numSamplePredRefLayers; i++)
+    {
+      xConfirmPara(m_acLayerCfg[layerIdx].m_samplePredRefLayerIds[i] > m_acLayerCfg[layerIdx].m_layerId, "Cannot reference higher layers");
+      xConfirmPara(m_acLayerCfg[layerIdx].m_samplePredRefLayerIds[i] == m_acLayerCfg[layerIdx].m_layerId, "Cannot reference the current layer itself");
+    }
+  }
+  xConfirmPara( (m_acLayerCfg[0].m_numMotionPredRefLayers != 0) && (m_acLayerCfg[0].m_numMotionPredRefLayers != -1), "Layer 0 cannot have any reference layers" );
+  // NOTE: m_numMotionPredRefLayers  (for any layer) could be -1 (not signalled in cfg), in which case only the "previous layer" would be taken for reference
+  if( layerIdx > 0 )
+  {
+    xConfirmPara(m_acLayerCfg[layerIdx].m_numMotionPredRefLayers > layerIdx, "Cannot reference more layers than before current layer");
+    for(Int i = 0; i < m_acLayerCfg[layerIdx].m_numMotionPredRefLayers; i++)
+    {
+      xConfirmPara(m_acLayerCfg[layerIdx].m_motionPredRefLayerIds[i] > m_acLayerCfg[layerIdx].m_layerId, "Cannot reference higher layers");
+      xConfirmPara(m_acLayerCfg[layerIdx].m_motionPredRefLayerIds[i] == m_acLayerCfg[layerIdx].m_layerId, "Cannot reference the current layer itself");
+    }
+  }
+
+  xConfirmPara( (m_acLayerCfg[0].m_numActiveRefLayers != 0) && (m_acLayerCfg[0].m_numActiveRefLayers != -1), "Layer 0 cannot have any active reference layers" );
+  // NOTE: m_numActiveRefLayers  (for any layer) could be -1 (not signalled in cfg), in which case only the "previous layer" would be taken for reference
+  if( layerIdx > 0 )
+  {
+    Bool predEnabledFlag[MAX_LAYERS];
+    for (Int refLayer = 0; refLayer < layerIdx; refLayer++)
+    {
+      predEnabledFlag[refLayer] = false;
+    }
+    for(Int i = 0; i < m_acLayerCfg[layerIdx].m_numSamplePredRefLayers; i++)
+    {
+      predEnabledFlag[m_acLayerCfg[layerIdx].m_samplePredRefLayerIds[i]] = true;
+    }
+    for(Int i = 0; i < m_acLayerCfg[layerIdx].m_numMotionPredRefLayers; i++)
+    {
+      predEnabledFlag[m_acLayerCfg[layerIdx].m_motionPredRefLayerIds[i]] = true;
+    }
+    Int numDirectRefLayers = 0;
+    for (Int refLayer = 0; refLayer < layerIdx; refLayer++)
+    {
+      if (predEnabledFlag[refLayer] == true) numDirectRefLayers++;
+    }
+    xConfirmPara(m_acLayerCfg[layerIdx].m_numActiveRefLayers > numDirectRefLayers, "Cannot reference more layers than NumDirectRefLayers");
+    for(Int i = 0; i < m_acLayerCfg[layerIdx].m_numActiveRefLayers; i++)
+    {
+      xConfirmPara(m_acLayerCfg[layerIdx].m_predLayerIds[i] >= numDirectRefLayers, "Cannot reference higher layers");
+    }
+  }
+#endif //VPS_EXTN_DIRECT_REF_LAYERS
+#if M0040_ADAPTIVE_RESOLUTION_CHANGE
+  if (m_adaptiveResolutionChange > 0)
+  {
+    xConfirmPara(m_numLayers != 2, "Adaptive resolution change works with 2 layers only");
+    xConfirmPara(m_acLayerCfg[1].m_iIntraPeriod == 0 || (m_adaptiveResolutionChange % m_acLayerCfg[1].m_iIntraPeriod) != 0, "Adaptive resolution change must happen at enhancement layer RAP picture");
+  }
+#endif
+#if HIGHER_LAYER_IRAP_SKIP_FLAG
+  if (m_adaptiveResolutionChange > 0)
+  {
+    xConfirmPara(m_crossLayerIrapAlignFlag != 0, "Cross layer IRAP alignment must be disabled when using adaptive resolution change.");
+  }
+  if (m_skipPictureAtArcSwitch)
+  {
+    xConfirmPara(m_adaptiveResolutionChange <= 0, "Skip picture at ARC switching only works when Adaptive Resolution Change is active (AdaptiveResolutionChange > 0)");
+  }
+#endif
+  if( layerIdx < MAX_LAYERS-1 )
+  {
+    xConfirmPara(m_acLayerCfg[layerIdx].m_maxTidIlRefPicsPlus1 < 0 || m_acLayerCfg[layerIdx].m_maxTidIlRefPicsPlus1 > 7, "MaxTidIlRefPicsPlus1 must be in range 0 to 7");
+  }
+#if AUXILIARY_PICTURES
+  if( layerIdx < MAX_LAYERS-1 )
+  {
+#if R0062_AUX_PSEUDO_MONOCHROME
+    xConfirmPara(m_acLayerCfg[layerIdx].m_auxId < 0 || m_acLayerCfg[layerIdx].m_auxId > 2, "AuxId must be in range 0 to 2");
+#else
+    xConfirmPara(m_acLayerCfg[layerIdx].m_auxId < 0 || m_acLayerCfg[layerIdx].m_auxId > 4, "AuxId must be in range 0 to 4");
+    xConfirmPara(m_acLayerCfg[layerIdx].m_auxId > 0 && m_acLayerCfg[layerIdx].m_chromaFormatIDC != CHROMA_400, "Auxiliary picture must be monochrome picture");
+#endif
+  }
+#endif 
+#if Q0048_CGS_3D_ASYMLUT
+  xConfirmPara( m_nCGSFlag < 0 || m_nCGSFlag > 1 , "0<=CGS<=1" );
+#endif
+#endif //SVC_EXTENSION
+#undef xConfirmPara
+  if (check_failed)
+  {
+    exit(EXIT_FAILURE);
+  }
+}
+
+/** \todo use of global variables should be removed later
+ */
+#if LAYER_CTB
+Void TAppEncCfg::xSetGlobal(UInt layerId)
+{
+  // set max CU width & height
+  g_auiLayerMaxCUWidth[layerId]  = m_acLayerCfg[layerId].m_uiMaxCUWidth;
+  g_auiLayerMaxCUHeight[layerId] = m_acLayerCfg[layerId].m_uiMaxCUHeight;
+  
+  // compute actual CU depth with respect to config depth and max transform size
+  g_auiLayerAddCUDepth[layerId]  = 0;
+  while( (m_acLayerCfg[layerId].m_uiMaxCUWidth>>m_acLayerCfg[layerId].m_uiMaxCUDepth) > ( 1 << ( m_acLayerCfg[layerId].m_uiQuadtreeTULog2MinSize + g_auiLayerAddCUDepth[layerId] )  ) ) g_auiLayerAddCUDepth[layerId]++;
+  
+  m_acLayerCfg[layerId].m_uiMaxCUDepth += g_auiLayerAddCUDepth[layerId];
+  g_auiLayerAddCUDepth[layerId]++;
+  g_auiLayerMaxCUDepth[layerId] = m_acLayerCfg[layerId].m_uiMaxCUDepth;
+  
+#if O0194_DIFFERENT_BITDEPTH_EL_BL
+  // set internal bit-depth to constant value to make sure to be updated later
+  g_bitDepthY = -1;
+  g_bitDepthC = -1;
+  
+  g_uiPCMBitDepthLuma = -1;
+  g_uiPCMBitDepthChroma = -1;
+#else
+  // 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;
+#endif
+}
+#else
+Void TAppEncCfg::xSetGlobal()
+{
+#if SVC_EXTENSION
+  // Check for layerIdx equal to 0, it has to pe extended to other layers.
+  UInt layerIdx = 0;
+  Bool m_useExtendedPrecision = m_acLayerCfg[layerIdx].m_useExtendedPrecision;
+  Int m_internalBitDepth[]    = {m_acLayerCfg[layerIdx].m_internalBitDepth[CHANNEL_TYPE_LUMA], m_acLayerCfg[layerIdx].m_internalBitDepth[CHANNEL_TYPE_CHROMA]};
+  Int m_MSBExtendedBitDepth[] = {m_acLayerCfg[layerIdx].m_MSBExtendedBitDepth[CHANNEL_TYPE_LUMA], m_acLayerCfg[layerIdx].m_MSBExtendedBitDepth[CHANNEL_TYPE_CHROMA]};
+  ChromaFormat m_chromaFormatIDC = m_acLayerCfg[layerIdx].m_chromaFormatIDC;
+#endif
+
+  // 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++;
+
+  g_uiAddCUDepth+=getMaxCUDepthOffset(m_chromaFormatIDC, m_uiQuadtreeTULog2MinSize); // if minimum TU larger than 4x4, allow for additional part indices for 4:2:2 SubTUs.
+
+  m_uiMaxCUDepth += g_uiAddCUDepth;
+  g_uiAddCUDepth++;
+  g_uiMaxCUDepth = m_uiMaxCUDepth;
+
+  // set internal bit-depth and constants
+  for (UInt channelType = 0; channelType < MAX_NUM_CHANNEL_TYPE; channelType++)
+  {
+#if O0043_BEST_EFFORT_DECODING
+    g_bitDepthInStream[channelType] = g_bitDepth[channelType] = m_internalBitDepth[channelType];
+#else
+    g_bitDepth   [channelType] = m_internalBitDepth[channelType];
+#endif
+    g_PCMBitDepth[channelType] = m_bPCMInputBitDepthFlag ? m_MSBExtendedBitDepth[channelType] : m_internalBitDepth[channelType];
+
+    if (m_useExtendedPrecision) g_maxTrDynamicRange[channelType] = std::max<Int>(15, (g_bitDepth[channelType] + 6));
+    else                        g_maxTrDynamicRange[channelType] = 15;
+  }
+
+}
+#endif
+
+const Char *profileToString(const Profile::Name profile)
+{
+  static const UInt numberOfProfiles = sizeof(strToProfile)/sizeof(*strToProfile);
+
+  for (UInt profileIndex = 0; profileIndex < numberOfProfiles; profileIndex++)
+  {
+    if (strToProfile[profileIndex].value == profile) return strToProfile[profileIndex].str;
+  }
+
+  //if we get here, we didn't find this profile in the list - so there is an error
+  std::cerr << "ERROR: Unknown profile \"" << profile << "\" in profileToString" << std::endl;
+  assert(false);
+  exit(1);
+  return "";
+}
+
+Void TAppEncCfg::xPrintParameter()
+{
+  printf("\n");
+#if SVC_EXTENSION  
+  printf("Total number of layers            : %d\n", m_numLayers       );
+  printf("Multiview                         : %d\n", m_scalabilityMask[VIEW_ORDER_INDEX] );
+  printf("Scalable                          : %d\n", m_scalabilityMask[SCALABILITY_ID] );
+#if AVC_BASE
+#if VPS_AVC_BL_FLAG_REMOVAL
+  printf("Base layer                        : %s\n", m_nonHEVCBaseLayerFlag ? "Non-HEVC" : "HEVC");
+#else
+  printf("Base layer                        : %s\n", m_avcBaseLayerFlag ? "AVC" : "HEVC");
+#endif
+#endif
+#if AUXILIARY_PICTURES
+  printf("Auxiliary pictures                : %d\n", m_scalabilityMask[AUX_ID] );
+#endif
+#if M0040_ADAPTIVE_RESOLUTION_CHANGE
+  printf("Adaptive Resolution Change        : %d\n", m_adaptiveResolutionChange );
+#endif
+#if HIGHER_LAYER_IRAP_SKIP_FLAG
+  printf("Skip picture at ARC switch        : %d\n", m_skipPictureAtArcSwitch );
+#endif
+#if O0223_PICTURE_TYPES_ALIGN_FLAG
+  printf("Align picture type                : %d\n", m_crossLayerPictureTypeAlignFlag );
+#endif
+  printf("Cross layer IRAP alignment        : %d\n", m_crossLayerIrapAlignFlag );
+#if P0068_CROSS_LAYER_ALIGNED_IDR_ONLY_FOR_IRAP_FLAG
+  printf("IDR only for IRAP                 : %d\n", m_crossLayerAlignedIdrOnlyFlag );
+#endif
+#if O0194_WEIGHTED_PREDICTION_CGS
+  printf("InterLayerWeightedPred            : %d\n", m_useInterLayerWeightedPred );
+#endif
+#if O0215_PHASE_ALIGNMENT  
+  printf("Cross-layer sample alignment      : %d\n", m_phaseAlignFlag);
+#endif
+  printf("\n");
+  for(UInt layer=0; layer<m_numLayers; layer++)
+  {
+    printf("=== Layer %d settings === \n", layer);
+    m_acLayerCfg[layer].xPrintParameter();
+    printf("\n");
+  }
+  printf("=== Common configuration settings === \n");
+  printf("Bitstream      File               : %s\n", m_pBitstreamFile      );
+#else //SVC_EXTENSION
+  printf("Input          File               : %s\n", m_pchInputFile          );
+  printf("Bitstream      File               : %s\n", m_pchBitstreamFile      );
+  printf("Reconstruction File               : %s\n", m_pchReconFile          );
+  printf("Real     Format                   : %dx%d %dHz\n", m_iSourceWidth - m_confWinLeft - m_confWinRight, m_iSourceHeight - m_confWinTop - m_confWinBottom, m_iFrameRate );
+  printf("Internal Format                   : %dx%d %dHz\n", m_iSourceWidth, m_iSourceHeight, m_iFrameRate );
+#endif //SVC_EXTENSION
+
+  printf("Sequence PSNR output              : %s\n", (m_printMSEBasedSequencePSNR ? "Linear average, MSE-based" : "Linear average only") );
+  printf("Sequence MSE output               : %s\n", (m_printSequenceMSE ? "Enabled" : "Disabled") );
+  printf("Frame MSE output                  : %s\n", (m_printFrameMSE    ? "Enabled" : "Disabled") );
+  printf("Cabac-zero-word-padding           : %s\n", (m_cabacZeroWordPaddingEnabled? "Enabled" : "Disabled") );
+  if (m_isField)
+  {
+    printf("Frame/Field                       : Field based coding\n");
+    printf("Field index                       : %u - %d (%d fields)\n", m_FrameSkip, m_FrameSkip+m_framesToBeEncoded-1, m_framesToBeEncoded );
+    printf("Field Order                       : %s field first\n", m_isTopFieldFirst?"Top":"Bottom");
+
+  }
+  else
+  {
+    printf("Frame/Field                       : Frame based coding\n");
+    printf("Frame index                       : %u - %d (%d frames)\n", m_FrameSkip, m_FrameSkip+m_framesToBeEncoded-1, m_framesToBeEncoded );
+  }
+#if !MULTIPLE_PTL_SUPPORT
+  if (m_profile == Profile::MAINREXT)
+  {
+    const UInt intraIdx = m_intraConstraintFlag ? 1:0;
+    const UInt bitDepthIdx = (m_bitDepthConstraint == 8 ? 0 : (m_bitDepthConstraint ==10 ? 1 : (m_bitDepthConstraint == 12 ? 2 : (m_bitDepthConstraint == 16 ? 3 : 4 ))));
+    const UInt chromaFormatIdx = UInt(m_chromaFormatConstraint);
+    const ExtendedProfileName validProfileName = (bitDepthIdx > 3 || chromaFormatIdx>3) ? NONE : validRExtProfileNames[intraIdx][bitDepthIdx][chromaFormatIdx];
+    std::string rextSubProfile;
+    if (validProfileName!=NONE) rextSubProfile=enumToString(strToExtendedProfile, sizeof(strToExtendedProfile)/sizeof(*strToExtendedProfile), validProfileName);
+    if (rextSubProfile == "main_444_16") rextSubProfile="main_444_16 [NON STANDARD]";
+    printf("Profile                           : %s (%s)\n", profileToString(m_profile), (rextSubProfile.empty())?"INVALID REXT PROFILE":rextSubProfile.c_str() );
+  }
+  else
+  {
+    printf("Profile                           : %s\n", profileToString(m_profile) );
+  }
+#endif
+#if !LAYER_CTB
+  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);
+#endif
+  printf("Min PCM size                      : %d\n", 1 << m_uiPCMLog2MinSize);
+  printf("Motion search range               : %d\n", m_iSearchRange );
+#if !SVC_EXTENSION
+  printf("Intra period                      : %d\n", m_iIntraPeriod );
+#endif
+  printf("Decoding refresh type             : %d\n", m_iDecodingRefreshType );
+#if !SVC_EXTENSION
+  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("Max CU chroma QP adjustment depth : %d\n", m_maxCUChromaQpAdjustmentDepth);
+  printf("QP adaptation                     : %d (range=%d)\n", m_bUseAdaptiveQP, (m_bUseAdaptiveQP ? m_iQPAdaptationRange : 0) );
+  printf("GOP size                          : %d\n", m_iGOPSize );
+#if !O0194_DIFFERENT_BITDEPTH_EL_BL
+  printf("Input bit depth                   : (Y:%d, C:%d)\n", m_inputBitDepth[CHANNEL_TYPE_LUMA], m_inputBitDepth[CHANNEL_TYPE_CHROMA] );
+  printf("MSB-extended bit depth            : (Y:%d, C:%d)\n", m_MSBExtendedBitDepth[CHANNEL_TYPE_LUMA], m_MSBExtendedBitDepth[CHANNEL_TYPE_CHROMA] );
+  printf("Internal bit depth                : (Y:%d, C:%d)\n", m_internalBitDepth[CHANNEL_TYPE_LUMA], m_internalBitDepth[CHANNEL_TYPE_CHROMA] );
+  printf("PCM sample bit depth              : (Y:%d, C:%d)\n", g_PCMBitDepth[CHANNEL_TYPE_LUMA],      g_PCMBitDepth[CHANNEL_TYPE_CHROMA] );
+  printf("Extended precision processing     : %s\n", (m_useExtendedPrecision                   ? "Enabled" : "Disabled") );
+#endif
+  printf("Intra reference smoothing         : %s\n", (m_enableIntraReferenceSmoothing          ? "Enabled" : "Disabled") );
+  printf("Implicit residual DPCM            : %s\n", (m_useResidualDPCM[RDPCM_SIGNAL_IMPLICIT] ? "Enabled" : "Disabled") );
+  printf("Explicit residual DPCM            : %s\n", (m_useResidualDPCM[RDPCM_SIGNAL_EXPLICIT] ? "Enabled" : "Disabled") );
+  printf("Residual rotation                 : %s\n", (m_useResidualRotation                    ? "Enabled" : "Disabled") );
+  printf("Single significance map context   : %s\n", (m_useSingleSignificanceMapContext        ? "Enabled" : "Disabled") );
+  printf("Cross-component prediction        : %s\n", (m_useCrossComponentPrediction            ? (m_reconBasedCrossCPredictionEstimate ? "Enabled (reconstructed-residual-based estimate)" : "Enabled (encoder-side-residual-based estimate)") : "Disabled") );
+#if !O0194_DIFFERENT_BITDEPTH_EL_BL
+  printf("High-precision prediction weight  : %s\n", (m_useHighPrecisionPredictionWeighting    ? "Enabled" : "Disabled") );
+#endif
+  printf("Golomb-Rice parameter adaptation  : %s\n", (m_useGolombRiceParameterAdaptation       ? "Enabled" : "Disabled") );
+  printf("CABAC bypass bit alignment        : %s\n", (m_alignCABACBeforeBypass                 ? "Enabled" : "Disabled") );
+  if (m_bUseSAO)
+  {
+    printf("Sao Luma Offset bit shifts        : %d\n", m_saoOffsetBitShift[CHANNEL_TYPE_LUMA]);
+    printf("Sao Chroma Offset bit shifts      : %d\n", m_saoOffsetBitShift[CHANNEL_TYPE_CHROMA]);
+  }
+
+  switch (m_costMode)
+  {
+    case COST_STANDARD_LOSSY:               printf("Cost function:                    : Lossy coding (default)\n"); break;
+    case COST_SEQUENCE_LEVEL_LOSSLESS:      printf("Cost function:                    : Sequence_level_lossless coding\n"); break;
+    case COST_LOSSLESS_CODING:              printf("Cost function:                    : Lossless coding with fixed QP of %d\n", LOSSLESS_AND_MIXED_LOSSLESS_RD_COST_TEST_QP); break;
+    case COST_MIXED_LOSSLESS_LOSSY_CODING:  printf("Cost function:                    : Mixed_lossless_lossy coding with QP'=%d for lossless evaluation\n", LOSSLESS_AND_MIXED_LOSSLESS_RD_COST_TEST_QP_PRIME); break;
+    default:                                printf("Cost function:                    : Unknown\n"); break;
+  }
+
+#if !RC_SHVC_HARMONIZATION
+  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 );
+  }
+#endif
+
+  printf("Max Num Merge Candidates          : %d\n", m_maxNumMergeCand);
+  printf("\n");
+
+  printf("TOOL CFG: ");
+#if !O0194_DIFFERENT_BITDEPTH_EL_BL
+  printf("IBD:%d ", ((g_bitDepth[CHANNEL_TYPE_LUMA] > m_MSBExtendedBitDepth[CHANNEL_TYPE_LUMA]) || (g_bitDepth[CHANNEL_TYPE_CHROMA] > m_MSBExtendedBitDepth[CHANNEL_TYPE_CHROMA])));
+#endif
+  printf("HAD:%d ", m_bUseHADME           );
+  printf("RDQ:%d ", m_useRDOQ            );
+  printf("RDQTS:%d ", m_useRDOQTS        );
+  printf("RDpenalty:%d ", m_rdPenalty  );
+  printf("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  );
+#if FAST_INTRA_SHVC
+  printf("FIS:%d ", m_useFastIntraScalable  );
+#endif
+  printf("RQT:%d ", 1     );
+  printf("TransformSkip:%d ",     m_useTransformSkip              );
+  printf("TransformSkipFast:%d ", m_useTransformSkipFast       );
+  printf("TransformSkipLog2MaxSize:%d ", m_transformSkipLog2MaxSize);
+  printf("Slice: M=%d ", m_sliceMode);
+  if (m_sliceMode!=NO_SLICES)
+  {
+    printf("A=%d ", m_sliceArgument);
+  }
+  printf("SliceSegment: M=%d ",m_sliceSegmentMode);
+  if (m_sliceSegmentMode!=NO_SLICES)
+  {
+    printf("A=%d ", m_sliceSegmentArgument);
+  }
+  printf("CIP:%d ", m_bUseConstrainedIntraPred);
+  printf("SAO:%d ", (m_bUseSAO)?(1):(0));
+#if !LAYER_CTB
+  printf("PCM:%d ", (m_usePCM && (1<<m_uiPCMLog2MinSize) <= m_uiMaxCUWidth)? 1 : 0);
+#endif
+
+  if (m_TransquantBypassEnableFlag && m_CUTransquantBypassFlagForce)
+  {
+    printf("TransQuantBypassEnabled: =1");
+  }
+  else
+  {
+    printf("TransQuantBypassEnabled:%d ", (m_TransquantBypassEnableFlag)? 1:0 );
+  }
+
+  printf("WPP:%d ", (Int)m_useWeightedPred);
+  printf("WPB:%d ", (Int)m_useWeightedBiPred);
+  printf("PME:%d ", m_log2ParallelMergeLevel);
+#if !SVC_EXTENSION
+  printf(" WaveFrontSynchro:%d WaveFrontSubstreams:%d",
+          m_iWaveFrontSynchro, m_iWaveFrontSubstreams);
+#endif
+  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);
+#if SVC_EXTENSION
+  printf("RecalQP:%d ", m_recalculateQPAccordingToLambda ? 1 : 0 );
+  printf("EL_RAP_SliceType: %d ", m_elRapSliceBEnabled);
+  printf("REF_IDX_ME_ZEROMV: %d ", REF_IDX_ME_ZEROMV);
+  printf("ENCODER_FAST_MODE: %d ", ENCODER_FAST_MODE);
+  printf("REF_IDX_MFM: %d ", REF_IDX_MFM);
+  printf("O0194_DIFFERENT_BITDEPTH_EL_BL: %d ", O0194_DIFFERENT_BITDEPTH_EL_BL);
+  printf("O0194_JOINT_US_BITSHIFT: %d ", O0194_JOINT_US_BITSHIFT);
+#else
+  printf("RecalQP:%d", m_recalculateQPAccordingToLambda ? 1 : 0 );
+#endif
+#if Q0048_CGS_3D_ASYMLUT
+  printf("CGS: %d CGSMaxOctantDepth: %d CGSMaxYPartNumLog2: %d CGSLUTBit:%d " , m_nCGSFlag , m_nCGSMaxOctantDepth , m_nCGSMaxYPartNumLog2 , m_nCGSLUTBit );
+#endif
+#if R0151_CGS_3D_ASYMLUT_IMPROVE
+  printf("CGSAdaptC:%d " , m_nCGSAdaptiveChroma );
+#endif
+#if R0179_ENC_OPT_3DLUT_SIZE
+  printf("CGSSizeRDO:%d " , m_nCGSLutSizeRDO );
+#endif
+
+  printf("\n\n");
+
+  fflush(stdout);
+}
+
+Bool confirmPara(Bool bflag, const Char* message)
+{
+  if (!bflag)
+    return false;
+
+  printf("Error: %s\n",message);
+  return true;
+}
+
+#if SVC_EXTENSION
+#if OUTPUT_LAYER_SETS_CONFIG
+Void TAppEncCfg::cfgStringToArray(Int **arr, string const cfgString, Int const numEntries, const char* logString)
+#else
+Void TAppEncCfg::cfgStringToArray(Int **arr, string cfgString, Int numEntries, const char* logString)
+#endif
+{
+  Char *tempChar = cfgString.empty() ? NULL : strdup(cfgString.c_str());
+  if( numEntries > 0 )
+  {
+    Char *arrayEntry;
+    Int i = 0;
+    *arr = new Int[numEntries];
+
+#if OUTPUT_LAYER_SETS_CONFIG
+    if( tempChar == NULL )
+    {
+      arrayEntry = NULL;
+    }
+    else
+    {
+      arrayEntry = strtok( tempChar, " ,");
+    }
+#else
+    arrayEntry = strtok( tempChar, " ,");
+#endif
+    while(arrayEntry != NULL)
+    {
+      if( i >= numEntries )
+      {
+        printf( "%s: The number of entries specified is larger than the allowed number.\n", logString );
+        exit( EXIT_FAILURE );
+      }
+      *( *arr + i ) = atoi( arrayEntry );
+      arrayEntry = strtok(NULL, " ,");
+      i++;
+    }
+    if( i < numEntries )
+    {
+      printf( "%s: Some entries are not specified.\n", logString );
+      exit( EXIT_FAILURE );
+    }
+  }
+  else
+  {
+    *arr = NULL;
+  }
+
+  if( tempChar )
+  {
+    free( tempChar );
+    tempChar = NULL;
+  }
+}
+
+#if OUTPUT_LAYER_SETS_CONFIG
+Bool TAppEncCfg::scanStringToArray(string const cfgString, Int const numEntries, const char* logString, Int * const returnArray)
+{
+  Int *tempArray = NULL;
+  // For all layer sets
+  cfgStringToArray( &tempArray, cfgString, numEntries, logString );
+  if(tempArray)
+  {
+    for(Int i = 0; i < numEntries; i++)
+    {
+      returnArray[i] = tempArray[i];
+    }
+    delete [] tempArray; tempArray = NULL;
+    return true;
+  }
+  return false;
+}
+Bool TAppEncCfg::scanStringToArray(string const cfgString, Int const numEntries, const char* logString, std::vector<Int> & returnVector)
+{
+  Int *tempArray = NULL;
+  // For all layer sets
+  cfgStringToArray( &tempArray, cfgString, numEntries, logString );
+  if(tempArray)
+  {
+    returnVector.empty();
+    for(Int i = 0; i < numEntries; i++)
+    {
+      returnVector.push_back(tempArray[i]);
+    }
+    delete [] tempArray; tempArray = NULL;
+    return true;
+  }
+  return false;
+}
+#endif
+
+#if R0235_SMALLEST_LAYER_ID
+#if OUTPUT_LAYER_SETS_CONFIG
+Void TAppEncCfg::cfgStringToArrayNumEntries(Int **arr, string const cfgString, Int &numEntries, const char* logString)
+{
+  Char *tempChar = cfgString.empty() ? NULL : strdup(cfgString.c_str());
+  if (numEntries > 0)
+  {
+    Char *arrayEntry;
+    Int i = 0;
+    *arr = new Int[numEntries];
+
+    if (tempChar == NULL)
+    {
+      arrayEntry = NULL;
+    }
+    else
+    {
+      arrayEntry = strtok(tempChar, " ,");
+    }
+    while (arrayEntry != NULL)
+    {
+      if (i >= numEntries)
+      {
+        printf("%s: The number of entries specified is larger than the allowed number.\n", logString);
+        exit(EXIT_FAILURE);
+      }
+      *(*arr + i) = atoi(arrayEntry);
+      arrayEntry = strtok(NULL, " ,");
+      i++;
+    }
+    numEntries = i;
+    /*
+    if (i < numEntries)
+    {
+      printf("%s: Some entries are not specified.\n", logString);
+      exit(EXIT_FAILURE);
+    }
+    */
+  }
+  else
+  {
+    *arr = NULL;
+  }
+
+  if (tempChar)
+  {
+    free(tempChar);
+    tempChar = NULL;
+  }
+}
+
+Bool TAppEncCfg::scanStringToArrayNumEntries(string const cfgString, Int &numEntries, const char* logString, std::vector<Int> & returnVector)
+{
+  Int *tempArray = NULL;
+  numEntries = MAX_LAYERS;
+  // For all layer sets
+  cfgStringToArrayNumEntries(&tempArray, cfgString, numEntries, logString);
+  if (tempArray)
+  {
+    returnVector.empty();
+    for (Int i = 0; i < numEntries; i++)
+    {
+      returnVector.push_back(tempArray[i]);
+    }
+    delete[] tempArray; tempArray = NULL;
+    return true;
+  }
+  return false;
+}
+#endif
+#endif // R0235
+#endif //SVC_EXTENSION
+//! \}
Index: /tags/SHM-9.0/source/App/TAppEncoder/TAppEncCfg.h
===================================================================
--- /tags/SHM-9.0/source/App/TAppEncoder/TAppEncCfg.h	(revision 1088)
+++ /tags/SHM-9.0/source/App/TAppEncoder/TAppEncCfg.h	(revision 1088)
@@ -0,0 +1,621 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TAppEncCfg.h
+    \brief    Handle encoder configuration parameters (header)
+*/
+
+#ifndef __TAPPENCCFG__
+#define __TAPPENCCFG__
+
+#include "TLibCommon/CommonDef.h"
+
+#include "TLibEncoder/TEncCfg.h"
+#if SVC_EXTENSION
+#include "TAppEncLayerCfg.h"
+#endif
+#include <sstream>
+#include <vector>
+//! \ingroup TAppEncoder
+//! \{
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// encoder configuration class
+class TAppEncCfg
+{
+protected:
+  // file I/O
+#if SVC_EXTENSION
+  TAppEncLayerCfg m_acLayerCfg [MAX_LAYERS];
+  Int       m_layerId;
+  Int       m_numLayers;                                      ///< number of layers
+  Int       m_scalabilityMask[MAX_VPS_NUM_SCALABILITY_TYPES]; ///< scalability_mask
+  Char*     m_pBitstreamFile;                                 ///< output bitstream file
+  Double    m_adLambdaModifier[ MAX_TLAYER ];                 ///< Lambda modifier array for each temporal layer
+  // source specification
+  UInt      m_FrameSkip;                                      ///< number of skipped frames from the beginning
+  Int       m_framesToBeEncoded;                              ///< number of encoded frames
+#if AVC_BASE
+#if VPS_AVC_BL_FLAG_REMOVAL
+  Int       m_nonHEVCBaseLayerFlag;                           ///< non HEVC BL
+#else
+  Int       m_avcBaseLayerFlag;                               ///< avc_baselayer_flag
+#endif
+#endif
+  Bool      m_maxTidRefPresentFlag; 
+#if Q0078_ADD_LAYER_SETS
+  Int       m_numLayerSets;
+  Int       m_numLayerInIdList[MAX_VPS_LAYER_SETS_PLUS1];
+  Int       m_layerSetLayerIdList[MAX_VPS_LAYER_SETS_PLUS1][MAX_VPS_LAYER_IDX_PLUS1];
+  Int       m_numAddLayerSets;
+  Int       m_numHighestLayerIdx[MAX_VPS_LAYER_SETS_PLUS1];
+  Int       m_highestLayerIdx[MAX_VPS_LAYER_SETS_PLUS1][MAX_VPS_LAYER_IDX_PLUS1];
+#endif
+#if OUTPUT_LAYER_SETS_CONFIG
+  std::vector<Int>                m_outputLayerSetIdx;
+  Int       m_defaultTargetOutputLayerIdc;
+  Int       m_numOutputLayerSets;
+  std::vector<Int>                m_numOutputLayersInOutputLayerSet;
+  std::vector< std::vector<Int> > m_listOfOutputLayers;
+#endif
+  Bool      m_isField;                                        ///< enable field coding
+  Bool      m_isTopFieldFirst;
+#else
+  Char*     m_pchInputFile;                                   ///< source file name
+  Char*     m_pchBitstreamFile;                               ///< output bitstream file
+  Char*     m_pchReconFile;                                   ///< output reconstruction file
+  Double    m_adLambdaModifier[ MAX_TLAYER ];                 ///< Lambda modifier array for each temporal layer
+  // source specification
+  Int       m_iFrameRate;                                     ///< source frame-rates (Hz)
+  UInt      m_FrameSkip;                                   ///< number of skipped frames from the beginning
+  Int       m_iSourceWidth;                                   ///< source width in pixel
+  Int       m_iSourceHeight;                                  ///< source height in pixel (when interlaced = field height)
+
+  Int       m_iSourceHeightOrg;                               ///< original source height in pixel (when interlaced = frame height)
+
+  Bool      m_isField;                                        ///< enable field coding
+  Bool      m_isTopFieldFirst;
+
+  Int       m_conformanceWindowMode;
+  Int       m_confWinLeft;
+  Int       m_confWinRight;
+  Int       m_confWinTop;
+  Int       m_confWinBottom;
+  Int       m_framesToBeEncoded;                              ///< number of encoded frames
+  Int       m_aiPad[2];                                       ///< number of padded pixels for width and height
+#endif  
+  InputColourSpaceConversion m_inputColourSpaceConvert;       ///< colour space conversion to apply to input video
+  Bool      m_snrInternalColourSpace;                       ///< if true, then no colour space conversion is applied for snr calculation, otherwise inverse of input is applied.
+  Bool      m_outputInternalColourSpace;                    ///< if true, then no colour space conversion is applied for reconstructed video, otherwise inverse of input is applied.
+#if !SVC_EXTENSION
+  ChromaFormat m_InputChromaFormatIDC;
+#endif
+
+  Bool      m_printMSEBasedSequencePSNR;
+  Bool      m_printFrameMSE;
+  Bool      m_printSequenceMSE;
+  Bool      m_cabacZeroWordPaddingEnabled;
+
+#if MULTIPLE_PTL_SUPPORT
+  Int           m_numPTLInfo;
+  Profile::Name m_profileList[MAX_NUM_LAYER_IDS + 1];
+  Level::Tier   m_levelTierList[MAX_NUM_LAYER_IDS + 1];
+  Level::Name   m_levelList[MAX_NUM_LAYER_IDS + 1];
+  Profile::Name m_profileCompatibility[MAX_NUM_LAYER_IDS + 1];
+  Bool          m_progressiveSourceFlagList[MAX_NUM_LAYER_IDS + 1];
+  Bool          m_interlacedSourceFlagList[MAX_NUM_LAYER_IDS + 1];
+  Bool          m_nonPackedConstraintFlagList[MAX_NUM_LAYER_IDS + 1];
+  Bool          m_frameOnlyConstraintFlagList[MAX_NUM_LAYER_IDS + 1];
+
+  std::vector< std::vector<Int> > m_listOfLayerPTLofOlss;
+#else
+  // profile/level
+  Profile::Name m_profile;
+  Level::Tier   m_levelTier;
+  Level::Name   m_level;
+  UInt          m_bitDepthConstraint;
+  ChromaFormat  m_chromaFormatConstraint;
+  Bool          m_intraConstraintFlag;
+  Bool          m_lowerBitRateConstraintFlag;
+  Bool m_progressiveSourceFlag;
+  Bool m_interlacedSourceFlag;
+  Bool m_nonPackedConstraintFlag;
+  Bool m_frameOnlyConstraintFlag;
+#endif
+
+  // coding structure
+#if !SVC_EXTENSION
+  Int       m_iIntraPeriod;                                   ///< period of I-slice (random access period)
+#endif
+  Int       m_iDecodingRefreshType;                           ///< random access type
+  Int       m_iGOPSize;                                       ///< GOP size of hierarchical structure
+
+#if !Q0108_TSA_STSA
+  Int       m_extraRPSs;                                      ///< extra RPSs added to handle CRA
+#else
+  Int       m_extraRPSs[MAX_LAYERS];                          ///< extra RPSs added to handle CRA
+#endif
+
+  GOPEntry  m_GOPList[MAX_GOP];                               ///< the coding structure entries from the config file
+#if Q0108_TSA_STSA
+  GOPEntry  m_EhGOPList[MAX_LAYERS][MAX_GOP];                 ///< the enhancement layer coding structure entries from the config file
+  Int       m_inheritCodingStruct[MAX_LAYERS];
+#endif
+
+  Int       m_numReorderPics[MAX_TLAYER];                     ///< total number of reorder pictures
+  Int       m_maxDecPicBuffering[MAX_TLAYER];                 ///< total number of pictures in the decoded picture buffer
+  Bool      m_useCrossComponentPrediction;                    ///< flag enabling the use of cross-component prediction
+  Bool      m_reconBasedCrossCPredictionEstimate;             ///< causes the alpha calculation in encoder search to be based on the decoded residual rather than the pre-transform encoder-side residual
+  UInt      m_saoOffsetBitShift[MAX_NUM_CHANNEL_TYPE];        ///< number of bits for the upward bit shift operation on the decoded SAO offsets
+  Bool      m_useTransformSkip;                               ///< flag for enabling intra transform skipping
+  Bool      m_useTransformSkipFast;                           ///< flag for enabling fast intra transform skipping
+  UInt      m_transformSkipLog2MaxSize;                       ///< transform-skip maximum size (minimum of 2)
+  Bool      m_useResidualRotation;                            ///< control flag for transform-skip/transquant-bypass residual rotation
+  Bool      m_useSingleSignificanceMapContext;                ///< control flag for transform-skip/transquant-bypass single significance map context
+  Bool      m_useResidualDPCM[NUMBER_OF_RDPCM_SIGNALLING_MODES];///< control flags for residual DPCM
+  Bool      m_enableAMP;
+  Bool      m_useGolombRiceParameterAdaptation;               ///< control flag for Golomb-Rice parameter adaptation over each slice
+  Bool      m_alignCABACBeforeBypass;
+
+  // coding quality
+#if !SVC_EXTENSION
+  Double    m_fQP;                                            ///< QP value of key-picture (floating point)
+  Int       m_iQP;                                            ///< QP value of key-picture (integer)
+  Char*     m_pchdQPFile;                                     ///< QP offset for each slice (initialized from external file)
+  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_maxCUChromaQpAdjustmentDepth;
+
+  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
+  TComSEIMasteringDisplay m_masteringDisplay;
+
+  Bool      m_bUseAdaptiveQP;                                 ///< Flag for enabling QP adaptation based on a psycho-visual model
+  Int       m_iQPAdaptationRange;                             ///< dQP range by QP adaptation
+
+  Int       m_maxTempLayer;                                  ///< Max temporal layer
+#if Q0108_TSA_STSA
+  Int       m_EhMaxTempLayer[MAX_LAYERS];                    ///< Max temporal layer
+#endif
+
+#if !LAYER_CTB
+  // coding unit (CU) definition
+  // TODO: Remove MaxCUWidth/MaxCUHeight and replace with MaxCUSize.
+  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;
+#endif
+  
+  // coding tools (bit-depth)
+#if !O0194_DIFFERENT_BITDEPTH_EL_BL
+  Int       m_inputBitDepth   [MAX_NUM_CHANNEL_TYPE];         ///< bit-depth of input file
+  Int       m_outputBitDepth  [MAX_NUM_CHANNEL_TYPE];         ///< bit-depth of output file
+  Int       m_MSBExtendedBitDepth[MAX_NUM_CHANNEL_TYPE];      ///< bit-depth of input samples after MSB extension
+  Int       m_internalBitDepth[MAX_NUM_CHANNEL_TYPE];         ///< bit-depth codec operates at (input/output files will be converted)
+  Bool      m_useExtendedPrecision;
+  Bool      m_useHighPrecisionPredictionWeighting;
+#endif
+  //coding tools (chroma format)
+#if !SVC_EXTENSION
+  ChromaFormat m_chromaFormatIDC;
+#endif
+
+  // coding tools (PCM bit-depth)
+  Bool      m_bPCMInputBitDepthFlag;                          ///< 0: PCM bit-depth is internal bit-depth. 1: PCM bit-depth is input bit-depth.
+
+  // coding tool (SAO)
+  Bool      m_bUseSAO;
+  Int       m_maxNumOffsetsPerPic;                            ///< SAO maximun number of offset per picture
+  Bool      m_saoCtuBoundary;                                 ///< SAO parameter estimation using non-deblocked pixels for CTU bottom and right boundary areas
+  // coding tools (loop filter)
+  Bool      m_bLoopFilterDisable;                             ///< flag for using deblocking filter
+  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
+  Bool      m_enableIntraReferenceSmoothing;                  ///< flag for enabling(default)/disabling intra reference smoothing/filtering
+
+  // coding tools (encoder-only parameters)
+  Bool      m_bUseASR;                                        ///< flag for using adaptive motion search range
+  Bool      m_bUseHADME;                                      ///< flag for using HAD in sub-pel ME
+  Bool      m_useRDOQ;                                       ///< flag for using RD optimized quantization
+  Bool      m_useRDOQTS;                                     ///< flag for using RD optimized quantization for transform skip
+  Int       m_rdPenalty;                                      ///< RD-penalty for 32x32 TU for intra in non-intra slices (0: no RD-penalty, 1: RD-penalty, 2: maximum RD-penalty)
+  Int       m_iFastSearch;                                    ///< ME mode, 0 = full, 1 = diamond, 2 = PMVFAST
+  Int       m_iSearchRange;                                   ///< ME search range
+  Int       m_bipredSearchRange;                              ///< ME search range for bipred refinement
+  Bool      m_bUseFastEnc;                                    ///< flag for using fast encoder setting
+  Bool      m_bUseEarlyCU;                                    ///< flag for using Early CU setting
+  Bool      m_useFastDecisionForMerge;                        ///< flag for using Fast Decision Merge RD-Cost
+  Bool      m_bUseCbfFastMode;                              ///< flag for using Cbf Fast PU Mode Decision
+  Bool      m_useEarlySkipDetection;                         ///< flag for using Early SKIP Detection
+  Int       m_sliceMode;                                     ///< 0: no slice limits, 1 : max number of CTBs per slice, 2: max number of bytes per slice,
+                                                             ///< 3: max number of tiles per slice
+  Int       m_sliceArgument;                                 ///< argument according to selected slice mode
+  Int       m_sliceSegmentMode;                              ///< 0: no slice segment limits, 1 : max number of CTBs per slice segment, 2: max number of bytes per slice segment,
+                                                             ///< 3: max number of tiles per slice segment
+  Int       m_sliceSegmentArgument;                          ///< argument according to selected slice segment mode
+
+  Bool      m_bLFCrossSliceBoundaryFlag;  ///< 1: filter across slice boundaries 0: do not filter across slice boundaries
+  Bool      m_bLFCrossTileBoundaryFlag;   ///< 1: filter across tile boundaries  0: do not filter across tile boundaries
+  Bool      m_tileUniformSpacingFlag;
+  Int       m_numTileColumnsMinus1;
+  Int       m_numTileRowsMinus1;
+  std::vector<Int> m_tileColumnWidth;
+  std::vector<Int> m_tileRowHeight;
+#if !SVC_EXTENSION
+  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_iWaveFrontFlush; //< enable(1)/disable(0) the CABAC flush at the end of each line of LCUs.
+  Int       m_iWaveFrontSubstreams; //< If iWaveFrontSynchro, this is the number of substreams per frame (dependent tiles) or per tile (independent tiles).
+#endif
+  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;
+  Bool      m_chromaSamplingFilterSEIenabled;
+  Int       m_chromaSamplingHorFilterIdc;
+  Int       m_chromaSamplingVerFilterIdc;
+  Int       m_toneMapId;
+  Bool      m_toneMapCancelFlag;
+  Bool      m_toneMapPersistenceFlag;
+  Int       m_toneMapCodedDataBitDepth;
+  Int       m_toneMapTargetBitDepth;
+  Int       m_toneMapModelId;
+  Int       m_toneMapMinValue;
+  Int       m_toneMapMaxValue;
+  Int       m_sigmoidMidpoint;
+  Int       m_sigmoidWidth;
+  Int       m_numPivots;
+  Int       m_cameraIsoSpeedIdc;
+  Int       m_cameraIsoSpeedValue;
+  Int       m_exposureIndexIdc;
+  Int       m_exposureIndexValue;
+  Int       m_exposureCompensationValueSignFlag;
+  Int       m_exposureCompensationValueNumerator;
+  Int       m_exposureCompensationValueDenomIdc;
+  Int       m_refScreenLuminanceWhite;
+  Int       m_extendedRangeWhiteLevel;
+  Int       m_nominalBlackLevelLumaCodeValue;
+  Int       m_nominalWhiteLevelLumaCodeValue;
+  Int       m_extendedWhiteLevelLumaCodeValue;
+  Int*      m_startOfCodedInterval;
+  Int*      m_codedPivotValue;
+  Int*      m_targetPivotValue;
+  Int       m_framePackingSEIEnabled;
+  Int       m_framePackingSEIType;
+  Int       m_framePackingSEIId;
+  Int       m_framePackingSEIQuincunx;
+  Int       m_framePackingSEIInterpretation;
+  Int       m_segmentedRectFramePackingSEIEnabled;
+  Bool      m_segmentedRectFramePackingSEICancel;
+  Int       m_segmentedRectFramePackingSEIType;
+  Bool      m_segmentedRectFramePackingSEIPersistence;
+  Int       m_displayOrientationSEIAngle;
+  Int       m_temporalLevel0IndexSEIEnabled;
+  Int       m_gradualDecodingRefreshInfoEnabled;
+  Int       m_noDisplaySEITLayer;
+  Int       m_decodingUnitInfoSEIEnabled;
+  Int       m_SOPDescriptionSEIEnabled;
+  Int       m_scalableNestingSEIEnabled;
+  Bool      m_tmctsSEIEnabled;
+  Bool      m_timeCodeSEIEnabled;
+  Int       m_timeCodeSEINumTs;
+  TComSEITimeSet m_timeSetArray[MAX_TIMECODE_SEI_SETS];
+  Bool      m_kneeSEIEnabled;
+  Int       m_kneeSEIId;
+  Bool      m_kneeSEICancelFlag;
+  Bool      m_kneeSEIPersistenceFlag;
+  Int       m_kneeSEIInputDrange;
+  Int       m_kneeSEIInputDispLuminance;
+  Int       m_kneeSEIOutputDrange;
+  Int       m_kneeSEIOutputDispLuminance;
+  Int       m_kneeSEINumKneePointsMinus1;
+  Int*      m_kneeSEIInputKneePoint;
+  Int*      m_kneeSEIOutputKneePoint;
+  // 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 !RC_SHVC_HARMONIZATION
+  Bool      m_RCEnableRateControl;                ///< enable rate control or not
+  Int       m_RCTargetBitrate;                    ///< target bitrate when rate control is enabled
+  Int       m_RCKeepHierarchicalBit;              ///< 0: equal bit allocation; 1: fixed ratio bit allocation; 2: adaptive ratio bit allocation
+  Bool      m_RCLCULevelRC;                       ///< true: LCU level rate control; false: picture level rate control NOTE: code-tidy - rename to m_RCCtuLevelRC
+  Bool      m_RCUseLCUSeparateModel;              ///< use separate R-lambda model at LCU level                        NOTE: code-tidy - rename to m_RCUseCtuSeparateModel
+  Int       m_RCInitialQP;                        ///< inital QP for rate control
+  Bool      m_RCForceIntraQP;                     ///< force all intra picture to use initial QP or not
+#endif
+  ScalingListMode m_useScalingListId;                         ///< using quantization matrix
+  Char*     m_scalingListFile;                                ///< quantization matrix file name
+
+  Bool      m_TransquantBypassEnableFlag;                     ///< transquant_bypass_enable_flag setting in PPS.
+  Bool      m_CUTransquantBypassFlagForce;                    ///< if transquant_bypass_enable_flag, then, if true, all CU transquant bypass flags will be set to true.
+  CostMode  m_costMode;                                       ///< Cost mode to use
+
+  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 LAYERS_NOT_PRESENT_SEI
+  Int       m_layersNotPresentSEIEnabled;
+#endif
+#if P0123_ALPHA_CHANNEL_SEI
+  Bool      m_alphaSEIEnabled;
+  Bool      m_alphaCancelFlag;
+  Int       m_alphaUseIdc;
+  Int       m_alphaBitDepthMinus8;
+  Int       m_alphaTransparentValue;
+  Int       m_alphaOpaqueValue;
+  Bool      m_alphaIncrementFlag;
+  Bool      m_alphaClipFlag;
+  Bool      m_alphaClipTypeFlag;
+#endif
+#if SVC_EXTENSION
+#if FAST_INTRA_SHVC
+  Bool      m_useFastIntraScalable;                          ///< flag for using Fast Intra Decision for Scalable HEVC
+#endif
+#if Q0189_TMVP_CONSTRAINTS
+  Int       m_TMVPConstraintsSEIEnabled;
+#endif
+#if O0153_ALT_OUTPUT_LAYER_FLAG
+  Bool      m_altOutputLayerFlag;                             ///< Specifies the value of alt_output_laye_flag in VPS extension
+#endif
+  Int       m_elRapSliceBEnabled;
+#endif
+#if Q0074_COLOUR_REMAPPING_SEI
+#if !SVC_EXTENSION
+  Char*     m_colourRemapSEIFile;
+  Int       m_colourRemapSEIId;
+  Bool      m_colourRemapSEICancelFlag;
+  Bool      m_colourRemapSEIPersistenceFlag;
+  Bool      m_colourRemapSEIVideoSignalInfoPresentFlag;
+  Bool      m_colourRemapSEIFullRangeFlag;
+  Int       m_colourRemapSEIPrimaries;
+  Int       m_colourRemapSEITransferFunction;
+  Int       m_colourRemapSEIMatrixCoefficients;
+  Int       m_colourRemapSEIInputBitDepth;
+  Int       m_colourRemapSEIBitDepth;
+  Int       m_colourRemapSEIPreLutNumValMinus1[3];
+  Int*      m_colourRemapSEIPreLutCodedValue[3];
+  Int*      m_colourRemapSEIPreLutTargetValue[3];
+  Bool      m_colourRemapSEIMatrixPresentFlag;
+  Int       m_colourRemapSEILog2MatrixDenom;
+  Int       m_colourRemapSEICoeffs[3][3];
+  Int       m_colourRemapSEIPostLutNumValMinus1[3];
+  Int*      m_colourRemapSEIPostLutCodedValue[3];
+  Int*      m_colourRemapSEIPostLutTargetValue[3];
+#endif
+#endif
+  // internal member functions
+#if LAYER_CTB
+  Void  xSetGlobal      (UInt layerId);                       ///< set global variables
+#else
+  Void  xSetGlobal      ();                                   ///< set global variables
+#endif
+#if SVC_EXTENSION
+  Void  xCheckParameter (UInt layerIdx);                       ///< check validity of configuration values per layer
+#else
+  Void  xCheckParameter ();                                   ///< check validity of configuration values
+#endif
+  Void  xPrintParameter ();                                   ///< print configuration values
+  Void  xPrintUsage     ();                                   ///< print usage
+#if SVC_EXTENSION
+#if M0040_ADAPTIVE_RESOLUTION_CHANGE
+  Int       m_adaptiveResolutionChange;                       ///< Indicate adaptive resolution change frame
+#endif
+#if HIGHER_LAYER_IRAP_SKIP_FLAG
+  Bool      m_skipPictureAtArcSwitch;                         ///< Indicates that when ARC up-switching is performed the higher layer picture is a skip picture
+#endif
+#if REPN_FORMAT_IN_VPS
+  RepFormatCfg m_repFormatCfg[16];                            ///< Rep_format structures
+#endif
+#if N0383_IL_CONSTRAINED_TILE_SETS_SEI
+  Bool      m_interLayerConstrainedTileSetsSEIEnabled;
+  UInt      m_ilNumSetsInMessage;
+  Bool      m_skippedTileSetPresentFlag;
+  UInt      m_topLeftTileIndex[1024];
+  UInt      m_bottomRightTileIndex[1024];
+  UInt      m_ilcIdc[1024];
+#endif
+#if O0215_PHASE_ALIGNMENT
+  Bool      m_phaseAlignFlag;
+#endif
+#if O0223_PICTURE_TYPES_ALIGN_FLAG
+  Bool      m_crossLayerPictureTypeAlignFlag;
+#endif
+  Bool      m_crossLayerIrapAlignFlag;
+#if Q0096_OVERLAY_SEI
+  Bool                                m_overlaySEIEnabled;
+  Bool                                m_overlayInfoCancelFlag;
+  UInt                                m_overlayContentAuxIdMinus128;
+  UInt                                m_overlayLabelAuxIdMinus128;
+  UInt                                m_overlayAlphaAuxIdMinus128;
+  UInt                                m_overlayElementLabelValueLengthMinus8;
+  UInt                                m_numOverlaysMinus1;
+  std::vector<UInt>                   m_overlayIdx;  
+  std::vector<Bool>                   m_overlayLanguagePresentFlag;
+  std::vector<UInt>                   m_overlayContentLayerId;
+  std::vector<Bool>                   m_overlayLabelPresentFlag;
+  std::vector<UInt>                   m_overlayLabelLayerId;
+  std::vector<Bool>                   m_overlayAlphaPresentFlag;
+  std::vector<UInt>                   m_overlayAlphaLayerId;
+  std::vector<UInt>                   m_numOverlayElementsMinus1;
+  std::vector< std::vector<UInt> >    m_overlayElementLabelMin;
+  std::vector< std::vector<UInt> >    m_overlayElementLabelMax;
+  std::vector<string>                 m_overlayLanguage;  
+  std::vector<string>                 m_overlayName;  
+  std::vector< std::vector<string> >  m_overlayElementName;  
+  Bool                                m_overlayInfoPersistenceFlag;
+#endif
+#if P0068_CROSS_LAYER_ALIGNED_IDR_ONLY_FOR_IRAP_FLAG
+  Bool      m_crossLayerAlignedIdrOnlyFlag;
+#endif
+#if O0149_CROSS_LAYER_BLA_FLAG
+  Bool      m_crossLayerBLAFlag;
+#endif
+#if O0194_WEIGHTED_PREDICTION_CGS
+  Bool      m_useInterLayerWeightedPred;
+#endif
+#if Q0048_CGS_3D_ASYMLUT
+  Int  m_nCGSFlag;
+  Int  m_nCGSMaxOctantDepth;
+  Int  m_nCGSMaxYPartNumLog2;
+  Int  m_nCGSLUTBit;
+#if R0151_CGS_3D_ASYMLUT_IMPROVE
+  Int  m_nCGSAdaptiveChroma;
+#endif
+#if R0179_ENC_OPT_3DLUT_SIZE
+  Int  m_nCGSLutSizeRDO;
+#endif
+#endif 
+#endif //SVC_EXTENSION
+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
+  
+#if SVC_EXTENSION
+  Int  getNumFrameToBeEncoded()    {return m_framesToBeEncoded; }
+  Int  getNumLayer()               {return m_numLayers;         }
+  Int  getGOPSize()                {return m_iGOPSize;          }
+#if O0194_DIFFERENT_BITDEPTH_EL_BL
+  UInt getInternalBitDepth(Int iLayer, ChannelType type)      {return m_acLayerCfg[iLayer].m_internalBitDepth[type]; }
+  Bool getPCMInputBitDepthFlag()             {return m_bPCMInputBitDepthFlag;                  }
+#else
+  UInt getInternalBitDepth( ChannelType type )      {return m_internalBitDepth[type]; }  
+#endif
+#if !LAYER_CTB
+  UInt getMaxCUWidth()             {return m_uiMaxCUWidth;      }
+  UInt getMaxCUHeight()            {return m_uiMaxCUHeight;     }
+  UInt getMaxCUDepth()             {return m_uiMaxCUDepth;      }
+#endif
+  Int  getDecodingRefreshType()    {return m_iDecodingRefreshType; }
+  Int  getWaveFrontSynchro(Int layerIdx)        { return m_acLayerCfg[layerIdx].m_waveFrontSynchro; }
+  Void getDirFilename(string& filename, string& dir, const string path);
+#if OUTPUT_LAYER_SETS_CONFIG
+  Bool scanStringToArray(string const cfgString, Int const numEntries, const char* logString, Int * const returnArray);
+  Bool scanStringToArray(string const cfgString, Int const numEntries, const char* logString, std::vector<Int> &  returnVector);
+  Void cfgStringToArray(Int **arr, string const cfgString, Int const numEntries, const char* logString);
+#if R0235_SMALLEST_LAYER_ID
+  Bool scanStringToArrayNumEntries(string const cfgString, Int &numEntries, const char* logString, Int * const returnArray);
+  Bool scanStringToArrayNumEntries(string const cfgString, Int &numEntries, const char* logString, std::vector<Int> &  returnVector);
+  Void cfgStringToArrayNumEntries(Int **arr, string const cfgString, Int &numEntries, const char* logString);
+#endif
+#else
+  Void cfgStringToArray(Int **arr, string cfgString, Int numEntries, const char* logString);
+#endif
+#if REPN_FORMAT_IN_VPS
+  RepFormatCfg* getRepFormatCfg(Int i)  { return &m_repFormatCfg[i]; }
+#endif
+#if LAYER_CTB
+  Bool getUsePCM()                  { return m_usePCM;               }
+  UInt getPCMLog2MinSize  ()        { return  m_uiPCMLog2MinSize;    }
+#endif
+#endif
+};// END CLASS DEFINITION TAppEncCfg
+
+//! \}
+
+#endif // __TAPPENCCFG__
+
Index: /tags/SHM-9.0/source/App/TAppEncoder/TAppEncLayerCfg.cpp
===================================================================
--- /tags/SHM-9.0/source/App/TAppEncoder/TAppEncLayerCfg.cpp	(revision 1088)
+++ /tags/SHM-9.0/source/App/TAppEncoder/TAppEncLayerCfg.cpp	(revision 1088)
@@ -0,0 +1,601 @@
+/** \file     TAppEncLayerCfg.cpp
+\brief    Handle encoder configuration parameters
+*/
+
+#include <stdlib.h>
+#include <cassert>
+#include <cstring>
+#include <string>
+#include "TLibCommon/TComRom.h"
+#include "TAppEncCfg.h"
+#include "TAppEncLayerCfg.h"
+#include "TAppCommon/program_options_lite.h"
+
+#ifdef WIN32
+#define strdup _strdup
+#endif
+
+using namespace std;
+namespace po = df::program_options_lite;
+
+//! \ingroup TAppEncoder
+//! \{
+
+
+#if AUXILIARY_PICTURES
+static inline ChromaFormat numberToChromaFormat(const Int val)
+{
+  switch (val)
+  {
+    case 400: return CHROMA_400; break;
+    case 420: return CHROMA_420; break;
+    case 422: return CHROMA_422; break;
+    case 444: return CHROMA_444; break;
+    default:  return NUM_CHROMA_FORMAT;
+  }
+}
+#endif
+
+// ====================================================================================================================
+// Constructor / destructor / initialization / destroy
+// ====================================================================================================================
+#if SVC_EXTENSION
+TAppEncLayerCfg::TAppEncLayerCfg()
+  :m_cInputFile(string("")),
+  m_cReconFile(string("")),
+  m_conformanceMode( 0 ),
+  m_aidQP(NULL)
+#if REPN_FORMAT_IN_VPS
+, m_repFormatIdx (-1)
+#endif
+#if Q0074_COLOUR_REMAPPING_SEI
+,  m_colourRemapSEIFile(string(""))
+#endif
+{
+#if Q0074_COLOUR_REMAPPING_SEI
+  for( Int c=0 ; c<3 ; c++)
+  {
+    m_colourRemapSEIPreLutCodedValue[c]   = NULL;
+    m_colourRemapSEIPreLutTargetValue[c]  = NULL;
+    m_colourRemapSEIPostLutCodedValue[c]  = NULL;
+    m_colourRemapSEIPostLutTargetValue[c] = NULL;
+  }
+#endif
+  m_confWinLeft = m_confWinRight = m_confWinTop = m_confWinBottom = 0;
+  m_aiPad[1] = m_aiPad[0] = 0;
+  m_numRefLayerLocationOffsets = 0;
+#if O0098_SCALED_REF_LAYER_ID
+  ::memset(m_refLocationOffsetLayerId,   0, sizeof(m_refLocationOffsetLayerId));
+#endif
+  ::memset(m_scaledRefLayerLeftOffset,   0, sizeof(m_scaledRefLayerLeftOffset));
+  ::memset(m_scaledRefLayerTopOffset,    0, sizeof(m_scaledRefLayerTopOffset));
+  ::memset(m_scaledRefLayerRightOffset,  0, sizeof(m_scaledRefLayerRightOffset));
+  ::memset(m_scaledRefLayerBottomOffset, 0, sizeof(m_scaledRefLayerBottomOffset));
+#if REF_REGION_OFFSET
+  ::memset(m_scaledRefLayerOffsetPresentFlag, 0, sizeof(m_scaledRefLayerOffsetPresentFlag));
+  ::memset(m_refRegionOffsetPresentFlag, 0, sizeof(m_refRegionOffsetPresentFlag));
+  ::memset(m_refRegionLeftOffset,   0, sizeof(m_refRegionLeftOffset));
+  ::memset(m_refRegionTopOffset,    0, sizeof(m_refRegionTopOffset));
+  ::memset(m_refRegionRightOffset,  0, sizeof(m_refRegionRightOffset));
+  ::memset(m_refRegionBottomOffset, 0, sizeof(m_refRegionBottomOffset));
+#endif
+#if R0209_GENERIC_PHASE
+  ::memset(m_resamplePhaseSetPresentFlag, 0, sizeof(m_resamplePhaseSetPresentFlag));
+  ::memset(m_phaseHorLuma,   0, sizeof(m_phaseHorLuma));
+  ::memset(m_phaseVerLuma,   0, sizeof(m_phaseVerLuma));
+  ::memset(m_phaseHorChroma, 0, sizeof(m_phaseHorChroma));
+  ::memset(m_phaseVerChroma, 0, sizeof(m_phaseVerChroma));
+#else
+#if P0312_VERT_PHASE_ADJ 
+  ::memset(m_vertPhasePositionEnableFlag, 0, sizeof(m_vertPhasePositionEnableFlag));
+#endif
+#endif
+}
+
+TAppEncLayerCfg::~TAppEncLayerCfg()
+{
+  if ( m_aidQP )
+  {
+    delete[] m_aidQP;
+  }
+#if Q0074_COLOUR_REMAPPING_SEI
+  for( Int c=0 ; c<3 ; c++)
+  {
+    if ( m_colourRemapSEIPreLutCodedValue[c] )
+    {
+      delete[] m_colourRemapSEIPreLutCodedValue[c];
+    }
+    if ( m_colourRemapSEIPreLutTargetValue[c] )
+    {
+      delete[] m_colourRemapSEIPreLutTargetValue[c];
+    }
+    if ( m_colourRemapSEIPostLutCodedValue[c] )
+    {
+      delete[] m_colourRemapSEIPostLutCodedValue[c];
+    }
+    if ( m_colourRemapSEIPostLutTargetValue[c] )
+    {
+      delete[] m_colourRemapSEIPostLutTargetValue[c];
+    }
+  }
+#endif
+}
+
+Void TAppEncLayerCfg::create()
+{
+}
+
+Void TAppEncLayerCfg::destroy()
+{
+}
+
+
+// ====================================================================================================================
+// Public member functions
+// ====================================================================================================================
+
+/** \param  argc        number of arguments
+\param  argv        array of arguments
+\retval             true when success
+*/
+bool TAppEncLayerCfg::parseCfg( const string& cfgFileName  )
+{
+  string cfg_InputFile;
+  string cfg_ReconFile;
+  string cfg_dQPFile;
+#if AUXILIARY_PICTURES
+  Int tmpInputChromaFormat;
+  Int tmpChromaFormat;
+#endif
+#if Q0074_COLOUR_REMAPPING_SEI
+  string  cfg_colourRemapSEIFile;
+#endif
+
+  po::Options opts;
+  opts.addOptions()
+    ("InputFile,i",           cfg_InputFile,  string(""), "original YUV input file name")
+#if AVC_BASE
+    ("InputBLFile,-ibl",      cfg_InputFile,  string(""), "original YUV input file name")
+#endif
+    ("ReconFile,o",           cfg_ReconFile,  string(""), "reconstructed YUV output file name")
+    ("SourceWidth,-wdt",      m_iSourceWidth,  0, "Source picture width")
+    ("SourceHeight,-hgt",     m_iSourceHeight, 0, "Source picture height")
+    ("CroppingMode",          m_conformanceMode,  0, "Cropping mode (0: no cropping, 1:automatic padding, 2: padding, 3:cropping")
+#if AUXILIARY_PICTURES
+    ("InputChromaFormat",     tmpInputChromaFormat,  420, "InputChromaFormatIDC")
+    ("ChromaFormatIDC",       tmpChromaFormat,    420, "ChromaFormatIDC (400|420|422|444 or set 0 (default) for same as InputChromaFormat)")
+#endif
+    ("ConfLeft",              m_confWinLeft,            0, "Deprecated alias of ConfWinLeft")
+    ("ConfRight",             m_confWinRight,           0, "Deprecated alias of ConfWinRight")
+    ("ConfTop",               m_confWinTop,             0, "Deprecated alias of ConfWinTop")
+    ("ConfBottom",            m_confWinBottom,          0, "Deprecated alias of ConfWinBottom")
+    ("ConfWinLeft",           m_confWinLeft,            0, "Left offset for window conformance mode 3")
+    ("ConfWinRight",          m_confWinRight,           0, "Right offset for window conformance mode 3")
+    ("ConfWinTop",            m_confWinTop,             0, "Top offset for window conformance mode 3")
+    ("ConfWinBottom",         m_confWinBottom,          0, "Bottom offset for window conformance mode 3")
+    ("HorizontalPadding,-pdx",m_aiPad[0],      0, "horizontal source padding for cropping mode 2")
+    ("VerticalPadding,-pdy",  m_aiPad[1],      0, "vertical source padding for cropping mode 2")
+    ("IntraPeriod,-ip",       m_iIntraPeriod,  -1, "intra period in frames, (-1: only first frame)")
+    ("FrameRate,-fr",         m_iFrameRate,    0, "Frame rate")
+    ("dQPFile,m",             cfg_dQPFile, string(""), "dQP file name")
+    ("QP,q",                  m_fQP,          30.0, "Qp value, if value is float, QP is switched once during encoding")
+#if Q0074_COLOUR_REMAPPING_SEI
+    ("SEIColourRemappingInfoFile", cfg_colourRemapSEIFile, string(""), "Colour Remapping Information SEI parameters file name")
+#endif
+  ;
+
+  po::setDefaults(opts);
+  po::parseConfigFile(opts, cfgFileName);
+
+  m_cInputFile = cfg_InputFile;
+  m_cReconFile = cfg_ReconFile;
+  m_pchdQPFile = cfg_dQPFile.empty() ? NULL : strdup(cfg_dQPFile.c_str());
+#if AUXILIARY_PICTURES
+  m_InputChromaFormatIDC = numberToChromaFormat(tmpInputChromaFormat);
+  m_chromaFormatIDC   = ((tmpChromaFormat == 0) ? (m_InputChromaFormatIDC) : (numberToChromaFormat(tmpChromaFormat)));
+#endif
+#if Q0074_COLOUR_REMAPPING_SEI
+  m_colourRemapSEIFile = cfg_colourRemapSEIFile.empty() ? NULL : strdup(cfg_colourRemapSEIFile.c_str());
+#endif
+
+  // reading external dQP description from file
+  if ( m_pchdQPFile )
+  {
+    FILE* fpt=fopen( m_pchdQPFile, "r" );
+    if ( fpt )
+    {
+      Int iValue;
+      Int iPOC = 0;
+      while ( iPOC < m_cAppEncCfg->getNumFrameToBeEncoded() )
+      {
+        if ( fscanf(fpt, "%d", &iValue ) == EOF ) break;
+        m_aidQP[ iPOC ] = iValue;
+        iPOC++;
+      }
+      fclose(fpt);
+    }
+  }
+
+#if Q0074_COLOUR_REMAPPING_SEI
+  if( m_colourRemapSEIFile.size() > 0 )
+  {
+    FILE* fic;
+    Int retval;
+    if((fic = fopen(m_colourRemapSEIFile.c_str(),"r")) == (FILE*)NULL)
+    {
+      fprintf(stderr, "Can't open Colour Remapping Information SEI parameters file %s\n", m_colourRemapSEIFile.c_str());
+      exit(EXIT_FAILURE);
+    }
+
+    Int tempCode;
+    retval = fscanf( fic, "%d", &m_colourRemapSEIId );
+    retval = fscanf( fic, "%d", &tempCode );m_colourRemapSEICancelFlag = tempCode ? 1 : 0; 
+    if( !m_colourRemapSEICancelFlag )
+    {
+      retval = fscanf( fic, "%d", &tempCode );m_colourRemapSEIPersistenceFlag = tempCode ? 1 : 0; 
+      retval = fscanf( fic, "%d", &tempCode );m_colourRemapSEIVideoSignalInfoPresentFlag = tempCode ? 1 : 0; 
+      if( m_colourRemapSEIVideoSignalInfoPresentFlag )
+      {
+        retval = fscanf( fic, "%d", &tempCode );m_colourRemapSEIFullRangeFlag = tempCode ? 1 : 0; 
+        retval = fscanf( fic, "%d", &m_colourRemapSEIPrimaries );
+        retval = fscanf( fic, "%d", &m_colourRemapSEITransferFunction );
+        retval = fscanf( fic, "%d", &m_colourRemapSEIMatrixCoefficients );
+      }
+
+      retval = fscanf( fic, "%d", &m_colourRemapSEIInputBitDepth );
+      retval = fscanf( fic, "%d", &m_colourRemapSEIBitDepth );
+  
+      for( Int c=0 ; c<3 ; c++ )
+      {
+        retval = fscanf( fic, "%d", &m_colourRemapSEIPreLutNumValMinus1[c] );
+        if( m_colourRemapSEIPreLutNumValMinus1[c]>0 )
+        {
+          m_colourRemapSEIPreLutCodedValue[c]  = new Int[m_colourRemapSEIPreLutNumValMinus1[c]+1];
+          m_colourRemapSEIPreLutTargetValue[c] = new Int[m_colourRemapSEIPreLutNumValMinus1[c]+1];
+          for( Int i=0 ; i<=m_colourRemapSEIPreLutNumValMinus1[c] ; i++ )
+          {
+            retval = fscanf( fic, "%d", &m_colourRemapSEIPreLutCodedValue[c][i] );
+            retval = fscanf( fic, "%d", &m_colourRemapSEIPreLutTargetValue[c][i] );
+          }
+        }
+      }
+
+      retval = fscanf( fic, "%d", &tempCode );m_colourRemapSEIMatrixPresentFlag = tempCode ? 1 : 0; 
+      if( m_colourRemapSEIMatrixPresentFlag )
+      {
+        retval = fscanf( fic, "%d", &m_colourRemapSEILog2MatrixDenom );
+        for( Int c=0 ; c<3 ; c++ )
+          for( Int i=0 ; i<3 ; i++ )
+            retval = fscanf( fic, "%d", &m_colourRemapSEICoeffs[c][i] );
+      }
+
+      for( Int c=0 ; c<3 ; c++ )
+      {
+        retval = fscanf( fic, "%d", &m_colourRemapSEIPostLutNumValMinus1[c] );
+        if( m_colourRemapSEIPostLutNumValMinus1[c]>0 )
+        {
+          m_colourRemapSEIPostLutCodedValue[c]  = new Int[m_colourRemapSEIPostLutNumValMinus1[c]+1];
+          m_colourRemapSEIPostLutTargetValue[c] = new Int[m_colourRemapSEIPostLutNumValMinus1[c]+1];
+          for( Int i=0 ; i<=m_colourRemapSEIPostLutNumValMinus1[c] ; i++ )
+          {
+            retval = fscanf( fic, "%d", &m_colourRemapSEIPostLutCodedValue[c][i] );
+            retval = fscanf( fic, "%d", &m_colourRemapSEIPostLutTargetValue[c][i] );
+          }
+        }
+      }
+    }
+
+    fclose( fic );
+    if( retval != 1 )
+    {
+      fprintf(stderr, "Error while reading Colour Remapping Information SEI parameters file\n");
+      exit(EXIT_FAILURE);
+    }
+  }
+#endif
+
+  return true;
+}
+
+Void TAppEncLayerCfg::xPrintParameter()
+{
+  printf("Input File                        : %s\n", m_cInputFile.c_str()  );
+  printf("Reconstruction File               : %s\n", m_cReconFile.c_str()  );
+#if REPN_FORMAT_IN_VPS
+  printf("Real     Format                   : %dx%d %dHz\n", m_iSourceWidth - ( m_confWinLeft + m_confWinRight ) * TComSPS::getWinUnitX( m_chromaFormatIDC ), m_iSourceHeight - ( m_confWinTop + m_confWinBottom ) * TComSPS::getWinUnitY( m_chromaFormatIDC ), m_iFrameRate );
+#else
+  printf("Real     Format                   : %dx%d %dHz\n", m_iSourceWidth - m_confWinLeft - m_confWinRight, m_iSourceHeight - m_confWinTop - m_confWinBottom, m_iFrameRate );
+#endif
+  printf("Internal Format                   : %dx%d %dHz\n", m_iSourceWidth, m_iSourceHeight, m_iFrameRate );
+#if MULTIPLE_PTL_SUPPORT
+  printf("PTL index                         : %d\n", m_layerPTLIdx );
+#endif
+#if O0194_DIFFERENT_BITDEPTH_EL_BL
+  printf("Input bit depth                   : (Y:%d, C:%d)\n", m_inputBitDepth[CHANNEL_TYPE_LUMA], m_inputBitDepth[CHANNEL_TYPE_CHROMA] );
+  printf("Internal bit depth                : (Y:%d, C:%d)\n", m_internalBitDepth[CHANNEL_TYPE_LUMA], m_internalBitDepth[CHANNEL_TYPE_CHROMA] );
+  printf("PCM sample bit depth              : (Y:%d, C:%d)\n", m_cAppEncCfg->getPCMInputBitDepthFlag() ? m_inputBitDepth[CHANNEL_TYPE_LUMA] : m_internalBitDepth[CHANNEL_TYPE_LUMA], m_cAppEncCfg->getPCMInputBitDepthFlag() ? m_inputBitDepth[CHANNEL_TYPE_CHROMA] : m_internalBitDepth[CHANNEL_TYPE_CHROMA] );
+#endif
+  std::cout << "Input ChromaFormatIDC             :";
+
+  switch (m_InputChromaFormatIDC)
+  {
+  case CHROMA_400:  std::cout << " 4:0:0"; break;
+  case CHROMA_420:  std::cout << " 4:2:0"; break;
+  case CHROMA_422:  std::cout << " 4:2:2"; break;
+  case CHROMA_444:  std::cout << " 4:4:4"; break;
+  default:
+    std::cerr << "Invalid";
+    exit(1);
+  }
+  std::cout << std::endl;
+
+  std::cout << "Output (internal) ChromaFormatIDC :";
+  switch (m_chromaFormatIDC)
+  {
+  case CHROMA_400:  std::cout << " 4:0:0"; break;
+  case CHROMA_420:  std::cout << " 4:2:0"; break;
+  case CHROMA_422:  std::cout << " 4:2:2"; break;
+  case CHROMA_444:  std::cout << " 4:4:4"; break;
+  default:
+    std::cerr << "Invalid";
+    exit(1);
+  }
+  printf("\n");
+#if LAYER_CTB
+  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);
+#endif
+  printf("QP                                : %5.2f\n", m_fQP );
+  printf("Intra period                      : %d\n", m_iIntraPeriod );
+#if RC_SHVC_HARMONIZATION                    
+  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 );
+  }
+#endif
+  printf("WaveFrontSynchro                  : %d\n", m_waveFrontSynchro);
+  printf("WaveFrontSubstreams               : %d\n", m_iWaveFrontSubstreams);
+#if LAYER_CTB
+  printf("PCM                               : %d ", (m_cAppEncCfg->getUsePCM() && (1<<m_cAppEncCfg->getPCMLog2MinSize()) <= m_uiMaxCUWidth)? 1 : 0);
+#endif
+}
+
+Bool confirmPara(Bool bflag, const char* message);
+
+Bool TAppEncLayerCfg::xCheckParameter( Bool isField )
+{
+  switch (m_conformanceMode)
+  {
+  case 0:
+    {
+      // no cropping or padding
+      m_confWinLeft = m_confWinRight = m_confWinTop = m_confWinBottom = 0;
+      m_aiPad[1] = m_aiPad[0] = 0;
+      break;
+    }
+  case 1:
+    {
+      // conformance
+      if ((m_confWinLeft != 0) || (m_confWinRight != 0) || (m_confWinTop != 0) || (m_confWinBottom != 0))
+      {
+        fprintf(stderr, "Warning: Automatic padding enabled, but cropping parameters are set. Undesired size possible.\n");
+      }
+      if ((m_aiPad[1] != 0) || (m_aiPad[0] != 0))
+      {
+        fprintf(stderr, "Warning: Automatic padding enabled, but padding parameters are also set\n");
+      }
+
+      // automatic padding to minimum CU size
+#if LAYER_CTB
+      Int minCuSize = m_uiMaxCUHeight >> (m_uiMaxCUDepth - 1);
+#else
+      Int minCuSize = m_cAppEncCfg->getMaxCUHeight() >> (m_cAppEncCfg->getMaxCUDepth() - 1);
+#endif
+      if (m_iSourceWidth % minCuSize)
+      {
+        m_aiPad[0] = m_confWinRight  = ((m_iSourceWidth / minCuSize) + 1) * minCuSize - m_iSourceWidth;
+        m_iSourceWidth  += m_confWinRight;
+#if REPN_FORMAT_IN_VPS
+        m_confWinRight /= TComSPS::getWinUnitX( m_chromaFormatIDC );
+#endif
+      }
+      if (m_iSourceHeight % minCuSize)
+      {
+        m_aiPad[1] = m_confWinBottom = ((m_iSourceHeight / minCuSize) + 1) * minCuSize - m_iSourceHeight;
+        m_iSourceHeight += m_confWinBottom;
+        if ( isField )
+        {
+          m_iSourceHeightOrg += m_confWinBottom << 1;
+          m_aiPad[1] = m_confWinBottom << 1;
+        }
+#if REPN_FORMAT_IN_VPS
+        m_confWinBottom /= TComSPS::getWinUnitY( m_chromaFormatIDC );
+#endif
+      }
+      break;
+    }
+  case 2:
+    {
+      // conformance
+      if ((m_confWinLeft != 0) || (m_confWinRight != 0) || (m_confWinTop != 0) || (m_confWinBottom != 0))
+      {
+        fprintf(stderr, "Warning: Automatic padding enabled, but cropping parameters are set. Undesired size possible.\n");
+      }
+
+      //padding
+      m_iSourceWidth  += m_aiPad[0];
+      m_iSourceHeight += m_aiPad[1];
+      m_confWinRight  = m_aiPad[0];
+      m_confWinBottom = m_aiPad[1];
+#if REPN_FORMAT_IN_VPS
+      m_confWinRight /= TComSPS::getWinUnitX( m_chromaFormatIDC );
+      m_confWinBottom /= TComSPS::getWinUnitY( m_chromaFormatIDC );
+#endif
+      break;
+    }
+  case 3:
+    {
+      // conformance
+      if ((m_confWinLeft == 0) && (m_confWinRight == 0) && (m_confWinTop == 0) && (m_confWinBottom == 0))
+      {
+        fprintf(stderr, "Warning: Cropping enabled, but all cropping parameters set to zero\n");
+      }
+      if ((m_aiPad[1] != 0) || (m_aiPad[0]!=0))
+      {
+        fprintf(stderr, "Warning: Cropping enabled, padding parameters will be ignored\n");
+      }
+      m_aiPad[1] = m_aiPad[0] = 0;
+      break;
+    }
+  }
+
+  // allocate slice-based dQP values
+  Int iFrameToBeEncoded = m_cAppEncCfg->getNumFrameToBeEncoded();
+  Int iGOPSize = m_cAppEncCfg->getGOPSize();
+  if( m_aidQP == NULL )
+    m_aidQP = new Int[iFrameToBeEncoded + iGOPSize + 1 ];
+  ::memset( m_aidQP, 0, sizeof(Int)*( iFrameToBeEncoded + 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)( iFrameToBeEncoded - (m_fQP - m_iQP)*iFrameToBeEncoded + 0.5 );
+
+
+    iSwitchPOC = (Int)( (Double)iSwitchPOC / iGOPSize + 0.5 )*iGOPSize;
+    for ( Int i=iSwitchPOC; i<iFrameToBeEncoded + iGOPSize + 1; i++ )
+    {
+      m_aidQP[i] = 1;
+    }
+  }
+
+#if LAYER_CTB
+  UInt maxCUWidth = m_uiMaxCUWidth;
+  UInt maxCUHeight = m_uiMaxCUHeight;
+  UInt maxCUDepth = m_uiMaxCUDepth;
+#else
+  UInt maxCUWidth = m_cAppEncCfg->getMaxCUWidth();
+  UInt maxCUHeight = m_cAppEncCfg->getMaxCUHeight();
+  UInt maxCUDepth = m_cAppEncCfg->getMaxCUDepth();
+#endif
+  bool check_failed = false; /* abort if there is a fatal configuration problem */
+#define xConfirmPara(a,b) check_failed |= confirmPara(a,b)
+  // check range of parameters
+  xConfirmPara( m_iFrameRate <= 0,                                                          "Frame rate must be more than 1" );
+  xConfirmPara( (m_iSourceWidth  % (maxCUWidth  >> (maxCUDepth-1)))!=0,             "Resulting coded frame width must be a multiple of the minimum CU size");
+  xConfirmPara( (m_iSourceHeight % (maxCUHeight >> (maxCUDepth-1)))!=0,             "Resulting coded frame height must be a multiple of the minimum CU size");
+  xConfirmPara( (m_iIntraPeriod > 0 && m_iIntraPeriod < iGOPSize) || m_iIntraPeriod == 0, "Intra period must be more than GOP size, or -1 , not 0" );
+  if (m_cAppEncCfg->getDecodingRefreshType() == 2)
+  {
+    xConfirmPara( m_iIntraPeriod > 0 && m_iIntraPeriod <= iGOPSize ,                      "Intra period must be larger than GOP size for periodic IDR pictures");
+  }
+
+#if O0194_DIFFERENT_BITDEPTH_EL_BL
+  xConfirmPara( m_iQP <  -6 * (m_internalBitDepth[CHANNEL_TYPE_LUMA] - 8) || m_iQP > 51,                "QP exceeds supported range (-QpBDOffsety to 51)" );
+#else
+  xConfirmPara( m_iQP <  -6 * ((Int)m_cAppEncCfg->getInternalBitDepthY() - 8) || m_iQP > 51,                "QP exceeds supported range (-QpBDOffsety to 51)" );
+#endif
+
+  m_iWaveFrontSubstreams = m_waveFrontSynchro ? (m_iSourceHeight + maxCUHeight - 1) / maxCUHeight : 1;
+  xConfirmPara( m_waveFrontSynchro < 0, "WaveFrontSynchro cannot be negative" );
+  xConfirmPara( m_iWaveFrontSubstreams <= 0, "WaveFrontSubstreams must be positive" );
+  xConfirmPara( m_iWaveFrontSubstreams > 1 && !m_waveFrontSynchro, "Must have WaveFrontSynchro > 0 in order to have WaveFrontSubstreams > 1" );
+
+  //chekc parameters
+  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");
+
+#if !REPN_FORMAT_IN_VPS
+  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");
+#endif
+
+#if LAYER_CTB  
+  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_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" );
+
+  // 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");
+  }
+#endif
+#if Q0074_COLOUR_REMAPPING_SEI
+  if ( ( m_colourRemapSEIFile.size() > 0 ) && !m_colourRemapSEICancelFlag )
+  {
+    xConfirmPara( m_colourRemapSEIInputBitDepth < 8 || m_colourRemapSEIInputBitDepth > 16 , "colour_remap_input_bit_depth shall be in the range of 8 to 16, inclusive");
+    xConfirmPara( m_colourRemapSEIBitDepth < 8 || m_colourRemapSEIBitDepth > 16, "colour_remap_bit_depth shall be in the range of 8 to 16, inclusive");
+    for( Int c=0 ; c<3 ; c++)
+    {
+      xConfirmPara( m_colourRemapSEIPreLutNumValMinus1[c] < 0 || m_colourRemapSEIPreLutNumValMinus1[c] > 32, "pre_lut_num_val_minus1[c] shall be in the range of 0 to 32, inclusive");
+      if( m_colourRemapSEIPreLutNumValMinus1[c]>0 )
+        for( Int i=0 ; i<=m_colourRemapSEIPreLutNumValMinus1[c] ; i++)
+        {
+          xConfirmPara( m_colourRemapSEIPreLutCodedValue[c][i] < 0 || m_colourRemapSEIPreLutCodedValue[c][i] > ((1<<m_colourRemapSEIInputBitDepth)-1), "pre_lut_coded_value[c][i] shall be in the range of 0 to (1<<colour_remap_input_bit_depth)-1, inclusive");
+          xConfirmPara( m_colourRemapSEIPreLutTargetValue[c][i] < 0 || m_colourRemapSEIPreLutTargetValue[c][i] > ((1<<m_colourRemapSEIBitDepth)-1), "pre_lut_target_value[c][i] shall be in the range of 0 to (1<<colour_remap_bit_depth)-1, inclusive");
+        }
+      xConfirmPara( m_colourRemapSEIPostLutNumValMinus1[c] < 0 || m_colourRemapSEIPostLutNumValMinus1[c] > 32, "post_lut_num_val_minus1[c] shall be in the range of 0 to 32, inclusive");
+      if( m_colourRemapSEIPostLutNumValMinus1[c]>0 )
+        for( Int i=0 ; i<=m_colourRemapSEIPostLutNumValMinus1[c] ; i++)
+        { 
+          xConfirmPara( m_colourRemapSEIPostLutCodedValue[c][i] < 0 || m_colourRemapSEIPostLutCodedValue[c][i] > ((1<<m_colourRemapSEIBitDepth)-1), "post_lut_coded_value[c][i] shall be in the range of 0 to (1<<colour_remap_bit_depth)-1, inclusive");
+          xConfirmPara( m_colourRemapSEIPostLutTargetValue[c][i] < 0 || m_colourRemapSEIPostLutTargetValue[c][i] > ((1<<m_colourRemapSEIBitDepth)-1), "post_lut_target_value[c][i] shall be in the range of 0 to (1<<colour_remap_bit_depth)-1, inclusive");
+        }
+    }
+    if( m_colourRemapSEIMatrixPresentFlag )
+    {
+      xConfirmPara( m_colourRemapSEILog2MatrixDenom < 0 || m_colourRemapSEILog2MatrixDenom > 15, "log2_matrix_denom shall be in the range of 0 to 15, inclusive");
+      for( Int c=0 ; c<3 ; c++)
+        for( Int i=0 ; i<3 ; i++)
+          xConfirmPara( m_colourRemapSEICoeffs[c][i] < -32768 || m_colourRemapSEICoeffs[c][i] > 32767, "colour_remap_coeffs[c][i] shall be in the range of -32768 and 32767, inclusive");
+    }
+  }
+#endif
+
+#undef xConfirmPara
+  return check_failed;
+}
+
+#endif //SVC_EXTENSION
+
+
+//! \}
Index: /tags/SHM-9.0/source/App/TAppEncoder/TAppEncLayerCfg.h
===================================================================
--- /tags/SHM-9.0/source/App/TAppEncoder/TAppEncLayerCfg.h	(revision 1088)
+++ /tags/SHM-9.0/source/App/TAppEncoder/TAppEncLayerCfg.h	(revision 1088)
@@ -0,0 +1,240 @@
+
+/** \file     TAppEncLayerCfg.h
+    \brief    Handle encoder layer configuration parameters (header)
+*/
+#ifndef __TAPPENCLAYERCFG__
+#define __TAPPENCLAYERCFG__
+
+#if SVC_EXTENSION
+#include "TLibCommon/CommonDef.h"
+#include "TLibEncoder/TEncCfg.h"
+#include <sstream>
+#include <iomanip>
+
+using namespace std;
+class TAppEncCfg;
+//! \ingroup TAppEncoder
+//! \{
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// encoder layer configuration class
+class TAppEncLayerCfg
+{
+  friend class TAppEncCfg;
+  friend class TAppEncTop;
+protected:
+  // file I/O0
+  string    m_cInputFile;                                     ///< source file name
+  string    m_cReconFile;                                     ///< output reconstruction file
+  Int       m_layerId;                                        ///< layer Id
+  Int       m_iFrameRate;                                     ///< source frame-rates (Hz)
+  Int       m_iSourceWidth;                                   ///< source width in pixel
+  Int       m_iSourceHeight;                                  ///< source height in pixel (when interlaced = field height)
+  Int       m_iSourceHeightOrg;                               ///< original source height in pixel (when interlaced = frame height)
+  Int       m_conformanceMode;
+  Int       m_confWinLeft;
+  Int       m_confWinRight;
+  Int       m_confWinTop;
+  Int       m_confWinBottom;
+  Int       m_aiPad[2];                                       ///< number of padded pixels for width and height
+  Int       m_iIntraPeriod;                                   ///< period of I-slice (random access period)
+  Double    m_fQP;                                            ///< QP value of key-picture (floating point)
+  ChromaFormat m_chromaFormatIDC;
+  ChromaFormat m_InputChromaFormatIDC;
+  ChromaFormat m_chromaFormatConstraint;
+  UInt      m_bitDepthConstraint;
+  Bool      m_intraConstraintFlag;
+  Bool      m_lowerBitRateConstraintFlag;
+#if AUXILIARY_PICTURES
+  Int       m_auxId;
+#endif
+#if VPS_EXTN_DIRECT_REF_LAYERS
+  Int       *m_samplePredRefLayerIds;
+  Int       m_numSamplePredRefLayers;
+  Int       *m_motionPredRefLayerIds;
+  Int       m_numMotionPredRefLayers;
+  Int       *m_predLayerIds;
+  Int       m_numActiveRefLayers;
+#endif
+
+#if LAYER_CTB
+  // 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;
+#endif
+
+#if RC_SHVC_HARMONIZATION
+  Bool      m_RCEnableRateControl;                ///< enable rate control or not
+  Int       m_RCTargetBitrate;                    ///< target bitrate when rate control is enabled
+  Bool      m_RCKeepHierarchicalBit;              ///< whether keeping hierarchical bit allocation structure or not
+  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
+#endif
+
+  Int       m_maxTidIlRefPicsPlus1;
+  Int       m_waveFrontSynchro;                   ///< 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).
+
+  Int       m_iQP;                                            ///< QP value of key-picture (integer)
+  char*     m_pchdQPFile;                                     ///< QP offset for each slice (initialized from external file)
+  Int*      m_aidQP;                                          ///< array of slice QP values
+  TAppEncCfg* m_cAppEncCfg;                                   ///< pointer to app encoder config
+  Int       m_numRefLayerLocationOffsets;
+#if O0098_SCALED_REF_LAYER_ID
+  Int       m_refLocationOffsetLayerId  [MAX_LAYERS];
+#endif
+  Int       m_scaledRefLayerLeftOffset  [MAX_LAYERS];
+  Int       m_scaledRefLayerTopOffset   [MAX_LAYERS];
+  Int       m_scaledRefLayerRightOffset [MAX_LAYERS];
+  Int       m_scaledRefLayerBottomOffset[MAX_LAYERS];
+#if REF_REGION_OFFSET
+  Bool      m_scaledRefLayerOffsetPresentFlag [MAX_LAYERS];
+  Bool      m_refRegionOffsetPresentFlag      [MAX_LAYERS];
+  Int       m_refRegionLeftOffset  [MAX_LAYERS];
+  Int       m_refRegionTopOffset   [MAX_LAYERS];
+  Int       m_refRegionRightOffset [MAX_LAYERS];
+  Int       m_refRegionBottomOffset[MAX_LAYERS];
+#endif
+#if P0312_VERT_PHASE_ADJ
+  Bool      m_vertPhasePositionEnableFlag[MAX_LAYERS];
+#endif
+#if R0209_GENERIC_PHASE
+  Int       m_phaseHorLuma  [MAX_LAYERS];
+  Int       m_phaseVerLuma  [MAX_LAYERS];
+  Int       m_phaseHorChroma[MAX_LAYERS];
+  Int       m_phaseVerChroma[MAX_LAYERS];
+  Bool      m_resamplePhaseSetPresentFlag [MAX_LAYERS];
+#endif
+
+  Int       m_inputBitDepth   [MAX_NUM_CHANNEL_TYPE];         ///< bit-depth of input file
+  Int       m_outputBitDepth  [MAX_NUM_CHANNEL_TYPE];         ///< bit-depth of output file
+  Int       m_MSBExtendedBitDepth[MAX_NUM_CHANNEL_TYPE];      ///< bit-depth of input samples after MSB extension
+  Int       m_internalBitDepth[MAX_NUM_CHANNEL_TYPE];         ///< bit-depth codec operates at (input/output files will be converted)
+  UInt      m_saoOffsetBitShift[MAX_NUM_CHANNEL_TYPE];
+  Bool      m_useExtendedPrecision;
+  Bool      m_useHighPrecisionPredictionWeighting;
+
+#if REPN_FORMAT_IN_VPS
+  Int       m_repFormatIdx;
+#endif
+#if Q0074_COLOUR_REMAPPING_SEI
+  string    m_colourRemapSEIFile;                           ///< Colour Remapping Information SEI message parameters file
+  Int       m_colourRemapSEIId;
+  Bool      m_colourRemapSEICancelFlag;
+  Bool      m_colourRemapSEIPersistenceFlag;
+  Bool      m_colourRemapSEIVideoSignalInfoPresentFlag;
+  Bool      m_colourRemapSEIFullRangeFlag;
+  Int       m_colourRemapSEIPrimaries;
+  Int       m_colourRemapSEITransferFunction;
+  Int       m_colourRemapSEIMatrixCoefficients;
+  Int       m_colourRemapSEIInputBitDepth;
+  Int       m_colourRemapSEIBitDepth;
+  Int       m_colourRemapSEIPreLutNumValMinus1[3];
+  Int*      m_colourRemapSEIPreLutCodedValue[3];
+  Int*      m_colourRemapSEIPreLutTargetValue[3];
+  Bool      m_colourRemapSEIMatrixPresentFlag;
+  Int       m_colourRemapSEILog2MatrixDenom;
+  Int       m_colourRemapSEICoeffs[3][3];
+  Int       m_colourRemapSEIPostLutNumValMinus1[3];
+  Int*      m_colourRemapSEIPostLutCodedValue[3];
+  Int*      m_colourRemapSEIPostLutTargetValue[3];
+#endif
+
+#if R0071_IRAP_EOS_CROSS_LAYER_IMPACTS
+  Int       m_layerSwitchOffBegin;
+  Int       m_layerSwitchOffEnd;
+#endif
+
+#if MULTIPLE_PTL_SUPPORT
+  // profile/level
+  Int       m_layerPTLIdx;
+#endif
+
+public:
+  TAppEncLayerCfg();
+  virtual ~TAppEncLayerCfg();
+
+public:
+  Void  create    ();                                         ///< create option handling class
+  Void  destroy   ();                                         ///< destroy option handling class
+  bool  parseCfg  ( const string& cfgFileName );              ///< parse layer configuration file to fill member variables
+
+  Void  xPrintParameter();
+  Bool  xCheckParameter( Bool isField );
+
+  Void    setAppEncCfg(TAppEncCfg* p) {m_cAppEncCfg = p;          }
+
+  string  getInputFile()              {return m_cInputFile;       }
+  string  getReconFile()              {return m_cReconFile;       }
+  Int     getFrameRate()              {return m_iFrameRate;       }
+  Int     getSourceWidth()            {return m_iSourceWidth;     }
+  Int     getSourceHeight()           {return m_iSourceHeight;    }
+  Int     getSourceHeightOrg()        {return m_iSourceHeightOrg; }
+  Int     getConformanceMode()        { return m_conformanceMode; }
+  Int*    getPad()                    {return m_aiPad;            }
+  Double  getFloatQP()                {return m_fQP;              }
+  Int     getConfWinLeft()            {return m_confWinLeft;         }
+  Int     getConfWinRight()           {return m_confWinRight;        }
+  Int     getConfWinTop()             {return m_confWinTop;          }
+  Int     getConfWinBottom()          {return m_confWinBottom;       }
+#if AUXILIARY_PICTURES
+  ChromaFormat getInputChromaFormat()   {return m_InputChromaFormatIDC;}
+  ChromaFormat getChromaFormatIDC()     {return m_chromaFormatIDC;  }
+  Int          getAuxId()               {return m_auxId;            }
+#endif
+
+  Int     getIntQP()                  {return m_iQP;              } 
+  Int*    getdQPs()                   {return m_aidQP;            }
+#if VPS_EXTN_DIRECT_REF_LAYERS
+  Int     getNumSamplePredRefLayers()    {return m_numSamplePredRefLayers;   }
+  Int*    getSamplePredRefLayerIds()     {return m_samplePredRefLayerIds;    }
+  Int     getSamplePredRefLayerId(Int i) {return m_samplePredRefLayerIds[i]; }
+  Int     getNumMotionPredRefLayers()    {return m_numMotionPredRefLayers;   }
+  Int*    getMotionPredRefLayerIds()     {return m_motionPredRefLayerIds;    }
+  Int     getMotionPredRefLayerId(Int i) {return m_motionPredRefLayerIds[i]; }
+
+  Int     getNumActiveRefLayers()     {return m_numActiveRefLayers;}
+  Int*    getPredLayerIds()           {return m_predLayerIds;     }
+  Int     getPredLayerIdx(Int i)      {return m_predLayerIds[i];  }
+#endif
+#if RC_SHVC_HARMONIZATION
+  Bool    getRCEnableRateControl()    {return m_RCEnableRateControl;   }
+  Int     getRCTargetBitrate()        {return m_RCTargetBitrate;       }
+  Bool    getRCKeepHierarchicalBit()  {return m_RCKeepHierarchicalBit; }
+  Bool    getRCLCULevelRC()           {return m_RCLCULevelRC;          }
+  Bool    getRCUseLCUSeparateModel()  {return m_RCUseLCUSeparateModel; }
+  Int     getRCInitialQP()            {return m_RCInitialQP;           }
+  Bool    getRCForceIntraQP()         {return m_RCForceIntraQP;        }
+#endif
+#if REPN_FORMAT_IN_VPS
+  Int     getRepFormatIdx()           { return m_repFormatIdx;  }
+  Void    setRepFormatIdx(Int x)      { m_repFormatIdx = x;     }
+  Void    setSourceWidth(Int x)       { m_iSourceWidth = x;     }
+  Void    setSourceHeight(Int x)      { m_iSourceHeight = x;    }
+#endif
+  Int     getMaxTidIlRefPicsPlus1()   { return m_maxTidIlRefPicsPlus1; }
+#if LAYER_CTB
+  UInt    getMaxCUWidth()             {return m_uiMaxCUWidth;      }
+  UInt    getMaxCUHeight()            {return m_uiMaxCUHeight;     }
+  UInt    getMaxCUDepth()             {return m_uiMaxCUDepth;      }
+#endif
+}; // END CLASS DEFINITION TAppEncLayerCfg
+
+#endif //SVC_EXTENSION
+
+//! \}
+
+#endif // __TAPPENCLAYERCFG__
Index: /tags/SHM-9.0/source/App/TAppEncoder/TAppEncTop.cpp
===================================================================
--- /tags/SHM-9.0/source/App/TAppEncoder/TAppEncTop.cpp	(revision 1088)
+++ /tags/SHM-9.0/source/App/TAppEncoder/TAppEncTop.cpp	(revision 1088)
@@ -0,0 +1,2926 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TAppEncTop.cpp
+    \brief    Encoder application class
+*/
+
+#include <list>
+#include <fstream>
+#include <stdlib.h>
+#include <stdio.h>
+#include <fcntl.h>
+#include <assert.h>
+#if !SVC_EXTENSION
+#include <iomanip>
+#endif
+
+#include "TAppEncTop.h"
+#include "TLibEncoder/AnnexBwrite.h"
+
+using namespace std;
+
+//! \ingroup TAppEncoder
+//! \{
+
+// ====================================================================================================================
+// Constructor / destructor / initialization / destroy
+// ====================================================================================================================
+
+TAppEncTop::TAppEncTop()
+{
+  m_iFrameRcvd = 0;
+  m_totalBytes = 0;
+  m_essentialBytes = 0;
+#if SVC_EXTENSION
+  for(UInt layer=0; layer < MAX_LAYERS; layer++)
+  {
+    m_apcTEncTop[layer] = &m_acTEncTop[layer];
+  }
+#endif
+}
+
+TAppEncTop::~TAppEncTop()
+{
+}
+
+#if SVC_EXTENSION
+Void TAppEncTop::xInitLibCfg()
+{
+  TComVPS* vps = m_acTEncTop[0].getVPS();
+
+#if P0297_VPS_POC_LSB_ALIGNED_FLAG
+  vps->setVpsPocLsbAlignedFlag(false);
+#endif
+  vps->setMaxTLayers                                                      ( m_maxTempLayer );
+  if (m_maxTempLayer == 1)
+  {
+    vps->setTemporalNestingFlag(true);
+  }
+  for(Int i = 0; i < MAX_TLAYER; i++)
+  {
+    vps->setNumReorderPics                                                ( m_numReorderPics[i], i );
+    vps->setMaxDecPicBuffering                                            ( m_maxDecPicBuffering[i], i );
+  }
+
+#if REPN_FORMAT_IN_VPS  
+  Int maxRepFormatIdx = -1;
+  Int formatIdx = -1;
+  for(UInt layer=0; layer < m_numLayers; layer++)
+  {
+    // Auto generation of the format index
+    if( m_acLayerCfg[layer].getRepFormatIdx() == -1 )
+    {      
+      Bool found = false;
+      for( UInt idx = 0; idx < layer; idx++ )
+      {
+        if( m_acLayerCfg[layer].getSourceWidth() == m_acLayerCfg[idx].getSourceWidth() && m_acLayerCfg[layer].getSourceHeight() == m_acLayerCfg[idx].getSourceHeight()
+#if AUXILIARY_PICTURES
+          && m_acLayerCfg[layer].getChromaFormatIDC() == m_acLayerCfg[idx].getChromaFormatIDC()
+#endif
+#if O0194_DIFFERENT_BITDEPTH_EL_BL
+          && m_acLayerCfg[layer].m_internalBitDepth[CHANNEL_TYPE_LUMA] == m_acLayerCfg[idx].m_internalBitDepth[CHANNEL_TYPE_LUMA] && m_acLayerCfg[layer].m_internalBitDepth[CHANNEL_TYPE_CHROMA] == m_acLayerCfg[idx].m_internalBitDepth[CHANNEL_TYPE_CHROMA]
+#endif
+          )
+        {
+          found = true;
+          break;
+        }
+      }
+      if( !found )
+      {
+        formatIdx++;
+      }
+
+      m_acLayerCfg[layer].setRepFormatIdx( formatIdx );
+    }
+
+    assert( m_acLayerCfg[layer].getRepFormatIdx() != -1 && "RepFormatIdx not assigned for a layer" );
+
+    vps->setVpsRepFormatIdx( layer, m_acLayerCfg[layer].getRepFormatIdx() );
+
+    maxRepFormatIdx = std::max( m_acLayerCfg[layer].getRepFormatIdx(), maxRepFormatIdx );
+  }
+
+  assert( vps->getVpsRepFormatIdx( 0 ) == 0 );  // Base layer should point to the first one.
+
+  Int* mapIdxToLayer = new Int[maxRepFormatIdx + 1];
+
+  // Check that all the indices from 0 to maxRepFormatIdx are used in the VPS
+  for(Int i = 0; i <= maxRepFormatIdx; i++)
+  {
+    mapIdxToLayer[i] = -1;
+    UInt layer;
+    for(layer=0; layer < m_numLayers; layer++)
+    {
+      if( vps->getVpsRepFormatIdx(layer) == i )
+      {
+        mapIdxToLayer[i] = layer;
+        break;
+      }
+    }
+    assert( layer != m_numLayers );   // One of the VPS Rep format indices not set
+  }
+
+  vps->setVpsNumRepFormats                                                ( maxRepFormatIdx + 1 );
+
+#if Q0195_REP_FORMAT_CLEANUP
+  // When not present, the value of rep_format_idx_present_flag is inferred to be equal to 0
+  vps->setRepFormatIdxPresentFlag                                         ( vps->getVpsNumRepFormats() > 1 ? true : false );
+#else
+  vps->setRepFormatIdxPresentFlag                                         ( true );
+#endif
+
+  for(UInt idx=0; idx < vps->getVpsNumRepFormats(); idx++)
+  {
+    RepFormat *repFormat = vps->getVpsRepFormat( idx );
+#if REPN_FORMAT_CONTROL_FLAG
+    repFormat->setChromaAndBitDepthVpsPresentFlag                         ( true ); 
+    if (idx==0)
+    {
+      assert(repFormat->getChromaAndBitDepthVpsPresentFlag() == true); 
+    }
+#endif 
+    repFormat->setPicWidthVpsInLumaSamples                                ( m_acLayerCfg[mapIdxToLayer[idx]].getSourceWidth()   );
+    repFormat->setPicHeightVpsInLumaSamples                               ( m_acLayerCfg[mapIdxToLayer[idx]].getSourceHeight()  );
+#if AUXILIARY_PICTURES
+    repFormat->setChromaFormatVpsIdc                                      ( m_acLayerCfg[mapIdxToLayer[idx]].getChromaFormatIDC() );
+#else
+    repFormat->setChromaFormatVpsIdc                                      ( 1 );  // Need modification to change for each layer - corresponds to 420
+#endif
+    repFormat->setSeparateColourPlaneVpsFlag                              ( 0 );  // Need modification to change for each layer
+#if O0194_DIFFERENT_BITDEPTH_EL_BL
+    repFormat->setBitDepthVpsLuma                                         ( getInternalBitDepth(mapIdxToLayer[idx], CHANNEL_TYPE_LUMA)      );  // Need modification to change for each layer
+    repFormat->setBitDepthVpsChroma                                       ( getInternalBitDepth(mapIdxToLayer[idx], CHANNEL_TYPE_CHROMA)    );  // Need modification to change for each layer
+#else
+    repFormat->setBitDepthVpsLuma                                         ( getInternalBitDepth(CHANNEL_TYPE_LUMA)                        );  // Need modification to change for each layer
+    repFormat->setBitDepthVpsChroma                                       ( getInternalBitDepth(CHANNEL_TYPE_CHROMA)                      );  // Need modification to change for each layer
+#endif
+
+#if R0156_CONF_WINDOW_IN_REP_FORMAT
+    repFormat->getConformanceWindowVps().setWindow                        ( m_acLayerCfg[mapIdxToLayer[idx]].m_confWinLeft,                                                                             
+                                                                            m_acLayerCfg[mapIdxToLayer[idx]].m_confWinRight, 
+                                                                            m_acLayerCfg[mapIdxToLayer[idx]].m_confWinTop,
+                                                                            m_acLayerCfg[mapIdxToLayer[idx]].m_confWinBottom );
+#endif
+
+#if HIGHER_LAYER_IRAP_SKIP_FLAG
+    m_acTEncTop[mapIdxToLayer[idx]].setSkipPictureAtArcSwitch             ( m_skipPictureAtArcSwitch );
+#endif
+  }
+  delete [] mapIdxToLayer;
+#endif
+
+#if MULTIPLE_PTL_SUPPORT
+  //Populate PTL in VPS
+  TComVPS *pVPS = m_acTEncTop[0].getVPS();
+  for( Int ii = 0; ii < m_numPTLInfo; ii++ )
+  {
+    pVPS->getPTL(ii)->getGeneralPTL()->setLevelIdc(m_levelList[ii]);
+    pVPS->getPTL(ii)->getGeneralPTL()->setTierFlag(m_levelTierList[ii]);
+    pVPS->getPTL(ii)->getGeneralPTL()->setProfileIdc(m_profileList[ii]);
+    pVPS->getPTL(ii)->getGeneralPTL()->setProfileCompatibilityFlag(m_profileCompatibility[ii], 1);
+    pVPS->getPTL(ii)->getGeneralPTL()->setProgressiveSourceFlag(m_progressiveSourceFlagList[ii]);
+    pVPS->getPTL(ii)->getGeneralPTL()->setInterlacedSourceFlag(m_interlacedSourceFlagList[ii]);
+    pVPS->getPTL(ii)->getGeneralPTL()->setNonPackedConstraintFlag(m_nonPackedConstraintFlagList[ii]);
+    pVPS->getPTL(ii)->getGeneralPTL()->setFrameOnlyConstraintFlag(m_frameOnlyConstraintFlagList[ii]);
+  }
+  pVPS->setNumProfileTierLevel(m_numPTLInfo);
+
+  std::vector<int> myvector;
+  vps->getProfileLevelTierIdx()->resize(m_numOutputLayerSets);
+  for (int ii = 0; ii < m_numOutputLayerSets; ii++)
+  {
+    myvector =  m_listOfLayerPTLofOlss[ii];
+
+    for (std::vector<int>::iterator it = myvector.begin() ; it != myvector.end(); ++it)
+    {
+      pVPS->addProfileLevelTierIdx(ii, it[0]);
+    }
+  }
+#endif
+
+  assert( m_numLayers <= MAX_LAYERS );
+
+  for(UInt layer=0; layer<m_numLayers; layer++)
+  {
+#if O0194_DIFFERENT_BITDEPTH_EL_BL
+    //1
+    g_bitDepth[CHANNEL_TYPE_LUMA]   = m_acLayerCfg[layer].m_internalBitDepth[CHANNEL_TYPE_LUMA];
+    g_bitDepth[CHANNEL_TYPE_CHROMA] = m_acLayerCfg[layer].m_internalBitDepth[CHANNEL_TYPE_CHROMA];
+
+    g_PCMBitDepth[CHANNEL_TYPE_LUMA]   = m_bPCMInputBitDepthFlag ? m_acLayerCfg[layer].m_inputBitDepth[CHANNEL_TYPE_LUMA]   : m_acLayerCfg[layer].m_internalBitDepth[CHANNEL_TYPE_LUMA];
+    g_PCMBitDepth[CHANNEL_TYPE_CHROMA] = m_bPCMInputBitDepthFlag ? m_acLayerCfg[layer].m_inputBitDepth[CHANNEL_TYPE_CHROMA] : m_acLayerCfg[layer].m_internalBitDepth[CHANNEL_TYPE_CHROMA];
+
+    // Set this to be used in Upsampling filter in function "TComUpsampleFilter::upsampleBasePic"
+    g_bitDepthLayer[CHANNEL_TYPE_LUMA][m_acLayerCfg[layer].m_layerId]   = g_bitDepth[CHANNEL_TYPE_LUMA];
+    g_bitDepthLayer[CHANNEL_TYPE_CHROMA][m_acLayerCfg[layer].m_layerId] = g_bitDepth[CHANNEL_TYPE_CHROMA];
+
+#if O0194_WEIGHTED_PREDICTION_CGS
+    m_acTEncTop[layer].setInterLayerWeightedPredFlag                      ( m_useInterLayerWeightedPred );
+#endif
+#endif
+    
+#if MULTIPLE_PTL_SUPPORT
+    Int layerPTLIdx = m_acLayerCfg[layer].m_layerPTLIdx;
+    m_acTEncTop[layer].setProfile                                         ( m_profileList[layerPTLIdx] );
+    m_acTEncTop[layer].setLevel                                           ( m_levelTierList[layerPTLIdx], m_levelList[layerPTLIdx] );
+    m_acTEncTop[layer].setProgressiveSourceFlag                           ( m_progressiveSourceFlagList[layerPTLIdx] );
+    m_acTEncTop[layer].setInterlacedSourceFlag                            ( m_interlacedSourceFlagList[layerPTLIdx] );
+    m_acTEncTop[layer].setNonPackedConstraintFlag                         ( m_nonPackedConstraintFlagList[layerPTLIdx] );
+    m_acTEncTop[layer].setFrameOnlyConstraintFlag                         ( m_frameOnlyConstraintFlagList[layerPTLIdx] );
+    m_acTEncTop[layer].setBitDepthConstraintValue                         ( m_acLayerCfg[layer].m_bitDepthConstraint );
+    m_acTEncTop[layer].setChromaFormatConstraintValue                     ( m_acLayerCfg[layer].m_chromaFormatConstraint );
+    m_acTEncTop[layer].setIntraConstraintFlag                             ( m_acLayerCfg[layer].m_intraConstraintFlag );
+    m_acTEncTop[layer].setLowerBitRateConstraintFlag                      ( m_acLayerCfg[layer].m_lowerBitRateConstraintFlag );
+#else
+    m_acTEncTop[layer].setProfile                                         ( m_profile );
+    m_acTEncTop[layer].setLevel                                           ( m_levelTier, m_level );
+    m_acTEncTop[layer].setProgressiveSourceFlag                           ( m_progressiveSourceFlag );
+    m_acTEncTop[layer].setInterlacedSourceFlag                            ( m_interlacedSourceFlag );
+    m_acTEncTop[layer].setNonPackedConstraintFlag                         ( m_nonPackedConstraintFlag );
+    m_acTEncTop[layer].setFrameOnlyConstraintFlag                         ( m_frameOnlyConstraintFlag );
+    m_acTEncTop[layer].setBitDepthConstraintValue                         ( m_bitDepthConstraint );
+    m_acTEncTop[layer].setChromaFormatConstraintValue                     ( m_acLayerCfg[layer].m_chromaFormatConstraint );
+    m_acTEncTop[layer].setIntraConstraintFlag                             ( m_intraConstraintFlag );
+    m_acTEncTop[layer].setLowerBitRateConstraintFlag                      ( m_lowerBitRateConstraintFlag );
+#endif
+
+    m_acTEncTop[layer].setPrintMSEBasedSequencePSNR                       ( m_printMSEBasedSequencePSNR);
+    m_acTEncTop[layer].setPrintFrameMSE                                   ( m_printFrameMSE);
+    m_acTEncTop[layer].setPrintSequenceMSE                                ( m_printSequenceMSE);
+    m_acTEncTop[layer].setCabacZeroWordPaddingEnabled                     ( m_cabacZeroWordPaddingEnabled );
+
+    m_acTEncTop[layer].setFrameRate                                       ( m_acLayerCfg[layer].getFrameRate() );
+    m_acTEncTop[layer].setFrameSkip                                       ( m_FrameSkip );
+    m_acTEncTop[layer].setSourceWidth                                     ( m_acLayerCfg[layer].getSourceWidth() );
+    m_acTEncTop[layer].setSourceHeight                                    ( m_acLayerCfg[layer].getSourceHeight() );
+    m_acTEncTop[layer].setConformanceWindow                               ( m_acLayerCfg[layer].m_confWinLeft, m_acLayerCfg[layer].m_confWinRight, m_acLayerCfg[layer].m_confWinTop, m_acLayerCfg[layer].m_confWinBottom );
+    m_acTEncTop[layer].setFramesToBeEncoded                               ( m_framesToBeEncoded );
+
+#if REF_IDX_MFM
+#if AVC_BASE
+#if VPS_AVC_BL_FLAG_REMOVAL
+    m_acTEncTop[layer].setMFMEnabledFlag                                  (layer == 0 ? false : ( m_nonHEVCBaseLayerFlag ? false : true ) && m_acLayerCfg[layer].getNumMotionPredRefLayers());
+#else
+    m_acTEncTop[layer].setMFMEnabledFlag                                  (layer == 0 ? false : ( m_avcBaseLayerFlag ? false : true ) && m_acLayerCfg[layer].getNumMotionPredRefLayers());
+#endif
+#else
+    m_acTEncTop[layer].setMFMEnabledFlag                                  (layer == 0 ? false : ( m_acLayerCfg[layer].getNumMotionPredRefLayers() > 0 ) );
+#endif
+#endif
+    // set layer ID
+    m_acTEncTop[layer].setLayerId                                         ( m_acLayerCfg[layer].m_layerId );
+    m_acTEncTop[layer].setNumLayer                                        ( m_numLayers );
+    m_acTEncTop[layer].setLayerEnc                                        ( m_apcTEncTop );
+
+    //====== Coding Structure ========
+    m_acTEncTop[layer].setIntraPeriod                                     ( m_acLayerCfg[layer].m_iIntraPeriod );
+    m_acTEncTop[layer].setDecodingRefreshType                             ( m_iDecodingRefreshType );
+    m_acTEncTop[layer].setGOPSize                                         ( m_iGOPSize );
+#if Q0108_TSA_STSA
+    m_acTEncTop[layer].setGopList                                         ( layer ? m_EhGOPList[layer] : m_GOPList );
+#else
+    m_acTEncTop[layer].setGopList                                         ( m_GOPList );
+#endif
+
+#if !Q0108_TSA_STSA
+    m_acTEncTop[layer].setExtraRPSs                                       ( m_extraRPSs );
+#else
+    m_acTEncTop[layer].setExtraRPSs                                       ( m_extraRPSs[layer] );
+#endif
+    for(Int i = 0; i < MAX_TLAYER; i++)
+    {
+      m_acTEncTop[layer].setNumReorderPics                                ( m_numReorderPics[i], i );
+      m_acTEncTop[layer].setMaxDecPicBuffering                            ( m_maxDecPicBuffering[i], i );
+    }
+    for( UInt uiLoop = 0; uiLoop < MAX_TLAYER; ++uiLoop )
+    {
+      m_acTEncTop[layer].setLambdaModifier                                ( uiLoop, m_adLambdaModifier[ uiLoop ] );
+    }
+    m_acTEncTop[layer].setQP                                              ( m_acLayerCfg[layer].getIntQP() );
+
+    m_acTEncTop[layer].setPad                                             ( m_acLayerCfg[layer].getPad() );
+#if !Q0108_TSA_STSA
+    m_acTEncTop[layer].setMaxTempLayer                                    ( m_maxTempLayer );
+#else
+    if (layer== 0)
+    {
+      m_acTEncTop[layer].setMaxTempLayer                                  ( m_maxTempLayer );
+    }
+    else
+    {
+      m_acTEncTop[layer].setMaxTempLayer                                  ( m_EhMaxTempLayer[layer] );
+    }
+#endif
+    m_acTEncTop[layer].setUseAMP( m_enableAMP );
+
+    if( layer < m_numLayers - 1 )
+    {
+       m_acTEncTop[layer].setMaxTidIlRefPicsPlus1                         ( m_acLayerCfg[layer].getMaxTidIlRefPicsPlus1());
+    }
+
+#if VPS_EXTN_DIRECT_REF_LAYERS
+    if(layer)
+    {
+      UInt prevLayerIdx = 0;
+      UInt prevLayerId  = 0;
+      if (m_acLayerCfg[layer].getNumActiveRefLayers() > 0)
+      {
+        prevLayerIdx = m_acLayerCfg[layer].getPredLayerIdx(m_acLayerCfg[layer].getNumActiveRefLayers() - 1);
+        prevLayerId  = m_acTEncTop[layer].getRefLayerId(prevLayerIdx);
+      }
+      for(Int i = 0; i < MAX_VPS_LAYER_IDX_PLUS1; i++)
+      {
+        m_acTEncTop[layer].setSamplePredEnabledFlag                       (i, false);
+        m_acTEncTop[layer].setMotionPredEnabledFlag                       (i, false);
+      }
+      if(m_acLayerCfg[layer].getNumSamplePredRefLayers() == -1)
+      {
+        // Not included in the configuration file; assume that each layer depends on previous layer
+        m_acTEncTop[layer].setNumSamplePredRefLayers                      (1);      // One sample pred ref. layer
+        m_acTEncTop[layer].setSamplePredRefLayerId                        (prevLayerIdx, prevLayerId);   // Previous layer
+        m_acTEncTop[layer].setSamplePredEnabledFlag                       (prevLayerIdx, true);
+      }
+      else
+      {
+        m_acTEncTop[layer].setNumSamplePredRefLayers                      ( m_acLayerCfg[layer].getNumSamplePredRefLayers() );
+        for(Int i = 0; i < m_acTEncTop[layer].getNumSamplePredRefLayers(); i++)
+        {
+          m_acTEncTop[layer].setSamplePredRefLayerId                      ( i, m_acLayerCfg[layer].getSamplePredRefLayerId(i));
+        }
+      }
+      if(m_acLayerCfg[layer].getNumMotionPredRefLayers() == -1)
+      {
+        // Not included in the configuration file; assume that each layer depends on previous layer
+        m_acTEncTop[layer].setNumMotionPredRefLayers                      (1);      // One motion pred ref. layer
+        m_acTEncTop[layer].setMotionPredRefLayerId                        (prevLayerIdx, prevLayerId);   // Previous layer
+        m_acTEncTop[layer].setMotionPredEnabledFlag                       (prevLayerIdx, true);
+      }
+      else
+      {
+        m_acTEncTop[layer].setNumMotionPredRefLayers                      ( m_acLayerCfg[layer].getNumMotionPredRefLayers() );
+        for(Int i = 0; i < m_acTEncTop[layer].getNumMotionPredRefLayers(); i++)
+        {
+          m_acTEncTop[layer].setMotionPredRefLayerId                      ( i, m_acLayerCfg[layer].getMotionPredRefLayerId(i));
+        }
+      }
+      Int numDirectRefLayers = 0;
+
+      assert( layer < MAX_LAYERS );
+
+      for (Int i = 0; i < m_acLayerCfg[layer].m_layerId; i++)
+      {
+        Int refLayerId = -1;
+
+        for( Int layerIdc = 0; layerIdc < m_acTEncTop[layer].getNumSamplePredRefLayers(); layerIdc++ )
+        {
+          if( m_acLayerCfg[layer].getSamplePredRefLayerId(layerIdc) == i )
+          {
+            refLayerId = i;
+            m_acTEncTop[layer].setSamplePredEnabledFlag( numDirectRefLayers, true );
+            break;
+          }
+        }
+
+        for( Int layerIdc = 0; layerIdc < m_acTEncTop[layer].getNumMotionPredRefLayers(); layerIdc++ )
+        {
+          if( m_acLayerCfg[layer].getMotionPredRefLayerId(layerIdc) == i )
+          {
+            refLayerId = i;
+            m_acTEncTop[layer].setMotionPredEnabledFlag( numDirectRefLayers, true );
+            break;
+          }
+        }
+
+        if( refLayerId >= 0 )
+        {
+          m_acTEncTop[layer].setRefLayerId                                ( numDirectRefLayers, refLayerId );
+          numDirectRefLayers++;
+        }
+      }
+
+      m_acTEncTop[layer].setNumDirectRefLayers                            ( numDirectRefLayers );
+
+      if(m_acLayerCfg[layer].getNumActiveRefLayers() == -1)
+      {
+        m_acTEncTop[layer].setNumActiveRefLayers                          ( m_acTEncTop[layer].getNumDirectRefLayers() );
+        for( Int i = 0; i < m_acTEncTop[layer].getNumActiveRefLayers(); i++ )
+        {
+          m_acTEncTop[layer].setPredLayerIdx(i, i);
+        }
+      }
+      else
+      {
+        m_acTEncTop[layer].setNumActiveRefLayers                          ( m_acLayerCfg[layer].getNumActiveRefLayers() );
+        for(Int i = 0; i < m_acTEncTop[layer].getNumActiveRefLayers(); i++)
+        {
+          m_acTEncTop[layer].setPredLayerIdx                              ( i, m_acLayerCfg[layer].getPredLayerIdx(i));
+        }
+      }
+    }
+    else
+    {
+      assert( layer == 0 );
+      m_acTEncTop[layer].setNumDirectRefLayers(0);
+    }
+#endif //VPS_EXTN_DIRECT_REF_LAYERS
+    //===== Slice ========
+
+    //====== Loop/Deblock Filter ========
+    m_acTEncTop[layer].setLoopFilterDisable                                ( m_bLoopFilterDisable       );
+    m_acTEncTop[layer].setLoopFilterOffsetInPPS                            ( m_loopFilterOffsetInPPS );
+    m_acTEncTop[layer].setLoopFilterBetaOffset                             ( m_loopFilterBetaOffsetDiv2  );
+    m_acTEncTop[layer].setLoopFilterTcOffset                               ( m_loopFilterTcOffsetDiv2    );
+    m_acTEncTop[layer].setDeblockingFilterControlPresent                   ( m_DeblockingFilterControlPresent);
+    m_acTEncTop[layer].setDeblockingFilterMetric                           ( m_DeblockingFilterMetric );
+
+    //====== Motion search ========
+    m_acTEncTop[layer].setFastSearch                                       ( m_iFastSearch  );
+    m_acTEncTop[layer].setSearchRange                                      ( m_iSearchRange );
+    m_acTEncTop[layer].setBipredSearchRange                                ( m_bipredSearchRange );
+
+    //====== Quality control ========
+    m_acTEncTop[layer].setMaxDeltaQP                                       ( m_iMaxDeltaQP  );
+    m_acTEncTop[layer].setMaxCuDQPDepth                                    ( m_iMaxCuDQPDepth  );
+    m_acTEncTop[layer].setMaxCUChromaQpAdjustmentDepth                     ( m_maxCUChromaQpAdjustmentDepth );
+    m_acTEncTop[layer].setChromaCbQpOffset                                 ( m_cbQpOffset     );
+    m_acTEncTop[layer].setChromaCrQpOffset                                 ( m_crQpOffset  );
+
+    m_acTEncTop[layer].setChromaFormatIdc                                  ( m_acLayerCfg[layer].m_chromaFormatIDC  );
+
+#if ADAPTIVE_QP_SELECTION
+    m_acTEncTop[layer].setUseAdaptQpSelect                                 ( m_bUseAdaptQpSelect   );
+#endif
+    
+    m_acTEncTop[layer].setUseAdaptiveQP                                    ( m_bUseAdaptiveQP  );
+    m_acTEncTop[layer].setQPAdaptationRange                                ( m_iQPAdaptationRange );
+    m_acTEncTop[layer].setUseExtendedPrecision                             ( m_acLayerCfg[layer].m_useExtendedPrecision );
+    m_acTEncTop[layer].setUseHighPrecisionPredictionWeighting              ( m_acLayerCfg[layer].m_useHighPrecisionPredictionWeighting );
+
+    //====== Tool list ========    
+    m_acTEncTop[layer].setDeltaQpRD                                        ( m_uiDeltaQpRD  );
+    m_acTEncTop[layer].setUseASR                                           ( m_bUseASR      );
+    m_acTEncTop[layer].setUseHADME                                         ( m_bUseHADME    );    
+    m_acTEncTop[layer].setdQPs                                             ( m_acLayerCfg[layer].getdQPs() );
+    m_acTEncTop[layer].setUseRDOQ                                          ( m_useRDOQ     );
+    m_acTEncTop[layer].setUseRDOQTS                                        ( m_useRDOQTS   );
+    m_acTEncTop[layer].setRDpenalty                                        ( m_rdPenalty );
+#if LAYER_CTB
+    m_acTEncTop[layer].setQuadtreeTULog2MaxSize                            ( m_acLayerCfg[layer].m_uiQuadtreeTULog2MaxSize );
+    m_acTEncTop[layer].setQuadtreeTULog2MinSize                            ( m_acLayerCfg[layer].m_uiQuadtreeTULog2MinSize );
+    m_acTEncTop[layer].setQuadtreeTUMaxDepthInter                          ( m_acLayerCfg[layer].m_uiQuadtreeTUMaxDepthInter );
+    m_acTEncTop[layer].setQuadtreeTUMaxDepthIntra                          ( m_acLayerCfg[layer].m_uiQuadtreeTUMaxDepthIntra );
+#else
+    m_acTEncTop[layer].setQuadtreeTULog2MaxSize                            ( m_uiQuadtreeTULog2MaxSize );
+    m_acTEncTop[layer].setQuadtreeTULog2MinSize                            ( m_uiQuadtreeTULog2MinSize );
+    m_acTEncTop[layer].setQuadtreeTUMaxDepthInter                          ( m_uiQuadtreeTUMaxDepthInter );
+    m_acTEncTop[layer].setQuadtreeTUMaxDepthIntra                          ( m_uiQuadtreeTUMaxDepthIntra );
+#endif
+    m_acTEncTop[layer].setUseFastEnc                                       ( m_bUseFastEnc  );
+    m_acTEncTop[layer].setUseEarlyCU                                       ( m_bUseEarlyCU  );
+    m_acTEncTop[layer].setUseFastDecisionForMerge                          ( m_useFastDecisionForMerge  );
+    m_acTEncTop[layer].setUseCbfFastMode                                   ( m_bUseCbfFastMode  );
+    m_acTEncTop[layer].setUseEarlySkipDetection                            ( m_useEarlySkipDetection );
+    m_acTEncTop[layer].setUseCrossComponentPrediction                      ( m_useCrossComponentPrediction );
+    m_acTEncTop[layer].setUseReconBasedCrossCPredictionEstimate            ( m_reconBasedCrossCPredictionEstimate );
+    m_acTEncTop[layer].setSaoOffsetBitShift                                ( CHANNEL_TYPE_LUMA  , m_saoOffsetBitShift[CHANNEL_TYPE_LUMA]   );
+    m_acTEncTop[layer].setSaoOffsetBitShift                                ( CHANNEL_TYPE_CHROMA, m_saoOffsetBitShift[CHANNEL_TYPE_CHROMA] );
+    m_acTEncTop[layer].setUseTransformSkip                                 ( m_useTransformSkip      );
+    m_acTEncTop[layer].setUseTransformSkipFast                             ( m_useTransformSkipFast  );
+    m_acTEncTop[layer].setUseResidualRotation                              ( m_useResidualRotation   );
+    m_acTEncTop[layer].setUseSingleSignificanceMapContext                  ( m_useSingleSignificanceMapContext   );
+    m_acTEncTop[layer].setUseGolombRiceParameterAdaptation                 ( m_useGolombRiceParameterAdaptation );
+    m_acTEncTop[layer].setAlignCABACBeforeBypass                           ( m_alignCABACBeforeBypass );
+    m_acTEncTop[layer].setTransformSkipLog2MaxSize                         ( m_transformSkipLog2MaxSize  );
+    for (UInt signallingModeIndex = 0; signallingModeIndex < NUMBER_OF_RDPCM_SIGNALLING_MODES; signallingModeIndex++)
+    {
+      m_acTEncTop[layer].setUseResidualDPCM                                ( RDPCMSignallingMode(signallingModeIndex), m_useResidualDPCM[signallingModeIndex]);
+    }
+    m_acTEncTop[layer].setUseConstrainedIntraPred                          ( m_bUseConstrainedIntraPred );
+    m_acTEncTop[layer].setPCMLog2MinSize                                   ( m_uiPCMLog2MinSize);
+    m_acTEncTop[layer].setUsePCM                                           ( m_usePCM );
+    m_acTEncTop[layer].setPCMLog2MaxSize                                   ( m_pcmLog2MaxSize);
+    m_acTEncTop[layer].setMaxNumMergeCand                                  ( m_maxNumMergeCand );
+
+
+    //====== Weighted Prediction ========
+    m_acTEncTop[layer].setUseWP                                            ( m_useWeightedPred      );
+    m_acTEncTop[layer].setWPBiPred                                         ( m_useWeightedBiPred   );
+#if FAST_INTRA_SHVC
+    m_acTEncTop[layer].setUseFastIntraScalable                             ( m_useFastIntraScalable );
+#endif
+#if O0194_WEIGHTED_PREDICTION_CGS
+    if( layer != 0 && m_useInterLayerWeightedPred )
+    {
+      // Enable weighted prediction for enhancement layer
+      m_acTEncTop[layer].setUseWP                                           ( true   );
+      m_acTEncTop[layer].setWPBiPred                                        ( true   );
+    }
+#endif
+    //====== Parallel Merge Estimation ========
+    m_acTEncTop[layer].setLog2ParallelMergeLevelMinus2                      ( m_log2ParallelMergeLevel - 2 );
+
+    //====== Slice ========
+    m_acTEncTop[layer].setSliceMode                                         ( (SliceConstraint) m_sliceMode );
+    m_acTEncTop[layer].setSliceArgument                                     ( m_sliceArgument            );
+
+    //====== Dependent Slice ========
+    m_acTEncTop[layer].setSliceSegmentMode                                  ( (SliceConstraint) m_sliceSegmentMode );
+    m_acTEncTop[layer].setSliceSegmentArgument                              ( m_sliceSegmentArgument     );
+
+    if(m_sliceMode == NO_SLICES )
+    {
+      m_bLFCrossSliceBoundaryFlag = true;
+    }
+
+    m_acTEncTop[layer].setLFCrossSliceBoundaryFlag                          ( m_bLFCrossSliceBoundaryFlag );
+    m_acTEncTop[layer].setUseSAO                                            ( m_bUseSAO );
+    m_acTEncTop[layer].setMaxNumOffsetsPerPic                               ( m_maxNumOffsetsPerPic );
+
+    m_acTEncTop[layer].setSaoCtuBoundary                                    ( m_saoCtuBoundary );
+    m_acTEncTop[layer].setPCMInputBitDepthFlag                              ( m_bPCMInputBitDepthFlag);
+    m_acTEncTop[layer].setPCMFilterDisableFlag                              ( m_bPCMFilterDisableFlag);
+
+    m_acTEncTop[layer].setDisableIntraReferenceSmoothing                    (!m_enableIntraReferenceSmoothing );
+    m_acTEncTop[layer].setDecodedPictureHashSEIEnabled                      ( m_decodedPictureHashSEIEnabled );
+    m_acTEncTop[layer].setRecoveryPointSEIEnabled                           ( m_recoveryPointSEIEnabled );
+    m_acTEncTop[layer].setBufferingPeriodSEIEnabled                         ( m_bufferingPeriodSEIEnabled );
+    m_acTEncTop[layer].setPictureTimingSEIEnabled                           ( m_pictureTimingSEIEnabled );
+    m_acTEncTop[layer].setToneMappingInfoSEIEnabled                         ( m_toneMappingInfoSEIEnabled );
+    m_acTEncTop[layer].setTMISEIToneMapId                                   ( m_toneMapId );
+    m_acTEncTop[layer].setTMISEIToneMapCancelFlag                           ( m_toneMapCancelFlag );
+    m_acTEncTop[layer].setTMISEIToneMapPersistenceFlag                      ( m_toneMapPersistenceFlag );
+    m_acTEncTop[layer].setTMISEICodedDataBitDepth                           ( m_toneMapCodedDataBitDepth );
+    m_acTEncTop[layer].setTMISEITargetBitDepth                              ( m_toneMapTargetBitDepth );
+    m_acTEncTop[layer].setTMISEIModelID                                     ( m_toneMapModelId );
+    m_acTEncTop[layer].setTMISEIMinValue                                    ( m_toneMapMinValue );
+    m_acTEncTop[layer].setTMISEIMaxValue                                    ( m_toneMapMaxValue );
+    m_acTEncTop[layer].setTMISEISigmoidMidpoint                             ( m_sigmoidMidpoint );
+    m_acTEncTop[layer].setTMISEISigmoidWidth                                ( m_sigmoidWidth );
+    m_acTEncTop[layer].setTMISEIStartOfCodedInterva                         ( m_startOfCodedInterval );
+    m_acTEncTop[layer].setTMISEINumPivots                                   ( m_numPivots );
+    m_acTEncTop[layer].setTMISEICodedPivotValue                             ( m_codedPivotValue );
+    m_acTEncTop[layer].setTMISEITargetPivotValue                            ( m_targetPivotValue );
+    m_acTEncTop[layer].setTMISEICameraIsoSpeedIdc                           ( m_cameraIsoSpeedIdc );
+    m_acTEncTop[layer].setTMISEICameraIsoSpeedValue                         ( m_cameraIsoSpeedValue );
+    m_acTEncTop[layer].setTMISEIExposureIndexIdc                            ( m_exposureIndexIdc );
+    m_acTEncTop[layer].setTMISEIExposureIndexValue                          ( m_exposureIndexValue );
+    m_acTEncTop[layer].setTMISEIExposureCompensationValueSignFlag           ( m_exposureCompensationValueSignFlag );
+    m_acTEncTop[layer].setTMISEIExposureCompensationValueNumerator          ( m_exposureCompensationValueNumerator );
+    m_acTEncTop[layer].setTMISEIExposureCompensationValueDenomIdc           ( m_exposureCompensationValueDenomIdc );
+    m_acTEncTop[layer].setTMISEIRefScreenLuminanceWhite                     ( m_refScreenLuminanceWhite );
+    m_acTEncTop[layer].setTMISEIExtendedRangeWhiteLevel                     ( m_extendedRangeWhiteLevel );
+    m_acTEncTop[layer].setTMISEINominalBlackLevelLumaCodeValue              ( m_nominalBlackLevelLumaCodeValue );
+    m_acTEncTop[layer].setTMISEINominalWhiteLevelLumaCodeValue              ( m_nominalWhiteLevelLumaCodeValue );
+    m_acTEncTop[layer].setTMISEIExtendedWhiteLevelLumaCodeValue             ( m_extendedWhiteLevelLumaCodeValue );
+    m_acTEncTop[layer].setChromaSamplingFilterHintEnabled                   ( m_chromaSamplingFilterSEIenabled );
+    m_acTEncTop[layer].setChromaSamplingHorFilterIdc                        ( m_chromaSamplingHorFilterIdc );
+    m_acTEncTop[layer].setChromaSamplingVerFilterIdc                        ( m_chromaSamplingVerFilterIdc );
+    m_acTEncTop[layer].setFramePackingArrangementSEIEnabled                 ( m_framePackingSEIEnabled );
+    m_acTEncTop[layer].setFramePackingArrangementSEIType                    ( m_framePackingSEIType );
+    m_acTEncTop[layer].setFramePackingArrangementSEIId                      ( m_framePackingSEIId );
+    m_acTEncTop[layer].setFramePackingArrangementSEIQuincunx                ( m_framePackingSEIQuincunx );
+    m_acTEncTop[layer].setFramePackingArrangementSEIInterpretation          ( m_framePackingSEIInterpretation );
+    m_acTEncTop[layer].setSegmentedRectFramePackingArrangementSEIEnabled    ( m_segmentedRectFramePackingSEIEnabled );
+    m_acTEncTop[layer].setSegmentedRectFramePackingArrangementSEICancel     ( m_segmentedRectFramePackingSEICancel );
+    m_acTEncTop[layer].setSegmentedRectFramePackingArrangementSEIType       ( m_segmentedRectFramePackingSEIType );
+    m_acTEncTop[layer].setSegmentedRectFramePackingArrangementSEIPersistence( m_segmentedRectFramePackingSEIPersistence );
+    m_acTEncTop[layer].setDisplayOrientationSEIAngle                        ( m_displayOrientationSEIAngle );
+    m_acTEncTop[layer].setTemporalLevel0IndexSEIEnabled                     ( m_temporalLevel0IndexSEIEnabled );
+    m_acTEncTop[layer].setGradualDecodingRefreshInfoEnabled                 ( m_gradualDecodingRefreshInfoEnabled );
+    m_acTEncTop[layer].setNoDisplaySEITLayer                                ( m_noDisplaySEITLayer );
+    m_acTEncTop[layer].setDecodingUnitInfoSEIEnabled                        ( m_decodingUnitInfoSEIEnabled );
+    m_acTEncTop[layer].setSOPDescriptionSEIEnabled                          ( m_SOPDescriptionSEIEnabled );
+    m_acTEncTop[layer].setScalableNestingSEIEnabled                         ( m_scalableNestingSEIEnabled );
+    m_acTEncTop[layer].setTMCTSSEIEnabled                                   ( m_tmctsSEIEnabled );
+    m_acTEncTop[layer].setTimeCodeSEIEnabled                                ( m_timeCodeSEIEnabled );
+    m_acTEncTop[layer].setNumberOfTimeSets                                  ( m_timeCodeSEINumTs );
+    for(Int i = 0; i < m_timeCodeSEINumTs; i++) { m_acTEncTop[layer].setTimeSet(m_timeSetArray[i], i); }
+    m_acTEncTop[layer].setKneeSEIEnabled                                    ( m_kneeSEIEnabled );
+    m_acTEncTop[layer].setKneeSEIId                                         ( m_kneeSEIId );
+    m_acTEncTop[layer].setKneeSEICancelFlag                                 ( m_kneeSEICancelFlag );
+    m_acTEncTop[layer].setKneeSEIPersistenceFlag                            ( m_kneeSEIPersistenceFlag );    
+    m_acTEncTop[layer].setKneeSEIInputDrange                                ( m_kneeSEIInputDrange );
+    m_acTEncTop[layer].setKneeSEIInputDispLuminance                         ( m_kneeSEIInputDispLuminance );
+    m_acTEncTop[layer].setKneeSEIOutputDrange                               ( m_kneeSEIOutputDrange );
+    m_acTEncTop[layer].setKneeSEIOutputDispLuminance                        ( m_kneeSEIOutputDispLuminance );
+    m_acTEncTop[layer].setKneeSEINumKneePointsMinus1                        ( m_kneeSEINumKneePointsMinus1 );
+    m_acTEncTop[layer].setKneeSEIInputKneePoint                             ( m_kneeSEIInputKneePoint );
+    m_acTEncTop[layer].setKneeSEIOutputKneePoint                            ( m_kneeSEIOutputKneePoint );
+    m_acTEncTop[layer].setMasteringDisplaySEI                               ( m_masteringDisplay );
+#if P0123_ALPHA_CHANNEL_SEI
+    m_acTEncTop[layer].setAlphaSEIEnabled                                   ( m_alphaSEIEnabled );
+    m_acTEncTop[layer].setAlphaCancelFlag                                   ( m_alphaCancelFlag );
+    m_acTEncTop[layer].setAlphaUseIdc                                       ( m_alphaUseIdc );
+    m_acTEncTop[layer].setAlphaBitDepthMinus8                               ( m_alphaBitDepthMinus8 );
+    m_acTEncTop[layer].setAlphaTransparentValue                             ( m_alphaTransparentValue );
+    m_acTEncTop[layer].setAlphaOpaqueValue                                  ( m_alphaOpaqueValue );
+    m_acTEncTop[layer].setAlphaIncrementFlag                                ( m_alphaIncrementFlag );
+    m_acTEncTop[layer].setAlphaClipFlag                                     ( m_alphaClipFlag );
+    m_acTEncTop[layer].setAlphaClipTypeFlag                                 ( m_alphaClipTypeFlag );
+#endif
+#if Q0096_OVERLAY_SEI
+    m_acTEncTop[layer].setOverlaySEIEnabled                                 ( m_overlaySEIEnabled );
+    m_acTEncTop[layer].setOverlaySEICancelFlag                              ( m_overlayInfoCancelFlag );
+    m_acTEncTop[layer].setOverlaySEIContentAuxIdMinus128                    ( m_overlayContentAuxIdMinus128 );
+    m_acTEncTop[layer].setOverlaySEILabelAuxIdMinus128                      ( m_overlayLabelAuxIdMinus128 );
+    m_acTEncTop[layer].setOverlaySEIAlphaAuxIdMinus128                      ( m_overlayAlphaAuxIdMinus128 );
+    m_acTEncTop[layer].setOverlaySEIElementLabelValueLengthMinus8           ( m_overlayElementLabelValueLengthMinus8 );
+    m_acTEncTop[layer].setOverlaySEINumOverlaysMinus1                       ( m_numOverlaysMinus1 );
+    m_acTEncTop[layer].setOverlaySEIIdx                                     ( m_overlayIdx );
+    m_acTEncTop[layer].setOverlaySEILanguagePresentFlag                     ( m_overlayLanguagePresentFlag );
+    m_acTEncTop[layer].setOverlaySEIContentLayerId                          ( m_overlayContentLayerId );
+    m_acTEncTop[layer].setOverlaySEILabelPresentFlag                        ( m_overlayLabelPresentFlag );
+    m_acTEncTop[layer].setOverlaySEILabelLayerId                            ( m_overlayLabelLayerId );
+    m_acTEncTop[layer].setOverlaySEIAlphaPresentFlag                        ( m_overlayAlphaPresentFlag );
+    m_acTEncTop[layer].setOverlaySEIAlphaLayerId                            ( m_overlayAlphaLayerId );
+    m_acTEncTop[layer].setOverlaySEINumElementsMinus1                       ( m_numOverlayElementsMinus1 );
+    m_acTEncTop[layer].setOverlaySEIElementLabelMin                         ( m_overlayElementLabelMin );
+    m_acTEncTop[layer].setOverlaySEIElementLabelMax                         ( m_overlayElementLabelMax );
+    m_acTEncTop[layer].setOverlaySEILanguage                                ( m_overlayLanguage );
+    m_acTEncTop[layer].setOverlaySEIName                                    ( m_overlayName );
+    m_acTEncTop[layer].setOverlaySEIElementName                             ( m_overlayElementName );
+    m_acTEncTop[layer].setOverlaySEIPersistenceFlag                         ( m_overlayInfoPersistenceFlag );
+#endif
+#if Q0074_COLOUR_REMAPPING_SEI
+    m_acTEncTop[layer].setCRISEIFile                            ( const_cast<Char*>(m_acLayerCfg[layer].m_colourRemapSEIFile.c_str()) );
+    m_acTEncTop[layer].setCRISEIId                              ( m_acLayerCfg[layer].m_colourRemapSEIId );
+    m_acTEncTop[layer].setCRISEICancelFlag                      ( m_acLayerCfg[layer].m_colourRemapSEICancelFlag );
+    m_acTEncTop[layer].setCRISEIPersistenceFlag                 ( m_acLayerCfg[layer].m_colourRemapSEIPersistenceFlag );
+    m_acTEncTop[layer].setCRISEIVideoSignalInfoPresentFlag      ( m_acLayerCfg[layer].m_colourRemapSEIVideoSignalInfoPresentFlag );
+    m_acTEncTop[layer].setCRISEIFullRangeFlag                   ( m_acLayerCfg[layer].m_colourRemapSEIFullRangeFlag );
+    m_acTEncTop[layer].setCRISEIPrimaries                       ( m_acLayerCfg[layer].m_colourRemapSEIPrimaries );
+    m_acTEncTop[layer].setCRISEITransferFunction                ( m_acLayerCfg[layer].m_colourRemapSEITransferFunction );
+    m_acTEncTop[layer].setCRISEIMatrixCoefficients              ( m_acLayerCfg[layer].m_colourRemapSEIMatrixCoefficients );
+    m_acTEncTop[layer].setCRISEIInputBitDepth                   ( m_acLayerCfg[layer].m_colourRemapSEIInputBitDepth );
+    m_acTEncTop[layer].setCRISEIBitDepth                        ( m_acLayerCfg[layer].m_colourRemapSEIBitDepth );
+    m_acTEncTop[layer].setCRISEIPreLutNumValMinus1              ( m_acLayerCfg[layer].m_colourRemapSEIPreLutNumValMinus1 );
+    m_acTEncTop[layer].setCRISEIPreLutCodedValue                ( m_acLayerCfg[layer].m_colourRemapSEIPreLutCodedValue );
+    m_acTEncTop[layer].setCRISEIPreLutTargetValue               ( m_acLayerCfg[layer].m_colourRemapSEIPreLutTargetValue );
+    m_acTEncTop[layer].setCRISEIMatrixPresentFlag               ( m_acLayerCfg[layer].m_colourRemapSEIMatrixPresentFlag );
+    m_acTEncTop[layer].setCRISEILog2MatrixDenom                 ( m_acLayerCfg[layer].m_colourRemapSEILog2MatrixDenom );
+    m_acTEncTop[layer].setCRISEICoeffs                          ( m_acLayerCfg[layer].m_colourRemapSEICoeffs );
+    m_acTEncTop[layer].setCRISEIPostLutNumValMinus1             ( m_acLayerCfg[layer].m_colourRemapSEIPostLutNumValMinus1 );
+    m_acTEncTop[layer].setCRISEIPostLutCodedValue               ( m_acLayerCfg[layer]. m_colourRemapSEIPostLutCodedValue );
+    m_acTEncTop[layer].setCRISEIPostLutTargetValue              ( m_acLayerCfg[layer].m_colourRemapSEIPostLutTargetValue );
+#endif    
+#if LAYERS_NOT_PRESENT_SEI
+    m_acTEncTop[layer].setLayersNotPresentSEIEnabled            ( m_layersNotPresentSEIEnabled );
+#endif    
+#if Q0189_TMVP_CONSTRAINTS
+    m_acTEncTop[layer].setTMVPConstraintsSEIEnabled             ( m_TMVPConstraintsSEIEnabled);           
+#endif
+#if N0383_IL_CONSTRAINED_TILE_SETS_SEI
+    m_acTEncTop[layer].setInterLayerConstrainedTileSetsSEIEnabled( m_interLayerConstrainedTileSetsSEIEnabled );
+    m_acTEncTop[layer].setIlNumSetsInMessage                    ( m_ilNumSetsInMessage );
+    m_acTEncTop[layer].setSkippedTileSetPresentFlag             ( m_skippedTileSetPresentFlag );
+    m_acTEncTop[layer].setTopLeftTileIndex                      ( m_topLeftTileIndex );
+    m_acTEncTop[layer].setBottomRightTileIndex                  ( m_bottomRightTileIndex );
+    m_acTEncTop[layer].setIlcIdc                                ( m_ilcIdc );
+#endif
+    m_acTEncTop[layer].setTileUniformSpacingFlag                ( m_tileUniformSpacingFlag );
+    m_acTEncTop[layer].setNumColumnsMinus1                      ( m_numTileColumnsMinus1 );
+    m_acTEncTop[layer].setNumRowsMinus1                         ( m_numTileRowsMinus1 );
+    if(!m_tileUniformSpacingFlag)
+    {
+      m_acTEncTop[layer].setColumnWidth                         ( m_tileColumnWidth );
+      m_acTEncTop[layer].setRowHeight                           ( m_tileRowHeight );
+    }
+    m_acTEncTop[layer].xCheckGSParameters();
+    Int uiTilesCount = (m_numTileRowsMinus1+1) * (m_numTileColumnsMinus1+1);
+    if(uiTilesCount == 1)
+    {
+      m_bLFCrossTileBoundaryFlag = true;
+    }
+    m_acTEncTop[layer].setLFCrossTileBoundaryFlag               ( m_bLFCrossTileBoundaryFlag );
+    m_acTEncTop[layer].setWaveFrontSynchro                      ( m_acLayerCfg[layer].m_waveFrontSynchro );
+    m_acTEncTop[layer].setWaveFrontSubstreams                   ( m_acLayerCfg[layer].m_iWaveFrontSubstreams );
+    m_acTEncTop[layer].setTMVPModeId                            ( m_TMVPModeId );
+    m_acTEncTop[layer].setUseScalingListId                      ( m_useScalingListId  );
+    m_acTEncTop[layer].setScalingListFile                       ( m_scalingListFile   );
+    m_acTEncTop[layer].setSignHideFlag                          ( m_signHideFlag );
+#if RC_SHVC_HARMONIZATION
+    m_acTEncTop[layer].setUseRateCtrl                           ( m_acLayerCfg[layer].getRCEnableRateControl() );
+    m_acTEncTop[layer].setTargetBitrate                         ( m_acLayerCfg[layer].getRCTargetBitrate() );
+    m_acTEncTop[layer].setKeepHierBit                           ( m_acLayerCfg[layer].getRCKeepHierarchicalBit() );
+    m_acTEncTop[layer].setLCULevelRC                            ( m_acLayerCfg[layer].getRCLCULevelRC() );
+    m_acTEncTop[layer].setUseLCUSeparateModel                   ( m_acLayerCfg[layer].getRCUseLCUSeparateModel() );
+    m_acTEncTop[layer].setInitialQP                             ( m_acLayerCfg[layer].getRCInitialQP() );
+    m_acTEncTop[layer].setForceIntraQP                          ( m_acLayerCfg[layer].getRCForceIntraQP() );
+#else
+    m_acTEncTop[layer].setUseRateCtrl                           ( m_RCEnableRateControl );
+    m_acTEncTop[layer].setTargetBitrate                         ( m_RCTargetBitrate );
+    m_acTEncTop[layer].setKeepHierBit                           ( m_RCKeepHierarchicalBit );
+    m_acTEncTop[layer].setLCULevelRC                            ( m_RCLCULevelRC );
+    m_acTEncTop[layer].setUseLCUSeparateModel                   ( m_RCUseLCUSeparateModel );
+    m_acTEncTop[layer].setInitialQP                             ( m_RCInitialQP );
+    m_acTEncTop[layer].setForceIntraQP                          ( m_RCForceIntraQP );
+#endif
+    m_acTEncTop[layer].setTransquantBypassEnableFlag            ( m_TransquantBypassEnableFlag );
+    m_acTEncTop[layer].setCUTransquantBypassFlagForceValue      ( m_CUTransquantBypassFlagForce );
+    m_acTEncTop[layer].setCostMode                              ( m_costMode );
+    m_acTEncTop[layer].setUseRecalculateQPAccordingToLambda     ( m_recalculateQPAccordingToLambda );
+    m_acTEncTop[layer].setUseStrongIntraSmoothing               ( m_useStrongIntraSmoothing );
+    m_acTEncTop[layer].setActiveParameterSetsSEIEnabled         ( m_activeParameterSetsSEIEnabled );
+    m_acTEncTop[layer].setVuiParametersPresentFlag              ( m_vuiParametersPresentFlag );
+    m_acTEncTop[layer].setAspectRatioInfoPresentFlag            ( m_aspectRatioInfoPresentFlag);
+    m_acTEncTop[layer].setAspectRatioIdc                        ( m_aspectRatioIdc );
+    m_acTEncTop[layer].setSarWidth                              ( m_sarWidth );
+    m_acTEncTop[layer].setSarHeight                             ( m_sarHeight );
+    m_acTEncTop[layer].setOverscanInfoPresentFlag               ( m_overscanInfoPresentFlag );
+    m_acTEncTop[layer].setOverscanAppropriateFlag               ( m_overscanAppropriateFlag );
+    m_acTEncTop[layer].setVideoSignalTypePresentFlag            ( m_videoSignalTypePresentFlag );
+    m_acTEncTop[layer].setVideoFormat                           ( m_videoFormat );
+    m_acTEncTop[layer].setVideoFullRangeFlag                    ( m_videoFullRangeFlag );
+    m_acTEncTop[layer].setColourDescriptionPresentFlag          ( m_colourDescriptionPresentFlag );
+    m_acTEncTop[layer].setColourPrimaries                       ( m_colourPrimaries );
+    m_acTEncTop[layer].setTransferCharacteristics               ( m_transferCharacteristics );
+    m_acTEncTop[layer].setMatrixCoefficients                    ( m_matrixCoefficients );
+    m_acTEncTop[layer].setChromaLocInfoPresentFlag              ( m_chromaLocInfoPresentFlag );
+    m_acTEncTop[layer].setChromaSampleLocTypeTopField           ( m_chromaSampleLocTypeTopField );
+    m_acTEncTop[layer].setChromaSampleLocTypeBottomField        ( m_chromaSampleLocTypeBottomField );
+    m_acTEncTop[layer].setNeutralChromaIndicationFlag           ( m_neutralChromaIndicationFlag );
+    m_acTEncTop[layer].setDefaultDisplayWindow                  ( m_defDispWinLeftOffset, m_defDispWinRightOffset, m_defDispWinTopOffset, m_defDispWinBottomOffset );
+    m_acTEncTop[layer].setFrameFieldInfoPresentFlag             ( m_frameFieldInfoPresentFlag );
+    m_acTEncTop[layer].setPocProportionalToTimingFlag           ( m_pocProportionalToTimingFlag );
+    m_acTEncTop[layer].setNumTicksPocDiffOneMinus1              ( m_numTicksPocDiffOneMinus1    );
+    m_acTEncTop[layer].setBitstreamRestrictionFlag              ( m_bitstreamRestrictionFlag );
+    m_acTEncTop[layer].setTilesFixedStructureFlag               ( m_tilesFixedStructureFlag );
+    m_acTEncTop[layer].setMotionVectorsOverPicBoundariesFlag    ( m_motionVectorsOverPicBoundariesFlag );
+    m_acTEncTop[layer].setMinSpatialSegmentationIdc             ( m_minSpatialSegmentationIdc );
+    m_acTEncTop[layer].setMaxBytesPerPicDenom                   ( m_maxBytesPerPicDenom );
+    m_acTEncTop[layer].setMaxBitsPerMinCuDenom                  ( m_maxBitsPerMinCuDenom );
+    m_acTEncTop[layer].setLog2MaxMvLengthHorizontal             ( m_log2MaxMvLengthHorizontal );
+    m_acTEncTop[layer].setLog2MaxMvLengthVertical               ( m_log2MaxMvLengthVertical );
+    m_acTEncTop[layer].setElRapSliceTypeB                       (layer == 0? 0 : m_elRapSliceBEnabled);
+
+    if( layer > 0 )
+    {
+#if REF_REGION_OFFSET
+#if AUXILIARY_PICTURES
+      Int subWidthC  = ( m_acLayerCfg[layer].m_chromaFormatIDC == CHROMA_420 || m_acLayerCfg[layer].m_chromaFormatIDC == CHROMA_422 ) ? 2 : 1;
+      Int subHeightC = ( m_acLayerCfg[layer].m_chromaFormatIDC == CHROMA_420 ) ? 2 : 1;
+#else
+      Int subWidthC  = 2;
+      Int subHeightC = 2;
+#endif
+#endif
+      m_acTEncTop[layer].setNumRefLayerLocationOffsets          ( m_acLayerCfg[layer].m_numRefLayerLocationOffsets );
+      for(Int i = 0; i < m_acLayerCfg[layer].m_numRefLayerLocationOffsets; i++)
+      {
+#if O0098_SCALED_REF_LAYER_ID
+        m_acTEncTop[layer].setRefLocationOffsetLayerId          (i, m_acLayerCfg[layer].m_refLocationOffsetLayerId[i]);
+#endif
+#if REF_REGION_OFFSET
+        m_acTEncTop[layer].setScaledRefLayerOffsetPresentFlag   ( i, m_acLayerCfg[layer].m_scaledRefLayerOffsetPresentFlag[i] );
+        m_acTEncTop[layer].getScaledRefLayerWindow(i).setWindow ( subWidthC  * m_acLayerCfg[layer].m_scaledRefLayerLeftOffset[i], subWidthC  * m_acLayerCfg[layer].m_scaledRefLayerRightOffset[i],
+                                                                  subHeightC * m_acLayerCfg[layer].m_scaledRefLayerTopOffset[i],  subHeightC * m_acLayerCfg[layer].m_scaledRefLayerBottomOffset[i]);
+#else
+#if P0312_VERT_PHASE_ADJ
+        m_acTEncTop[layer].setVertPhasePositionEnableFlag       ( i, m_acLayerCfg[layer].m_vertPhasePositionEnableFlag[i] );
+        m_acTEncTop[layer].getScaledRefLayerWindow(i).setWindow ( 2*m_acLayerCfg[layer].m_scaledRefLayerLeftOffset[i], 2*m_acLayerCfg[layer].m_scaledRefLayerRightOffset[i],
+          2*m_acLayerCfg[layer].m_scaledRefLayerTopOffset[i], 2*m_acLayerCfg[layer].m_scaledRefLayerBottomOffset[i], m_acLayerCfg[layer].m_vertPhasePositionEnableFlag[i] );
+#else
+        m_acTEncTop[layer].getScaledRefLayerWindow(i).setWindow ( 2*m_acLayerCfg[layer].m_scaledRefLayerLeftOffset[i], 2*m_acLayerCfg[layer].m_scaledRefLayerRightOffset[i],
+          2*m_acLayerCfg[layer].m_scaledRefLayerTopOffset[i], 2*m_acLayerCfg[layer].m_scaledRefLayerBottomOffset[i]);
+#endif
+#endif
+        Int rlSubWidthC  = ( m_acLayerCfg[i].m_chromaFormatIDC == CHROMA_420 || m_acLayerCfg[i].m_chromaFormatIDC == CHROMA_422 ) ? 2 : 1;
+        Int rlSubHeightC = ( m_acLayerCfg[i].m_chromaFormatIDC == CHROMA_420 ) ? 2 : 1;
+
+        m_acTEncTop[layer].setRefRegionOffsetPresentFlag        ( i, m_acLayerCfg[layer].m_refRegionOffsetPresentFlag[i] );
+        m_acTEncTop[layer].getRefLayerWindow(i).setWindow       ( rlSubWidthC  * m_acLayerCfg[layer].m_refRegionLeftOffset[i], rlSubWidthC  * m_acLayerCfg[layer].m_refRegionRightOffset[i],
+                                                                  rlSubHeightC * m_acLayerCfg[layer].m_refRegionTopOffset[i],  rlSubHeightC * m_acLayerCfg[layer].m_refRegionBottomOffset[i]);
+#if R0209_GENERIC_PHASE
+        m_acTEncTop[layer].setResamplePhaseSetPresentFlag       ( i, m_acLayerCfg[layer].m_resamplePhaseSetPresentFlag[i] );
+        m_acTEncTop[layer].setPhaseHorLuma                      ( i, m_acLayerCfg[layer].m_phaseHorLuma[i] );
+        m_acTEncTop[layer].setPhaseVerLuma                      ( i, m_acLayerCfg[layer].m_phaseVerLuma[i] );
+        m_acTEncTop[layer].setPhaseHorChroma                    ( i, m_acLayerCfg[layer].m_phaseHorChroma[i] );
+        m_acTEncTop[layer].setPhaseVerChroma                    ( i, m_acLayerCfg[layer].m_phaseVerChroma[i] );
+#endif
+      }
+    }
+
+#if M0040_ADAPTIVE_RESOLUTION_CHANGE
+    m_acTEncTop[layer].setAdaptiveResolutionChange               ( m_adaptiveResolutionChange );
+#endif
+#if R0071_IRAP_EOS_CROSS_LAYER_IMPACTS
+    m_acTEncTop[layer].setLayerSwitchOffBegin                    (m_acLayerCfg[layer].m_layerSwitchOffBegin);
+    m_acTEncTop[layer].setLayerSwitchOffEnd                      (m_acLayerCfg[layer].m_layerSwitchOffEnd);
+#endif
+#if AUXILIARY_PICTURES
+    m_acTEncTop[layer].setChromaFormatIDC                        ( m_acLayerCfg[layer].m_chromaFormatIDC );
+#endif
+#if O0153_ALT_OUTPUT_LAYER_FLAG
+    m_acTEncTop[layer].setAltOuputLayerFlag                      ( m_altOutputLayerFlag );
+#endif
+#if O0149_CROSS_LAYER_BLA_FLAG
+    m_acTEncTop[layer].setCrossLayerBLAFlag                      ( m_crossLayerBLAFlag );
+#endif
+#if Q0048_CGS_3D_ASYMLUT
+    m_acTEncTop[layer].setCGSFlag                                ( layer == 0 ? 0 : m_nCGSFlag );
+    m_acTEncTop[layer].setCGSMaxOctantDepth                      ( m_nCGSMaxOctantDepth );
+    m_acTEncTop[layer].setCGSMaxYPartNumLog2                     ( m_nCGSMaxYPartNumLog2 );
+    m_acTEncTop[layer].setCGSLUTBit                              ( m_nCGSLUTBit );
+#if R0151_CGS_3D_ASYMLUT_IMPROVE
+    m_acTEncTop[layer].setCGSAdaptChroma                         ( m_nCGSAdaptiveChroma );
+#endif
+#if R0179_ENC_OPT_3DLUT_SIZE
+    m_acTEncTop[layer].setCGSLutSizeRDO                          ( m_nCGSLutSizeRDO );
+#endif
+#endif
+#if Q0078_ADD_LAYER_SETS
+    m_acTEncTop[layer].setNumAddLayerSets                        ( m_numAddLayerSets );
+#endif
+  }
+}
+#else //SVC_EXTENSION
+Void TAppEncTop::xInitLibCfg()
+{
+  TComVPS vps;
+
+  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 );
+  }
+  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.setBitDepthConstraintValue                           ( m_bitDepthConstraint );
+  m_cTEncTop.setChromaFormatConstraintValue                       ( m_chromaFormatConstraint );
+  m_cTEncTop.setIntraConstraintFlag                               ( m_intraConstraintFlag );
+  m_cTEncTop.setLowerBitRateConstraintFlag                        ( m_lowerBitRateConstraintFlag );
+
+  m_cTEncTop.setPrintMSEBasedSequencePSNR                         ( m_printMSEBasedSequencePSNR);
+  m_cTEncTop.setPrintFrameMSE                                     ( m_printFrameMSE);
+  m_cTEncTop.setPrintSequenceMSE                                  ( m_printSequenceMSE);
+  m_cTEncTop.setCabacZeroWordPaddingEnabled                       ( m_cabacZeroWordPaddingEnabled );
+
+  m_cTEncTop.setFrameRate                                         ( m_iFrameRate );
+  m_cTEncTop.setFrameSkip                                         ( m_FrameSkip );
+  m_cTEncTop.setSourceWidth                                       ( m_iSourceWidth );
+  m_cTEncTop.setSourceHeight                                      ( m_iSourceHeight );
+  m_cTEncTop.setConformanceWindow                                 ( m_confWinLeft, m_confWinRight, m_confWinTop, m_confWinBottom );
+  m_cTEncTop.setFramesToBeEncoded                                 ( m_framesToBeEncoded );
+
+  //====== Coding Structure ========
+  m_cTEncTop.setIntraPeriod                                       ( m_iIntraPeriod );
+  m_cTEncTop.setDecodingRefreshType                               ( m_iDecodingRefreshType );
+  m_cTEncTop.setGOPSize                                           ( m_iGOPSize );
+  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 );
+  }
+  for( UInt uiLoop = 0; uiLoop < MAX_TLAYER; ++uiLoop )
+  {
+    m_cTEncTop.setLambdaModifier                                  ( uiLoop, m_adLambdaModifier[ uiLoop ] );
+  }
+  m_cTEncTop.setQP                                                ( m_iQP );
+
+  m_cTEncTop.setPad                                               ( m_aiPad );
+
+  m_cTEncTop.setMaxTempLayer                                      ( m_maxTempLayer );
+  m_cTEncTop.setUseAMP( m_enableAMP );
+
+  //===== Slice ========
+
+  //====== Loop/Deblock Filter ========
+  m_cTEncTop.setLoopFilterDisable                                 ( m_bLoopFilterDisable       );
+  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.setMaxCUChromaQpAdjustmentDepth                      ( m_maxCUChromaQpAdjustmentDepth );
+  m_cTEncTop.setChromaCbQpOffset                                  ( m_cbQpOffset     );
+  m_cTEncTop.setChromaCrQpOffset                                  ( m_crQpOffset  );
+
+  m_cTEncTop.setChromaFormatIdc                                   ( m_chromaFormatIDC  );
+
+#if ADAPTIVE_QP_SELECTION
+  m_cTEncTop.setUseAdaptQpSelect                                  ( m_bUseAdaptQpSelect   );
+#endif
+
+  m_cTEncTop.setUseAdaptiveQP                                     ( m_bUseAdaptiveQP  );
+  m_cTEncTop.setQPAdaptationRange                                 ( m_iQPAdaptationRange );
+  m_cTEncTop.setUseExtendedPrecision                              ( m_useExtendedPrecision );
+  m_cTEncTop.setUseHighPrecisionPredictionWeighting               ( m_useHighPrecisionPredictionWeighting );
+  //====== Tool list ========
+  m_cTEncTop.setDeltaQpRD                                         ( m_uiDeltaQpRD  );
+  m_cTEncTop.setUseASR                                            ( m_bUseASR      );
+  m_cTEncTop.setUseHADME                                          ( m_bUseHADME    );
+  m_cTEncTop.setdQPs                                              ( m_aidQP        );
+  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 );
+#if FAST_INTRA_SHVC
+  m_cTEncTop.setUseFastIntraScalable                              ( m_useFastIntraScalable );
+#endif
+  m_cTEncTop.setUseCrossComponentPrediction                       ( m_useCrossComponentPrediction );
+  m_cTEncTop.setUseReconBasedCrossCPredictionEstimate             ( m_reconBasedCrossCPredictionEstimate );
+  m_cTEncTop.setSaoOffsetBitShift                                 ( CHANNEL_TYPE_LUMA  , m_saoOffsetBitShift[CHANNEL_TYPE_LUMA]   );
+  m_cTEncTop.setSaoOffsetBitShift                                 ( CHANNEL_TYPE_CHROMA, m_saoOffsetBitShift[CHANNEL_TYPE_CHROMA] );
+  m_cTEncTop.setUseTransformSkip                                  ( m_useTransformSkip      );
+  m_cTEncTop.setUseTransformSkipFast                              ( m_useTransformSkipFast  );
+  m_cTEncTop.setUseResidualRotation                               ( m_useResidualRotation   );
+  m_cTEncTop.setUseSingleSignificanceMapContext                   ( m_useSingleSignificanceMapContext   );
+  m_cTEncTop.setUseGolombRiceParameterAdaptation                  ( m_useGolombRiceParameterAdaptation );
+  m_cTEncTop.setAlignCABACBeforeBypass                            ( m_alignCABACBeforeBypass );
+  m_cTEncTop.setTransformSkipLog2MaxSize                          ( m_transformSkipLog2MaxSize  );
+  for (UInt signallingModeIndex = 0; signallingModeIndex < NUMBER_OF_RDPCM_SIGNALLING_MODES; signallingModeIndex++)
+  {
+    m_cTEncTop.setUseResidualDPCM                                 ( RDPCMSignallingMode(signallingModeIndex), m_useResidualDPCM[signallingModeIndex]);
+  }
+  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                                         ( (SliceConstraint) m_sliceMode );
+  m_cTEncTop.setSliceArgument                                     ( m_sliceArgument            );
+
+  //====== Dependent Slice ========
+  m_cTEncTop.setSliceSegmentMode                                  (  (SliceConstraint) m_sliceSegmentMode );
+  m_cTEncTop.setSliceSegmentArgument                              ( m_sliceSegmentArgument     );
+
+  if(m_sliceMode == NO_SLICES )
+  {
+    m_bLFCrossSliceBoundaryFlag = true;
+  }
+  m_cTEncTop.setLFCrossSliceBoundaryFlag                          ( m_bLFCrossSliceBoundaryFlag );
+  m_cTEncTop.setUseSAO                                            ( m_bUseSAO );
+  m_cTEncTop.setMaxNumOffsetsPerPic                               ( m_maxNumOffsetsPerPic);
+
+  m_cTEncTop.setSaoCtuBoundary                                    ( m_saoCtuBoundary);
+  m_cTEncTop.setPCMInputBitDepthFlag                              ( m_bPCMInputBitDepthFlag);
+  m_cTEncTop.setPCMFilterDisableFlag                              ( m_bPCMFilterDisableFlag);
+
+  m_cTEncTop.setDisableIntraReferenceSmoothing                    (!m_enableIntraReferenceSmoothing );
+  m_cTEncTop.setDecodedPictureHashSEIEnabled                      ( m_decodedPictureHashSEIEnabled );
+  m_cTEncTop.setRecoveryPointSEIEnabled                           ( m_recoveryPointSEIEnabled );
+  m_cTEncTop.setBufferingPeriodSEIEnabled                         ( m_bufferingPeriodSEIEnabled );
+  m_cTEncTop.setPictureTimingSEIEnabled                           ( m_pictureTimingSEIEnabled );
+  m_cTEncTop.setToneMappingInfoSEIEnabled                         ( m_toneMappingInfoSEIEnabled );
+  m_cTEncTop.setTMISEIToneMapId                                   ( m_toneMapId );
+  m_cTEncTop.setTMISEIToneMapCancelFlag                           ( m_toneMapCancelFlag );
+  m_cTEncTop.setTMISEIToneMapPersistenceFlag                      ( m_toneMapPersistenceFlag );
+  m_cTEncTop.setTMISEICodedDataBitDepth                           ( m_toneMapCodedDataBitDepth );
+  m_cTEncTop.setTMISEITargetBitDepth                              ( m_toneMapTargetBitDepth );
+  m_cTEncTop.setTMISEIModelID                                     ( m_toneMapModelId );
+  m_cTEncTop.setTMISEIMinValue                                    ( m_toneMapMinValue );
+  m_cTEncTop.setTMISEIMaxValue                                    ( m_toneMapMaxValue );
+  m_cTEncTop.setTMISEISigmoidMidpoint                             ( m_sigmoidMidpoint );
+  m_cTEncTop.setTMISEISigmoidWidth                                ( m_sigmoidWidth );
+  m_cTEncTop.setTMISEIStartOfCodedInterva                         ( m_startOfCodedInterval );
+  m_cTEncTop.setTMISEINumPivots                                   ( m_numPivots );
+  m_cTEncTop.setTMISEICodedPivotValue                             ( m_codedPivotValue );
+  m_cTEncTop.setTMISEITargetPivotValue                            ( m_targetPivotValue );
+  m_cTEncTop.setTMISEICameraIsoSpeedIdc                           ( m_cameraIsoSpeedIdc );
+  m_cTEncTop.setTMISEICameraIsoSpeedValue                         ( m_cameraIsoSpeedValue );
+  m_cTEncTop.setTMISEIExposureIndexIdc                            ( m_exposureIndexIdc );
+  m_cTEncTop.setTMISEIExposureIndexValue                          ( m_exposureIndexValue );
+  m_cTEncTop.setTMISEIExposureCompensationValueSignFlag           ( m_exposureCompensationValueSignFlag );
+  m_cTEncTop.setTMISEIExposureCompensationValueNumerator          ( m_exposureCompensationValueNumerator );
+  m_cTEncTop.setTMISEIExposureCompensationValueDenomIdc           ( m_exposureCompensationValueDenomIdc );
+  m_cTEncTop.setTMISEIRefScreenLuminanceWhite                     ( m_refScreenLuminanceWhite );
+  m_cTEncTop.setTMISEIExtendedRangeWhiteLevel                     ( m_extendedRangeWhiteLevel );
+  m_cTEncTop.setTMISEINominalBlackLevelLumaCodeValue              ( m_nominalBlackLevelLumaCodeValue );
+  m_cTEncTop.setTMISEINominalWhiteLevelLumaCodeValue              ( m_nominalWhiteLevelLumaCodeValue );
+  m_cTEncTop.setTMISEIExtendedWhiteLevelLumaCodeValue             ( m_extendedWhiteLevelLumaCodeValue );
+  m_cTEncTop.setChromaSamplingFilterHintEnabled                   ( m_chromaSamplingFilterSEIenabled );
+  m_cTEncTop.setChromaSamplingHorFilterIdc                        ( m_chromaSamplingHorFilterIdc );
+  m_cTEncTop.setChromaSamplingVerFilterIdc                        ( m_chromaSamplingVerFilterIdc );
+  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.setSegmentedRectFramePackingArrangementSEIEnabled    ( m_segmentedRectFramePackingSEIEnabled );
+  m_cTEncTop.setSegmentedRectFramePackingArrangementSEICancel     ( m_segmentedRectFramePackingSEICancel );
+  m_cTEncTop.setSegmentedRectFramePackingArrangementSEIType       ( m_segmentedRectFramePackingSEIType );
+  m_cTEncTop.setSegmentedRectFramePackingArrangementSEIPersistence( m_segmentedRectFramePackingSEIPersistence );
+  m_cTEncTop.setDisplayOrientationSEIAngle                        ( m_displayOrientationSEIAngle );
+  m_cTEncTop.setTemporalLevel0IndexSEIEnabled                     ( m_temporalLevel0IndexSEIEnabled );
+  m_cTEncTop.setGradualDecodingRefreshInfoEnabled                 ( m_gradualDecodingRefreshInfoEnabled );
+  m_cTEncTop.setNoDisplaySEITLayer                                ( m_noDisplaySEITLayer );
+  m_cTEncTop.setDecodingUnitInfoSEIEnabled                        ( m_decodingUnitInfoSEIEnabled );
+  m_cTEncTop.setSOPDescriptionSEIEnabled                          ( m_SOPDescriptionSEIEnabled );
+  m_cTEncTop.setScalableNestingSEIEnabled                         ( m_scalableNestingSEIEnabled );
+  m_cTEncTop.setTMCTSSEIEnabled                                   ( m_tmctsSEIEnabled );
+  m_cTEncTop.setTimeCodeSEIEnabled                                ( m_timeCodeSEIEnabled );
+  m_cTEncTop.setNumberOfTimeSets                                  ( m_timeCodeSEINumTs );
+  for(Int i = 0; i < m_timeCodeSEINumTs; i++) { m_cTEncTop.setTimeSet(m_timeSetArray[i], i); }
+  m_cTEncTop.setKneeSEIEnabled                                    ( m_kneeSEIEnabled );
+  m_cTEncTop.setKneeSEIId                                         ( m_kneeSEIId );
+  m_cTEncTop.setKneeSEICancelFlag                                 ( m_kneeSEICancelFlag );
+  m_cTEncTop.setKneeSEIPersistenceFlag                            ( m_kneeSEIPersistenceFlag );
+  m_cTEncTop.setKneeSEIInputDrange                                ( m_kneeSEIInputDrange );
+  m_cTEncTop.setKneeSEIInputDispLuminance                         ( m_kneeSEIInputDispLuminance );
+  m_cTEncTop.setKneeSEIOutputDrange                               ( m_kneeSEIOutputDrange );
+  m_cTEncTop.setKneeSEIOutputDispLuminance                        ( m_kneeSEIOutputDispLuminance );
+  m_cTEncTop.setKneeSEINumKneePointsMinus1                        ( m_kneeSEINumKneePointsMinus1 );
+  m_cTEncTop.setKneeSEIInputKneePoint                             ( m_kneeSEIInputKneePoint );
+  m_cTEncTop.setKneeSEIOutputKneePoint                            ( m_kneeSEIOutputKneePoint );
+  m_cTEncTop.setMasteringDisplaySEI                               ( m_masteringDisplay );
+#if Q0074_COLOUR_REMAPPING_SEI
+  m_cTEncTop.setCRISEIFile                       ( m_colourRemapSEIFile );
+  m_cTEncTop.setCRISEIId                         ( m_colourRemapSEIId );
+  m_cTEncTop.setCRISEICancelFlag                 ( m_colourRemapSEICancelFlag );
+  m_cTEncTop.setCRISEIPersistenceFlag            ( m_colourRemapSEIPersistenceFlag );
+  m_cTEncTop.setCRISEIVideoSignalInfoPresentFlag ( m_colourRemapSEIVideoSignalInfoPresentFlag );
+  m_cTEncTop.setCRISEIFullRangeFlag              ( m_colourRemapSEIFullRangeFlag );
+  m_cTEncTop.setCRISEIPrimaries                  ( m_colourRemapSEIPrimaries );
+  m_cTEncTop.setCRISEITransferFunction           ( m_colourRemapSEITransferFunction );
+  m_cTEncTop.setCRISEIMatrixCoefficients         ( m_colourRemapSEIMatrixCoefficients );
+  m_cTEncTop.setCRISEIInputBitDepth              ( m_colourRemapSEIInputBitDepth );
+  m_cTEncTop.setCRISEIBitDepth                   ( m_colourRemapSEIBitDepth );
+  m_cTEncTop.setCRISEIPreLutNumValMinus1         ( m_colourRemapSEIPreLutNumValMinus1 );
+  m_cTEncTop.setCRISEIPreLutCodedValue           ( m_colourRemapSEIPreLutCodedValue );
+  m_cTEncTop.setCRISEIPreLutTargetValue          ( m_colourRemapSEIPreLutTargetValue );
+  m_cTEncTop.setCRISEIMatrixPresentFlag          ( m_colourRemapSEIMatrixPresentFlag );
+  m_cTEncTop.setCRISEILog2MatrixDenom            ( m_colourRemapSEILog2MatrixDenom );
+  m_cTEncTop.setCRISEICoeffs                     ( m_colourRemapSEICoeffs );
+  m_cTEncTop.setCRISEIPostLutNumValMinus1        ( m_colourRemapSEIPostLutNumValMinus1 );
+  m_cTEncTop.setCRISEIPostLutCodedValue          ( m_colourRemapSEIPostLutCodedValue );
+  m_cTEncTop.setCRISEIPostLutTargetValue         ( m_colourRemapSEIPostLutTargetValue );
+#endif
+#if LAYERS_NOT_PRESENT_SEI
+  m_cTEncTop.setLayersNotPresentSEIEnabled( m_layersNotPresentSEIEnabled );
+#endif
+  m_cTEncTop.setTileUniformSpacingFlag                            ( m_tileUniformSpacingFlag );
+  m_cTEncTop.setNumColumnsMinus1                                  ( m_numTileColumnsMinus1 );
+  m_cTEncTop.setNumRowsMinus1                                     ( m_numTileRowsMinus1 );
+  if(!m_tileUniformSpacingFlag)
+  {
+    m_cTEncTop.setColumnWidth                                     ( m_tileColumnWidth );
+    m_cTEncTop.setRowHeight                                       ( m_tileRowHeight );
+  }
+  m_cTEncTop.xCheckGSParameters();
+  Int uiTilesCount = (m_numTileRowsMinus1+1) * (m_numTileColumnsMinus1+1);
+  if(uiTilesCount == 1)
+  {
+    m_bLFCrossTileBoundaryFlag = true;
+  }
+  m_cTEncTop.setLFCrossTileBoundaryFlag                           ( m_bLFCrossTileBoundaryFlag );
+  m_cTEncTop.setWaveFrontSynchro                                  ( m_iWaveFrontSynchro );
+  m_cTEncTop.setWaveFrontSubstreams                               ( m_iWaveFrontSubstreams );
+  m_cTEncTop.setTMVPModeId                                        ( m_TMVPModeId );
+  m_cTEncTop.setUseScalingListId                                  ( m_useScalingListId  );
+  m_cTEncTop.setScalingListFile                                   ( m_scalingListFile   );
+  m_cTEncTop.setSignHideFlag                                      ( m_signHideFlag);
+  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 );
+  m_cTEncTop.setTransquantBypassEnableFlag                        ( m_TransquantBypassEnableFlag );
+  m_cTEncTop.setCUTransquantBypassFlagForceValue                  ( m_CUTransquantBypassFlagForce );
+  m_cTEncTop.setCostMode                                          ( m_costMode );
+  m_cTEncTop.setUseRecalculateQPAccordingToLambda                 ( m_recalculateQPAccordingToLambda );
+  m_cTEncTop.setUseStrongIntraSmoothing                           ( m_useStrongIntraSmoothing );
+  m_cTEncTop.setActiveParameterSetsSEIEnabled                     ( m_activeParameterSetsSEIEnabled );
+  m_cTEncTop.setVuiParametersPresentFlag                          ( m_vuiParametersPresentFlag );
+  m_cTEncTop.setAspectRatioInfoPresentFlag                        ( m_aspectRatioInfoPresentFlag);
+  m_cTEncTop.setAspectRatioIdc                                    ( m_aspectRatioIdc );
+  m_cTEncTop.setSarWidth                                          ( m_sarWidth );
+  m_cTEncTop.setSarHeight                                         ( m_sarHeight );
+  m_cTEncTop.setOverscanInfoPresentFlag                           ( m_overscanInfoPresentFlag );
+  m_cTEncTop.setOverscanAppropriateFlag                           ( m_overscanAppropriateFlag );
+  m_cTEncTop.setVideoSignalTypePresentFlag                        ( m_videoSignalTypePresentFlag );
+  m_cTEncTop.setVideoFormat                                       ( m_videoFormat );
+  m_cTEncTop.setVideoFullRangeFlag                                ( m_videoFullRangeFlag );
+  m_cTEncTop.setColourDescriptionPresentFlag                      ( m_colourDescriptionPresentFlag );
+  m_cTEncTop.setColourPrimaries                                   ( m_colourPrimaries );
+  m_cTEncTop.setTransferCharacteristics                           ( m_transferCharacteristics );
+  m_cTEncTop.setMatrixCoefficients                                ( m_matrixCoefficients );
+  m_cTEncTop.setChromaLocInfoPresentFlag                          ( m_chromaLocInfoPresentFlag );
+  m_cTEncTop.setChromaSampleLocTypeTopField                       ( m_chromaSampleLocTypeTopField );
+  m_cTEncTop.setChromaSampleLocTypeBottomField                    ( m_chromaSampleLocTypeBottomField );
+  m_cTEncTop.setNeutralChromaIndicationFlag                       ( m_neutralChromaIndicationFlag );
+  m_cTEncTop.setDefaultDisplayWindow                              ( m_defDispWinLeftOffset, m_defDispWinRightOffset, m_defDispWinTopOffset, m_defDispWinBottomOffset );
+  m_cTEncTop.setFrameFieldInfoPresentFlag                         ( m_frameFieldInfoPresentFlag );
+  m_cTEncTop.setPocProportionalToTimingFlag                       ( m_pocProportionalToTimingFlag );
+  m_cTEncTop.setNumTicksPocDiffOneMinus1                          ( m_numTicksPocDiffOneMinus1    );
+  m_cTEncTop.setBitstreamRestrictionFlag                          ( m_bitstreamRestrictionFlag );
+  m_cTEncTop.setTilesFixedStructureFlag                           ( m_tilesFixedStructureFlag );
+  m_cTEncTop.setMotionVectorsOverPicBoundariesFlag                ( m_motionVectorsOverPicBoundariesFlag );
+  m_cTEncTop.setMinSpatialSegmentationIdc                         ( m_minSpatialSegmentationIdc );
+  m_cTEncTop.setMaxBytesPerPicDenom                               ( m_maxBytesPerPicDenom );
+  m_cTEncTop.setMaxBitsPerMinCuDenom                              ( m_maxBitsPerMinCuDenom );
+  m_cTEncTop.setLog2MaxMvLengthHorizontal                         ( m_log2MaxMvLengthHorizontal );
+  m_cTEncTop.setLog2MaxMvLengthVertical                           ( m_log2MaxMvLengthVertical );
+}
+#endif //SVC_EXTENSION
+
+Void TAppEncTop::xCreateLib()
+{
+  // Video I/O
+#if SVC_EXTENSION
+  // initialize global variables
+  initROM();
+
+  for(UInt layer=0; layer<m_numLayers; layer++)
+  {
+#if O0194_DIFFERENT_BITDEPTH_EL_BL
+    //2
+    for( UInt channelTypeIndex = 0; channelTypeIndex < MAX_NUM_CHANNEL_TYPE; channelTypeIndex++)
+    {
+      g_bitDepth[channelTypeIndex]    = m_acLayerCfg[layer].m_internalBitDepth[channelTypeIndex];
+      g_PCMBitDepth[channelTypeIndex] = m_bPCMInputBitDepthFlag ? m_acLayerCfg[layer].m_inputBitDepth[channelTypeIndex] : m_acLayerCfg[layer].m_internalBitDepth[channelTypeIndex];
+    }
+#endif
+#if LAYER_CTB
+    g_uiMaxCUWidth  = g_auiLayerMaxCUWidth[layer];
+    g_uiMaxCUHeight = g_auiLayerMaxCUHeight[layer];
+    g_uiMaxCUDepth  = g_auiLayerMaxCUDepth[layer];
+    g_uiAddCUDepth  = g_auiLayerAddCUDepth[layer];
+#endif
+    // Video I/O
+#if O0194_DIFFERENT_BITDEPTH_EL_BL
+    m_acTVideoIOYuvInputFile[layer].open( (Char *)m_acLayerCfg[layer].getInputFile().c_str(),  false, m_acLayerCfg[layer].m_inputBitDepth, m_acLayerCfg[layer].m_MSBExtendedBitDepth, m_acLayerCfg[layer].m_internalBitDepth );  // read  mode
+#else
+    m_acTVideoIOYuvInputFile[layer].open( (Char *)m_acLayerCfg[layer].getInputFile().c_str(),  false, m_inputBitDepth, m_MSBExtendedBitDepth, m_internalBitDepth );  // read  mode
+#endif
+    m_acTVideoIOYuvInputFile[layer].skipFrames(m_FrameSkip, m_acLayerCfg[layer].getSourceWidth() - m_acLayerCfg[layer].getPad()[0], m_acLayerCfg[layer].getSourceHeight() - m_acLayerCfg[layer].getPad()[1], m_acLayerCfg[layer].m_InputChromaFormatIDC);
+
+    if (!m_acLayerCfg[layer].getReconFile().empty())
+    {
+#if O0194_DIFFERENT_BITDEPTH_EL_BL
+      m_acTVideoIOYuvReconFile[layer].open((Char *)m_acLayerCfg[layer].getReconFile().c_str(), true, m_acLayerCfg[layer].m_outputBitDepth, m_acLayerCfg[layer].m_MSBExtendedBitDepth, m_acLayerCfg[layer].m_internalBitDepth );  // write mode
+#else
+      m_acTVideoIOYuvReconFile[layer].open((Char *)m_acLayerCfg[layer].getReconFile().c_str(), true, m_outputBitDepth, m_MSBExtendedBitDepth, m_internalBitDepth );  // write mode
+#endif
+    }
+
+    // Neo Decoder
+    m_acTEncTop[layer].create();
+  }
+#else //SVC_EXTENSION
+  // Video I/O
+  m_cTVideoIOYuvInputFile.open( m_pchInputFile,     false, m_inputBitDepth, m_MSBExtendedBitDepth, m_internalBitDepth );  // read  mode
+  m_cTVideoIOYuvInputFile.skipFrames(m_FrameSkip, m_iSourceWidth - m_aiPad[0], m_iSourceHeight - m_aiPad[1], m_InputChromaFormatIDC);
+
+  if (m_pchReconFile)
+  {
+    m_cTVideoIOYuvReconFile.open(m_pchReconFile, true, m_outputBitDepth, m_outputBitDepth, m_internalBitDepth);  // write mode
+  }
+
+  // Neo Decoder
+  m_cTEncTop.create();
+#endif //SVC_EXTENSION
+}
+
+Void TAppEncTop::xDestroyLib()
+{
+  // Video I/O
+#if SVC_EXTENSION
+  // destroy ROM
+  destroyROM();
+
+  for(UInt layer=0; layer<m_numLayers; layer++)
+  {
+#if LAYER_CTB
+    g_uiMaxCUWidth  = g_auiLayerMaxCUWidth[layer];
+    g_uiMaxCUHeight = g_auiLayerMaxCUHeight[layer];
+    g_uiMaxCUDepth  = g_auiLayerMaxCUDepth[layer];
+    g_uiAddCUDepth  = g_auiLayerAddCUDepth[layer];
+#endif
+
+    m_acTVideoIOYuvInputFile[layer].close();
+    m_acTVideoIOYuvReconFile[layer].close();
+
+    m_acTEncTop[layer].destroy();
+  }
+#else //SVC_EXTENSION
+  m_cTVideoIOYuvInputFile.close();
+  m_cTVideoIOYuvReconFile.close();
+
+  // Neo Decoder
+  m_cTEncTop.destroy();
+#endif //SVC_EXTENSION
+}
+
+Void TAppEncTop::xInitLib(Bool isFieldCoding)
+{
+#if SVC_EXTENSION
+  TComVPS* vps = m_acTEncTop[0].getVPS();
+  m_acTEncTop[0].getVPS()->setMaxLayers( m_numLayers );
+
+  UInt i = 0, dimIdLen = 0;
+
+  while((1 << dimIdLen) < m_numLayers)
+  {
+    dimIdLen++;
+  }
+  vps->setDimensionIdLen(0, dimIdLen);
+  vps->setNuhLayerIdPresentFlag(false);
+  vps->setLayerIdInNuh(0, 0);
+  vps->setLayerIdxInVps(0, 0);
+  for(i = 1; i < vps->getMaxLayers(); i++)
+  {
+    vps->setLayerIdInNuh(i, m_acLayerCfg[i].m_layerId);    
+    vps->setLayerIdxInVps(vps->getLayerIdInNuh(i), i);
+    vps->setDimensionId(i, 0, i);
+
+    if( m_acLayerCfg[i].m_layerId != i )
+    {
+      vps->setNuhLayerIdPresentFlag(true);
+    }
+  }
+
+  for(UInt layer=0; layer<m_numLayers; layer++)
+  {
+#if O0194_DIFFERENT_BITDEPTH_EL_BL
+    //3
+    for (UInt channelTypeIndex = 0; channelTypeIndex < MAX_NUM_CHANNEL_TYPE; channelTypeIndex++)
+    {
+      g_bitDepth[channelTypeIndex]    = m_acLayerCfg[layer].m_internalBitDepth[channelTypeIndex];
+      g_PCMBitDepth[channelTypeIndex] = m_bPCMInputBitDepthFlag ? m_acLayerCfg[layer].m_inputBitDepth[channelTypeIndex] : m_acLayerCfg[layer].m_internalBitDepth[channelTypeIndex];
+    }
+#endif
+#if LAYER_CTB
+    g_uiMaxCUWidth  = g_auiLayerMaxCUWidth[layer];
+    g_uiMaxCUHeight = g_auiLayerMaxCUHeight[layer];
+    g_uiMaxCUDepth  = g_auiLayerMaxCUDepth[layer];
+    g_uiAddCUDepth  = g_auiLayerAddCUDepth[layer];
+
+    memcpy( g_auiZscanToRaster, g_auiLayerZscanToRaster[layer], sizeof( g_auiZscanToRaster ) );
+    memcpy( g_auiRasterToZscan, g_auiLayerRasterToZscan[layer], sizeof( g_auiRasterToZscan ) );
+    memcpy( g_auiRasterToPelX,  g_auiLayerRasterToPelX[layer],  sizeof( g_auiRasterToPelX ) );
+    memcpy( g_auiRasterToPelY,  g_auiLayerRasterToPelY[layer],  sizeof( g_auiRasterToPelY ) );
+#endif
+    m_acTEncTop[layer].init(isFieldCoding);
+  }
+
+#if VPS_EXTN_OP_LAYER_SETS
+  vps->setMaxLayerId( m_acLayerCfg[m_numLayers - 1].m_layerId );    // Set max-layer ID
+
+  vps->setVpsExtensionFlag( m_numLayers > 1 ? true : false );
+
+#if Q0078_ADD_LAYER_SETS
+#if OUTPUT_LAYER_SETS_CONFIG
+  if (m_numLayerSets > 1)
+  {
+    vps->setNumLayerSets(m_numLayerSets);
+#else
+  if (m_numLayerSets > 0)
+  {
+    vps->setNumLayerSets(m_numLayerSets+1);
+#endif
+    for (Int setId = 1; setId < vps->getNumLayerSets(); setId++)
+    {
+      for (Int layerId = 0; layerId <= vps->getMaxLayerId(); layerId++)
+      {
+        vps->setLayerIdIncludedFlag(false, setId, layerId);
+      }
+    }
+    for (Int setId = 1; setId < vps->getNumLayerSets(); setId++)
+    {
+#if OUTPUT_LAYER_SETS_CONFIG
+      for( i = 0; i < m_numLayerInIdList[setId]; i++ )
+      {
+        Int layerId = m_layerSetLayerIdList[setId][i];
+        Int layerIdx = vps->getLayerIdxInVps(m_layerSetLayerIdList[setId][i]);
+#else
+      for( i = 0; i < m_numLayerInIdList[setId-1]; i++ )
+      {
+        Int layerId = m_layerSetLayerIdList[setId-1][i];
+#endif
+#if O0194_DIFFERENT_BITDEPTH_EL_BL
+        //4
+        g_bitDepth[CHANNEL_TYPE_LUMA]   = m_acLayerCfg[layerIdx].m_internalBitDepth[CHANNEL_TYPE_LUMA];
+        g_bitDepth[CHANNEL_TYPE_CHROMA] = m_acLayerCfg[layerIdx].m_internalBitDepth[CHANNEL_TYPE_CHROMA];
+
+        g_PCMBitDepth[CHANNEL_TYPE_LUMA]   = m_bPCMInputBitDepthFlag ? m_acLayerCfg[layerIdx].m_inputBitDepth[CHANNEL_TYPE_LUMA]   : m_acLayerCfg[layerIdx].m_internalBitDepth[CHANNEL_TYPE_LUMA];
+        g_PCMBitDepth[CHANNEL_TYPE_CHROMA] = m_bPCMInputBitDepthFlag ? m_acLayerCfg[layerIdx].m_inputBitDepth[CHANNEL_TYPE_CHROMA] : m_acLayerCfg[layerIdx].m_internalBitDepth[CHANNEL_TYPE_CHROMA];
+#endif
+
+        vps->setLayerIdIncludedFlag(true, setId, layerId);
+      }
+    }
+  }
+  else
+  {
+    // Default layer sets
+#endif
+    vps->setNumLayerSets(m_numLayers);
+    for (Int setId = 1; setId < vps->getNumLayerSets(); setId++)
+    {
+      for (Int layerIdx = 0; layerIdx <= vps->getMaxLayers(); layerIdx++)
+      {
+#if O0194_DIFFERENT_BITDEPTH_EL_BL
+        //4
+        UInt layerId = vps->getLayerIdInNuh(layerIdx);
+        g_bitDepth[CHANNEL_TYPE_LUMA]   = m_acLayerCfg[layerIdx].m_internalBitDepth[CHANNEL_TYPE_LUMA];
+        g_bitDepth[CHANNEL_TYPE_CHROMA] = m_acLayerCfg[layerIdx].m_internalBitDepth[CHANNEL_TYPE_CHROMA];
+
+        g_PCMBitDepth[CHANNEL_TYPE_LUMA]   = m_bPCMInputBitDepthFlag ? m_acLayerCfg[layerIdx].m_inputBitDepth[CHANNEL_TYPE_LUMA]   : m_acLayerCfg[layerIdx].m_internalBitDepth[CHANNEL_TYPE_LUMA];
+        g_PCMBitDepth[CHANNEL_TYPE_CHROMA] = m_bPCMInputBitDepthFlag ? m_acLayerCfg[layerIdx].m_inputBitDepth[CHANNEL_TYPE_CHROMA] : m_acLayerCfg[layerIdx].m_internalBitDepth[CHANNEL_TYPE_CHROMA];
+#endif
+        if (layerId <= setId)
+        {
+          vps->setLayerIdIncludedFlag(true, setId, layerId);
+        }
+        else
+        {
+          vps->setLayerIdIncludedFlag(false, setId, layerId);
+        }
+      }
+    }
+#if Q0078_ADD_LAYER_SETS
+  }
+#endif
+#if Q0078_ADD_LAYER_SETS
+  vps->setVpsNumLayerSetsMinus1(vps->getNumLayerSets() - 1);
+  vps->setNumAddLayerSets(m_numAddLayerSets);
+  vps->setNumLayerSets(vps->getNumLayerSets() + vps->getNumAddLayerSets());
+  if (m_numAddLayerSets > 0)
+  {
+    for (Int setId = 0; setId < m_numAddLayerSets; setId++)
+    {
+      for (Int j = 0; j < m_numHighestLayerIdx[setId]; j++)
+      {
+        vps->setHighestLayerIdxPlus1(setId, j + 1, m_highestLayerIdx[setId][j] + 1);
+      }
+    }
+  }
+#endif
+#if VPS_EXTN_MASK_AND_DIM_INFO
+#if AVC_BASE
+#if VPS_AVC_BL_FLAG_REMOVAL
+  vps->setNonHEVCBaseLayerFlag( m_nonHEVCBaseLayerFlag );
+  if ( m_nonHEVCBaseLayerFlag )
+  {
+    vps->setBaseLayerInternalFlag (false);
+  }
+#else
+  vps->setAvcBaseLayerFlag(m_avcBaseLayerFlag);
+#endif
+#else
+  vps->setAvcBaseLayerFlag(false);
+#endif
+  vps->setSplittingFlag(false);
+  for(i = 0; i < MAX_VPS_NUM_SCALABILITY_TYPES; i++)
+  {
+    vps->setScalabilityMask(i, false);
+  }
+  if(m_numLayers > 1)
+  {
+    Int scalabilityTypes = 0;
+    for(i = 0; i < MAX_VPS_NUM_SCALABILITY_TYPES; i++)
+    {
+      vps->setScalabilityMask(i, m_scalabilityMask[i]);
+      scalabilityTypes += m_scalabilityMask[i];
+    }
+#if AUXILIARY_PICTURES
+    assert( scalabilityTypes <= 2 );
+#else
+    assert( scalabilityTypes == 1 );
+#endif
+    vps->setNumScalabilityTypes(scalabilityTypes);
+  }
+  else
+  {
+    vps->setNumScalabilityTypes(0);
+  }
+  
+#if AUXILIARY_PICTURES
+  if (m_scalabilityMask[AUX_ID])
+  {
+    UInt maxAuxId = 0;
+    UInt auxDimIdLen = 1;
+    Int  auxId = vps->getNumScalabilityTypes() - 1;
+    for(i = 1; i < vps->getMaxLayers(); i++)
+    {
+      if (m_acLayerCfg[i].getAuxId() > maxAuxId)
+      {
+        maxAuxId = m_acLayerCfg[i].getAuxId();
+      }
+    }
+    while((1 << auxDimIdLen) < (maxAuxId + 1))
+    {
+      auxDimIdLen++;
+    }
+    vps->setDimensionIdLen(auxId, auxDimIdLen);
+    for(i = 1; i < vps->getMaxLayers(); i++)
+    {
+      vps->setDimensionId(i, auxId, m_acLayerCfg[i].getAuxId());
+    }
+  }
+#endif
+#endif
+#if VPS_TSLAYERS
+  vps->setMaxTSLayersPresentFlag(true);
+
+  for( i = 0; i < vps->getMaxLayers(); i++ )
+  {
+    vps->setMaxTSLayersMinus1(i, vps->getMaxTLayers()-1);
+  }
+#endif
+  vps->setMaxTidRefPresentFlag(m_maxTidRefPresentFlag);
+  if (vps->getMaxTidRefPresentFlag())
+  {
+    for( i = 0; i < vps->getMaxLayers() - 1; i++ )
+    {
+      for( Int j = i+1; j < vps->getMaxLayers(); j++)
+      {
+        vps->setMaxTidIlRefPicsPlus1(i, j, m_acTEncTop[i].getMaxTidIlRefPicsPlus1());
+      }
+    }
+  }
+  else
+  {
+    for( i = 0; i < vps->getMaxLayers() - 1; i++ )
+    {
+      for( Int j = i+1; j < vps->getMaxLayers(); j++)
+      {
+        vps->setMaxTidIlRefPicsPlus1(i, j, 7);
+      }
+    }
+  }
+    vps->setIlpSshSignalingEnabledFlag(false);
+#if VPS_EXTN_PROFILE_INFO
+#if !MULTIPLE_PTL_SUPPORT
+#if LIST_OF_PTL
+  vps->getPTLForExtnPtr()->resize(1);   // Dummy object - unused.
+  for(i = 0; i < vps->getMaxLayers(); i++)
+  {
+    // TODO: The profile tier level have to be given support to be included in the configuration files
+    if(i == 0)
+    {
+      if( vps->getBaseLayerInternalFlag() && vps->getMaxLayers() > 1 )
+      {
+        vps->setProfilePresentFlag(1, false);
+        vps->getPTLForExtnPtr()->push_back( *(m_acTEncTop[0].getSPS()->getPTL()) );
+      }
+    }
+    else  // i > 0
+    {
+      vps->setProfilePresentFlag(i, true);
+      // Note - may need to be changed for other layer structures.
+      vps->getPTLForExtnPtr()->push_back( *(m_acTEncTop[0].getSPS()->getPTL()) );
+    }
+  }
+#else
+  vps->getPTLForExtnPtr()->resize(vps->getNumLayerSets());
+  for(Int setId = 1; setId < vps->getNumLayerSets(); setId++)
+  {
+    vps->setProfilePresentFlag(setId, true);
+    // Note - may need to be changed for other layer structures.
+    *(vps->getPTLForExtn(setId)) = *(m_acTEncTop[setId].getSPS()->getPTL());
+  }
+#endif
+#endif
+#endif
+#if VPS_EXTN_DIRECT_REF_LAYERS
+  // Direct reference layers
+  UInt maxDirectRefLayers = 0;
+#if O0096_DEFAULT_DEPENDENCY_TYPE
+  Bool isDefaultDirectDependencyTypeSet = false;
+#endif
+  for (UInt layerCtr = 1; layerCtr < vps->getMaxLayers(); layerCtr++)
+  {
+    UInt layerId = vps->getLayerIdInNuh(layerCtr);
+    Int numDirectRefLayers = 0;
+
+    vps->setNumDirectRefLayers(layerId, m_acTEncTop[layerCtr].getNumDirectRefLayers());
+    maxDirectRefLayers = max<UInt>(maxDirectRefLayers, vps->getNumDirectRefLayers(layerId));
+
+    for (i = 0; i < vps->getNumDirectRefLayers(layerId); i++)
+    {
+      vps->setRefLayerId(layerId, i, m_acTEncTop[layerCtr].getRefLayerId(i));
+    }
+    // Set direct dependency flag
+    // Initialize flag to 0
+    for (Int refLayerCtr = 0; refLayerCtr < layerCtr; refLayerCtr++)
+    {
+      vps->setDirectDependencyFlag(layerCtr, refLayerCtr, false);
+    }
+    for (i = 0; i < vps->getNumDirectRefLayers(layerId); i++)
+    {
+      vps->setDirectDependencyFlag(layerCtr, vps->getLayerIdxInVps(m_acTEncTop[layerCtr].getRefLayerId(i)), true);
+    }
+    // prediction indications
+    vps->setDirectDepTypeLen(2); // sample and motion types are encoded
+    for (Int refLayerCtr = 0; refLayerCtr < layerCtr; refLayerCtr++)
+    {
+      if (vps->getDirectDependencyFlag(layerCtr, refLayerCtr))
+      {
+        assert(m_acTEncTop[layerCtr].getSamplePredEnabledFlag(numDirectRefLayers) || m_acTEncTop[layerCtr].getMotionPredEnabledFlag(numDirectRefLayers));
+        vps->setDirectDependencyType(layerCtr, refLayerCtr, ((m_acTEncTop[layerCtr].getSamplePredEnabledFlag(numDirectRefLayers) ? 1 : 0) |
+          (m_acTEncTop[layerCtr].getMotionPredEnabledFlag(numDirectRefLayers) ? 2 : 0)) - 1);
+#if O0096_DEFAULT_DEPENDENCY_TYPE
+        if (!isDefaultDirectDependencyTypeSet)
+        {
+          vps->setDefaultDirectDependecyTypeFlag(1);
+          vps->setDefaultDirectDependecyType(vps->getDirectDependencyType(layerCtr, refLayerCtr));
+          isDefaultDirectDependencyTypeSet = true;
+        }
+        else if (vps->getDirectDependencyType(layerCtr, refLayerCtr) != vps->getDefaultDirectDependencyType())
+        {
+          vps->setDefaultDirectDependecyTypeFlag(0);
+        }
+#endif
+        numDirectRefLayers ++;
+      }
+      else
+      {
+        vps->setDirectDependencyType(layerCtr, refLayerCtr, 0);
+      }
+    }
+  }
+
+#if O0092_0094_DEPENDENCY_CONSTRAINT
+  vps->setNumRefLayers();
+
+  if (vps->getMaxLayers() > MAX_REF_LAYERS)
+  {
+    for (UInt layerCtr = 1; layerCtr <= vps->getMaxLayers() - 1; layerCtr++)
+    {
+      assert(vps->getNumRefLayers(vps->getLayerIdInNuh(layerCtr)) <= MAX_REF_LAYERS);
+    }
+  }
+#endif
+#if FIX_LAYER_ID_INIT
+  // The Layer ID List variables should be derived here.
+#if DERIVE_LAYER_ID_LIST_VARIABLES
+  vps->deriveLayerIdListVariables();
+#endif
+#endif
+#if Q0078_ADD_LAYER_SETS
+  vps->setPredictedLayerIds();
+  vps->setTreePartitionLayerIdList();
+#if FIX_LAYER_ID_INIT
+  vps->deriveLayerIdListVariablesForAddLayerSets();
+#else
+  vps->setLayerIdIncludedFlagsForAddLayerSets();
+#endif
+#endif
+#endif
+#if OUTPUT_LAYER_SETS_CONFIG
+
+  vps->setDefaultTargetOutputLayerIdc( m_defaultTargetOutputLayerIdc ); // As per configuration file
+
+  if( m_numOutputLayerSets == -1 )  // # of output layer sets not specified in the configuration file
+  {
+    vps->setNumOutputLayerSets(vps->getNumLayerSets());
+
+    for(i = 1; i < vps->getNumLayerSets(); i++)
+    {
+        vps->setOutputLayerSetIdx(i, i);
+    }
+  }
+  else
+  {
+    vps->setNumOutputLayerSets( m_numOutputLayerSets );
+    for( Int olsCtr = 0; olsCtr < vps->getNumLayerSets(); olsCtr ++ ) // Default output layer sets
+    {
+      vps->setOutputLayerSetIdx(olsCtr, olsCtr);
+    }
+    for( Int olsCtr = vps->getNumLayerSets(); olsCtr < vps->getNumOutputLayerSets(); olsCtr ++ )  // Non-default output layer sets
+    {
+      vps->setOutputLayerSetIdx(olsCtr, m_outputLayerSetIdx[olsCtr - vps->getNumLayerSets()]);
+    }
+  }
+#endif
+  // Target output layer
+#if !MULTIPLE_PTL_SUPPORT
+#if LIST_OF_PTL
+  vps->setNumProfileTierLevel( vps->getPTLForExtnPtr()->size() ); // +1 for the base VPS PTL()
+#else
+  vps->setNumOutputLayerSets(vps->getNumLayerSets());
+  vps->setNumProfileTierLevel(vps->getNumLayerSets());
+#endif
+#endif
+#if !OUTPUT_LAYER_SETS_CONFIG // Taken care by configuration file parameter
+#if P0295_DEFAULT_OUT_LAYER_IDC
+  vps->setDefaultTargetOutputLayerIdc(1);
+#else
+#if O0109_DEFAULT_ONE_OUT_LAYER_IDC
+  vps->setDefaultOneTargetOutputLayerIdc(1);
+#else
+  vps->setDefaultOneTargetOutputLayerFlag(true);
+#endif
+#endif
+#endif
+#if !PER_LAYER_PTL
+  for(i = 1; i < vps->getNumLayerSets(); i++)
+  {
+    vps->setProfileLevelTierIdx(i, i);
+#if !OUTPUT_LAYER_SETS_CONFIG
+    vps->setOutputLayerSetIdx(i, i);
+#endif
+  }  
+#endif
+#endif
+ #if VPS_DPB_SIZE_TABLE
+#if !FIX_LAYER_ID_INIT  // must be derived earlier to not delete additional layer sets
+  // The Layer ID List variables can be derived here.  
+#if DERIVE_LAYER_ID_LIST_VARIABLES
+  vps->deriveLayerIdListVariables();
+#endif
+#endif
+#if RESOLUTION_BASED_DPB
+  vps->assignSubDpbIndices();
+#else
+  vps->deriveNumberOfSubDpbs();
+#endif
+  vps->setOutputLayerFlag( 0, 0, 1 );
+
+  // derive OutputLayerFlag[i][j] 
+#if !OUTPUT_LAYER_SETS_CONFIG
+  if( vps->getDefaultTargetOutputLayerIdc() == 1 )
+#endif
+  {
+    // default_output_layer_idc equal to 1 specifies that only the layer with the highest value of nuh_layer_id such that nuh_layer_id equal to nuhLayerIdA and 
+    // AuxId[ nuhLayerIdA ] equal to 0 in each of the output layer sets with index in the range of 1 to vps_num_layer_sets_minus1, inclusive, is an output layer of its output layer set.
+
+    // Include the highest layer as output layer for each layer set
+    for(Int lsIdx = 1; lsIdx <= vps->getVpsNumLayerSetsMinus1(); lsIdx++)
+    {
+      for( UInt layer = 0; layer < vps->getNumLayersInIdList(lsIdx); layer++ )
+      {
+#if !Q0078_ADD_LAYER_SETS  // the following condition is incorrect and is not needed anyway
+        if( vps->getLayerIdIncludedFlag(lsIdx, layer) )      
+#endif
+        {
+#if OUTPUT_LAYER_SETS_CONFIG
+          switch(vps->getDefaultTargetOutputLayerIdc())
+          {
+            case 0: vps->setOutputLayerFlag( lsIdx, layer, 1 );
+              break;
+            case 1: vps->setOutputLayerFlag( lsIdx, layer, layer == vps->getNumLayersInIdList(lsIdx) - 1 );
+              break;
+            case 2:
+            case 3: vps->setOutputLayerFlag( lsIdx, layer, (layer != vps->getNumLayersInIdList(lsIdx) - 1) ? std::find( m_listOfOutputLayers[lsIdx].begin(), m_listOfOutputLayers[lsIdx].end(), m_layerSetLayerIdList[lsIdx][layer]) != m_listOfOutputLayers[lsIdx].end() 
+                                                                                                           : m_listOfOutputLayers[lsIdx][m_listOfOutputLayers[lsIdx].size()-1] == m_layerSetLayerIdList[lsIdx][layer] );
+              break;
+          }
+#else
+          vps->setOutputLayerFlag( lsIdx, layer, layer == vps->getNumLayersInIdList(lsIdx) - 1 );
+#endif
+        }
+      }
+    }
+#if OUTPUT_LAYER_SETS_CONFIG
+    for( Int olsIdx = vps->getVpsNumLayerSetsMinus1() + 1; olsIdx < vps->getNumOutputLayerSets(); olsIdx++ )
+    {
+      for( UInt layer = 0; layer < vps->getNumLayersInIdList(vps->getOutputLayerSetIdx(olsIdx)); layer++ )
+      {
+        vps->setOutputLayerFlag( olsIdx, layer, (layer != vps->getNumLayersInIdList(vps->getOutputLayerSetIdx(olsIdx)) - 1) ? std::find( m_listOfOutputLayers[olsIdx].begin(), m_listOfOutputLayers[olsIdx].end(), vps->getLayerSetLayerIdList(vps->getOutputLayerSetIdx(olsIdx), layer)) != m_listOfOutputLayers[olsIdx].end()
+                                                                                                                            : m_listOfOutputLayers[olsIdx][m_listOfOutputLayers[olsIdx].size()-1] == vps->getLayerSetLayerIdList(vps->getOutputLayerSetIdx(olsIdx), layer) );
+      }
+    }
+#endif
+  }
+#if !OUTPUT_LAYER_SETS_CONFIG
+  else
+  {
+    // cases when default_output_layer_idc is not equal to 1
+    assert(!"default_output_layer_idc not equal to 1 is not yet supported");
+  }
+#endif
+#if NECESSARY_LAYER_FLAG
+  vps->deriveNecessaryLayerFlag();
+  vps->checkNecessaryLayerFlagCondition();
+#endif
+#if !MULTIPLE_PTL_SUPPORT
+#if PER_LAYER_PTL
+  vps->getProfileLevelTierIdx()->resize(vps->getNumOutputLayerSets());
+  vps->getProfileLevelTierIdx(0)->push_back( vps->getBaseLayerInternalFlag() && vps->getMaxLayers() > 1 ? 1 : 0 ); // Default 0-th output layer set
+  for(i = 1; i < vps->getNumOutputLayerSets(); i++)
+  {
+    Int layerSetIdxForOutputLayerSet = vps->getOutputLayerSetIdx( i );
+    Int numLayerInLayerSet = vps->getNumLayersInIdList( layerSetIdxForOutputLayerSet );
+    for(Int j = 0; j < numLayerInLayerSet; j++)
+    {
+      Int layerIdxInVps = vps->getLayerIdxInVps( vps->getLayerSetLayerIdList(layerSetIdxForOutputLayerSet, j) );
+      if( vps->getNecessaryLayerFlag(i, j) )
+      {
+        vps->getProfileLevelTierIdx(i)->push_back( vps->getBaseLayerInternalFlag() && vps->getMaxLayers() > 1 ? layerIdxInVps + 1 : layerIdxInVps);
+      }
+      else
+      {
+        vps->getProfileLevelTierIdx(i)->push_back( -1 );
+      }
+    }
+  }
+#endif
+#endif
+#if SUB_LAYERS_IN_LAYER_SET
+  vps->calculateMaxSLInLayerSets();
+#endif
+  // Initialize dpb_size_table() for all ouput layer sets in the VPS extension
+  for(i = 1; i < vps->getNumOutputLayerSets(); i++)
+  {
+#if CHANGE_NUMSUBDPB_IDX
+    Int layerSetIdxForOutputLayerSet = vps->getOutputLayerSetIdx( i );
+#endif
+    Int layerSetId = vps->getOutputLayerSetIdx(i);
+
+    for(Int j = 0; j < vps->getMaxTLayers(); j++)
+    {
+
+      Int maxNumReorderPics = -1;
+#if CHANGE_NUMSUBDPB_IDX
+#if RESOLUTION_BASED_DPB
+      for(Int k = 0; k < vps->getNumLayersInIdList(layerSetIdxForOutputLayerSet); k++)
+#else
+      for(Int k = 0; k < vps->getNumSubDpbs(layerSetIdxForOutputLayerSet); k++)
+#endif
+#else
+      for(Int k = 0; k < vps->getNumSubDpbs(i); k++)
+#endif
+      {
+        Int layerId = vps->getLayerSetLayerIdList(layerSetId, k); // k-th layer in the output layer set
+#if RESOLUTION_BASED_DPB
+        vps->setMaxVpsLayerDecPicBuffMinus1( i, k, j, m_acTEncTop[layerId].getMaxDecPicBuffering(j) - 1 );
+        // Add sub-DPB sizes of layers belonging to a sub-DPB. If a different sub-DPB size is calculated
+        // at the encoder, modify below
+        Int oldValue = vps->getMaxVpsDecPicBufferingMinus1( i, vps->getSubDpbAssigned( layerSetIdxForOutputLayerSet, k ), j );
+        oldValue += vps->getMaxVpsLayerDecPicBuffMinus1( i, k, j ) + 1;
+        vps->setMaxVpsDecPicBufferingMinus1( i, vps->getSubDpbAssigned( layerSetIdxForOutputLayerSet, k ), j, oldValue );
+#else
+        vps->setMaxVpsDecPicBufferingMinus1( i, k, j,  m_acTEncTop[vps->getLayerIdxInVps(layerId)].getMaxDecPicBuffering(j) - 1 );
+#endif
+        maxNumReorderPics       = std::max( maxNumReorderPics, m_acTEncTop[vps->getLayerIdxInVps(layerId)].getNumReorderPics(j));
+      }
+#if RESOLUTION_BASED_DPB
+      for(Int k = 0; k < vps->getNumSubDpbs(i); k++)
+      {
+        // Decrement m_maxVpsDecPicBufferingMinus1
+        Int oldValue = vps->getMaxVpsDecPicBufferingMinus1( i, vps->getSubDpbAssigned( layerSetIdxForOutputLayerSet, k ), j );
+        vps->setMaxVpsDecPicBufferingMinus1( i, vps->getSubDpbAssigned( layerSetIdxForOutputLayerSet, k ), j, oldValue - 1 );
+      }
+#endif
+      vps->setMaxVpsNumReorderPics(i, j, maxNumReorderPics);
+      vps->determineSubDpbInfoFlags();
+    }
+  }
+#endif
+    vps->setMaxOneActiveRefLayerFlag(maxDirectRefLayers > 1 ? false : true);
+#if O0062_POC_LSB_NOT_PRESENT_FLAG
+    for(i = 1; i< vps->getMaxLayers(); i++)
+    {
+      if( vps->getNumDirectRefLayers( vps->getLayerIdInNuh(i) ) == 0  )
+      {
+#if Q0078_ADD_LAYER_SETS
+        vps->setPocLsbNotPresentFlag(i, true); // make independedent layers base-layer compliant
+#else
+        vps->setPocLsbNotPresentFlag(i, false);
+#endif
+      }
+    }
+#endif
+#if O0223_PICTURE_TYPES_ALIGN_FLAG
+    vps->setCrossLayerPictureTypeAlignFlag( m_crossLayerPictureTypeAlignFlag );
+#endif
+#if P0068_CROSS_LAYER_ALIGNED_IDR_ONLY_FOR_IRAP_FLAG
+    vps->setCrossLayerAlignedIdrOnlyFlag( m_crossLayerAlignedIdrOnlyFlag );
+#endif
+    vps->setCrossLayerIrapAlignFlag( m_crossLayerIrapAlignFlag );
+    for(UInt layerCtr = 1;layerCtr <= vps->getMaxLayers() - 1; layerCtr++)
+    {
+      for(Int refLayerCtr = 0; refLayerCtr < layerCtr; refLayerCtr++)
+      {
+        if (vps->getDirectDependencyFlag( layerCtr, refLayerCtr))
+        {
+          if(m_acTEncTop[layerCtr].getIntraPeriod() !=  m_acTEncTop[refLayerCtr].getIntraPeriod())
+          {
+            vps->setCrossLayerIrapAlignFlag(false);
+            break;
+          }
+        }
+      }
+    }
+#if M0040_ADAPTIVE_RESOLUTION_CHANGE
+  vps->setSingleLayerForNonIrapFlag(m_adaptiveResolutionChange > 0 ? true : false);
+#endif 
+#if HIGHER_LAYER_IRAP_SKIP_FLAG
+  vps->setHigherLayerIrapSkipFlag(m_skipPictureAtArcSwitch);
+#endif
+#if !P0125_REVERT_VPS_EXTN_OFFSET_TO_RESERVED
+#if !VPS_EXTN_OFFSET_CALC
+#if VPS_EXTN_OFFSET
+  // to be updated according to the current semantics
+  vps->setExtensionOffset( 0xffff );
+#endif
+#endif
+#endif
+
+#if O0215_PHASE_ALIGNMENT
+  vps->setPhaseAlignFlag( m_phaseAlignFlag );
+#endif
+
+#if P0300_ALT_OUTPUT_LAYER_FLAG
+  for (Int k = 0; k < MAX_VPS_LAYER_SETS_PLUS1; k++)
+  {
+    vps->setAltOuputLayerFlag( k, m_altOutputLayerFlag );
+  }
+#else
+#if O0153_ALT_OUTPUT_LAYER_FLAG
+  vps->setAltOuputLayerFlag( m_altOutputLayerFlag );
+#endif
+#endif
+
+#if P0312_VERT_PHASE_ADJ
+  Bool vpsVuiVertPhaseInUseFlag = false;
+  for( UInt layerId = 1; layerId < m_numLayers; layerId++ )
+  {
+    for( i = 0; i < m_acLayerCfg[layerId].m_numScaledRefLayerOffsets; i++ )
+    {
+      if( m_acTEncTop[layerId].getVertPhasePositionEnableFlag(i) )
+      {
+        vpsVuiVertPhaseInUseFlag = true;
+        break;
+      }
+    }
+  }
+  vps->setVpsVuiVertPhaseInUseFlag( vpsVuiVertPhaseInUseFlag );
+#endif
+
+#if VPS_VUI_BSP_HRD_PARAMS
+  vps->setVpsVuiBspHrdPresentFlag(false);
+  TEncTop *pcCfg = &m_acTEncTop[0];
+  if( pcCfg->getBufferingPeriodSEIEnabled() )
+  {
+    Int j;
+    vps->setVpsVuiBspHrdPresentFlag(true);
+    vps->setVpsNumAddHrdParams( vps->getMaxLayers() );
+    vps->createBspHrdParamBuffer(vps->getVpsNumAddHrdParams() + 1);
+    for( i = vps->getNumHrdParameters(), j = 0; i < vps->getNumHrdParameters() + vps->getVpsNumAddHrdParams(); i++, j++ )
+    {
+      vps->setCprmsAddPresentFlag( j, true );
+      vps->setNumSubLayerHrdMinus1( j, vps->getMaxTLayers() - 1 );
+
+      UInt layerIdx = j;
+      TEncTop *pcCfgLayer = &m_acTEncTop[layerIdx];
+
+      Int iPicWidth         = pcCfgLayer->getSourceWidth();
+      Int iPicHeight        = pcCfgLayer->getSourceHeight();
+#if LAYER_CTB
+      UInt uiWidthInCU       = ( iPicWidth  % m_acLayerCfg[layerIdx].m_uiMaxCUWidth  ) ? iPicWidth  / m_acLayerCfg[layerIdx].m_uiMaxCUWidth  + 1 : iPicWidth  / m_acLayerCfg[layerIdx].m_uiMaxCUWidth;
+      UInt uiHeightInCU      = ( iPicHeight % m_acLayerCfg[layerIdx].m_uiMaxCUHeight ) ? iPicHeight / m_acLayerCfg[layerIdx].m_uiMaxCUHeight + 1 : iPicHeight / m_acLayerCfg[layerIdx].m_uiMaxCUHeight;
+      UInt maxCU = pcCfgLayer->getSliceArgument() >> ( m_acLayerCfg[layerIdx].m_uiMaxCUDepth << 1);
+#else
+      UInt uiWidthInCU       = ( iPicWidth %m_uiMaxCUWidth  ) ? iPicWidth /m_uiMaxCUWidth  + 1 : iPicWidth /m_uiMaxCUWidth;
+      UInt uiHeightInCU      = ( iPicHeight%m_uiMaxCUHeight ) ? iPicHeight/m_uiMaxCUHeight + 1 : iPicHeight/m_uiMaxCUHeight;
+      UInt maxCU = pcCfgLayer->getSliceArgument() >> ( m_uiMaxCUDepth << 1);
+#endif
+      UInt uiNumCUsInFrame   = uiWidthInCU * uiHeightInCU;
+
+      UInt numDU = ( pcCfgLayer->getSliceMode() == 1 ) ? ( uiNumCUsInFrame / maxCU ) : ( 0 );
+      if( uiNumCUsInFrame % maxCU != 0 || numDU == 0 )
+      {
+        numDU ++;
+      }
+      vps->getBspHrd(i)->setNumDU( numDU );
+      vps->setBspHrdParameters( i, pcCfgLayer->getFrameRate(), numDU, pcCfgLayer->getTargetBitrate(), ( pcCfgLayer->getIntraPeriod() > 0 ) );
+    }
+
+    // Signalling of additional partitioning schemes
+    for(Int h = 1; h < vps->getNumOutputLayerSets(); h++)
+    {
+      Int lsIdx = vps->getOutputLayerSetIdx( h );
+      vps->setNumSignalledPartitioningSchemes(h, 1);  // Only the default per-layer partitioning scheme
+      for( j = 1; j < vps->getNumSignalledPartitioningSchemes(h); j++ )
+      {
+        // ToDo: Add code for additional partitioning schemes here
+        // ToDo: Initialize num_partitions_in_scheme_minus1 and layer_included_in_partition_flag
+      }
+
+      for( i = 0; i < vps->getNumSignalledPartitioningSchemes(h); i++ )
+      {
+        if( i == 0 )
+        {
+          for(Int t = 0; t <= vps->getMaxSLayersInLayerSetMinus1( lsIdx ); t++)
+          {
+            vps->setNumBspSchedulesMinus1( h, i, t, 0 );
+            for( j = 0; j <= vps->getNumBspSchedulesMinus1(h, i, t); j++ )
+            {
+              for( Int k = 0; k <= vps->getNumPartitionsInSchemeMinus1(h, i); k++ )
+              {
+                // Only for the default partition
+                Int nuhlayerId = vps->getLayerSetLayerIdList( lsIdx, k);
+                Int layerIdxInVps = vps->getLayerIdxInVps( nuhlayerId );
+                vps->setBspHrdIdx(h, i, t, j, k, layerIdxInVps + vps->getNumHrdParameters());
+
+                vps->setBspSchedIdx(h, i, t, j, k, 0);
+              }
+            }
+          }
+        }
+        else
+        {
+          assert(0);    // Need to add support for additional partitioning schemes.
+        }
+      }
+    }
+  }
+#else
+
+#if O0164_MULTI_LAYER_HRD
+  vps->setVpsVuiBspHrdPresentFlag(false);
+  TEncTop *pcCfg = &m_acTEncTop[0];
+  if( pcCfg->getBufferingPeriodSEIEnabled() )
+  {
+    vps->setVpsVuiBspHrdPresentFlag(true);
+#if Q0078_ADD_LAYER_SETS
+    vps->setVpsNumBspHrdParametersMinus1(vps->getVpsNumLayerSetsMinus1() - 1); 
+#else
+    vps->setVpsNumBspHrdParametersMinus1(vps->getNumLayerSets() - 2); 
+#endif
+    vps->createBspHrdParamBuffer(vps->getVpsNumBspHrdParametersMinus1() + 1);
+    for ( i = 0; i <= vps->getVpsNumBspHrdParametersMinus1(); i++ )
+    {
+      vps->setBspCprmsPresentFlag(i, true);
+
+      UInt layerId = i + 1;
+      TEncTop *pcCfgLayer = &m_acTEncTop[layerId];
+
+      Int iPicWidth         = pcCfgLayer->getSourceWidth();
+      Int iPicHeight        = pcCfgLayer->getSourceHeight();
+#if LAYER_CTB
+      UInt uiWidthInCU       = ( iPicWidth  % m_acLayerCfg[layerId].m_uiMaxCUWidth  ) ? iPicWidth  / m_acLayerCfg[layerId].m_uiMaxCUWidth  + 1 : iPicWidth  / m_acLayerCfg[layerId].m_uiMaxCUWidth;
+      UInt uiHeightInCU      = ( iPicHeight % m_acLayerCfg[layerId].m_uiMaxCUHeight ) ? iPicHeight / m_acLayerCfg[layerId].m_uiMaxCUHeight + 1 : iPicHeight / m_acLayerCfg[layerId].m_uiMaxCUHeight;
+#else
+      UInt uiWidthInCU       = ( iPicWidth %m_uiMaxCUWidth  ) ? iPicWidth /m_uiMaxCUWidth  + 1 : iPicWidth /m_uiMaxCUWidth;
+      UInt uiHeightInCU      = ( iPicHeight%m_uiMaxCUHeight ) ? iPicHeight/m_uiMaxCUHeight + 1 : iPicHeight/m_uiMaxCUHeight;
+#endif
+      UInt uiNumCUsInFrame   = uiWidthInCU * uiHeightInCU;
+
+#if LAYER_CTB
+      UInt maxCU = pcCfgLayer->getSliceArgument() >> ( m_acLayerCfg[layerId].m_uiMaxCUDepth << 1);
+#else
+      UInt maxCU = pcCfgLayer->getSliceArgument() >> ( m_uiMaxCUDepth << 1);
+#endif
+      UInt numDU = ( pcCfgLayer->getSliceMode() == 1 ) ? ( uiNumCUsInFrame / maxCU ) : ( 0 );
+      if( uiNumCUsInFrame % maxCU != 0 || numDU == 0 )
+      {
+        numDU ++;
+      }
+      vps->getBspHrd(i)->setNumDU( numDU );
+      vps->setBspHrdParameters( i, pcCfgLayer->getFrameRate(), numDU, pcCfgLayer->getTargetBitrate(), ( pcCfgLayer->getIntraPeriod() > 0 ) );
+    }
+#if Q0078_ADD_LAYER_SETS
+    for (UInt h = 1; h <= vps->getVpsNumLayerSetsMinus1(); h++)
+#else
+    for(UInt h = 1; h <= (vps->getNumLayerSets()-1); h++)
+#endif
+    {
+      vps->setNumBitstreamPartitions(h, 1);
+      for( i = 0; i < vps->getNumBitstreamPartitions(h); i++ )
+      {
+        for( UInt j = 0; j <= (vps->getMaxLayers()-1); j++ )
+        {
+          if (vps->getLayerIdIncludedFlag(h, j) && h == j)
+          {
+            vps->setLayerInBspFlag(h, i, j, true);
+          }
+        }
+      }
+      vps->setNumBspSchedCombinations(h, 1);
+      for( i = 0; i < vps->getNumBspSchedCombinations(h); i++ )
+      {
+        for( UInt j = 0; j < vps->getNumBitstreamPartitions(h); j++ )
+        {
+          vps->setBspCombHrdIdx(h, i, j, 0);
+          vps->setBspCombSchedIdx(h, i, j, 0);
+        }
+      }
+    }
+  }
+#endif
+#endif
+
+#else //SVC_EXTENSION
+  m_cTEncTop.init(isFieldCoding);
+#endif //SVC_EXTENSION
+}
+
+// ====================================================================================================================
+// 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
+ .
+ */
+#if SVC_EXTENSION
+Void TAppEncTop::encode()
+{
+  fstream bitstreamFile(m_pBitstreamFile, fstream::binary | fstream::out);
+  if (!bitstreamFile)
+  {
+    fprintf(stderr, "\nfailed to open bitstream file `%s' for writing\n", m_pBitstreamFile);
+    exit(EXIT_FAILURE);
+  }
+
+  TComPicYuv*       pcPicYuvOrg [MAX_LAYERS];
+  TComPicYuv*       pcPicYuvRec = NULL;
+
+  // initialize internal class & member variables
+  xInitLibCfg();
+  xCreateLib();
+  xInitLib(m_isField);
+
+  // main encoder loop
+  Int   iNumEncoded = 0, iTotalNumEncoded = 0;
+  Bool  bEos = false;
+
+  const InputColourSpaceConversion ipCSC  =  m_inputColourSpaceConvert;
+  const InputColourSpaceConversion snrCSC = (!m_snrInternalColourSpace) ? m_inputColourSpaceConvert : IPCOLOURSPACE_UNCHANGED;
+
+  list<AccessUnit> outputAccessUnits; ///< list of access units to write out.  is populated by the encoding process
+
+  TComPicYuv acPicYuvTrueOrg[MAX_LAYERS];
+
+  for(UInt layer=0; layer<m_numLayers; layer++)
+  {
+#if O0194_DIFFERENT_BITDEPTH_EL_BL
+    //5
+    g_bitDepth[CHANNEL_TYPE_LUMA]   = m_acLayerCfg[layer].m_internalBitDepth[CHANNEL_TYPE_LUMA];
+    g_bitDepth[CHANNEL_TYPE_CHROMA] = m_acLayerCfg[layer].m_internalBitDepth[CHANNEL_TYPE_CHROMA];
+
+    g_PCMBitDepth[CHANNEL_TYPE_LUMA]   = m_bPCMInputBitDepthFlag ? m_acLayerCfg[layer].m_inputBitDepth[CHANNEL_TYPE_LUMA] : m_acLayerCfg[layer].m_internalBitDepth[CHANNEL_TYPE_LUMA];
+    g_PCMBitDepth[CHANNEL_TYPE_CHROMA] = m_bPCMInputBitDepthFlag ? m_acLayerCfg[layer].m_inputBitDepth[CHANNEL_TYPE_CHROMA] : m_acLayerCfg[layer].m_internalBitDepth[CHANNEL_TYPE_CHROMA];
+#endif
+    // allocate original YUV buffer
+    pcPicYuvOrg[layer] = new TComPicYuv;
+    if( m_isField )
+    {
+#if LAYER_CTB
+      pcPicYuvOrg[layer]->create( m_acLayerCfg[layer].getSourceWidth(), m_acLayerCfg[layer].getSourceHeightOrg(), m_acLayerCfg[layer].getChromaFormatIDC(), m_acLayerCfg[layer].m_uiMaxCUWidth, m_acLayerCfg[layer].m_uiMaxCUHeight, m_acLayerCfg[layer].m_uiMaxCUDepth, NULL );
+      acPicYuvTrueOrg[layer].create( m_acLayerCfg[layer].getSourceWidth(), m_acLayerCfg[layer].getSourceHeightOrg(), m_acLayerCfg[layer].getChromaFormatIDC(), m_acLayerCfg[layer].m_uiMaxCUWidth, m_acLayerCfg[layer].m_uiMaxCUHeight, m_acLayerCfg[layer].m_uiMaxCUDepth, NULL );
+#else
+      pcPicYuvOrg[layer]->create( m_acLayerCfg[layer].getSourceWidth(), m_acLayerCfg[layer].getSourceHeightOrg(), m_acLayerCfg[layer].getChromaFormatIDC(), m_uiMaxCUWidth, m_uiMaxCUHeight, m_uiMaxCUDepth, NULL );
+      acPicYuvTrueOrg[layer].create( m_acLayerCfg[layer].getSourceWidth(), m_acLayerCfg[layer].getSourceHeightOrg(), m_acLayerCfg[layer].getChromaFormatIDC(), m_uiMaxCUWidth, m_uiMaxCUHeight, m_uiMaxCUDepth, NULL );
+#endif
+    }
+    else
+    {
+#if LAYER_CTB
+      pcPicYuvOrg[layer]->create( m_acLayerCfg[layer].getSourceWidth(), m_acLayerCfg[layer].getSourceHeight(), m_acLayerCfg[layer].getChromaFormatIDC(), m_acLayerCfg[layer].m_uiMaxCUWidth, m_acLayerCfg[layer].m_uiMaxCUHeight, m_acLayerCfg[layer].m_uiMaxCUDepth, NULL );
+      acPicYuvTrueOrg[layer].create( m_acLayerCfg[layer].getSourceWidth(), m_acLayerCfg[layer].getSourceHeight(), m_acLayerCfg[layer].getChromaFormatIDC(), m_acLayerCfg[layer].m_uiMaxCUWidth, m_acLayerCfg[layer].m_uiMaxCUHeight, m_acLayerCfg[layer].m_uiMaxCUDepth, NULL );
+#else
+      pcPicYuvOrg[layer]->create( m_acLayerCfg[layer].getSourceWidth(), m_acLayerCfg[layer].getSourceHeight(), m_acLayerCfg[layer].getChromaFormatIDC(), m_uiMaxCUWidth, m_uiMaxCUHeight, m_uiMaxCUDepth, NULL );
+      acPicYuvTrueOrg[layer].create( m_acLayerCfg[layer].getSourceWidth(), m_acLayerCfg[layer].getSourceHeight(), m_acLayerCfg[layer].getChromaFormatIDC(), m_uiMaxCUWidth, m_uiMaxCUHeight, m_uiMaxCUDepth, NULL );
+#endif
+    }
+  }
+
+  Bool bFirstFrame = true;
+  while ( !bEos )
+  {
+    // Read enough frames
+    Bool bFramesReadyToCode = false;
+    while(!bFramesReadyToCode)
+    {
+      for(UInt layer=0; layer<m_numLayers; layer++)
+      {
+#if O0194_DIFFERENT_BITDEPTH_EL_BL
+        //6
+        for (UInt channelTypeIndex = 0; channelTypeIndex < MAX_NUM_CHANNEL_TYPE; channelTypeIndex++)
+        {
+          g_bitDepth[channelTypeIndex]    = m_acLayerCfg[layer].m_internalBitDepth[channelTypeIndex];
+          g_PCMBitDepth[channelTypeIndex] = m_bPCMInputBitDepthFlag ? m_acLayerCfg[layer].m_inputBitDepth[channelTypeIndex] : m_acLayerCfg[layer].m_internalBitDepth[channelTypeIndex];
+        }
+#endif
+#if LAYER_CTB
+        g_uiMaxCUWidth  = g_auiLayerMaxCUWidth[layer];
+        g_uiMaxCUHeight = g_auiLayerMaxCUHeight[layer];
+        g_uiMaxCUDepth  = g_auiLayerMaxCUDepth[layer];
+        g_uiAddCUDepth  = g_auiLayerAddCUDepth[layer];
+#endif
+
+        // get buffers
+        xGetBuffer(pcPicYuvRec, layer);
+
+        // read input YUV file
+        m_acTVideoIOYuvInputFile[layer].read( pcPicYuvOrg[layer], &acPicYuvTrueOrg[layer], ipCSC, m_acLayerCfg[layer].getPad(), m_acLayerCfg[layer].getInputChromaFormat() );
+
+#if AUXILIARY_PICTURES
+#if R0062_AUX_PSEUDO_MONOCHROME
+        if ( m_acLayerCfg[layer].getChromaFormatIDC() == CHROMA_400 ||
+             (m_apcTEncTop[0]->getVPS()->getScalabilityMask(AUX_ID) && (m_acLayerCfg[layer].getAuxId() == AUX_ALPHA || m_acLayerCfg[layer].getAuxId() == AUX_DEPTH)) )
+#else
+        if (m_acLayerCfg[layer].getChromaFormatIDC() == CHROMA_400)
+#endif
+        {
+          pcPicYuvOrg[layer]->convertToMonochrome();
+        }
+#endif
+
+        if(layer == m_numLayers-1)
+        {
+          // increase number of received frames
+          m_iFrameRcvd++;
+          // check end of file
+          bEos = (m_isField && (m_iFrameRcvd == (m_framesToBeEncoded >> 1) )) || ( !m_isField && (m_iFrameRcvd == m_framesToBeEncoded) );
+        }
+
+        if ( m_isField )
+        {
+          m_acTEncTop[layer].encodePrep( pcPicYuvOrg[layer], &acPicYuvTrueOrg[layer], m_isTopFieldFirst );
+        }
+        else
+        {
+          m_acTEncTop[layer].encodePrep( pcPicYuvOrg[layer], &acPicYuvTrueOrg[layer] );
+        }
+      }
+
+      bFramesReadyToCode = !(!bFirstFrame && ( m_acTEncTop[m_numLayers-1].getNumPicRcvd() != m_iGOPSize && m_iGOPSize ) && !bEos );
+    }
+    Bool flush = 0;
+    // if end of file (which is only detected on a read failure) flush the encoder of any queued pictures
+    if (m_acTVideoIOYuvInputFile[m_numLayers-1].isEof())
+    {
+      flush = true;
+      bEos = true;
+      m_iFrameRcvd--;
+      m_acTEncTop[m_numLayers-1].setFramesToBeEncoded(m_iFrameRcvd);
+    }
+
+#if RC_SHVC_HARMONIZATION
+    for(UInt layer=0; layer<m_numLayers; layer++)
+    {
+      if ( m_acTEncTop[layer].getUseRateCtrl() )
+      {
+        (m_acTEncTop[layer].getRateCtrl())->initRCGOP(m_acTEncTop[layer].getNumPicRcvd());
+      }
+    }
+#endif
+
+#if M0040_ADAPTIVE_RESOLUTION_CHANGE
+    if (m_adaptiveResolutionChange)
+    {
+      for(UInt layer = 0; layer < m_numLayers; layer++)
+      {
+        TComList<TComPicYuv*>::iterator iterPicYuvRec;
+        for (iterPicYuvRec = m_acListPicYuvRec[layer].begin(); iterPicYuvRec != m_acListPicYuvRec[layer].end(); iterPicYuvRec++)
+        {
+          TComPicYuv* recPic = *(iterPicYuvRec);
+          recPic->setReconstructed(false);
+        }
+      }
+    }
+#endif
+
+    // loop through frames in one GOP
+    for ( UInt iPicIdInGOP=0; iPicIdInGOP < (bFirstFrame? 1:m_iGOPSize); iPicIdInGOP++ )
+    {
+      // layer by layer for each frame
+      for(UInt layer=0; layer<m_numLayers; layer++)
+      {
+#if O0194_DIFFERENT_BITDEPTH_EL_BL
+        //7
+        for (UInt channelTypeIndex = 0; channelTypeIndex < MAX_NUM_CHANNEL_TYPE; channelTypeIndex++)
+        {
+          g_bitDepth[channelTypeIndex]    = m_acLayerCfg[layer].m_internalBitDepth[channelTypeIndex];
+          g_PCMBitDepth[channelTypeIndex] = m_bPCMInputBitDepthFlag ? m_acLayerCfg[layer].m_inputBitDepth[channelTypeIndex] : m_acLayerCfg[layer].m_internalBitDepth[channelTypeIndex];
+        }
+#endif
+#if LAYER_CTB
+        g_uiMaxCUWidth  = g_auiLayerMaxCUWidth[layer];
+        g_uiMaxCUHeight = g_auiLayerMaxCUHeight[layer];
+        g_uiMaxCUDepth  = g_auiLayerMaxCUDepth[layer];
+        g_uiAddCUDepth  = g_auiLayerAddCUDepth[layer];
+
+        memcpy( g_auiZscanToRaster, g_auiLayerZscanToRaster[layer], sizeof( g_auiZscanToRaster ) );
+        memcpy( g_auiRasterToZscan, g_auiLayerRasterToZscan[layer], sizeof( g_auiRasterToZscan ) );
+        memcpy( g_auiRasterToPelX,  g_auiLayerRasterToPelX[layer],  sizeof( g_auiRasterToPelX ) );
+        memcpy( g_auiRasterToPelY,  g_auiLayerRasterToPelY[layer],  sizeof( g_auiRasterToPelY ) );
+#endif
+        // call encoding function for one frame
+        if ( m_isField ) m_acTEncTop[layer].encode( flush ? 0 : pcPicYuvOrg[layer], snrCSC, m_acListPicYuvRec[layer], outputAccessUnits, iPicIdInGOP, m_isTopFieldFirst );
+        else             m_acTEncTop[layer].encode( flush ? 0 : pcPicYuvOrg[layer], snrCSC, m_acListPicYuvRec[layer], outputAccessUnits, iPicIdInGOP );
+      }
+    }
+#if R0247_SEI_ACTIVE
+    if(bFirstFrame)
+    {
+      list<AccessUnit>::iterator first_au = outputAccessUnits.begin();
+      if( m_nonHEVCBaseLayerFlag )
+      {
+        first_au++;
+      }
+      AccessUnit::iterator it_sps;
+      for (it_sps = first_au->begin(); it_sps != first_au->end(); it_sps++)
+      {
+        if( (*it_sps)->m_nalUnitType == NAL_UNIT_SPS )
+        {
+          break;
+        }
+      }
+
+      for (list<AccessUnit>::iterator it_au = ++outputAccessUnits.begin(); it_au != outputAccessUnits.end(); it_au++)
+      {
+        for (AccessUnit::iterator it_nalu = it_au->begin(); it_nalu != it_au->end(); it_nalu++)
+        {
+          if( (*it_nalu)->m_nalUnitType == NAL_UNIT_SPS )
+          {
+            first_au->insert(++it_sps, *it_nalu);
+            it_nalu = it_au->erase(it_nalu);
+          }
+        }
+      }
+    }
+
+#endif
+
+#if RC_SHVC_HARMONIZATION
+    for(UInt layer=0; layer<m_numLayers; layer++)
+    {
+      if ( m_acTEncTop[layer].getUseRateCtrl() )
+      {
+        (m_acTEncTop[layer].getRateCtrl())->destroyRCGOP();
+      }
+    }
+#endif
+
+    iTotalNumEncoded = 0;
+    for(UInt layer=0; layer<m_numLayers; layer++)
+    {
+#if O0194_DIFFERENT_BITDEPTH_EL_BL
+      //8
+      for (UInt channelTypeIndex = 0; channelTypeIndex < MAX_NUM_CHANNEL_TYPE; channelTypeIndex++)
+      {
+        g_bitDepth[channelTypeIndex]    = m_acLayerCfg[layer].m_internalBitDepth[channelTypeIndex];
+        g_PCMBitDepth[channelTypeIndex] = m_bPCMInputBitDepthFlag ? m_acLayerCfg[layer].m_inputBitDepth[channelTypeIndex] : m_acLayerCfg[layer].m_internalBitDepth[channelTypeIndex];
+      }
+#endif
+      // write bistream to file if necessary
+      iNumEncoded = m_acTEncTop[layer].getNumPicRcvd();
+      if ( iNumEncoded > 0 )
+      {
+        xWriteRecon(layer, iNumEncoded);
+        iTotalNumEncoded += iNumEncoded;
+      }
+      m_acTEncTop[layer].setNumPicRcvd( 0 );
+    }
+
+    // write bitstream out
+    if(iTotalNumEncoded)
+    {
+#if P0130_EOB
+      if( bEos )
+      {
+        OutputNALUnit nalu(NAL_UNIT_EOB);
+        nalu.m_layerId = 0;
+
+        AccessUnit& accessUnit = outputAccessUnits.back();
+#if T_ID_EOB_BUG_FIX
+        nalu.m_temporalId = 0;
+#else
+        nalu.m_temporalId = accessUnit.front()->m_temporalId;
+#endif
+        accessUnit.push_back(new NALUnitEBSP(nalu));
+      }
+#endif
+      xWriteStream(bitstreamFile, iTotalNumEncoded, outputAccessUnits);
+      outputAccessUnits.clear();
+    }
+
+    // print out summary
+    if (bEos)
+    {
+      printOutSummary(m_isTopFieldFirst, m_printMSEBasedSequencePSNR, m_printSequenceMSE);
+    }
+
+    bFirstFrame = false;
+  }
+  // delete original YUV buffer
+  for(UInt layer=0; layer<m_numLayers; layer++)
+  {
+    pcPicYuvOrg[layer]->destroy();
+    delete pcPicYuvOrg[layer];
+    pcPicYuvOrg[layer] = NULL;
+
+    // delete used buffers in encoder class
+    m_acTEncTop[layer].deletePicBuffer();
+    acPicYuvTrueOrg[layer].destroy();
+  }
+
+  // delete buffers & classes
+  xDeleteBuffer();
+  xDestroyLib();
+
+  printRateSummary();
+
+  return;
+}
+
+Void TAppEncTop::printOutSummary(Bool isField, const Bool printMSEBasedSNR, const Bool printSequenceMSE)
+{
+  UInt layer;
+
+  // set frame rate
+  for(layer = 0; layer < m_numLayers; layer++)
+  {
+    if(isField)
+    {
+      m_gcAnalyzeAll[layer].setFrmRate( m_acLayerCfg[layer].getFrameRate() * 2);
+      m_gcAnalyzeI[layer].setFrmRate( m_acLayerCfg[layer].getFrameRate() * 2 );
+      m_gcAnalyzeP[layer].setFrmRate( m_acLayerCfg[layer].getFrameRate() * 2 );
+      m_gcAnalyzeB[layer].setFrmRate( m_acLayerCfg[layer].getFrameRate() * 2 );
+    }
+    else
+    {
+      m_gcAnalyzeAll[layer].setFrmRate( m_acLayerCfg[layer].getFrameRate());
+      m_gcAnalyzeI[layer].setFrmRate( m_acLayerCfg[layer].getFrameRate() );
+      m_gcAnalyzeP[layer].setFrmRate( m_acLayerCfg[layer].getFrameRate() );
+      m_gcAnalyzeB[layer].setFrmRate( m_acLayerCfg[layer].getFrameRate() );
+    }
+  }
+
+  //-- all
+  printf( "\n\nSUMMARY --------------------------------------------------------\n" );
+  for(layer = 0; layer < m_numLayers; layer++)
+  {
+    m_gcAnalyzeAll[layer].printOut('a', m_acLayerCfg[layer].getChromaFormatIDC(), printMSEBasedSNR, printSequenceMSE, layer);
+  }
+
+  printf( "\n\nI Slices--------------------------------------------------------\n" );
+  for(layer = 0; layer < m_numLayers; layer++)
+  {
+    m_gcAnalyzeI[layer].printOut('i', m_acLayerCfg[layer].getChromaFormatIDC(), printMSEBasedSNR, printSequenceMSE, layer);
+  }
+
+  printf( "\n\nP Slices--------------------------------------------------------\n" );
+  for(layer = 0; layer < m_numLayers; layer++)
+  {
+    m_gcAnalyzeP[layer].printOut('p', m_acLayerCfg[layer].getChromaFormatIDC(), printMSEBasedSNR, printSequenceMSE, layer);
+  }
+
+  printf( "\n\nB Slices--------------------------------------------------------\n" );
+  for(layer = 0; layer < m_numLayers; layer++)
+  {
+    m_gcAnalyzeB[layer].printOut('b', m_acLayerCfg[layer].getChromaFormatIDC(), printMSEBasedSNR, printSequenceMSE, layer);
+  }
+
+  if(isField)
+  {
+    for(layer = 0; layer < m_numLayers; layer++)
+    {
+      //-- interlaced summary
+      m_gcAnalyzeAll_in.setFrmRate( m_acLayerCfg[layer].getFrameRate());
+      m_gcAnalyzeAll_in.setBits(m_gcAnalyzeB[layer].getBits());
+      // prior to the above statement, the interlace analyser does not contain the correct total number of bits.
+
+      printf( "\n\nSUMMARY INTERLACED ---------------------------------------------\n" );
+      m_gcAnalyzeAll_in.printOut('a', m_acLayerCfg[layer].getChromaFormatIDC(), printMSEBasedSNR, printSequenceMSE, layer);
+
+#if _SUMMARY_OUT_
+      m_gcAnalyzeAll_in.printSummaryOutInterlaced();
+#endif
+    }
+  }
+
+  printf("\n");
+  //printf("\nRVM: %.3lf\n" , xCalculateRVM());
+}
+
+#else
+// ====================================================================================================================
+// Public member functions
+// ====================================================================================================================
+
+/**
+ - create internal class
+ - initialize internal variable
+ - until the end of input YUV file, call encoding function in TEncTop class
+ - delete allocated buffers
+ - destroy internal class
+ .
+ */
+Void TAppEncTop::encode()
+{
+  fstream bitstreamFile(m_pchBitstreamFile, fstream::binary | fstream::out);
+  if (!bitstreamFile)
+  {
+    fprintf(stderr, "\nfailed to open bitstream file `%s' for writing\n", m_pchBitstreamFile);
+    exit(EXIT_FAILURE);
+  }
+
+  TComPicYuv*       pcPicYuvOrg = new TComPicYuv;
+  TComPicYuv*       pcPicYuvRec = NULL;
+
+  // initialize internal class & member variables
+  xInitLibCfg();
+  xCreateLib();
+  xInitLib(m_isField);
+
+  printChromaFormat();
+
+  // main encoder loop
+  Int   iNumEncoded = 0;
+  Bool  bEos = false;
+
+  const InputColourSpaceConversion ipCSC  =  m_inputColourSpaceConvert;
+  const InputColourSpaceConversion snrCSC = (!m_snrInternalColourSpace) ? m_inputColourSpaceConvert : IPCOLOURSPACE_UNCHANGED;
+
+  list<AccessUnit> outputAccessUnits; ///< list of access units to write out.  is populated by the encoding process
+
+  TComPicYuv cPicYuvTrueOrg;
+
+  // allocate original YUV buffer
+  if( m_isField )
+  {
+    pcPicYuvOrg->create( m_iSourceWidth, m_iSourceHeightOrg, m_chromaFormatIDC, m_uiMaxCUWidth, m_uiMaxCUHeight, m_uiMaxCUDepth );
+  cPicYuvTrueOrg.create(m_iSourceWidth, m_iSourceHeightOrg, m_chromaFormatIDC, m_uiMaxCUWidth, m_uiMaxCUHeight, m_uiMaxCUDepth);
+  }
+  else
+  {
+    pcPicYuvOrg->create( m_iSourceWidth, m_iSourceHeight, m_chromaFormatIDC, m_uiMaxCUWidth, m_uiMaxCUHeight, m_uiMaxCUDepth );
+  cPicYuvTrueOrg.create(m_iSourceWidth, m_iSourceHeight, m_chromaFormatIDC, m_uiMaxCUWidth, m_uiMaxCUHeight, m_uiMaxCUDepth);
+  }
+
+  while ( !bEos )
+  {
+    // get buffers
+    xGetBuffer(pcPicYuvRec);
+
+    // read input YUV file
+    m_cTVideoIOYuvInputFile.read( pcPicYuvOrg, &cPicYuvTrueOrg, ipCSC, m_aiPad, m_InputChromaFormatIDC );
+
+    // increase number of received frames
+    m_iFrameRcvd++;
+
+    bEos = (m_isField && (m_iFrameRcvd == (m_framesToBeEncoded >> 1) )) || ( !m_isField && (m_iFrameRcvd == m_framesToBeEncoded) );
+
+    Bool flush = 0;
+    // if end of file (which is only detected on a read failure) flush the encoder of any queued pictures
+    if (m_cTVideoIOYuvInputFile.isEof())
+    {
+      flush = true;
+      bEos = true;
+      m_iFrameRcvd--;
+      m_cTEncTop.setFramesToBeEncoded(m_iFrameRcvd);
+    }
+
+    // call encoding function for one frame
+    if ( m_isField ) m_cTEncTop.encode( bEos, flush ? 0 : pcPicYuvOrg, flush ? 0 : &cPicYuvTrueOrg, snrCSC, m_cListPicYuvRec, outputAccessUnits, iNumEncoded, m_isTopFieldFirst );
+    else             m_cTEncTop.encode( bEos, flush ? 0 : pcPicYuvOrg, flush ? 0 : &cPicYuvTrueOrg, snrCSC, m_cListPicYuvRec, outputAccessUnits, iNumEncoded );
+
+    // write bistream to file if necessary
+    if ( iNumEncoded > 0 )
+    {
+      xWriteOutput(bitstreamFile, iNumEncoded, outputAccessUnits);
+      outputAccessUnits.clear();
+    }
+  }
+
+  m_cTEncTop.printSummary(m_isField);
+
+  // delete original YUV buffer
+  pcPicYuvOrg->destroy();
+  delete pcPicYuvOrg;
+  pcPicYuvOrg = NULL;
+
+  // delete used buffers in encoder class
+  m_cTEncTop.deletePicBuffer();
+  cPicYuvTrueOrg.destroy();
+
+  // delete buffers & classes
+  xDeleteBuffer();
+  xDestroyLib();
+
+  printRateSummary();
+
+  return;
+}
+#endif
+
+// ====================================================================================================================
+// 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 SVC_EXTENSION
+Void TAppEncTop::xGetBuffer( TComPicYuv*& rpcPicYuvRec, UInt layer)
+{
+  assert( m_iGOPSize > 0 );
+
+  // org. buffer
+  if ( m_acListPicYuvRec[layer].size() >= (UInt)m_iGOPSize ) // buffer will be 1 element longer when using field coding, to maintain first field whilst processing second.
+  {
+    rpcPicYuvRec = m_acListPicYuvRec[layer].popFront();
+
+  }
+  else
+  {
+    rpcPicYuvRec = new TComPicYuv;
+
+#if LAYER_CTB
+    rpcPicYuvRec->create( m_acLayerCfg[layer].getSourceWidth(), m_acLayerCfg[layer].getSourceHeight(), m_acLayerCfg[layer].getChromaFormatIDC(), m_acLayerCfg[layer].m_uiMaxCUWidth, m_acLayerCfg[layer].m_uiMaxCUHeight, m_acLayerCfg[layer].m_uiMaxCUDepth, NULL );
+#else
+    rpcPicYuvRec->create( m_acLayerCfg[layer].getSourceWidth(), m_acLayerCfg[layer].getSourceHeight(), m_acLayerCfg[layer].getChromaFormatIDC(), m_uiMaxCUWidth, m_uiMaxCUHeight, m_uiMaxCUDepth, NULL );
+#endif
+
+  }
+  m_acListPicYuvRec[layer].pushBack( rpcPicYuvRec );
+}
+
+Void TAppEncTop::xDeleteBuffer( )
+{
+  for(UInt layer=0; layer<m_numLayers; layer++)
+  {
+    TComList<TComPicYuv*>::iterator iterPicYuvRec  = m_acListPicYuvRec[layer].begin();
+
+    Int iSize = Int( m_acListPicYuvRec[layer].size() );
+
+    for ( Int i = 0; i < iSize; i++ )
+    {
+      TComPicYuv*  pcPicYuvRec  = *(iterPicYuvRec++);
+      pcPicYuvRec->destroy();
+      delete pcPicYuvRec; pcPicYuvRec = NULL;
+    }
+  }
+}
+
+Void TAppEncTop::xWriteRecon(UInt layer, Int iNumEncoded)
+{
+#if REPN_FORMAT_IN_VPS
+  ChromaFormat chromaFormatIdc = m_acLayerCfg[layer].getChromaFormatIDC();
+  Int xScal = TComSPS::getWinUnitX( chromaFormatIdc );
+  Int yScal = TComSPS::getWinUnitY( chromaFormatIdc );
+#endif
+
+  const InputColourSpaceConversion ipCSC = (!m_outputInternalColourSpace) ? m_inputColourSpaceConvert : IPCOLOURSPACE_UNCHANGED;
+
+  if (m_isField)
+  {
+    //Reinterlace fields
+    Int i;
+    TComList<TComPicYuv*>::iterator iterPicYuvRec = m_acListPicYuvRec[layer].end();
+
+    for ( i = 0; i < iNumEncoded; i++ )
+    {
+      --iterPicYuvRec;
+    }
+
+    for ( i = 0; i < iNumEncoded/2; i++ )
+    {
+      TComPicYuv*  pcPicYuvRecTop  = *(iterPicYuvRec++);
+      TComPicYuv*  pcPicYuvRecBottom  = *(iterPicYuvRec++);
+
+#if M0040_ADAPTIVE_RESOLUTION_CHANGE
+      if (!m_acLayerCfg[layer].getReconFile().empty() && pcPicYuvRecTop->isReconstructed() && pcPicYuvRecBottom->isReconstructed())
+#else
+      if (!m_acLayerCfg[layer].getReconFile().empty())
+#endif
+      {
+#if REPN_FORMAT_IN_VPS
+        m_acTVideoIOYuvReconFile[layer].write( pcPicYuvRecTop, pcPicYuvRecBottom, ipCSC, m_acLayerCfg[layer].getConfWinLeft() * xScal, m_acLayerCfg[layer].getConfWinRight() * xScal, 
+          m_acLayerCfg[layer].getConfWinTop() * yScal, m_acLayerCfg[layer].getConfWinBottom() * yScal, NUM_CHROMA_FORMAT, m_isTopFieldFirst );
+#else
+        m_acTVideoIOYuvReconFile[layer].write( pcPicYuvRecTop, pcPicYuvRecBottom, ipCSC, m_acLayerCfg[layer].getConfWinLeft(), m_acLayerCfg[layer].getConfWinRight(), m_acLayerCfg[layer].getConfWinTop(), m_acLayerCfg[layer].getConfWinBottom(), NUM_CHROMA_FORMAT, m_isTopFieldFirst );
+#endif
+      }
+    }
+  }
+  else
+  {
+    Int i;
+
+    TComList<TComPicYuv*>::iterator iterPicYuvRec = m_acListPicYuvRec[layer].end();
+
+    for ( i = 0; i < iNumEncoded; i++ )
+    {
+      --iterPicYuvRec;
+    }
+
+    for ( i = 0; i < iNumEncoded; i++ )
+    {
+      TComPicYuv*  pcPicYuvRec  = *(iterPicYuvRec++);
+#if M0040_ADAPTIVE_RESOLUTION_CHANGE
+      if (!m_acLayerCfg[layer].getReconFile().empty() && pcPicYuvRec->isReconstructed())
+#else
+      if (!m_acLayerCfg[layer].getReconFile().empty())
+#endif
+      {
+#if REPN_FORMAT_IN_VPS
+        m_acTVideoIOYuvReconFile[layer].write( pcPicYuvRec, ipCSC, m_acLayerCfg[layer].getConfWinLeft() * xScal, m_acLayerCfg[layer].getConfWinRight() * xScal,
+          m_acLayerCfg[layer].getConfWinTop() * yScal, m_acLayerCfg[layer].getConfWinBottom() * yScal );
+#else
+        m_acTVideoIOYuvReconFile[layer].write( pcPicYuvRec, ipCSC, m_acLayerCfg[layer].getConfWinLeft(), m_acLayerCfg[layer].getConfWinRight(),
+          m_acLayerCfg[layer].getConfWinTop(), m_acLayerCfg[layer].getConfWinBottom() );
+#endif
+      }
+    }
+  }
+}
+
+Void TAppEncTop::xWriteStream(std::ostream& bitstreamFile, Int iNumEncoded, const std::list<AccessUnit>& accessUnits)
+{
+  if (m_isField)
+  {
+    //Reinterlace fields
+    Int i;
+    list<AccessUnit>::const_iterator iterBitstream = accessUnits.begin();
+
+#if M0040_ADAPTIVE_RESOLUTION_CHANGE
+    for ( i = 0; i < iNumEncoded/2 && iterBitstream != accessUnits.end(); i++ )
+#else
+    for ( i = 0; i < iNumEncoded/2; i++ )
+#endif
+    {
+      const AccessUnit& auTop = *(iterBitstream++);
+      const vector<UInt>& statsTop = writeAnnexB(bitstreamFile, auTop);
+      rateStatsAccum(auTop, statsTop);
+
+      const AccessUnit& auBottom = *(iterBitstream++);
+      const vector<UInt>& statsBottom = writeAnnexB(bitstreamFile, auBottom);
+      rateStatsAccum(auBottom, statsBottom);
+    }
+  }
+  else
+  {
+    Int i;
+
+    list<AccessUnit>::const_iterator iterBitstream = accessUnits.begin();
+
+#if M0040_ADAPTIVE_RESOLUTION_CHANGE
+    for ( i = 0; i < iNumEncoded && iterBitstream != accessUnits.end(); i++ )
+#else
+    for ( i = 0; i < iNumEncoded; i++ )
+#endif
+    {
+      const AccessUnit& au = *(iterBitstream++);
+      const vector<UInt>& stats = writeAnnexB(bitstreamFile, au);
+      rateStatsAccum(au, stats);
+    }
+  }
+}
+
+#else // SVC_EXTENSION
+Void TAppEncTop::xGetBuffer( TComPicYuv*& rpcPicYuvRec)
+{
+  assert( m_iGOPSize > 0 );
+
+  // org. buffer
+  if ( m_cListPicYuvRec.size() >= (UInt)m_iGOPSize ) // buffer will be 1 element longer when using field coding, to maintain first field whilst processing second.
+  {
+    rpcPicYuvRec = m_cListPicYuvRec.popFront();
+
+  }
+  else
+  {
+    rpcPicYuvRec = new TComPicYuv;
+
+    rpcPicYuvRec->create( m_iSourceWidth, m_iSourceHeight, m_chromaFormatIDC, m_uiMaxCUWidth, m_uiMaxCUHeight, m_uiMaxCUDepth );
+
+  }
+  m_cListPicYuvRec.pushBack( rpcPicYuvRec );
+}
+
+Void TAppEncTop::xDeleteBuffer( )
+{
+  TComList<TComPicYuv*>::iterator iterPicYuvRec  = m_cListPicYuvRec.begin();
+
+  Int iSize = Int( m_cListPicYuvRec.size() );
+
+  for ( Int i = 0; i < iSize; i++ )
+  {
+    TComPicYuv*  pcPicYuvRec  = *(iterPicYuvRec++);
+    pcPicYuvRec->destroy();
+    delete pcPicYuvRec; pcPicYuvRec = NULL;
+  }
+
+}
+
+/** \param iNumEncoded  number of encoded frames
+ */
+Void TAppEncTop::xWriteOutput(std::ostream& bitstreamFile, Int iNumEncoded, const std::list<AccessUnit>& accessUnits)
+{
+  const InputColourSpaceConversion ipCSC = (!m_outputInternalColourSpace) ? m_inputColourSpaceConvert : IPCOLOURSPACE_UNCHANGED;
+
+  if (m_isField)
+  {
+    //Reinterlace fields
+    Int i;
+    TComList<TComPicYuv*>::iterator iterPicYuvRec = m_cListPicYuvRec.end();
+    list<AccessUnit>::const_iterator iterBitstream = accessUnits.begin();
+
+    for ( i = 0; i < iNumEncoded; i++ )
+    {
+      --iterPicYuvRec;
+    }
+
+    for ( i = 0; i < iNumEncoded/2; i++ )
+    {
+      TComPicYuv*  pcPicYuvRecTop  = *(iterPicYuvRec++);
+      TComPicYuv*  pcPicYuvRecBottom  = *(iterPicYuvRec++);
+
+      if (m_pchReconFile)
+      {
+        m_cTVideoIOYuvReconFile.write( pcPicYuvRecTop, pcPicYuvRecBottom, ipCSC, m_confWinLeft, m_confWinRight, m_confWinTop, m_confWinBottom, NUM_CHROMA_FORMAT, m_isTopFieldFirst );
+      }
+
+      const AccessUnit& auTop = *(iterBitstream++);
+      const vector<UInt>& statsTop = writeAnnexB(bitstreamFile, auTop);
+      rateStatsAccum(auTop, statsTop);
+
+      const AccessUnit& auBottom = *(iterBitstream++);
+      const vector<UInt>& statsBottom = writeAnnexB(bitstreamFile, auBottom);
+      rateStatsAccum(auBottom, statsBottom);
+    }
+  }
+  else
+  {
+    Int i;
+
+    TComList<TComPicYuv*>::iterator iterPicYuvRec = m_cListPicYuvRec.end();
+    list<AccessUnit>::const_iterator iterBitstream = accessUnits.begin();
+
+    for ( i = 0; i < iNumEncoded; i++ )
+    {
+      --iterPicYuvRec;
+    }
+
+    for ( i = 0; i < iNumEncoded; i++ )
+    {
+      TComPicYuv*  pcPicYuvRec  = *(iterPicYuvRec++);
+      if (m_pchReconFile)
+      {
+        m_cTVideoIOYuvReconFile.write( pcPicYuvRec, ipCSC, m_confWinLeft, m_confWinRight, m_confWinTop, m_confWinBottom );
+      }
+
+      const AccessUnit& au = *(iterBitstream++);
+      const vector<UInt>& stats = writeAnnexB(bitstreamFile, au);
+      rateStatsAccum(au, stats);
+    }
+  }
+}
+#endif
+
+/**
+ *
+ */
+Void TAppEncTop::rateStatsAccum(const AccessUnit& au, const std::vector<UInt>& annexBsizes)
+{
+  AccessUnit::const_iterator it_au = au.begin();
+  vector<UInt>::const_iterator it_stats = annexBsizes.begin();
+
+  for (; it_au != au.end(); it_au++, it_stats++)
+  {
+    switch ((*it_au)->m_nalUnitType)
+    {
+    case NAL_UNIT_CODED_SLICE_TRAIL_R:
+    case NAL_UNIT_CODED_SLICE_TRAIL_N:
+    case NAL_UNIT_CODED_SLICE_TSA_R:
+    case NAL_UNIT_CODED_SLICE_TSA_N:
+    case NAL_UNIT_CODED_SLICE_STSA_R:
+    case NAL_UNIT_CODED_SLICE_STSA_N:
+    case NAL_UNIT_CODED_SLICE_BLA_W_LP:
+    case NAL_UNIT_CODED_SLICE_BLA_W_RADL:
+    case NAL_UNIT_CODED_SLICE_BLA_N_LP:
+    case NAL_UNIT_CODED_SLICE_IDR_W_RADL:
+    case NAL_UNIT_CODED_SLICE_IDR_N_LP:
+    case NAL_UNIT_CODED_SLICE_CRA:
+    case NAL_UNIT_CODED_SLICE_RADL_N:
+    case NAL_UNIT_CODED_SLICE_RADL_R:
+    case NAL_UNIT_CODED_SLICE_RASL_N:
+    case NAL_UNIT_CODED_SLICE_RASL_R:
+    case NAL_UNIT_VPS:
+    case NAL_UNIT_SPS:
+    case NAL_UNIT_PPS:
+      m_essentialBytes += *it_stats;
+      break;
+    default:
+      break;
+    }
+
+    m_totalBytes += *it_stats;
+  }
+}
+
+Void TAppEncTop::printRateSummary()
+{
+#if SVC_EXTENSION
+  Double time = (Double) m_iFrameRcvd / m_acLayerCfg[m_numLayers-1].getFrameRate();
+#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 !SVC_EXTENSION
+Void TAppEncTop::printChromaFormat()
+{
+  std::cout << std::setw(43) << "Input ChromaFormatIDC = ";
+  switch (m_InputChromaFormatIDC)
+  {
+  case CHROMA_400:  std::cout << "  4:0:0"; break;
+  case CHROMA_420:  std::cout << "  4:2:0"; break;
+  case CHROMA_422:  std::cout << "  4:2:2"; break;
+  case CHROMA_444:  std::cout << "  4:4:4"; break;
+  default:
+    std::cerr << "Invalid";
+    exit(1);
+  }
+  std::cout << std::endl;
+
+  std::cout << std::setw(43) << "Output (internal) ChromaFormatIDC = ";
+  switch (m_cTEncTop.getChromaFormatIdc())
+  {
+  case CHROMA_400:  std::cout << "  4:0:0"; break;
+  case CHROMA_420:  std::cout << "  4:2:0"; break;
+  case CHROMA_422:  std::cout << "  4:2:2"; break;
+  case CHROMA_444:  std::cout << "  4:4:4"; break;
+  default:
+    std::cerr << "Invalid";
+    exit(1);
+  }
+  std::cout << "\n" << std::endl;
+}
+#endif
+
+//! \}
Index: /tags/SHM-9.0/source/App/TAppEncoder/TAppEncTop.h
===================================================================
--- /tags/SHM-9.0/source/App/TAppEncoder/TAppEncTop.h	(revision 1088)
+++ /tags/SHM-9.0/source/App/TAppEncoder/TAppEncTop.h	(revision 1088)
@@ -0,0 +1,125 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \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"
+
+//! \ingroup TAppEncoder
+//! \{
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// encoder application class
+class TAppEncTop : public TAppEncCfg
+{
+private:
+  // class interface
+#if SVC_EXTENSION
+  TEncTop                    m_acTEncTop [MAX_LAYERS];                    ///< encoder class
+  TEncTop*                   m_apcTEncTop [MAX_LAYERS];                   ///< encoder pointer class
+  TVideoIOYuv                m_acTVideoIOYuvInputFile [MAX_LAYERS];       ///< input YUV file
+  TVideoIOYuv                m_acTVideoIOYuvReconFile [MAX_LAYERS];       ///< output reconstruction file
+
+  TComList<TComPicYuv*>      m_acListPicYuvRec [MAX_LAYERS];              ///< list of reconstruction YUV files
+#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
+#endif
+  
+  Int                        m_iFrameRcvd;                  ///< number of received frames
+
+  UInt m_essentialBytes;
+  UInt m_totalBytes;
+
+protected:
+  // initialization
+  Void  xCreateLib        ();                               ///< create files & encoder class
+  Void  xInitLibCfg       ();                               ///< initialize internal variables
+  Void  xInitLib          (Bool isFieldCoding);             ///< initialize encoder class
+  Void  xDestroyLib       ();                               ///< destroy encoder class
+
+  /// obtain required buffers
+#if SVC_EXTENSION
+  Void xGetBuffer(TComPicYuv*& rpcPicYuvRec, UInt layer);
+#else
+  Void xGetBuffer(TComPicYuv*& rpcPicYuvRec);
+#endif
+  
+  /// delete allocated buffers
+  Void  xDeleteBuffer     ();
+
+  // file I/O
+#if SVC_EXTENSION
+  Void xWriteRecon(UInt layer, Int iNumEncoded);
+  Void xWriteStream(std::ostream& bitstreamFile, Int iNumEncoded, const std::list<AccessUnit>& accessUnits);
+  Void printOutSummary(Bool isField, const Bool printMSEBasedSNR, const Bool printSequenceMSE);
+#else
+  Void xWriteOutput(std::ostream& bitstreamFile, Int iNumEncoded, const std::list<AccessUnit>& accessUnits); ///< write bitstream to file
+  Void printChromaFormat();
+#endif
+  Void rateStatsAccum(const AccessUnit& au, const std::vector<UInt>& stats);
+  Void printRateSummary();
+  
+public:
+  TAppEncTop();
+  virtual ~TAppEncTop();
+
+  Void        encode      ();                               ///< main encoding function
+#if SVC_EXTENSION
+  TEncTop&    getTEncTop  (UInt layer)   { return  m_acTEncTop[layer]; }      ///< return encoder class pointer reference
+#else
+  TEncTop&    getTEncTop  ()   { return  m_cTEncTop; }      ///< return encoder class pointer reference
+#endif
+};// END CLASS DEFINITION TAppEncTop
+
+//! \}
+
+#endif // __TAPPENCTOP__
+
Index: /tags/SHM-9.0/source/App/TAppEncoder/encmain.cpp
===================================================================
--- /tags/SHM-9.0/source/App/TAppEncoder/encmain.cpp	(revision 1088)
+++ /tags/SHM-9.0/source/App/TAppEncoder/encmain.cpp	(revision 1088)
@@ -0,0 +1,114 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     encmain.cpp
+    \brief    Encoder application main
+*/
+
+#include <time.h>
+#include <iostream>
+#include "TAppEncTop.h"
+#include "TAppCommon/program_options_lite.h"
+
+//! \ingroup TAppEncoder
+//! \{
+
+#include "../Lib/TLibCommon/Debug.h"
+
+// ====================================================================================================================
+// Main function
+// ====================================================================================================================
+
+int main(int argc, char* argv[])
+{
+  TAppEncTop  cTAppEncTop;
+
+  // print information
+  fprintf( stdout, "\n" );
+#if SVC_EXTENSION
+  fprintf( stdout, "SHM software: Encoder Version [%s]", NV_VERSION );
+#else
+  fprintf( stdout, "HM software: Encoder Version [%s] (including RExt)", NV_VERSION );
+#endif
+  fprintf( stdout, NVM_ONOS );
+  fprintf( stdout, NVM_COMPILEDBY );
+  fprintf( stdout, NVM_BITS );
+  fprintf( stdout, "\n\n" );
+
+  // create application encoder class
+  cTAppEncTop.create();
+
+  // parse configuration
+  try
+  {
+    if(!cTAppEncTop.parseCfg( argc, argv ))
+    {
+      cTAppEncTop.destroy();
+#if ENVIRONMENT_VARIABLE_DEBUG_AND_TEST
+      EnvVar::printEnvVar();
+#endif
+      return 1;
+    }
+  }
+  catch (df::program_options_lite::ParseFailure &e)
+  {
+    std::cerr << "Error parsing option \""<< e.arg <<"\" with argument \""<< e.val <<"\"." << std::endl;
+    return 1;
+  }
+
+#if PRINT_MACRO_VALUES
+  printMacroSettings();
+#endif
+
+#if ENVIRONMENT_VARIABLE_DEBUG_AND_TEST
+  EnvVar::printEnvVarInUse();
+#endif
+
+  // starting time
+  Double dResult;
+  clock_t 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: /tags/SHM-9.0/source/App/utils/BitrateTargeting/ExtractBitrates.cpp
===================================================================
--- /tags/SHM-9.0/source/App/utils/BitrateTargeting/ExtractBitrates.cpp	(revision 1088)
+++ /tags/SHM-9.0/source/App/utils/BitrateTargeting/ExtractBitrates.cpp	(revision 1088)
@@ -0,0 +1,164 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "ExtractBitrates.h"
+#include <string>
+#include <sstream>
+#include <cassert>
+#include <limits>
+#include <map>
+
+namespace
+{
+  /// Maintains a sum and a sample-count for calculating averages
+  class Tally
+  {
+    public:
+      
+      /// Contructs a new zeroed tally
+      Tally( ): m_sum( 0.0 ), m_numSlices( 0 ) { }
+      
+      /// Adds to the sum and increments the sample-count
+      void add( double in ) { ++m_numSlices; m_sum += in; }
+      
+      /// \return The calculated average
+      double average( ) const { return m_sum / ( double )m_numSlices; }
+    
+    private:
+      double m_sum;
+      unsigned long m_numSlices;
+  };
+  
+  /// Ignores all of the the characters up to and including a given character
+  /// \param line The line being read from
+  /// \param iLine The active input stream
+  /// \param character The character to ignore up to
+  /// \throw POCParseException if the stream goes bad before character is encountered or just after character is encountered
+  void ignoreUpTo( const std::string& line, std::istream& iLine, char character )
+  {
+    while( iLine.good( ) && character != iLine.get( ) )
+      ;
+    if( !iLine.good( ) ) throw POCParseException( line );
+  }
+  
+  /// Extracts the average bitrates for each of the temporal layers from the given log
+  /// \param i The input stream that represents the log
+  /// \return A map that countains the average bitrates for each temporal layer.  Each pair contains the QP value in first and the average bitrate in second.
+  /// \throw POCParseException if an error occured while parsing a POC line
+  std::map< unsigned char, double > extractBitratesForQPs( std::istream& i )
+  {
+    std::map< unsigned char, Tally > tallyMap;
+    
+    while( i.good( ) )
+    {
+      // Initialize variables for this line
+      std::string line;
+      std::getline( i, line );
+      std::istringstream iLine( line );
+      if( !iLine.good( ) ) continue;
+      
+      // Ignore the "POC"
+      if( iLine.get( ) != 'P' ) continue;
+      if( !iLine.good( ) ) continue;
+      if( iLine.get( ) != 'O' ) continue;
+      if( !iLine.good( ) ) continue;
+      if( iLine.get( ) != 'C' ) continue;
+      if( !iLine.good( ) ) throw POCParseException( line );
+      
+      ignoreUpTo( line, iLine, '(' );
+      
+      if( iLine.get( ) != ' ' ) throw POCParseException( line );
+      if( !iLine.good( ) ) throw POCParseException( line );
+      
+      if( 'I' == iLine.get( ) ) continue;
+      if( !iLine.good( ) ) throw POCParseException( line );
+      
+      ignoreUpTo( line, iLine, ' ' );
+      ignoreUpTo( line, iLine, ' ' );
+      
+      // Parse the qpIndex
+      long qpIndexLong;
+      iLine >> qpIndexLong;
+      if( ( long )std::numeric_limits< unsigned char >::max( ) < qpIndexLong ) throw POCParseException( line );
+      unsigned char qpIndex( ( unsigned char )qpIndexLong );
+      if( !iLine.good( ) ) throw POCParseException( line );
+      
+      ignoreUpTo( line, iLine, ')' );
+      ignoreUpTo( line, iLine, ' ' );
+      
+      // Parse the number of bits
+      unsigned long bitsULong;
+      iLine >> bitsULong;
+      if( !iLine.good( ) ) throw POCParseException( line );
+      
+      // Find the tally that corresponds to our QP.  If there is no such tally yet, then add a new one to the map.
+      std::map< unsigned char, Tally >::iterator iter( tallyMap.find( qpIndex ) );
+      if( tallyMap.end( ) == iter )
+      {
+        tallyMap[ qpIndex ] = Tally( );
+        iter = tallyMap.find( qpIndex );
+      }
+      assert( iter != tallyMap.end( ) );
+      
+      iter->second.add( ( double )bitsULong );
+    }
+    
+    // Populate and return the result based on all of the tallies
+    std::map< unsigned char, double > result;
+    for( std::map< unsigned char, Tally >::const_iterator iter( tallyMap.begin( ) ); iter != tallyMap.end( ); ++iter )
+    {
+      result[ iter->first ] = iter->second.average( );
+    }
+    return result;
+  }
+}
+
+std::vector< double > extractBitratesForTemporalLayers( std::istream& i )
+{
+  std::vector< double > result;
+  
+  std::map< unsigned char, double > bitratesForQPsMap( extractBitratesForQPs( i ) );
+  if( !bitratesForQPsMap.empty( ) )
+  {
+    unsigned char expectedNextQPIndex( bitratesForQPsMap.begin( )->first );
+    
+    for( std::map< unsigned char, double >::const_iterator i( bitratesForQPsMap.begin( ) ); i != bitratesForQPsMap.end( ); ++i )
+    {
+      if( i->first != expectedNextQPIndex ) throw NonContiguousQPSetException( );
+      ++expectedNextQPIndex;
+      result.push_back( i->second );
+    }
+  }
+  
+  return result;
+}
Index: /tags/SHM-9.0/source/App/utils/BitrateTargeting/ExtractBitrates.h
===================================================================
--- /tags/SHM-9.0/source/App/utils/BitrateTargeting/ExtractBitrates.h	(revision 1088)
+++ /tags/SHM-9.0/source/App/utils/BitrateTargeting/ExtractBitrates.h	(revision 1088)
@@ -0,0 +1,71 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef __EXTRACTBITRATES__
+#define __EXTRACTBITRATES__
+
+#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: /tags/SHM-9.0/source/App/utils/BitrateTargeting/ExtractBitratesMain.cpp
===================================================================
--- /tags/SHM-9.0/source/App/utils/BitrateTargeting/ExtractBitratesMain.cpp	(revision 1088)
+++ /tags/SHM-9.0/source/App/utils/BitrateTargeting/ExtractBitratesMain.cpp	(revision 1088)
@@ -0,0 +1,99 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include <iostream>
+#include <cassert>
+#include "ExtractBitrates.h"
+
+/// In out, finds the first occurence of toFind and replaces it with "e"
+/// \pre toFind must have a size of 2
+/// \pre The first character in toFind muts be 'e'
+/// \pre out must contain toFind
+void replaceWithE( std::string &out, const std::string& toFind )
+{
+  assert( 2 == toFind.size( ) );
+  assert( 'e' == toFind[ 0 ] );
+  
+  std::string::size_type pos( out.find( toFind ) );
+  assert( pos != std::string::npos );
+  out.erase( pos + 1, 1 );
+}
+
+/// Formatted output for a double with appropriate formatting applied (correct number of digits, etc.)
+void outputDouble( std::ostream& left, double right )
+{
+  std::ostringstream oss;
+  oss.precision( 6 );
+  oss << std::scientific << right;
+  std::string s( oss.str( ) );
+  
+  replaceWithE( s, "e+" );
+  replaceWithE( s, "e0" );
+  
+  left << s;
+}
+
+int main( int, char** )
+{
+  try
+  {
+    std::vector< double > result( extractBitratesForTemporalLayers( std::cin ) );  // Extract the bitrate vector
+    
+    // Output the bitrate vector
+    if( 0 < result.size( ) )
+    {
+      std::vector< double >::const_iterator iter( result.begin( ) );
+      outputDouble( std::cout, *iter );
+      for( ; ; )
+      {
+        ++iter;
+        if( result.end( ) == iter )
+        {
+          break;
+        }
+        else
+        {
+          std::cout << " ";
+          outputDouble( std::cout, *iter );
+        }
+      }
+    }
+    
+    return 0;
+  }
+  catch( std::exception& e )
+  {
+    std::cerr << e.what( ) << std::endl;
+    return 1;
+  }
+}
Index: /tags/SHM-9.0/source/App/utils/BitrateTargeting/GuessLambdaModifiers.cpp
===================================================================
--- /tags/SHM-9.0/source/App/utils/BitrateTargeting/GuessLambdaModifiers.cpp	(revision 1088)
+++ /tags/SHM-9.0/source/App/utils/BitrateTargeting/GuessLambdaModifiers.cpp	(revision 1088)
@@ -0,0 +1,397 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "GuessLambdaModifiers.h"
+#include <limits>
+#include <cassert>
+#include <cmath>
+
+namespace
+{
+  /// Formatted input for a bitrate vector
+  /// \param left The input stream that contains the bitrate vector
+  /// \param right The vector to be written to
+  /// \pre right must be empty
+  void parseBitrateVector( std::istream& left, std::vector< double >& right )
+  {
+    assert( right.empty( ) );
+    
+    for( ; ; )
+    {
+      assert( left.good( ) );
+      
+      double bitrate;
+      left >> bitrate;
+      if( left.fail( ) ) break;
+      if( bitrate <= ( double )0.0 )
+      {
+        left.setstate( std::istream::failbit );
+      }
+      else
+      {
+        right.push_back( bitrate );
+      }
+      if( !left.good( ) ) break;
+      
+      if( left.peek( ) == ' ' )
+      {
+        left.ignore( );
+      }
+      else
+      {
+        break;
+      }
+    }
+  }
+  
+  /// Makes a next guess for a single Lambda-modifier based on only one previous guess
+  /// \param initialAdjustmentParameter The proportionality to use between the target bitrate and the previous guess
+  /// \param target The target bitrate value that this Lambda-modifier is trying to reach
+  /// \param previousPoint The previous guess
+  /// \return The Lambda-modifier guess
+  /// \pre The given point must contain only positive non-zero values
+  double incrementLambdaModifier(
+      double initialAdjustmentParameter,
+      double targetBitrate,
+      const Point& previousPoint )
+  {
+    assert( ( double )0.0 < previousPoint.lambdaModifier );
+    assert( ( double )0.0 < previousPoint.bitrate );
+    
+    double extrapolated( previousPoint.lambdaModifier * targetBitrate / previousPoint.bitrate );
+    return previousPoint.lambdaModifier + initialAdjustmentParameter * ( extrapolated - previousPoint.lambdaModifier );
+  }
+}
+
+double polateLambdaModifier( double targetBitrate, const Point& point1, const Point& point2 )
+{
+  assert( 0.0 < point1.lambdaModifier );
+  assert( 0.0 < point2.lambdaModifier );
+  assert( 0.0 < point1.bitrate );
+  assert( 0.0 < point2.bitrate );
+  assert( point1.lambdaModifier != point2.lambdaModifier );
+  assert( point1.bitrate != point2.bitrate );
+  
+  // Calculate and return the result
+  double denominator( point1.bitrate - point2.bitrate );
+  double result( point1.lambdaModifier
+      + ( point1.lambdaModifier - point2.lambdaModifier ) / denominator * ( targetBitrate - point1.bitrate ) );
+  return result;
+}
+
+double guessLambdaModifier(
+    double initialAdjustmentParameter,
+    double targetBitrate,
+    const std::list< Point >& pointList,
+    double interDampeningFactor )
+{
+  assert( ( double )0.0 < interDampeningFactor );
+  assert( interDampeningFactor <= ( double )1.0 );
+  assert( !pointList.empty( ) );
+  
+  double preliminaryResult;
+  
+  if( 1 == pointList.size( ) )  // If there is only one prevous point, then we cannot interpolate, so we call incrementLambdaModifier
+  {
+    preliminaryResult = incrementLambdaModifier( initialAdjustmentParameter, targetBitrate, pointList.back( ) );
+  }
+  else  // If there are at least two previous points, then we may be able to interpolate
+  {
+    std::list< Point >::const_reverse_iterator i( pointList.rbegin( ) );
+    Point point1 = *i;
+    ++i;
+    Point point2 = *i;
+    
+    // If the slope is either horizontal or vertical, we cannot interpolate
+    if( point1.lambdaModifier == point2.lambdaModifier || point1.bitrate == point2.bitrate )
+    {
+      preliminaryResult = incrementLambdaModifier( initialAdjustmentParameter, targetBitrate, pointList.back( ) );
+    }
+    else  // If the slope is not horizontal and not vertical, we can interpolate
+    {
+      preliminaryResult = polateLambdaModifier( targetBitrate, point1, point2 );
+    }
+  }
+  
+  double previousResult( pointList.back( ).lambdaModifier );
+  
+  // Apply "intra dampening"
+  {
+    double intermediate( std::log( ( double )1.0 + std::abs( preliminaryResult - previousResult ) / previousResult ) );
+    assert( ( double )0.0 <= intermediate );
+    if( ( preliminaryResult - previousResult ) < 0.0 )
+    {
+      preliminaryResult = previousResult * ( ( double )1.0 - intermediate );
+    }
+    else
+    {
+      preliminaryResult = previousResult * ( ( double )1.0 + intermediate );
+    }
+  }
+  
+  // Apply "inter dampening factor".  If necessary, reduce the factor until a positive result is acheived.
+  double result;
+  do
+  {
+    result = previousResult + interDampeningFactor * ( preliminaryResult - previousResult );
+    interDampeningFactor /= ( double )2.0;
+  } while( result <= ( double )0.0 );
+  return result;
+}
+
+namespace
+{
+  /// Extracts a single point at the given index from a full meta-log entry
+  Point pointFromFullMetaLogEntry( unsigned char index, const MetaLogEntry< std::vector< double > >& fullEntry )
+  {
+    Point result;
+    result.lambdaModifier = fullEntry.lambdaModifiers[ index ];
+    result.bitrate = fullEntry.bitrateVector[ index ];
+    return result;
+  }
+  
+  /// Calculates the inter dampening factor based
+  /// \param parameter The inter dampening parameter which determines how severely the inter dampening factor is affected by Lambda-modifier changes at previous temporal layers
+  /// \param cumulativeDelta The sum of the percentage changes of the Lambda-modifiers at the previous temporal layers
+  /// \return The calculated inter dampening factor
+  /// \pre cumulativeDelta must be non-negative
+  /// \pre parameter must be non-negative
+  double interDampeningFactor( double parameter, double cumulativeDelta )
+  {
+    assert( 0.0 <= cumulativeDelta );
+    assert( 0.0 <= parameter );
+    return ( double )1.0 / ( parameter * cumulativeDelta + ( double )1.0 );
+  }
+}
+
+std::vector< double > guessLambdaModifiers(
+    double initialAdjustmentParameter,
+    const std::vector< double > &targetBitrateVector,
+    const std::list< MetaLogEntry< std::vector< double > > >& metaLogEntryList )
+{
+  assert( !targetBitrateVector.empty( ) );
+  assert( !metaLogEntryList.empty( ) );
+  
+  double cumulativeDelta( 0.0 );
+  std::vector< double > resultVector;
+  for( unsigned char i( 0 ); i < targetBitrateVector.size( ); ++i )
+  {
+    // Populate pointList with up to two of the previous points
+    std::list< Point > pointList;
+    std::list< MetaLogEntry< std::vector< double > > >::const_reverse_iterator j( metaLogEntryList.rbegin( ) );
+    pointList.push_front( pointFromFullMetaLogEntry( i, *j ) );
+    ++j;
+    if( j != metaLogEntryList.rend( ) ) pointList.push_front( pointFromFullMetaLogEntry( i, *j ) );
+    
+    // Calculate the new Lambda-modifier guess and add it to the result vector
+    const double newLambdaModifier( guessLambdaModifier(
+        initialAdjustmentParameter,
+        targetBitrateVector[ i ],  // target bitrate
+        pointList,
+        interDampeningFactor( 50.0, cumulativeDelta ) ) );
+    resultVector.push_back( newLambdaModifier );
+    
+    // Increment the cumulativeDelta
+    const double oldLambdaModifier( pointList.back( ).lambdaModifier );
+    cumulativeDelta += std::abs( newLambdaModifier - oldLambdaModifier ) / oldLambdaModifier;
+  }
+  
+  return resultVector;
+}
+
+namespace
+{
+  /// Ignores all of the the characters up to and including a given character
+  /// \param i The active input stream
+  /// \param character The character to ignore up to
+  /// \throw MetaLogParseException if the stream goes bad before character is encountered or just after character is encountered
+  void ignoreUpTo( std::istream& i, char character )
+  {
+    while( i.good( ) && character != i.get( ) )
+      ;
+    if( !i.good( ) ) throw MetaLogParseException( );
+  }
+  
+  /// Parses a Lambda-modifier map
+  /// \param right The map to write the output to
+  void parseLambdaModifierMap( std::istream& left, std::map< unsigned char, double >& right )
+  {
+    for( ; ; )
+    {
+      assert( left.good( ) );
+      
+      // Ignore the "-LM"
+      if( '-' != left.get( ) ) left.setstate( std::istream::failbit );
+      if( !left.good( ) ) break;
+      if( 'L' != left.get( ) ) left.setstate( std::istream::failbit );
+      if( !left.good( ) ) break;
+      if( 'M' != left.get( ) ) left.setstate( std::istream::failbit );
+      if( !left.good( ) ) break;
+      
+      // Parse the index
+      long indexLong;
+      left >> indexLong;
+      if( !left.good( ) ) break;
+      if( indexLong < std::numeric_limits< unsigned char >::min( ) ) left.setstate( std::istream::failbit );
+      if( std::numeric_limits< unsigned char >::max( ) < indexLong ) left.setstate( std::istream::failbit );
+      if( !left.good( ) ) break;
+      unsigned char index( ( unsigned char )indexLong );
+      
+      if( ' ' != left.get( ) ) left.setstate( std::istream::failbit );
+      if( !left.good( ) ) break;
+      
+      // Parse the Lambda-modifier
+      double lambdaModifier;
+      left >> lambdaModifier;
+      if( lambdaModifier <= ( double )0.0 || ( !right.empty( ) && ( right.count( index ) != 0 || index <= right.rbegin( )->first ) ) )
+      {
+        left.setstate( std::istream::failbit );
+      }
+      else
+      {
+        right[ index ] = lambdaModifier;
+      }
+      if( !left.good( ) ) break;
+      
+      // If we peek and see a space, then there should be more Lambda-modifiers to parse.  Otherwise, we are finished.
+      if( left.peek( ) == ' ' )
+      {
+        left.ignore( );
+      }
+      else
+      {
+        break;
+      }
+    }
+  }
+  
+  /// Extracts the indexes from the given maps
+  /// \return The set of indexes
+  std::set< unsigned char > indexSetFromMap( const std::map< unsigned char, double >& in )
+  {
+    std::set< unsigned char > result;
+    for( typename std::map< unsigned char, double >::const_iterator i( in.begin( ) ); i != in.end( ); ++i )
+    {
+      result.insert( i->first );
+    }
+    return result;
+  }
+}
+
+void guessLambdaModifiers(
+    std::ostream& o,
+    std::istream& initialAdjustmentParameterIstream,
+    std::istream& targetsIstream,
+    std::istream& metaLogIstream )
+{
+  // Parse the initialAdjustmentParameter
+  double initialAdjustmentParameter;
+  initialAdjustmentParameterIstream >> initialAdjustmentParameter;
+  if( initialAdjustmentParameterIstream.fail( ) || initialAdjustmentParameterIstream.good( ) )
+  {
+    throw InitialAdjustmentParameterParseException( );
+  }
+  
+  // Parse the targets
+  std::vector< double > targetVector;
+  parseBitrateVector( targetsIstream, targetVector );
+  if( targetVector.empty( ) || targetsIstream.fail( ) || targetsIstream.good( ) ) throw TargetsParseException( );
+  
+  // Parse the metalog
+  std::list< MetaLogEntry< std::map< unsigned char, double > > > metaLogEntryList;
+  do
+  {
+    // Parse the Lambda-modifiers
+    MetaLogEntry< std::map< unsigned char, double > > entry;
+    parseLambdaModifierMap( metaLogIstream, entry.lambdaModifiers );
+    if( !metaLogIstream.good( ) ) throw MetaLogParseException( );
+    
+    // Skip the ';'
+    if( ';' != metaLogIstream.get( ) ) throw MetaLogParseException( );
+    if( !metaLogIstream.good( ) ) throw MetaLogParseException( );
+    
+    // Parse the bitrates
+    parseBitrateVector( metaLogIstream, entry.bitrateVector );
+    if( metaLogIstream.fail( ) ) throw MetaLogParseException( );
+    metaLogEntryList.push_back( entry );
+    
+    if( !metaLogIstream.good( ) ) break;
+    if( metaLogIstream.get( ) != '\n' ) throw MetaLogParseException( );
+    metaLogIstream.peek( );
+  } while( metaLogIstream.good( ) );
+  if( metaLogEntryList.empty( ) ) throw MetaLogParseException( );  // The meta-log should not be empty
+  
+  // Initialize firstIndexVector and check that the sizes and indexes match
+  std::set< unsigned char > firstIndexSet( indexSetFromMap( metaLogEntryList.front( ).lambdaModifiers ) );
+  if( firstIndexSet.size( ) != targetVector.size( ) ) throw MismatchedIndexesException( );
+  for( std::list< MetaLogEntry< std::map< unsigned char, double > > >::const_iterator i( metaLogEntryList.begin( ) );
+      i != metaLogEntryList.end( );
+      ++i )
+  {
+    if( indexSetFromMap( i->lambdaModifiers ) != firstIndexSet ) throw MismatchedIndexesException( );
+    if( i->bitrateVector.size( ) != targetVector.size( ) ) throw MismatchedIndexesException( );
+  }
+  
+  // Initialize simplifiedMetaLogEntryList
+  std::list< MetaLogEntry< std::vector< double > > > simplifiedMetaLogEntryList;
+  for( std::list< MetaLogEntry< std::map< unsigned char, double > > >::const_iterator i( metaLogEntryList.begin( ) );
+      i != metaLogEntryList.end( );
+      ++i )
+  {
+    simplifiedMetaLogEntryList.push_back( MetaLogEntry< std::vector< double > >( ) );
+    for( std::map< unsigned char, double >::const_iterator j( i->lambdaModifiers.begin( ) ); j != i->lambdaModifiers.end( ); ++j )
+    {
+      simplifiedMetaLogEntryList.back( ).lambdaModifiers.push_back( j->second );
+    }
+    simplifiedMetaLogEntryList.back( ).bitrateVector = i->bitrateVector;
+  }
+  
+  // Run the calculations
+  std::vector< double > resultVector( guessLambdaModifiers( initialAdjustmentParameter, targetVector, simplifiedMetaLogEntryList ) );
+  
+  // Output the results
+  std::set< unsigned char >::const_iterator indexIter( firstIndexSet.begin( ) );
+  std::vector< double >::const_iterator resultIter( resultVector.begin( ) );
+  do
+  {
+    if( indexIter != firstIndexSet.begin( ) ) o << " ";
+    o << "-LM" << ( long )( *indexIter ) << " ";
+    o.setf( std::ostream::fixed, std::ostream::floatfield );
+    o.precision( 7 );
+    o << ( *resultIter );
+    
+    ++indexIter;
+    ++resultIter;
+  } while( indexIter != firstIndexSet.end( ) );
+  assert( resultIter == resultVector.end( ) );  // The index set and the result vector should be the same size
+}
Index: /tags/SHM-9.0/source/App/utils/BitrateTargeting/GuessLambdaModifiers.h
===================================================================
--- /tags/SHM-9.0/source/App/utils/BitrateTargeting/GuessLambdaModifiers.h	(revision 1088)
+++ /tags/SHM-9.0/source/App/utils/BitrateTargeting/GuessLambdaModifiers.h	(revision 1088)
@@ -0,0 +1,148 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef __GUESSLAMBDAMODIFIERS__
+#define __GUESSLAMBDAMODIFIERS__
+
+#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: /tags/SHM-9.0/source/App/utils/BitrateTargeting/GuessLambdaModifiersMain.cpp
===================================================================
--- /tags/SHM-9.0/source/App/utils/BitrateTargeting/GuessLambdaModifiersMain.cpp	(revision 1088)
+++ /tags/SHM-9.0/source/App/utils/BitrateTargeting/GuessLambdaModifiersMain.cpp	(revision 1088)
@@ -0,0 +1,72 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+
+#include "RuntimeError.h"
+#include "GuessLambdaModifiers.h"
+#include <iostream>
+
+class WrongNumberOfArgumentsException: public RuntimeError
+{
+  public:
+    virtual ~WrongNumberOfArgumentsException( ) throw( ) { }
+  protected:
+    void outputWhat( std::ostream& o ) const { o << "Wrong number of arguments"; }
+};
+
+int main( int argc, char** ppArgv )
+{
+  try
+  {
+    if( argc != 3 ) throw WrongNumberOfArgumentsException( );
+    
+    std::string initialAdjustmentParameterString( ppArgv[ 1 ] );
+    std::istringstream initialAdjustmentParameterIstream( initialAdjustmentParameterString );
+    
+    std::string targetBitratesString( ppArgv[ 2 ] );
+    std::istringstream targetBitratesIstream( targetBitratesString );
+    
+    guessLambdaModifiers( std::cout, initialAdjustmentParameterIstream, targetBitratesIstream, std::cin );
+    return 0;
+  
+  }
+  catch( std::exception& e )
+  {
+    std::cerr << e.what( ) << std::endl;
+  }
+  catch( ... )
+  {
+    std::cerr << "Unknown exception" << std::endl;
+  }
+  return 1;
+}
Index: /tags/SHM-9.0/source/App/utils/BitrateTargeting/RuntimeError.h
===================================================================
--- /tags/SHM-9.0/source/App/utils/BitrateTargeting/RuntimeError.h	(revision 1088)
+++ /tags/SHM-9.0/source/App/utils/BitrateTargeting/RuntimeError.h	(revision 1088)
@@ -0,0 +1,76 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef __RUNTIMEERROR__
+#define __RUNTIMEERROR__
+
+#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: /tags/SHM-9.0/source/App/utils/BitrateTargeting/encode.shl
===================================================================
--- /tags/SHM-9.0/source/App/utils/BitrateTargeting/encode.shl	(revision 1088)
+++ /tags/SHM-9.0/source/App/utils/BitrateTargeting/encode.shl	(revision 1088)
@@ -0,0 +1,151 @@
+# The copyright in this software is being made available under the BSD
+# License, included below. This software may be subject to other third party
+# and contributor rights, including patent rights, and no such rights are
+# granted under this license.  
+#
+# Copyright (c) 2010-2014, ITU/ISO/IEC
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions are met:
+#
+#  * Redistributions of source code must retain the above copyright notice,
+#    this list of conditions and the following disclaimer.
+#  * Redistributions in binary form must reproduce the above copyright notice,
+#    this list of conditions and the following disclaimer in the documentation
+#    and/or other materials provided with the distribution.
+#  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+#    be used to endorse or promote products derived from this software without
+#    specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+# BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+# THE POSSIBILITY OF SUCH DAMAGE.
+
+# This files contains shell code that is common to both encodeCommand.sh and targetBitrates.sh.
+
+# Run this function to validate a "-option value" pair of arguments
+function checkDollarTwo {
+  if [[ "" == $2 ]] ; then
+    printf "An argument must follow $1.\n" >&2
+    outputUsageAndExit
+  fi
+}
+
+# If the second argument is empty (not provided), output an error message and the usage, and then exit
+function verifyProvided {
+  if [[ "" == $2 ]] ; then
+    printf "The $1 parameter must be provided.\n" >&2
+    outputUsageAndExit
+  fi
+}
+
+function verifyNotDirectory {
+  if [[ `printf "$2\n" | grep '/$'` != "" ]] ; then
+    printf "The $1 parameter cannot be a directory.\n" >&2
+    outputUsageAndExit
+  fi
+}
+
+function verifyDirectory {
+  if [[ "" == `printf "$2\n" | grep '/$'` ]] ; then
+    printf "The $1 parameter must be a directory.\n" >&2
+    outputUsageAndExit
+  fi
+}
+
+function verifyConfigurationIdentifier {
+  case $configurationIdentifier in
+    ldLC) ;;
+    raLC) ;;
+    inLC) ;;
+    ldHE) ;;
+    raHE) ;;
+    inHE) ;;
+    *)
+      printf "The provided $CONFIGURATION_IDENTIFIER_STRING is invalid.  It must be \"ldLC\", \"raLC\", \"inLC\", \"ldHE\", \"raHE\", or \"inHE\".\n" >&2
+      outputUsageAndExit
+      ;;
+  esac
+}
+
+function verifyQ {
+  case $1 in
+    22)  ;;
+    27)  ;;
+    32)  ;;
+    37)  ;;
+    *)
+      printf "The provided $Q_STRING, \"$1\", is invalid.  It must be \"22\", \"27\", \"32\", or \"37\".\n" >&2
+      outputUsageAndExit
+    ;;
+  esac
+}
+
+Q_OPTION="-q"
+EXECUTABLE_OPTION="-e"
+CONFIGURATION_IDENTIFIER_OPTION="-ci"
+OUTPUT_DIRECTORY_OPTION="-o"
+EXTRA_ARGUMENTS_OPTION="-ea"
+CONFIGURATION_PATH_OPTION="-cp"
+CONFIGURATION_DIRECTORY_OPTION="-cd"
+
+Q_STRING="q ($Q_OPTION)"
+CONFIGURATION_IDENTIFIER_STRING="configuration identifier ($CONFIGURATION_IDENTIFIER_OPTION)"
+INPUT_NAME_STRING="input name"
+OUTPUT_DIRECTORY_STRING="output directory ($OUTPUT_DIRECTORY_OPTION)"
+
+USAGE_INDENT="  "
+INPUT_NAME_USAGE_STRING=inputName
+CONFIGURATION_IDENTIFIER_USAGE_STRING=configurationIdentifier
+Q_USAGE_STRING=q
+OUTPUT_DIRECTORY_USAGE_STRING=outputDirectory
+EXTRA_ARGUMENTS_USAGE_STRING=extraArguments
+
+function outputConfigurationIdentifierUsage {
+  echo "${USAGE_INDENT}$CONFIGURATION_IDENTIFIER_USAGE_STRING specifies the configuration (ldHE, ldLC, raHE, raLC, inHE, or inLC)." >&2
+}
+
+function outputQUsage {
+  echo "${USAGE_INDENT}$Q_USAGE_STRING is the QP value (22, 27, 32, or 37)." >&2
+}
+
+function outputOutputDirectoryUsage {
+  echo "${USAGE_INDENT}$OUTPUT_DIRECTORY_USAGE_STRING is the directory that will contain the output log, YUV, and bin." >&2
+}
+
+function outputInputNameUsage {
+  echo "${USAGE_INDENT}$INPUT_NAME_USAGE_STRING is the name of the input sequence.  Must be one of the following:" >&2
+  echo "${USAGE_INDENT}${USAGE_INDENT}NebutaFestival_2560x1600_60_10bit_crop" >&2
+  echo "${USAGE_INDENT}${USAGE_INDENT}SteamLocomotiveTrain_2560x1600_60_10bit_crop" >&2
+  echo "${USAGE_INDENT}${USAGE_INDENT}Traffic_2560x1600_30_crop" >&2
+  echo "${USAGE_INDENT}${USAGE_INDENT}PeopleOnStreet_2560x1600_30_crop" >&2
+  echo "${USAGE_INDENT}${USAGE_INDENT}BQTerrace_1920x1080_60" >&2
+  echo "${USAGE_INDENT}${USAGE_INDENT}BasketballDrive_1920x1080_50" >&2
+  echo "${USAGE_INDENT}${USAGE_INDENT}Cactus_1920x1080_50" >&2
+  echo "${USAGE_INDENT}${USAGE_INDENT}Kimono1_1920x1080_24" >&2
+  echo "${USAGE_INDENT}${USAGE_INDENT}ParkScene_1920x1080_24" >&2
+  echo "${USAGE_INDENT}${USAGE_INDENT}vidyo1_720p_60" >&2
+  echo "${USAGE_INDENT}${USAGE_INDENT}vidyo3_720p_60" >&2
+  echo "${USAGE_INDENT}${USAGE_INDENT}vidyo4_720p_60" >&2
+  echo "${USAGE_INDENT}${USAGE_INDENT}RaceHorses_832x480_30" >&2
+  echo "${USAGE_INDENT}${USAGE_INDENT}BQMall_832x480_60" >&2
+  echo "${USAGE_INDENT}${USAGE_INDENT}PartyScene_832x480_50" >&2
+  echo "${USAGE_INDENT}${USAGE_INDENT}BasketballDrill_832x480_50" >&2
+  echo "${USAGE_INDENT}${USAGE_INDENT}RaceHorses_416x240_30" >&2
+  echo "${USAGE_INDENT}${USAGE_INDENT}BQSquare_416x240_60" >&2
+  echo "${USAGE_INDENT}${USAGE_INDENT}BlowingBubbles_416x240_50" >&2
+  echo "${USAGE_INDENT}${USAGE_INDENT}BasketballPass_416x240_50" >&2
+  echo "${USAGE_INDENT}${USAGE_INDENT}BasketballDrillText_832x480_50" >&2
+  echo "${USAGE_INDENT}${USAGE_INDENT}Chinaspeed_1024x768_30" >&2
+  echo "${USAGE_INDENT}${USAGE_INDENT}SlideEditing_1280x720_30" >&2
+  echo "${USAGE_INDENT}${USAGE_INDENT}SlideShow_1280x720_20" >&2
+}
Index: /tags/SHM-9.0/source/App/utils/BitrateTargeting/encodeCommand.sh
===================================================================
--- /tags/SHM-9.0/source/App/utils/BitrateTargeting/encodeCommand.sh	(revision 1088)
+++ /tags/SHM-9.0/source/App/utils/BitrateTargeting/encodeCommand.sh	(revision 1088)
@@ -0,0 +1,258 @@
+#! /bin/sh
+
+# The copyright in this software is being made available under the BSD
+# License, included below. This software may be subject to other third party
+# and contributor rights, including patent rights, and no such rights are
+# granted under this license.  
+#
+# Copyright (c) 2010-2014, ITU/ISO/IEC
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions are met:
+#
+#  * Redistributions of source code must retain the above copyright notice,
+#    this list of conditions and the following disclaimer.
+#  * Redistributions in binary form must reproduce the above copyright notice,
+#    this list of conditions and the following disclaimer in the documentation
+#    and/or other materials provided with the distribution.
+#  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+#    be used to endorse or promote products derived from this software without
+#    specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+# BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+# THE POSSIBILITY OF SUCH DAMAGE.
+
+# Outputs a command to run the encoder for a given set of arguments.  The encoder typically requires a lot of arguments to run, so this script can be more convenient than running the encoder direcly because it automatically generates many of the arguments.
+
+# "Include" encode.shl which contains common shell script code related to encoding
+SUB_TOOLS_DIRECTORY=$(echo "$0" | sed -e 's/[^\/]*$//')
+. ${SUB_TOOLS_DIRECTORY}encode.shl
+
+USE_LOG_FILE_OPTION="-l"
+INPUT_DIRECTORY_OPTION="-id"
+NUM_FRAMES_OPTION="-f"
+
+function outputUsageAndExit {
+  local EXECUTABLE_USAGE_STRING=executable
+  local INPUT_DIRECTORY_USAGE_STRING=inputDirectory
+  local CONFIGURATION_PATH_USAGE_STRING=configurationPath
+  local CONFIGURATION_DIRECTORY_USAGE_STRING=configurationDirectory
+  local NUM_FRAMES_USAGE_STRING=numFrames
+  
+  echo "Usage: $0 $CONFIGURATION_IDENTIFIER_OPTION $CONFIGURATION_IDENTIFIER_USAGE_STRING ($CONFIGURATION_PATH_OPTION $CONFIGURATION_PATH_USAGE_STRING -or- $CONFIGURATION_DIRECTORY_OPTION $CONFIGURATION_DIRECTORY_USAGE_STRING) $Q_OPTION $Q_USAGE_STRING $EXECUTABLE_OPTION $EXECUTABLE_USAGE_STRING [$NUM_FRAMES_OPTION $NUM_FRAMES_USAGE_STRING] [$EXTRA_ARGUMENTS_OPTION $EXTRA_ARGUMENTS_USAGE_STRING] $OUTPUT_DIRECTORY_OPTION $OUTPUT_DIRECTORY_USAGE_STRING [$USE_LOG_FILE_OPTION] [$INPUT_DIRECTORY_OPTION $INPUT_DIRECTORY_USAGE_STRING] $INPUT_NAME_USAGE_STRING" >&2
+  outputConfigurationIdentifierUsage
+  echo "${USAGE_INDENT}$CONFIGURATION_PATH_USAGE_STRING is the path of the configuration file to use.  Either this or $CONFIGURATION_DIRECTORY_USAGE_STRING must be specified (but not both)." >&2
+  echo "${USAGE_INDENT}$CONFIGURATION_DIRECTORY_USAGE_STRING is the path of the directory that contains the configuration files.  The particular file will be chosen based on $CONFIGURATION_IDENTIFIER_USAGE_STRING.  Either this or $CONFIGURATION_PATH_USAGE_STRING must be specified (but not both)." >&2
+  outputQUsage
+  echo "${USAGE_INDENT}$EXECUTABLE_USAGE_STRING is the path of the encoder executable." >&2
+  echo "${USAGE_INDENT}$NUM_FRAMES_USAGE_STRING is the number of frames to encode.  If omitted, the entire sequence will be encoded." >&2
+  echo "${USAGE_INDENT}$EXTRA_ARGUMENTS_USAGE_STRING is any extra arguments that should be passed on to the encoder." >&2
+  outputOutputDirectoryUsage
+  echo "${USAGE_INDENT}If $USE_LOG_FILE_OPTION is specified, the encoder will output to a log file.  Otherwise it will output to the standard output." >&2
+  echo "${USAGE_INDENT}$INPUT_DIRECTORY_USAGE_STRING is the directory that contains the sequences.  The default value is the SEQUENCE_DIR environment variable." >&2
+  outputInputNameUsage
+  
+  exit 1
+}
+
+# Used to lookup the width, height, number of frames, and frame rate for a given sequence
+table=`printf "${table}\nNebutaFestival_2560x1600_60_10bit_crop          2560   1600   300        60"`
+table=`printf "${table}\nSteamLocomotiveTrain_2560x1600_60_10bit_crop    2560   1600   300        60"`
+table=`printf "${table}\nTraffic_2560x1600_30_crop                       2560   1600   150        30"`
+table=`printf "${table}\nPeopleOnStreet_2560x1600_30_crop                2560   1600   150        30"`
+table=`printf "${table}\nBQTerrace_1920x1080_60                          1920   1080   600        60"`
+table=`printf "${table}\nBasketballDrive_1920x1080_50                    1920   1080   500        50"`
+table=`printf "${table}\nCactus_1920x1080_50                             1920   1080   500        50"`
+table=`printf "${table}\nKimono1_1920x1080_24                            1920   1080   240        24"`
+table=`printf "${table}\nParkScene_1920x1080_24                          1920   1080   240        24"`
+table=`printf "${table}\nvidyo1_720p_60                                  1280    720   600        60"`
+table=`printf "${table}\nvidyo3_720p_60                                  1280    720   600        60"`
+table=`printf "${table}\nvidyo4_720p_60                                  1280    720   600        60"`
+table=`printf "${table}\nRaceHorses_832x480_30                            832    480   300        30"`
+table=`printf "${table}\nBQMall_832x480_60                                832    480   600        60"`
+table=`printf "${table}\nPartyScene_832x480_50                            832    480   500        50"`
+table=`printf "${table}\nBasketballDrill_832x480_50                       832    480   500        50"`
+table=`printf "${table}\nRaceHorses_416x240_30                            416    240   300        30"`
+table=`printf "${table}\nBQSquare_416x240_60                              416    240   600        60"`
+table=`printf "${table}\nBlowingBubbles_416x240_50                        416    240   500        50"`
+table=`printf "${table}\nBasketballPass_416x240_50                        416    240   500        50"`
+table=`printf "${table}\nBasketballDrillText_832x480_50                   832    480   500        50"`
+table=`printf "${table}\nChinaspeed_1024x768_30                          1024    768   500        30"`
+table=`printf "${table}\nSlideEditing_1280x720_30                        1280    720   300        30"`
+table=`printf "${table}\nSlideShow_1280x720_20                           1280    720   500        20"`
+
+EXECUTABLE_STRING="executable ($EXECUTABLE_OPTION)"
+INPUT_DIRECTORY_STRING="input directory ($INPUT_DIRECTORY_OPTION)"
+CONFIGURATION_PATH_STRING="configuration path ($CONFIGURATION_PATH_OPTION)"
+CONFIGURATION_DIRECTORY_STRING="configuration directory ($CONFIGURATION_DIRECTORY_OPTION)"
+
+inputDirectory="$SEQUENCE_DIR"  # The default input directory is taken from this environment variable
+
+# For every argument $1
+while [ "" != "$*" ] ; do
+  case $1 in
+    $USE_LOG_FILE_OPTION)
+      useLogFile=$1
+    ;;
+    -*)
+      checkDollarTwo "$1" "$2"
+      case $1 in
+        $EXECUTABLE_OPTION) executable=$2 ;;
+        $INPUT_DIRECTORY_OPTION) inputDirectory=$2 ;;
+        $EXTRA_ARGUMENTS_OPTION) extraArguments=$2 ;;
+        $Q_OPTION) q=$2 ;;
+        $OUTPUT_DIRECTORY_OPTION) outputDirectory=$2 ;;
+        $CONFIGURATION_IDENTIFIER_OPTION) configurationIdentifier=$2 ;;
+        $CONFIGURATION_PATH_OPTION) configurationPath=$2 ;;
+        $CONFIGURATION_DIRECTORY_OPTION) configurationDirectory=$2 ;;
+        $NUM_FRAMES_OPTION) numFrames=$2 ;;
+        *)
+          printf "You entered an invalid option: \"$1\".\n" >&2
+          outputUsageAndExit
+        ;;
+      esac
+      shift
+    ;;
+    *)
+      if [[ "" == $inputName ]] ; then
+        inputName=$1
+      else
+        printf "You entered too many arguments.\n" >&2
+        outputUsageAndExit
+      fi
+    ;;
+  esac
+  
+  shift
+done
+
+verifyProvided "$EXECUTABLE_STRING" "$executable"
+verifyNotDirectory "$EXECUTABLE_STRING" "$executable"
+
+verifyDirectory "$INPUT_DIRECTORY_STRING" "$inputDirectory"
+
+verifyProvided "$Q_STRING" "$q"
+verifyQ $q
+
+verifyProvided "$OUTPUT_DIRECTORY_STRING" "$outputDirectory"
+verifyDirectory "$OUTPUT_DIRECTORY_STRING" "$outputDirectory"
+
+verifyProvided "$CONFIGURATION_IDENTIFIER_STRING" "$configurationIdentifier"
+verifyConfigurationIdentifier "$configurationIdentifier"
+
+# Validate $configurationPath or $configurationDirectory
+if [[ $configurationPath != "" ]] ; then
+  verifyNotDirectory "$CONFIGURATION_PATH_STRING" "$configurationPath"
+else
+  if [[ "" == $configurationDirectory ]] ; then
+    printf "You must enter a $CONFIGURATION_PATH_STRING or $CONFIGURATION_DIRECTORY_STRING.\n" >&2
+    outputUsageAndExit
+  else
+    verifyDirectory "$CONFIGURATION_DIRECTORY_STRING" "$configurationDirectory"
+  fi
+fi
+
+verifyProvided "$INPUT_NAME_STRING" "$inputName"
+verifyNotDirectory "$INPUT_NAME_STRING" "$inputName"
+
+# If configurationPath is not already populated, populate it based on the configuration directory and the configuration identifier
+if [[ "" == $configurationPath ]] ; then
+  configurationPath="${configurationDirectory}encoder_"
+  case $configurationIdentifier in
+    ldLC) configurationPath="${configurationPath}lowdelay_loco" ;;
+    raLC) configurationPath="${configurationPath}randomaccess_loco" ;;
+    inLC) configurationPath="${configurationPath}intra_loco" ;;
+    ldHE) configurationPath="${configurationPath}lowdelay" ;;
+    raHE) configurationPath="${configurationPath}randomaccess" ;;
+    *)    configurationPath="${configurationPath}intra" ;;  # inHE
+  esac
+  configurationPath="${configurationPath}.cfg"
+fi
+
+# Validate the input name and populate masterLine which contains the line from the table for the given sequence
+masterLine=`printf "$table" | grep -i "^$inputName "`
+if [[ "" == $masterLine ]] ; then
+  printf "Invalid input name.\n" >&2
+  outputUsageAndExit
+fi
+
+# If numFrames is not yet initialized, initialize it by looking up the values in the table
+if [[ "" == $numFrames ]] ; then
+  numFrames=`printf -- "$masterLine" | awk '{ print $4 }'`
+fi
+
+# Initialize these variables by looking up the values in the table
+frameRate=`printf -- "$masterLine" | awk '{ print $5 }'`
+width=`printf -- "$masterLine" | awk '{ print $2 }'`
+height=`printf -- "$masterLine" | awk '{ print $3 }'`
+
+# Initialize intraPeriod
+case $configurationIdentifier in
+  ld*)
+    intraPeriod="-1"
+  ;;
+  ra*)
+    if [[ 20 == "$frameRate" ]] ; then
+      intraPeriod="16"
+    else
+      intraPeriod=$(expr "$frameRate" + 4)
+      intraPeriod=$(expr "$intraPeriod" / 8)
+      intraPeriod=$(expr "$intraPeriod" \* 8)
+    fi
+  ;;
+  in*)
+    intraPeriod="1"
+  ;;
+  *)
+    outputConfigurationIdentifierErrorAndExit
+  ;;
+esac
+
+# Initialize tenBit if the given sequence is 10-bit
+printf -- "$inputName" | grep -i '10bit' > /dev/null
+case $? in
+  0)  tenBit="--InputBitDepth=10 "
+    ;;
+  1)  ;;
+  *)  exit $?
+    ;;
+esac
+
+outputPathBegin="${outputDirectory}${inputName}_${configurationIdentifier}_q${q}"
+
+# Output the command
+printf -- "$executable "
+printf -- "-c $configurationPath "
+printf -- "-i $inputDirectory$inputName.yuv "
+printf -- "-f $numFrames "
+printf -- "-fr $frameRate "
+printf -- "-wdt $width "
+printf -- "-hgt $height "
+printf -- "-ip $intraPeriod "
+printf -- "$tenBit"
+if [[ $tenBit != "" ]] ; then
+  printf " "
+fi
+printf -- "$extraArguments"
+if [[ $extraArguments != "" ]] ; then
+  printf -- " "
+fi
+printf -- "-q $q "
+printf -- "-b $outputPathBegin.bin "
+printf -- "-o $outputPathBegin.yuv "
+if [[ "" != $useLogFile ]] ; then
+  printf -- "&> $outputPathBegin.log"
+fi
+printf "\n"
+
+exit 0
Index: /tags/SHM-9.0/source/App/utils/BitrateTargeting/makefile
===================================================================
--- /tags/SHM-9.0/source/App/utils/BitrateTargeting/makefile	(revision 1088)
+++ /tags/SHM-9.0/source/App/utils/BitrateTargeting/makefile	(revision 1088)
@@ -0,0 +1,54 @@
+# The copyright in this software is being made available under the BSD
+# License, included below. This software may be subject to other third party
+# and contributor rights, including patent rights, and no such rights are
+# granted under this license.  
+#
+# Copyright (c) 2010-2014, ITU/ISO/IEC
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions are met:
+#
+#  * Redistributions of source code must retain the above copyright notice,
+#    this list of conditions and the following disclaimer.
+#  * Redistributions in binary form must reproduce the above copyright notice,
+#    this list of conditions and the following disclaimer in the documentation
+#    and/or other materials provided with the distribution.
+#  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+#    be used to endorse or promote products derived from this software without
+#    specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+# BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+# THE POSSIBILITY OF SUCH DAMAGE.
+
+CPPFLAGS = -D NDEBUG -Wall -Wextra
+
+extractBitratesObjects = ExtractBitrates.o ExtractBitratesMain.o
+extractBitratesExecutable = extractBitrates.exe
+
+guessLambdaModifiersObjects = GuessLambdaModifiers.o GuessLambdaModifiersMain.o
+guessLambdaModifiersExecutable = guessLambdaModifiers.exe
+
+all: $(extractBitratesExecutable) $(guessLambdaModifiersExecutable)
+
+$(extractBitratesExecutable): $(extractBitratesObjects)
+	g++ -o $@ $(extractBitratesObjects)
+$(guessLambdaModifiersExecutable): $(guessLambdaModifiersObjects)
+	g++ -o $@ $(guessLambdaModifiersObjects)
+
+ExtractBitrates.o: ExtractBitrates.h RuntimeError.h
+ExtractBitratesMain.o: ExtractBitrates.h RuntimeError.h
+GuessLambdaModifiers.o: GuessLambdaModifiers.h RuntimeError.h
+GuessLambdaModifiersMain.o: GuessLambdaModifiers.h RuntimeError.h
+
+clean:
+	rm $(extractBitratesExecutable) $(extractBitratesObjects) $(guessLambdaModifiersExecutable) $(guessLambdaModifiersObjects)
Index: /tags/SHM-9.0/source/App/utils/BitrateTargeting/targetBitrates.sh
===================================================================
--- /tags/SHM-9.0/source/App/utils/BitrateTargeting/targetBitrates.sh	(revision 1088)
+++ /tags/SHM-9.0/source/App/utils/BitrateTargeting/targetBitrates.sh	(revision 1088)
@@ -0,0 +1,409 @@
+#! /bin/sh
+
+# The copyright in this software is being made available under the BSD
+# License, included below. This software may be subject to other third party
+# and contributor rights, including patent rights, and no such rights are
+# granted under this license.  
+#
+# Copyright (c) 2010-2014, ITU/ISO/IEC
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions are met:
+#
+#  * Redistributions of source code must retain the above copyright notice,
+#    this list of conditions and the following disclaimer.
+#  * Redistributions in binary form must reproduce the above copyright notice,
+#    this list of conditions and the following disclaimer in the documentation
+#    and/or other materials provided with the distribution.
+#  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+#    be used to endorse or promote products derived from this software without
+#    specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+# BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+# THE POSSIBILITY OF SUCH DAMAGE.
+
+
+SUB_TOOLS_DIRECTORY=$(echo "$0" | sed -e 's/[^\/]*$//')
+. ${SUB_TOOLS_DIRECTORY}encode.shl
+
+LAMBDA_MODIFIER_PREFIX="LM"
+
+RESUME_MODE_OPTION="-rm"
+TARGET_BITRATES_OPTION="-tb"
+INITIAL_LAMBDA_MODIFIERS_OPTION="-il"
+ENCODE_COMMAND_ARGS_OPTION="-ca"
+
+function outputUsageAndExit {
+  local TARGET_BITRATES_USAGE_STRING=targetBitrates
+  local INITIAL_LAMBDA_MODIFIERS_USAGE_STRING=initialLambdaModifiers
+  local ENCODE_COMMAND_ARGS_USAGE_STRING=encodeCommandArgs
+  
+  echo "Usage: $0 [$RESUME_MODE_OPTION] $CONFIGURATION_IDENTIFIER_OPTION $CONFIGURATION_IDENTIFIER_USAGE_STRING $Q_OPTION $Q_USAGE_STRING $TARGET_BITRATES_OPTION $TARGET_BITRATES_USAGE_STRING [$INITIAL_LAMBDA_MODIFIERS_OPTION $INITIAL_LAMBDA_MODIFIERS_USAGE_STRING] [$ENCODE_COMMAND_ARGS_OPTION $ENCODE_COMMAND_ARGS_USAGE_STRING] [$EXTRA_ARGUMENTS_OPTION $EXTRA_ARGUMENTS_USAGE_STRING] $OUTPUT_DIRECTORY_OPTION $OUTPUT_DIRECTORY_USAGE_STRING $INPUT_NAME_USAGE_STRING" >&2
+  echo "${USAGE_INDENT}$RESUME_MODE_OPTION engages resume mode which allows the user to resume an execution that was interrupted before completion."
+  outputConfigurationIdentifierUsage
+  outputQUsage
+  echo "${USAGE_INDENT}$TARGET_BITRATES_USAGE_STRING is the target bitrates.  For example: \"23:35 24:3473242 etc...\"." >&2
+  echo "${USAGE_INDENT}$INITIAL_LAMBDA_MODIFIERS_USAGE_STRING is the Lambda-modifiers to use for the first guess.  For example: \"$-{LAMBDA_MODIFIER_PREFIX}23 1e0 $-{LAMBDA_MODIFIER_PREFIX}24 0.98 etc...\"" >&2
+  echo "${USAGE_INDENT}$ENCODE_COMMAND_ARGS_USAGE_STRING is the extra arguments to be passed to encodeCommand.sh.  The common arguments that are available to both $0 and encodeCommand.sh should not be passed though this argument.  For example, don't pass $Q_OPTION here because it is an option of $0.  $EXECUTABLE_OPTION and ($CONFIGURATION_PATH_OPTION or $CONFIGURATION_DIRECTORY_OPTION) must be passed through this argument.  For example, \"$ENCODE_COMMAND_ARGS_OPTION '$EXECUTABLE_OPTION ~/bin/encode.exe $CONFIGURATION_DIRECTORY_OPTION ~/cfg/'\"." >&2
+  echo "${USAGE_INDENT}$EXTRA_ARGUMENTS_USAGE_STRING specifies extra arguments to be passed directly to the encoder (not to encodeCommand.sh)." >&2
+  outputOutputDirectoryUsage
+  outputInputNameUsage
+  
+  exit 1
+}
+
+NORMAL_MODE="NORMAL_MODE"
+RESUME_MODE="RESUME_MODE"
+mode="$NORMAL_MODE"
+
+# For every argument $1
+while [ "" != "$*" ] ; do
+  case $1 in
+    $RESUME_MODE_OPTION)
+      mode="$RESUME_MODE"
+    ;;
+    -*)
+      checkDollarTwo "$1" "$2"
+      case $1 in
+        $EXTRA_ARGUMENTS_OPTION) extraArguments=$2 ;;
+        $Q_OPTION) q=$2 ;;
+        $OUTPUT_DIRECTORY_OPTION) outputDirectory=$2 ;;
+        $CONFIGURATION_IDENTIFIER_OPTION) configurationIdentifier=$2 ;;
+        $TARGET_BITRATES_OPTION) targetBitrates=$2 ;;
+        $INITIAL_LAMBDA_MODIFIERS_OPTION) initialLambdaModifiers=$2 ;;
+        $ENCODE_COMMAND_ARGS_OPTION) encodeCommandArgs=$2 ;;
+        *)
+          printf "You entered an invalid option: \"$1\".\n" >&2
+          outputUsageAndExit
+        ;;
+      esac
+      shift
+    ;;
+    *)
+      if [[ "" == $inputName ]] ; then
+        inputName=$1
+      else
+        printf "You entered too many arguments.\n" >&2
+        outputUsageAndExit
+      fi
+    ;;
+  esac
+  
+  shift
+done
+
+verifyProvided "$Q_STRING" "$q"
+verifyQ $q
+
+verifyProvided "$OUTPUT_DIRECTORY_STRING" "$outputDirectory"
+verifyDirectory "$OUTPUT_DIRECTORY_STRING" "$outputDirectory"
+
+verifyProvided "$CONFIGURATION_IDENTIFIER_STRING" "$configurationIdentifier"
+verifyConfigurationIdentifier "$configurationIdentifier"
+
+verifyProvided "target bitrates ($TARGET_BITRATES_OPTION)" "$targetBitrates"
+verifyProvided "$INPUT_NAME_STRING" "$inputName"
+
+outputPathBegin="${outputDirectory}${inputName}_${configurationIdentifier}_q${q}"
+logPath="$outputPathBegin.log"
+metaLogPath="${outputPathBegin}_meta.log"
+
+TRUE=true
+
+# Outputs "$TRUE" if the given file exist.  Outputs nothing if the given file does not exist.  The first argument is the path to the supposed file.
+function doesFileExist {
+  ls $1 &> /dev/null
+  if [[ 0 == "$?" ]] ; then
+    echo "$TRUE"
+  fi
+}
+
+# Validate the mode (normal or resume) based on whether or not the meta-log file already exists
+if [[ "$TRUE" == "$(doesFileExist "$metaLogPath")" ]] ; then
+  if [[ "$NORMAL_MODE" == "$mode" ]] ; then
+    echo "$metaLogPath already exists.  Consider using resume-mode." >&2
+    outputUsageAndExit
+  else  # Resume-mode
+    cat "$metaLogPath"  # Output the pre-existing meta-log so we can resume where we left off
+  fi
+else  # Meta-log file does not exist
+  if [[ "$RESUME_MODE" == "$mode" ]] ; then
+    echo "$metaLogPath does not exist and resume-mode is enabled." >&2
+    outputUsageAndExit
+  fi
+fi
+
+# Outputs the number of elements in the given bitrate vector
+function bitrateVectorSize {
+  echo "$1" | sed -e 's/[^ ]//g' | wc -c | sed -e 's/^ *//'
+}
+
+# Initialize targetBitrateVectorSize
+targetBitrateVectorSize="$(bitrateVectorSize "$targetBitrates")"
+
+# Outputs the product of the two input values
+function multiply {
+  echo | awk "{print $1 * $2}"
+}
+
+# Extracts the bitrate at the given index from the given bitrate vector.  The first argument is the given index and the second argument in the given bitrate vector.
+function extractBitrateFromVector {
+  local localIndex=$(expr "$1" "+" "1")
+  echo "$2" | awk "{ print \$$localIndex }"
+}
+
+# Outputs a bitrate vector by multiplying the $targetBitrates vector by a given scalar.  The first argument is the given scalar.
+function populateBitrates {
+  local lI=0
+  local lResult=""
+  while true ; do
+    local lTargetBitrate=$(extractBitrateFromVector "$lI" "$targetBitrates")
+    if [[ "" == "$lTargetBitrate" ]] ; then
+      break;
+    fi
+    local lNew=$(multiply "$lTargetBitrate" "$1")
+    lResult="$lResult $lNew"
+    ((++lI))
+  done
+  echo "$lResult" | sed -e 's/^ //'
+}
+
+# Initialize the ranges
+outerRangeMins=$(populateBitrates "0.980")
+innerRangeMins=$(populateBitrates "0.985")
+innerRangeMaxs=$(populateBitrates "1.015")
+outerRangeMaxs=$(populateBitrates "1.020")
+
+# Outputs the given string to the meta-log (both the file and stdout) with no newline character.  The first argument is the string to output.
+function outputToMetaLogNoNewline {
+  toPrint=`echo $1 | sed -e 's/%/%%/g'`
+  printf -- "$toPrint"
+  printf -- "$toPrint" >> $metaLogPath
+}
+
+# Outputs the given string to the meta-log (both the file and stdout) with a newline character.  The first argument is the string to output.
+function outputToMetaLogWithNewline {
+  echo "$1"
+  echo "$1" >> $metaLogPath
+}
+
+# Extracts the Lambda-modifier at the given index from $lambdaModifiers.  The first argument is the given index.
+function extractLambdaModifier {
+  printf -- "$lambdaModifiers" | sed -e 's/^-//' | sed -e 's/ -/\
+/g' | grep "${LAMBDA_MODIFIER_PREFIX}$1 " | sed -e 's/^[^ ]* //'
+}
+
+# Outputs the given Lambda-modifier with a fixed number of decimal points.  The first argument is the given Lambda-modifier.
+function formatLambdaModifier {
+  printf "%.7f" "$1"
+}
+
+# Outputs $lambdaModifiers to the meta-log with proper formatting
+function outputLambdaModifiersToMetaLog {
+  local lI=0
+  local lLambdaModifier=$(extractLambdaModifier "$lI")
+  local lLambdaModifier=$(formatLambdaModifier "$lLambdaModifier")
+  local lOutput="-${LAMBDA_MODIFIER_PREFIX}$lI $lLambdaModifier"
+  while true ; do
+    ((++lI))
+    local lLambdaModifier=$(extractLambdaModifier "$lI")
+    if [[ "" == "$lLambdaModifier" ]] ; then
+      break
+    fi
+    local lLambdaModifier=$(formatLambdaModifier "$lLambdaModifier")
+    local lOutput="$lOutput -${LAMBDA_MODIFIER_PREFIX}$lI $lLambdaModifier"
+  done
+  outputToMetaLogNoNewline "$lOutput;"
+}
+
+# Initialize lambdaModifiers and output it to the meta-log
+if [[ "$RESUME_MODE" == "$mode" ]] ; then
+  if [[ "" == "$initialLambdaModifiers" ]] ; then  # If no initial lambda-modifiers provided, use default value
+    lambdaModifiers=$(tail -n 1 < "$metaLogPath" | sed -e 's/;$//')
+  else  # Initial lambda-modifiers provided
+    echo "You cannot use $RESUME_MODE and specify the initial lambda-modifiers.  In resume-mode, the lambda-modifiers will be retreived from the last line of the meta-log." >&2
+    outputUsageAndExit
+  fi
+else
+  if [[ "" == "$initialLambdaModifiers" ]] ; then  # If no initial lambda-modifiers provided, use default value
+    lambdaModifiers="-${LAMBDA_MODIFIER_PREFIX}0 1"
+    for (( i=1; i<"$targetBitrateVectorSize"; ++i )); do
+      lambdaModifiers="$lambdaModifiers -${LAMBDA_MODIFIER_PREFIX}${i} 1"
+    done
+  else  # Initial lambda-modifiers provided
+    lambdaModifiers="$initialLambdaModifiers"
+  fi
+  outputLambdaModifiersToMetaLog
+fi
+
+# Calculates the difference percentage between the given target bitrate and the given bitrate, appropriately formats this difference percentage, and then outputs it.  The first argument is the given target bitrate and the second argument is the given bitrate.
+function calculateAndFormatDifferencePercentage {
+  # Calculate the result and format it with the right number of decimal places
+  local result=$(echo | awk "{print 100*($2-$1)/$1}")
+  local result=$(printf "%.3f" "$result")
+  
+  # Separate the sign from the result
+  local sign=$(echo "$result" | sed -e 's/[^-]*$//')
+  if [[ "$sign" != "-" ]] ; then
+    local sign="+"
+  fi
+  local result=$(echo "$result" | sed -e 's/^-//')
+  
+  # Pad leading zereos to make two digits before the decimal point
+  if [[ 2 == $(echo "$result" | sed -e 's/\..*$//' | wc -c | sed -e 's/^ *//') ]] ; then
+    local result="0$result"
+  fi
+  
+  # Output the result including the sign and the percent sign
+  echo "${sign}${result}%"
+}
+
+# Outputs $TRUE i.f.f. the first argument is less than the second argument
+function lessOrEqual {
+  echo | awk "{ if($1 < $2) print \"$TRUE\" }"
+}
+
+# Outputs $TRUE i.f.f. the second argument is greater than the first argument and less than the third argument ($1 < $2 < $3)
+function isInRange {
+  if [[ "$TRUE" == $(lessOrEqual "$1" "$2") ]] ; then
+    if [[ "$TRUE" == $(lessOrEqual "$2" "$3") ]] ; then
+      echo "$TRUE"
+    fi
+  fi
+}
+
+# From the given bitrate vector, outputs the "bad" bitrates by filtering out the "good" bitrates.  The first argument is the index of the last good bitrate and the second argument is the given bitrate vector.  If the first argument is -1, then the given bitrate vector is outputted in its entirety.
+function filterOutGoodBitrates {
+  local result="$2"
+  for (( i=0; i<="$1"; ++i )); do
+    result=$(echo "$result" | sed -e 's/^[^ ]* //')
+  done
+  echo "$result"
+}
+
+# Outputs a given line from the given variable.  The first argument is the line number to output and the second argument is the given variable to extract the line from.
+function outputLine {
+  echo "$2" | head -n "$(expr "$1" + 1)" | tail -n 1
+}
+
+# Initialize iterationCount
+if [[ "$RESUME_MODE" == "$mode" ]] ; then
+  iterationCount=$(wc -l < "$metaLogPath" | sed -e 's/^ *//')
+else
+  iterationCount=0
+fi
+
+ITERATION_COUNT_LIMIT=50  # The number of attempts to make before giving up
+
+while true ; do  # The main loop
+  
+  # Run the encoder
+  sh ${SUB_TOOLS_DIRECTORY}encodeCommand.sh $inputName $encodeCommandArgs $CONFIGURATION_IDENTIFIER_OPTION $configurationIdentifier $Q_OPTION $q $OUTPUT_DIRECTORY_OPTION $outputDirectory -ea "$extraArguments $lambdaModifiers" | sh > $logPath
+  if [[ $? != 0 ]] ; then
+    printf "Unexpected exit status from encodeCommand.sh\n" >&2
+    exit 1
+  fi
+  
+  # Extract and output the bitrates
+  bitrates=`${SUB_TOOLS_DIRECTORY}extractBitrates.exe < $logPath`
+  outputToMetaLogNoNewline "$bitrates;"
+  
+  # Make sure that the index set of the extracted bitrates matches the index set of the target bitrates
+  if [[ "$targetBitrateVectorSize" != "$(bitrateVectorSize "$bitrates")" ]] ; then
+    echo "Index set from the extracted bitrates does not match the index set from the target bitrates" >&2
+    exit 1
+  fi
+  
+  # Calculate the bitrate difference percentages and output them to the meta-log
+  percentages="$(calculateAndFormatDifferencePercentage "$(extractBitrateFromVector "0" "$targetBitrates")" "$(extractBitrateFromVector "0" "$bitrates")")"
+  for (( i=1; i<"$targetBitrateVectorSize"; ++i )); do
+    percentages="$percentages $(calculateAndFormatDifferencePercentage "$(extractBitrateFromVector "$i" "$targetBitrates")" "$(extractBitrateFromVector "$i" "$bitrates")")"
+  done
+  outputToMetaLogNoNewline "$percentages;"
+  
+  # Initialize and output areBitratesSatismodifiery
+  areBitratesSatisfactory=yes
+  for (( i=0; ; ++i )) ; do
+    outerRangeMin=$(extractBitrateFromVector "$i" "$outerRangeMins")
+    bitrate=$(extractBitrateFromVector "$i" "$bitrates")
+    outerRangeMax=$(extractBitrateFromVector "$i" "$outerRangeMaxs")
+    if [[ "" == "$bitrate" ]] ; then
+      break
+    fi
+    if [[ $(isInRange "$outerRangeMin" "$bitrate" "$outerRangeMax") != "$TRUE" ]] ; then
+      areBitratesSatisfactory=no
+      break
+    fi
+  done
+  outputToMetaLogWithNewline "$areBitratesSatisfactory"
+  
+  # Exit if we are finished or if we have iterated too many times
+  if [[ yes == $areBitratesSatisfactory ]] ; then
+    mv "$logPath" "${outputPathBegin}_final.log"
+    exit 0
+  else
+    # Rename the deprecated log
+    countString="$iterationCount"
+    if [[ 1 == `printf -- "$countString" | wc -c | sed -e 's/^ *//'` ]] ; then
+      countString="0$countString"
+    fi
+    mv "$logPath" "${outputPathBegin}_dep${countString}.log"
+    
+    ((++iterationCount))
+    if [[ "$ITERATION_COUNT_LIMIT" == "$iterationCount" ]] ; then
+      outputToMetaLogWithNewline "Could not reach target bitrates"
+      exit 1
+    fi
+  fi
+  
+  filteredMetaLog=$(sed -e 's/;[^;]*$//' < $metaLogPath | sed -e 's/;[^;]*$//')
+  bitratesFromMetaLog=$(printf -- "$filteredMetaLog" | sed -e 's/^[^;]*;//')
+  
+  # Initialize goodIndex
+  goodIndex=-1
+  for (( i=0; i<"$targetBitrateVectorSize"; ++i )); do
+    innerRangeMin=$(extractBitrateFromVector "$i" "$innerRangeMins")
+    bitrate=$(extractBitrateFromVector "$i" "$bitrates")
+    innerRangeMax=$(extractBitrateFromVector "$i" "$innerRangeMaxs")
+    if [[ "$TRUE" == $(isInRange "$innerRangeMin" "$bitrate" "$innerRangeMax") ]] ; then
+      goodIndex="$i"
+    else
+      break
+    fi
+  done
+  
+  badBitrates=$(filterOutGoodBitrates "$goodIndex" "$bitratesFromMetaLog")
+  lambdaModifiersFromMetaLog=`printf -- "$filteredMetaLog" | sed -e 's/;[^;]*$//'`
+  badLambdaModifiers=`printf -- "$lambdaModifiersFromMetaLog" | sed -e "s/^.*-${LAMBDA_MODIFIER_PREFIX}$goodIndex [^ ]* //"`
+  lineCount=`printf -- "$badBitrates\n" | wc -l | sed -e 's/^ *//'`
+  
+  # Initialize guessLambdaModifiersIn
+  guessLambdaModifiersIn="$(outputLine 0 "$badLambdaModifiers");$(outputLine 0 "$badBitrates")"
+  for (( i=1; i<"$lineCount"; ++i )); do
+    guessLambdaModifiersIn="$(printf -- "$guessLambdaModifiersIn\n$(outputLine "$i" "$badLambdaModifiers");$(outputLine "$i" "$badBitrates")")"
+  done
+  
+  # Run guessLambdaModifiers
+  guessedLambdaModifiers=$(printf -- "$guessLambdaModifiersIn" | ${SUB_TOOLS_DIRECTORY}guessLambdaModifiers.exe "-.5" "$(filterOutGoodBitrates "$goodIndex" "$targetBitrates")")
+  if [[ $? != 0 ]] ; then
+    printf "Unexpected exit status from guessLambdaModifiers.exe\n" >&2
+    exit 1
+  fi
+  
+  # Initialize lambdaModifiers and output them to the meta-log
+  lastLambdaModifiersFromMetaLog=`printf -- "$filteredMetaLog" | tail -n 1 | sed -e "s/;[^;]*$//"`
+  goodLambdaModifiersFromMetaLog=`printf -- "$lastLambdaModifiersFromMetaLog" | tail -n 1 | sed -e "s/-${LAMBDA_MODIFIER_PREFIX}$(expr "$goodIndex" + 1).*$//"`
+  lambdaModifiers="${goodLambdaModifiersFromMetaLog}${guessedLambdaModifiers}"
+  outputLambdaModifiersToMetaLog
+  
+done
Index: /tags/SHM-9.0/source/App/utils/ExtractAddLS/ExtractAddLS.c
===================================================================
--- /tags/SHM-9.0/source/App/utils/ExtractAddLS/ExtractAddLS.c	(revision 1088)
+++ /tags/SHM-9.0/source/App/utils/ExtractAddLS/ExtractAddLS.c	(revision 1088)
@@ -0,0 +1,450 @@
+/* The copyright in this software is being made available under the BSD
+* License, included below. This software may be subject to other third party
+* and contributor rights, including patent rights, and no such rights are
+* granted under this license.
+*
+* Copyright (c) 2010-2014, ITU/ISO/IEC
+* All rights reserved.
+*
+* Redistribution and use in source and binary forms, with or without
+* modification, are permitted provided that the following conditions are met:
+*
+*  * Redistributions of source code must retain the above copyright notice,
+*    this list of conditions and the following disclaimer.
+*  * Redistributions in binary form must reproduce the above copyright notice,
+*    this list of conditions and the following disclaimer in the documentation
+*    and/or other materials provided with the distribution.
+*  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+*    be used to endorse or promote products derived from this software without
+*    specific prior written permission.
+*
+* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+* THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+
+
+enum NalUnitType
+{
+  NAL_UNIT_CODED_SLICE_TRAIL_N = 0,
+  NAL_UNIT_CODED_SLICE_TRAIL_R,
+
+  NAL_UNIT_CODED_SLICE_TSA_N,
+  NAL_UNIT_CODED_SLICE_TSA_R,
+
+  NAL_UNIT_CODED_SLICE_STSA_N,
+  NAL_UNIT_CODED_SLICE_STSA_R,
+
+  NAL_UNIT_CODED_SLICE_RADL_N,
+  NAL_UNIT_CODED_SLICE_RADL_R,
+
+  NAL_UNIT_CODED_SLICE_RASL_N,
+  NAL_UNIT_CODED_SLICE_RASL_R,
+
+  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,
+  NAL_UNIT_CODED_SLICE_BLA_W_RADL,
+  NAL_UNIT_CODED_SLICE_BLA_N_LP,
+  NAL_UNIT_CODED_SLICE_IDR_W_RADL,
+  NAL_UNIT_CODED_SLICE_IDR_N_LP,
+  NAL_UNIT_CODED_SLICE_CRA,
+  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,
+  NAL_UNIT_SPS,
+  NAL_UNIT_PPS,
+  NAL_UNIT_ACCESS_UNIT_DELIMITER,
+  NAL_UNIT_EOS,
+  NAL_UNIT_EOB,
+  NAL_UNIT_FILLER_DATA,
+  NAL_UNIT_PREFIX_SEI,
+  NAL_UNIT_SUFFIX_SEI,
+  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,
+};
+
+char *nalUnitNames[] =
+{
+  "NAL_UNIT_CODED_SLICE_TRAIL_N",
+  "NAL_UNIT_CODED_SLICE_TRAIL_R",
+
+  "NAL_UNIT_CODED_SLICE_TSA_N",
+  "NAL_UNIT_CODED_SLICE_TSA_R",
+
+  "NAL_UNIT_CODED_SLICE_STSA_N",
+  "NAL_UNIT_CODED_SLICE_STSA_R",
+
+  "NAL_UNIT_CODED_SLICE_RADL_N",
+  "NAL_UNIT_CODED_SLICE_RADL_R",
+
+  "NAL_UNIT_CODED_SLICE_RASL_N",
+  "NAL_UNIT_CODED_SLICE_RASL_R",
+
+  "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",
+  "NAL_UNIT_CODED_SLICE_BLA_W_RADL",
+  "NAL_UNIT_CODED_SLICE_BLA_N_LP",
+  "NAL_UNIT_CODED_SLICE_IDR_W_RADL",
+  "NAL_UNIT_CODED_SLICE_IDR_N_LP",
+  "NAL_UNIT_CODED_SLICE_CRA",
+  "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",
+  "NAL_UNIT_SPS",
+  "NAL_UNIT_PPS",
+  "NAL_UNIT_ACCESS_UNIT_DELIMITER",
+  "NAL_UNIT_EOS",
+  "NAL_UNIT_EOB",
+  "NAL_UNIT_FILLER_DATA",
+  "NAL_UNIT_PREFIX_SEI",
+  "NAL_UNIT_SUFFIX_SEI",
+  "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"
+};
+
+typedef struct NalUnitHeader_s
+{
+  int nalUnitType;
+  int nuhLayerId;
+  int nuhTemporalIdPlus1;
+} NalUnitHeader;
+
+
+int findStartCodePrefix(FILE *inFile, int *numStartCodeZeros)
+{
+  int numZeros = 0;
+  int currByte;
+  
+  for (;;)
+  {
+    currByte = fgetc(inFile);
+    if (currByte == EOF)
+    {
+      return 0;
+    }
+
+    if (currByte == 0x01 && numZeros > 1)
+    {
+      *numStartCodeZeros = numZeros;
+      return 1;
+    }
+    else if (currByte == 0)
+    {
+      numZeros++;
+    }
+    else
+    {
+      numZeros = 0;
+    }
+  }
+}
+
+int parseNalUnitHeader(FILE *inFile, NalUnitHeader *nalu)
+{
+  int byte0, byte1;
+
+  byte0 = fgetc(inFile);
+  byte1 = fgetc(inFile);
+
+  if (byte0 == EOF || byte1 == EOF)
+  {
+    return 0;
+  }
+
+  nalu->nalUnitType = (byte0 >> 1) & 0x3f;
+  nalu->nuhLayerId  = (((byte0 << 8) | byte1) >> 3) & 0x3f;
+  nalu->nuhTemporalIdPlus1 = byte1 & 0x07;
+
+  return 1;
+}
+
+void writeStartCodePrefixAndNUH(FILE *outFile, int numStartCodeZeros, NalUnitHeader *nalu)
+{
+  int byte0, byte1;
+  int i;
+
+  /* Start code prefix */
+  if (numStartCodeZeros > 3)
+  {
+    numStartCodeZeros = 3;
+  }
+  for (i = 0; i < numStartCodeZeros; i++)
+  {
+    fputc(0, outFile);
+  }
+  fputc(0x01, outFile);
+
+  /* NAL unit header */
+  byte0 = ((nalu->nalUnitType << 6) | nalu->nuhLayerId) >> 5;
+  byte1 = ((nalu->nuhLayerId << 3) | nalu->nuhTemporalIdPlus1) & 0xff;
+  fputc(byte0, outFile);
+  fputc(byte1, outFile);
+}
+
+int main(int argc, char **argv)
+{
+  FILE *inFile;
+  FILE *outFile;
+  int assignedBaseLayerId;
+  int tIdTarget = 6;
+  NalUnitHeader nalu;
+  int numStartCodeZeros;
+  int nalIsVpsSpsPpsEob;
+  int nalIsVpsSpsPpsEos;
+  int removeNal;
+  int layerIdListTarget[8];
+  int i;
+  int layerIdx;
+  int numLayerIds;
+  char nalName[32];
+
+  if (argc < 5 || argc > 10)
+  {
+    fprintf(stderr, "\n  Usage: ExtractAddLS <infile> <outfile> <max temporal ID> <list of layer IDs> \n\n");
+    fprintf(stderr, "  If only one layer ID 0 is given, base layer extration process is performed\n");
+    fprintf(stderr, "  If only one non-zero layer ID is given, independent non-base layer rewriting\n");
+    fprintf(stderr, "  process is performed\n");
+    fprintf(stderr, "  If more than one layer ID is given, sub-bitstream extraction process for\n");
+    fprintf(stderr, "  additional layer sets is performed (Layer ID list should exactly match\n");
+    fprintf(stderr, "  an additional layer set defined in VPS)\n");
+    exit(1);
+  }
+
+  inFile = fopen(argv[1], "rb");
+  if (inFile == NULL)
+  {
+    fprintf(stderr, "Cannot open input file %s\n", argv[1]);
+    exit(1);
+  }
+
+  outFile = fopen(argv[2], "wb");
+  if (outFile == NULL)
+  {
+    fprintf(stderr, "Cannot open output file %s\n", argv[2]);
+    exit(1);
+  }
+
+  tIdTarget = atoi(argv[3]);
+  if (tIdTarget < 0 || tIdTarget > 6)
+  {
+    fprintf(stderr, "Invalid maximum temporal ID (must be in range 0-6)\n");
+    exit(1);
+  }
+
+  for (i = 4, layerIdx = 0; i < argc; i++, layerIdx++)
+  {
+    layerIdListTarget[layerIdx] = atoi(argv[i]);
+    if (layerIdListTarget[layerIdx] < 0 || layerIdListTarget[layerIdx] > 7)
+    {
+      fprintf(stderr, "Invalid layer ID (must be in range 1-7)\n");
+      exit(1);
+    }
+  }
+
+  numLayerIds = layerIdx;
+  assignedBaseLayerId = layerIdListTarget[0];
+
+  /* Iterate through all NAL units */
+  for (;;)
+  {
+    if (!findStartCodePrefix(inFile, &numStartCodeZeros))
+    {
+      break;
+    }
+    if (!parseNalUnitHeader(inFile, &nalu))
+    {
+      break;
+    }
+
+    if (numLayerIds == 1)
+    {
+      /* base layer or independent non-base layer bitstream extraction */
+
+      /* temporary keep VPS so the extracted/rewriting bitstream can be decoded by HM */
+      nalIsVpsSpsPpsEob = (nalu.nalUnitType == NAL_UNIT_VPS || nalu.nalUnitType == NAL_UNIT_SPS || nalu.nalUnitType == NAL_UNIT_PPS || nalu.nalUnitType == NAL_UNIT_EOB);
+      removeNal = (!nalIsVpsSpsPpsEob && (nalu.nuhLayerId != assignedBaseLayerId))
+                  || (nalIsVpsSpsPpsEob && (nalu.nuhLayerId != 0))
+                  || ((nalu.nuhTemporalIdPlus1 - 1) > tIdTarget);
+      nalu.nuhLayerId = 0;
+    }
+    else /* numLayerIds > 1 */
+    {
+      /* sub-bitstream extraction process for additional layer sets */
+
+      int isTargetLayer = 0;
+
+      for (i = 0; i < numLayerIds; i++)
+      {
+        if (layerIdListTarget[i] == nalu.nuhLayerId)
+        {
+          isTargetLayer = 1;
+        }
+      }
+    
+      nalIsVpsSpsPpsEos = (nalu.nalUnitType == NAL_UNIT_VPS || nalu.nalUnitType == NAL_UNIT_SPS || nalu.nalUnitType == NAL_UNIT_PPS || nalu.nalUnitType == NAL_UNIT_EOS);
+
+      removeNal = (!(nalIsVpsSpsPpsEos || nalu.nalUnitType == NAL_UNIT_EOB) && !isTargetLayer)
+                || (nalIsVpsSpsPpsEos && (nalu.nuhLayerId != 0) && !isTargetLayer)
+                || ((nalu.nuhTemporalIdPlus1 - 1) > tIdTarget);
+    }
+
+    if (!removeNal)
+    {
+      /* Write current NAL unit to output bitstream */
+
+      long naluBytesStartPos;
+      long numNaluBytes;
+      long i;
+
+      printf("Keep  ");
+
+      writeStartCodePrefixAndNUH(outFile, numStartCodeZeros, &nalu);
+
+      naluBytesStartPos = ftell(inFile);
+      /* Find beginning of the next NAL unit to calculate length of the current unit */
+      if (findStartCodePrefix(inFile, &numStartCodeZeros))
+      {
+        numNaluBytes = ftell(inFile) - naluBytesStartPos - numStartCodeZeros - 1;
+      }
+      else
+      {
+        numNaluBytes = ftell(inFile) - naluBytesStartPos;
+      }
+      fseek(inFile, naluBytesStartPos, SEEK_SET);
+
+      i = 0;
+
+      if (numLayerIds == 1 && nalu.nalUnitType == NAL_UNIT_VPS)
+      {
+        char nalByte = fgetc(inFile);
+        nalByte = nalByte | (0x0C);  // set vps_max_layers_minus1 bits(5-4) to 0 for HM decoder
+        nalByte = nalByte & ~(0x03); // set vps_max_layers_minus1 bits(3-0) to 0 for HM decoder
+        fputc(nalByte, outFile); 
+        i++;
+        nalByte = fgetc(inFile);
+        nalByte = nalByte & ~(0xF0);
+        fputc(nalByte, outFile); 
+        i++;
+      }
+      else if (numLayerIds > 1 && nalu.nalUnitType == NAL_UNIT_VPS)
+      {
+        /* sub-bitstream extraction process for additional layer sets */
+        int nalByte = fgetc(inFile);
+        nalByte = nalByte & ~(0x04);  /* vps_base_layer_available_flag in each VPS is set equal to 0 */
+        fputc(nalByte, outFile);
+        i++;
+      }
+
+      for (; i < numNaluBytes; i++)
+      {
+        fputc(fgetc(inFile), outFile);
+      }
+    }
+    else
+    {
+      printf("-     ");
+    }
+
+    strcpy(nalName, nalUnitNames[nalu.nalUnitType]);
+    for (i = strlen(nalName); i < 31; i++)
+    {
+      nalName[i] = ' ';
+    }
+    nalName[31] = '\0';
+
+    printf("%s  layer ID: %i  temporal ID: %i\n", nalName, nalu.nuhLayerId, nalu.nuhTemporalIdPlus1 - 1);
+  }
+
+  fclose(inFile);
+  fclose(outFile);
+
+
+  return 0;
+}
Index: /tags/SHM-9.0/source/App/utils/ExtractAddLS/ReadMe.txt
===================================================================
--- /tags/SHM-9.0/source/App/utils/ExtractAddLS/ReadMe.txt	(revision 1088)
+++ /tags/SHM-9.0/source/App/utils/ExtractAddLS/ReadMe.txt	(revision 1088)
@@ -0,0 +1,21 @@
+
+This a tool that either:
+
+  1. Extracts an independent non-base layer from a multi-layer bitstream, converts it to a base-layer bistream and writes it to a file. The extraction processs is defined in chapter F.10.2 of the HEVC version 2 specification.
+
+or
+
+  2. Extracts an additional layer set sub-bitstream from multi-layer bitstream and writes it to a file. The extraction processs is defined in chapter F.10.3 of the HEVC version 2 specification.
+
+
+The tool is invoked as follows:
+
+  ExtractAddLS <infile> <outfile> <Max temporal ID> <layer IDs of the extracted layers>
+
+The process that is invoked is decided based on the number of IDs that are given in the layer ID list.  If only one layer ID is given, independent non-base layer rewriting process is invoked. If more than one layer ID is given, sub-bitstream extraction for additional layer sets is invoked.
+
+The result of independent non-base layer rewriting process can be decoded with an HEVC/H.265 v1 compliant decoder as long as the extracted independent layer conform with v1 specification text. The tool removes VPS from the output bitstream during rewriting so an HEVC/H.265 decoder should not expect it to be present.
+
+
+
+
Index: /tags/SHM-9.0/source/App/utils/annexBbytecount.cpp
===================================================================
--- /tags/SHM-9.0/source/App/utils/annexBbytecount.cpp	(revision 1088)
+++ /tags/SHM-9.0/source/App/utils/annexBbytecount.cpp	(revision 1088)
@@ -0,0 +1,233 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include <stdint.h>
+#include <cassert>
+#include <fstream>
+#include <sstream>
+#include <iostream>
+#include <string.h>
+
+#include "TLibDecoder/AnnexBread.h"
+
+using namespace std;
+
+static struct {
+  AnnexBStats expected;
+  unsigned data_len;
+  const char data[10];
+} tests[] = {
+  /* trivial cases: startcode, no payload */
+  {{0, 0, 3, 0, 0}, 3, {0,0,1}},
+  {{0, 1, 3, 0, 0}, 4, {0,0,0,1}},
+  {{2, 1, 3, 0, 0}, 6, {0,0,0,0,0,1}},
+  /* trivial cases: startcode, payload */
+  {{0, 0, 3, 1, 0}, 4, {0,0,1,2}},
+  {{0, 0, 3, 2, 0}, 5, {0,0,1,2,0}},
+  {{0, 0, 3, 3, 0}, 6, {0,0,1,2,0,0}},
+  {{0, 0, 3, 1, 3}, 7, {0,0,1,2,0,0,0}},
+  /* trivial cases: two nal units: extract the first */
+  {{0, 0, 3, 1, 0}, 8, {0,0,1,2,0,0,1,3}},
+  {{0, 0, 3, 1, 0}, 9, {0,0,1,2,0,0,0,1,3}},
+  {{0, 0, 3, 1, 1}, 10, {0,0,1,2,0,0,0,0,1,3}},
+  /* edge cases with EOF near start*/
+  {{0, 0, 0, 0, 0}, 0, {}},
+  {{1, 0, 0, 0, 0}, 1, {0}},
+  {{2, 0, 0, 0, 0}, 2, {0,0}},
+  {{3, 0, 0, 0, 0}, 3, {0,0,0}},
+};
+
+void selftest()
+{
+  /* test */
+  for (unsigned i = 0; i < sizeof(tests)/sizeof(*tests); i++)
+  {
+    istringstream in(string(tests[i].data, tests[i].data_len));
+    InputByteStream bs(in);
+
+    AnnexBStats actual = AnnexBStats();
+    vector<uint8_t> nalUnit;
+
+    byteStreamNALUnit(bs, nalUnit, actual);
+
+    cout << "Self-Test: " << i << ", {";
+    for (unsigned j = 0; j < tests[i].data_len; j++)
+    {
+      cout << hex << (unsigned int)tests[i].data[j] << dec;
+      if (j < tests[i].data_len-1)
+        cout << ",";
+    }
+    cout << "} ";
+
+    bool ok = true;
+#define VERIFY(a,b,m) \
+  if (a.m != b.m) { \
+    ok = false; \
+    cout << endl << "  MISSMATCH " #m << ", E(" << b.m << ") != " << a.m; \
+  }
+    VERIFY(actual, tests[i].expected, m_numLeadingZero8BitsBytes);
+    VERIFY(actual, tests[i].expected, m_numZeroByteBytes);
+    VERIFY(actual, tests[i].expected, m_numStartCodePrefixBytes);
+    VERIFY(actual, tests[i].expected, m_numBytesInNALUnit);
+    VERIFY(actual, tests[i].expected, m_numTrailingZero8BitsBytes);
+#undef VERIFY
+    if (ok)
+      cout << "OK";
+    cout << endl;
+  }
+}
+
+int main(int argc, char*argv[])
+{
+  selftest();
+
+  if (argc != 2)
+    return 0;
+
+  ifstream in(argv[1], ifstream::in | ifstream::binary);
+  InputByteStream bs(in);
+
+  AnnexBStats annexBStatsTotal = AnnexBStats();
+  AnnexBStats annexBStatsTotal_VCL = AnnexBStats();
+  AnnexBStats annexBStatsTotal_Filler = AnnexBStats();
+  AnnexBStats annexBStatsTotal_Other = AnnexBStats();
+  unsigned numNALUnits = 0;
+
+  cout << "NALUnits:" << endl;
+  while (!!in)
+  {
+    AnnexBStats annexBStatsSingle = AnnexBStats();
+    vector<uint8_t> nalUnit;
+
+    byteStreamNALUnit(bs, nalUnit, annexBStatsSingle);
+
+    int nal_unit_type = -1;
+    if (annexBStatsSingle.m_numBytesInNALUnit)
+    {
+      nal_unit_type = nalUnit[0] & 0x1f;
+    }
+
+    cout << " - NALU: #" << numNALUnits << " nal_unit_type:" << nal_unit_type << endl
+         << "   num_bytes(leading_zero_8bits): " << annexBStatsSingle.m_numLeadingZero8BitsBytes << endl
+         << "   num_bytes(zero_byte): " << annexBStatsSingle.m_numZeroByteBytes << endl
+         << "   num_bytes(start_code_prefix_one_3bytes): " << annexBStatsSingle.m_numStartCodePrefixBytes << endl
+         << "   NumBytesInNALunit: " << annexBStatsSingle.m_numBytesInNALUnit << endl
+         << "   num_bytes(trailing_zero_8bits): " << annexBStatsSingle.m_numTrailingZero8BitsBytes << endl
+         ;
+
+    annexBStatsTotal += annexBStatsSingle;
+    numNALUnits++;
+
+    if (!annexBStatsSingle.m_numBytesInNALUnit)
+      continue;
+
+    /* identify the NAL unit type and add stats to the correct
+     * accumulators */
+    switch (nalUnit[0] & 0x1f) {
+    case 1: case 2: case 3: case 4: case 5:
+      annexBStatsTotal_VCL += annexBStatsSingle;
+      break;
+    case 12:
+      annexBStatsTotal_Filler += annexBStatsSingle;
+      break;
+    default:
+      annexBStatsTotal_Other += annexBStatsSingle;
+    };
+  }
+
+  cout << "Summary: " << endl
+       << "  num_bytes(leading_zero_8bits): " << annexBStatsTotal.m_numLeadingZero8BitsBytes << endl
+       << "  num_bytes(zero_byte): " << annexBStatsTotal.m_numZeroByteBytes << endl
+       << "  num_bytes(start_code_prefix_one_3bytes): " << annexBStatsTotal.m_numStartCodePrefixBytes << endl
+       << "  NumBytesInNALunit: " << annexBStatsTotal.m_numBytesInNALUnit << endl
+       << "  num_bytes(trailing_zero_8bits): " << annexBStatsTotal.m_numTrailingZero8BitsBytes << endl
+       ;
+
+  cout << "Summary(VCL): " << endl
+       << "  num_bytes(leading_zero_8bits): " << annexBStatsTotal_VCL.m_numLeadingZero8BitsBytes << endl
+       << "  num_bytes(zero_byte): " << annexBStatsTotal_VCL.m_numZeroByteBytes << endl
+       << "  num_bytes(start_code_prefix_one_3bytes): " << annexBStatsTotal_VCL.m_numStartCodePrefixBytes << endl
+       << "  NumBytesInNALunit: " << annexBStatsTotal_VCL.m_numBytesInNALUnit << endl
+       << "  num_bytes(trailing_zero_8bits): " << annexBStatsTotal_VCL.m_numTrailingZero8BitsBytes << endl
+       ;
+
+  cout << "Summary(Filler): " << endl
+       << "  num_bytes(leading_zero_8bits): " << annexBStatsTotal_Filler.m_numLeadingZero8BitsBytes << endl
+       << "  num_bytes(zero_byte): " << annexBStatsTotal_Filler.m_numZeroByteBytes << endl
+       << "  num_bytes(start_code_prefix_one_3bytes): " << annexBStatsTotal_Filler.m_numStartCodePrefixBytes << endl
+       << "  NumBytesInNALunit: " << annexBStatsTotal_Filler.m_numBytesInNALUnit << endl
+       << "  num_bytes(trailing_zero_8bits): " << annexBStatsTotal_Filler.m_numTrailingZero8BitsBytes << endl
+       ;
+
+  cout << "Summary(Other): " << endl
+       << "  num_bytes(leading_zero_8bits): " << annexBStatsTotal_Other.m_numLeadingZero8BitsBytes << endl
+       << "  num_bytes(zero_byte): " << annexBStatsTotal_Other.m_numZeroByteBytes << endl
+       << "  num_bytes(start_code_prefix_one_3bytes): " << annexBStatsTotal_Other.m_numStartCodePrefixBytes << endl
+       << "  NumBytesInNALunit: " << annexBStatsTotal_Other.m_numBytesInNALUnit << endl
+       << "  num_bytes(trailing_zero_8bits): " << annexBStatsTotal_Other.m_numTrailingZero8BitsBytes << endl
+       ;
+
+  /* The first such type of bitstream, called Type I bitstream, is a
+   * NAL unit stream containing only the VCL NAL units and filler data
+   * NAL units for all access units in the bitstream.
+   */
+  unsigned totalBytes_T1HRD = annexBStatsTotal_VCL.m_numBytesInNALUnit + annexBStatsTotal_Filler.m_numBytesInNALUnit;
+
+  /*The second type of bitstream, called a Type II bitstream,
+   * contains, in addition to the VCL NAL units and filler data NAL
+   * units for all access units in the bitstream, at least one of
+   * the following:
+   *  (a) additional non-VCL NAL units other than filler data NAL
+   *      units.
+   */
+  unsigned totalBytes_T2aHRD = annexBStatsTotal.m_numBytesInNALUnit;
+
+  /*  (b) all leading_zero_8bits, zero_byte,
+   *      start_code_prefix_one_3bytes, and trailing_zero_8bits syntax
+   *      elements that form a byte stream from the NAL unit stream (as
+   *      specified in Annex B)
+   */
+  unsigned totalBytes_T2abHRD = 0;
+  totalBytes_T2abHRD += annexBStatsTotal.m_numLeadingZero8BitsBytes;
+  totalBytes_T2abHRD += annexBStatsTotal.m_numZeroByteBytes;
+  totalBytes_T2abHRD += annexBStatsTotal.m_numStartCodePrefixBytes;
+  totalBytes_T2abHRD += annexBStatsTotal.m_numBytesInNALUnit;
+  totalBytes_T2abHRD += annexBStatsTotal.m_numTrailingZero8BitsBytes;
+
+  cout << "Totals (bytes):" << endl;
+  cout << "  Type1 HRD: " << totalBytes_T1HRD << endl;
+  cout << "  Type2 HRD: " << totalBytes_T2aHRD << endl;
+  cout << "  Type2b HRD: " << totalBytes_T2abHRD << endl;
+
+  return 0;
+}
Index: /tags/SHM-9.0/source/App/utils/convert_NtoMbit_YCbCr.cpp
===================================================================
--- /tags/SHM-9.0/source/App/utils/convert_NtoMbit_YCbCr.cpp	(revision 1088)
+++ /tags/SHM-9.0/source/App/utils/convert_NtoMbit_YCbCr.cpp	(revision 1088)
@@ -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-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include <cstdlib>
+
+#include "TLibCommon/TComPicYuv.h"
+#include "TLibVideoIO/TVideoIOYuv.h"
+#include "TAppCommon/program_options_lite.h"
+
+using namespace std;
+namespace po = df::program_options_lite;
+
+Int main(Int argc, const char** argv)
+{
+  Bool do_help;
+  string filename_in, filename_out;
+  UInt width, height;
+  UInt bitdepth_in, bitdepth_out, chromaFormatRaw;
+  UInt num_frames;
+  UInt 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")
+  ("ChromaFormat", chromaFormatRaw, 420u, "chroma format. 400, 420, 422 or 444 only")
+  ("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;
+  }
+
+  ChromaFormat chromaFormatIDC=CHROMA_420;
+  switch (chromaFormatRaw)
+  {
+    case 400: chromaFormatIDC=CHROMA_400; break;
+    case 420: chromaFormatIDC=CHROMA_420; break;
+    case 422: chromaFormatIDC=CHROMA_422; break;
+    case 444: chromaFormatIDC=CHROMA_444; break;
+    default:
+      fprintf(stderr, "Bad chroma format string\n");
+      return EXIT_FAILURE;
+  }
+
+  TVideoIOYuv input;
+  TVideoIOYuv output;
+
+  Int inputBitDepths [MAX_NUM_CHANNEL_TYPE];
+  Int outputBitDepths[MAX_NUM_CHANNEL_TYPE];
+
+  for (UInt channelTypeIndex = 0; channelTypeIndex < MAX_NUM_CHANNEL_TYPE; channelTypeIndex++)
+  {
+    inputBitDepths [channelTypeIndex] = bitdepth_in;
+    outputBitDepths[channelTypeIndex] = bitdepth_out;
+  }
+
+  input.open((char*)filename_in.c_str(), false, inputBitDepths, inputBitDepths, outputBitDepths);
+  output.open((char*)filename_out.c_str(), true, outputBitDepths, outputBitDepths, outputBitDepths);
+
+  input.skipFrames(num_frames_skip, width, height, chromaFormatIDC);
+
+  TComPicYuv frame;
+  frame.create( width, height, chromaFormatIDC, 1, 1, 0 );
+
+  Int pad[2] = {0, 0};
+
+  TComPicYuv cPicYuvTrueOrg;
+  cPicYuvTrueOrg.create( width, height, chromaFormatIDC, 1, 1, 0 );
+
+  UInt num_frames_processed = 0;
+  while (!input.isEof()) 
+  {
+    if (! input.read(&frame, &cPicYuvTrueOrg, IPCOLOURSPACE_UNCHANGED, pad))
+    {
+      break;
+    }
+#if 0
+    Pel* img = frame.getAddr(COMPONENT_Y);
+    for (Int y = 0; y < height; y++)
+    {
+      for (Int x = 0; x < height; x++)
+        img[x] = 0;
+      img += frame.getStride();
+    }
+    img = frame.getAddr(COMPONENT_Y);
+    img[0] = 1;
+#endif
+
+    output.write(&frame, IPCOLOURSPACE_UNCHANGED);
+    num_frames_processed++;
+    if (num_frames_processed == num_frames)
+      break;
+  }
+
+  input.close();
+  output.close();
+  cPicYuvTrueOrg.destroy();
+
+  return EXIT_SUCCESS;
+}
Index: /tags/SHM-9.0/source/Lib/TAppCommon/program_options_lite.cpp
===================================================================
--- /tags/SHM-9.0/source/Lib/TAppCommon/program_options_lite.cpp	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TAppCommon/program_options_lite.cpp	(revision 1088)
@@ -0,0 +1,498 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#include <stdlib.h>
+#include <iostream>
+#include <fstream>
+#include <sstream>
+#include <string>
+#include <list>
+#include <map>
+#include <algorithm>
+#include "program_options_lite.h"
+
+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++)
+      {
+        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++)
+      {
+        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: /tags/SHM-9.0/source/Lib/TAppCommon/program_options_lite.h
===================================================================
--- /tags/SHM-9.0/source/Lib/TAppCommon/program_options_lite.h	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TAppCommon/program_options_lite.h	(revision 1088)
@@ -0,0 +1,289 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#include <iostream>
+#include <sstream>
+#include <string>
+#include <list>
+#include <map>
+
+#ifndef __PROGRAM_OPTIONS_LITE__
+#define __PROGRAM_OPTIONS_LITE__
+
+//! \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
+    {
+      OptionBase(const std::string& name, const std::string& desc)
+      : opt_string(name), opt_desc(desc)
+      {};
+      
+      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;
+    };
+    
+    /** Type specific option storage */
+    template<typename T>
+    struct Option : public OptionBase
+    {
+      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)
+      {}
+      
+      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;
+    }
+    
+    /** 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 1 //SVC_EXTENSION
+      template<typename T>
+      OptionSpecific&
+        operator()(const std::string& name, T* storage, T default_val, unsigned uiMaxNum, const std::string& desc = "" )
+      {
+        std::string cNameBuffer;
+        std::string cDescriptionBuffer;
+
+        cNameBuffer       .resize( name.size() + 10 );
+        cDescriptionBuffer.resize( desc.size() + 10 );
+
+        for ( unsigned int uiK = 0; uiK < uiMaxNum; uiK++ )
+        {
+          // isn't there are sprintf function for string??
+          sprintf((char*) cNameBuffer.c_str()       ,name.c_str(),uiK,uiK);
+          sprintf((char*) cDescriptionBuffer.c_str(),desc.c_str(),uiK,uiK);
+
+          size_t pos = cNameBuffer.find_first_of('\0');
+          if(pos != std::string::npos)
+            cNameBuffer.resize(pos);
+      
+          parent.addOption(new Option<T>( cNameBuffer, (storage[uiK]), default_val, cDescriptionBuffer ));
+        }
+
+        return *this;
+      }
+
+      template<typename T>
+      OptionSpecific&
+        operator()(const std::string& name, T** storage, T default_val, unsigned uiMaxNum, const std::string& desc = "" )
+      {
+        std::string cNameBuffer;
+        std::string cDescriptionBuffer;
+
+        cNameBuffer       .resize( name.size() + 10 );
+        cDescriptionBuffer.resize( desc.size() + 10 );
+
+        for ( unsigned int uiK = 0; uiK < uiMaxNum; uiK++ )
+        {
+          // isn't there are sprintf function for string??
+          sprintf((char*) cNameBuffer.c_str()       ,name.c_str(),uiK,uiK);
+          sprintf((char*) cDescriptionBuffer.c_str(),desc.c_str(),uiK,uiK);
+
+          size_t pos = cNameBuffer.find_first_of('\0');
+          if(pos != std::string::npos)
+            cNameBuffer.resize(pos);
+
+          parent.addOption(new Option<T>( cNameBuffer, *(storage[uiK]), default_val, cDescriptionBuffer ));
+        }
+
+        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 */
+
+//! \}
+
+#endif
Index: /tags/SHM-9.0/source/Lib/TLibCommon/AccessUnit.h
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibCommon/AccessUnit.h	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibCommon/AccessUnit.h	(revision 1088)
@@ -0,0 +1,76 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** 
+ \file     AccessUnit.h
+ \brief    Access Unit class (header)
+ */
+
+#pragma once
+
+#ifndef __ACCESSUNIT__
+#define __ACCESSUNIT__
+
+#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*> // NOTE: Should not inherit from STL.
+{
+public:
+  ~AccessUnit()
+  {
+    for (AccessUnit::iterator it = this->begin(); it != this->end(); it++)
+    {
+      delete *it;
+    }
+  }
+};
+
+//! \}
+
+#endif
Index: /tags/SHM-9.0/source/Lib/TLibCommon/CommonDef.h
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibCommon/CommonDef.h	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibCommon/CommonDef.h	(revision 1088)
@@ -0,0 +1,348 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     CommonDef.h
+    \brief    Defines constants, macros and tool parameters
+*/
+
+#ifndef __COMMONDEF__
+#define __COMMONDEF__
+
+#include <algorithm>
+#include <iostream>
+#include <assert.h>
+
+#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 SVC_EXTENSION
+#include <vector>
+#define NV_VERSION        "9.0 (HM-16.2)"                 ///< Current software version
+#else
+#define NV_VERSION        "16.2"                ///< Current software version
+#endif
+
+// ====================================================================================================================
+// Platform information
+// ====================================================================================================================
+
+#ifdef __GNUC__
+#define NVM_COMPILEDBY  "[GCC %d.%d.%d]", __GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__
+#ifdef __IA64__
+#define NVM_ONARCH    "[on 64-bit] "
+#else
+#define NVM_ONARCH    "[on 32-bit] "
+#endif
+#endif
+
+#ifdef __INTEL_COMPILER
+#define NVM_COMPILEDBY  "[ICC %d]", __INTEL_COMPILER
+#elif  _MSC_VER
+#define NVM_COMPILEDBY  "[VS %d]", _MSC_VER
+#endif
+
+#ifndef NVM_COMPILEDBY
+#define NVM_COMPILEDBY "[Unk-CXX]"
+#endif
+
+#ifdef _WIN32
+#define NVM_ONOS        "[Windows]"
+#elif  __linux
+#define NVM_ONOS        "[Linux]"
+#elif  __CYGWIN__
+#define NVM_ONOS        "[Cygwin]"
+#elif __APPLE__
+#define NVM_ONOS        "[Mac OS X]"
+#else
+#define NVM_ONOS "[Unk-OS]"
+#endif
+
+#define NVM_BITS          "[%d bit] ", (sizeof(Void*) == 8 ? 64 : 32) ///< used for checking 64-bit O/S
+
+#ifndef NULL
+#define NULL              0
+#endif
+
+// ====================================================================================================================
+// Common constants
+// ====================================================================================================================
+
+#define _SUMMARY_OUT_               0           ///< print-out PSNR results of all slices to summary.txt
+#define _SUMMARY_PIC_               0           ///< print-out PSNR results for each slice type to summary.txt
+
+#define MAX_GOP                     64          ///< max. value of hierarchical GOP size
+
+#define MAX_NUM_REF_PICS            16          ///< max. number of pictures used for reference
+#define MAX_NUM_REF                 16          ///< max. number of entries in picture reference list
+
+#define MAX_UINT                    0xFFFFFFFFU ///< max. value of unsigned 32-bit integer
+#define MAX_INT                     2147483647  ///< max. value of signed 32-bit integer
+#define MAX_INT64                   0x7FFFFFFFFFFFFFFFLL  ///< max. value of signed 64-bit integer
+#if RExt__HIGH_BIT_DEPTH_SUPPORT
+#define MAX_INTERMEDIATE_INT        MAX_INT64
+#else
+#define MAX_INTERMEDIATE_INT        MAX_INT
+#endif
+
+#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_bitDepth[MAX_NUM_CHANNEL_TYPE];
+
+#if O0194_DIFFERENT_BITDEPTH_EL_BL
+extern Int  g_bitDepthLayer[MAX_NUM_CHANNEL_TYPE][MAX_LAYERS];
+#endif
+#if O0194_WEIGHTED_PREDICTION_CGS
+extern void* g_refWeightACDCParam; //type:wpACDCParam
+#endif
+
+template <typename T> inline T Clip3 (const T minVal, const T maxVal, const T a) { return std::min<T> (std::max<T> (minVal, a) , maxVal); }  ///< general min/max clip
+template <typename T> inline T ClipBD(const T x, const Int bitDepth)             { return Clip3(T(0), T((1 << bitDepth)-1), x);           }
+template <typename T> inline T Clip  (const T x, const ChannelType type)         { return ClipBD(x, g_bitDepth[type]);                    }
+
+template <typename T> inline Void Check3( T minVal, T maxVal, T a)
+{
+  if ((a > maxVal) || (a < minVal))
+  {
+    std::cerr << "ERROR: Range check " << minVal << " >= " << a << " <= " << maxVal << " failed" << std::endl;
+    assert(false);
+    exit(1);
+  }
+}  ///< 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);                                             \
+}
+
+template <typename ValueType> inline ValueType leftShift       (const ValueType value, const Int shift) { return (shift >= 0) ? ( value                                  << shift) : ( value                                   >> -shift); }
+template <typename ValueType> inline ValueType rightShift      (const ValueType value, const Int shift) { return (shift >= 0) ? ( value                                  >> shift) : ( value                                   << -shift); }
+template <typename ValueType> inline ValueType leftShift_round (const ValueType value, const Int shift) { return (shift >= 0) ? ( value                                  << shift) : ((value + (ValueType(1) << (-shift - 1))) >> -shift); }
+template <typename ValueType> inline ValueType rightShift_round(const ValueType value, const Int shift) { return (shift >= 0) ? ((value + (ValueType(1) << (shift - 1))) >> shift) : ( value                                   << -shift); }
+#if O0043_BEST_EFFORT_DECODING
+// when shift = 0, returns value
+// when shift = 1, (value + 0 + value[1]) >> 1
+// when shift = 2, (value + 1 + value[2]) >> 2
+// when shift = 3, (value + 3 + value[3]) >> 3
+template <typename ValueType> inline ValueType rightShiftEvenRounding(const ValueType value, const UInt shift) { return (shift == 0) ? value : ((value + (1<<(shift-1))-1 + ((value>>shift)&1)) >> shift) ; }
+#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
+
+// Reference memory management
+#define DYN_REF_FREE                0           ///< dynamic free of reference memories
+
+// Explicit temporal layer QP offset
+#define MAX_TLAYER                  7           ///< max number of temporal layer
+#define HB_LAMBDA_FOR_LDC           1           ///< use of B-style lambda for non-key pictures in low-delay mode
+
+// Fast estimation of generalized B in low-delay mode
+#define GPB_SIMPLE                  1           ///< Simple GPB mode
+#if     GPB_SIMPLE
+#define GPB_SIMPLE_UNI              1           ///< Simple mode for uni-direction
+#endif
+
+// Fast ME using smoother MV assumption
+#define FASTME_SMOOTHER_MV          1           ///< reduce ME time using faster option
+
+// Adaptive search range depending on POC difference
+#define ADAPT_SR_SCALE              1           ///< division factor for adaptive search range
+
+#define CLIP_TO_709_RANGE           0
+
+// Early-skip threshold (encoder)
+#define EARLY_SKIP_THRES            1.50        ///< if RD < thres*avg[BestSkipRD]
+
+
+#define MAX_CHROMA_FORMAT_IDC      3
+
+// TODO: Existing names used for the different NAL unit types can be altered to better reflect the names in the spec.
+//       However, the names in the spec are not yet stable at this point. Once the names are stable, a cleanup 
+//       effort can be done without use of macros to alter the names used to indicate the different NAL unit types.
+enum NalUnitType
+{
+  NAL_UNIT_CODED_SLICE_TRAIL_N = 0,   // 0
+  NAL_UNIT_CODED_SLICE_TRAIL_R,   // 1
+  
+  NAL_UNIT_CODED_SLICE_TSA_N,     // 2
+  NAL_UNIT_CODED_SLICE_TSA_R,       // 3
+  
+  NAL_UNIT_CODED_SLICE_STSA_N,    // 4
+  NAL_UNIT_CODED_SLICE_STSA_R,    // 5
+
+  NAL_UNIT_CODED_SLICE_RADL_N,    // 6
+  NAL_UNIT_CODED_SLICE_RADL_R,      // 7
+  
+  NAL_UNIT_CODED_SLICE_RASL_N,    // 8
+  NAL_UNIT_CODED_SLICE_RASL_R,      // 9
+
+  NAL_UNIT_RESERVED_VCL_N10,
+  NAL_UNIT_RESERVED_VCL_R11,
+  NAL_UNIT_RESERVED_VCL_N12,
+  NAL_UNIT_RESERVED_VCL_R13,
+  NAL_UNIT_RESERVED_VCL_N14,
+  NAL_UNIT_RESERVED_VCL_R15,
+
+  NAL_UNIT_CODED_SLICE_BLA_W_LP,    // 16
+  NAL_UNIT_CODED_SLICE_BLA_W_RADL,  // 17
+  NAL_UNIT_CODED_SLICE_BLA_N_LP,  // 18
+  NAL_UNIT_CODED_SLICE_IDR_W_RADL,  // 19
+  NAL_UNIT_CODED_SLICE_IDR_N_LP,  // 20
+  NAL_UNIT_CODED_SLICE_CRA,       // 21
+  NAL_UNIT_RESERVED_IRAP_VCL22,
+  NAL_UNIT_RESERVED_IRAP_VCL23,
+
+  NAL_UNIT_RESERVED_VCL24,
+  NAL_UNIT_RESERVED_VCL25,
+  NAL_UNIT_RESERVED_VCL26,
+  NAL_UNIT_RESERVED_VCL27,
+  NAL_UNIT_RESERVED_VCL28,
+  NAL_UNIT_RESERVED_VCL29,
+  NAL_UNIT_RESERVED_VCL30,
+  NAL_UNIT_RESERVED_VCL31,
+
+  NAL_UNIT_VPS,                   // 32
+  NAL_UNIT_SPS,                   // 33
+  NAL_UNIT_PPS,                   // 34
+  NAL_UNIT_ACCESS_UNIT_DELIMITER, // 35
+  NAL_UNIT_EOS,                   // 36
+  NAL_UNIT_EOB,                   // 37
+  NAL_UNIT_FILLER_DATA,           // 38
+  NAL_UNIT_PREFIX_SEI,              // 39
+  NAL_UNIT_SUFFIX_SEI,              // 40
+
+  NAL_UNIT_RESERVED_NVCL41,
+  NAL_UNIT_RESERVED_NVCL42,
+  NAL_UNIT_RESERVED_NVCL43,
+  NAL_UNIT_RESERVED_NVCL44,
+  NAL_UNIT_RESERVED_NVCL45,
+  NAL_UNIT_RESERVED_NVCL46,
+  NAL_UNIT_RESERVED_NVCL47,
+  NAL_UNIT_UNSPECIFIED_48,
+  NAL_UNIT_UNSPECIFIED_49,
+  NAL_UNIT_UNSPECIFIED_50,
+  NAL_UNIT_UNSPECIFIED_51,
+  NAL_UNIT_UNSPECIFIED_52,
+  NAL_UNIT_UNSPECIFIED_53,
+  NAL_UNIT_UNSPECIFIED_54,
+  NAL_UNIT_UNSPECIFIED_55,
+  NAL_UNIT_UNSPECIFIED_56,
+  NAL_UNIT_UNSPECIFIED_57,
+  NAL_UNIT_UNSPECIFIED_58,
+  NAL_UNIT_UNSPECIFIED_59,
+  NAL_UNIT_UNSPECIFIED_60,
+  NAL_UNIT_UNSPECIFIED_61,
+  NAL_UNIT_UNSPECIFIED_62,
+  NAL_UNIT_UNSPECIFIED_63,
+  NAL_UNIT_INVALID,
+};
+
+#if OUTPUT_LAYER_SET_INDEX
+class CommonDecoderParams
+{
+  Int m_targetLayerId;
+  Int m_targetOutputLayerSetIdx;
+  std::vector<Int> *m_targetDecLayerIdSet;
+  Bool m_valueCheckedFlag;
+  Int m_highestTId;
+public:
+  CommonDecoderParams():
+#if FIX_CONF_MODE
+    m_targetLayerId(MAX_VPS_LAYER_IDX_PLUS1)
+#else
+    m_targetLayerId(0)
+#endif
+    , m_targetOutputLayerSetIdx(-1)
+    , m_targetDecLayerIdSet(NULL)
+    , m_valueCheckedFlag(false)
+    , m_highestTId(6)
+ {}
+
+  Void setTargetLayerId(const Int x) { m_targetLayerId = x;   }
+  Int  getTargetLayerId()            { return m_targetLayerId;}
+  
+  Void setTargetOutputLayerSetIdx(const Int x) { m_targetOutputLayerSetIdx = x;   }
+  Int  getTargetOutputLayerSetIdx()            { return m_targetOutputLayerSetIdx;}
+
+  Void               setTargetDecLayerIdSet(std::vector<Int> *x) { m_targetDecLayerIdSet = x;   }
+  std::vector<Int>*  getTargetDecLayerIdSet()                    { return m_targetDecLayerIdSet;}
+  
+  Void setValueCheckedFlag(const Bool x) { m_valueCheckedFlag = x;   }
+  Bool getValueCheckedFlag()            { return m_valueCheckedFlag;}
+  
+  Void setHighestTId(const Int x) { m_highestTId = x; }
+  Int  getHighestTId()            { return m_highestTId; }
+};
+#endif
+//! \}
+
+#endif // end of #ifndef  __COMMONDEF__
+
Index: /tags/SHM-9.0/source/Lib/TLibCommon/ContextModel.cpp
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibCommon/ContextModel.cpp	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibCommon/ContextModel.cpp	(revision 1088)
@@ -0,0 +1,129 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     ContextModel.cpp
+    \brief    context model class
+*/
+
+#include <algorithm>
+
+#include "ContextModel.h"
+
+using namespace std;
+//! \ingroup TLibCommon
+//! \{
+
+// ====================================================================================================================
+// Public member functions
+// ====================================================================================================================
+
+/**
+ - initialize context model with respect to QP and initialization value
+ .
+ \param  qp         input QP value
+ \param  initValue  8 bit initialization value
+ */
+Void ContextModel::init( Int qp, Int initValue )
+{
+  qp = Clip3(0, 51, qp);
+
+  Int  slope      = (initValue>>4)*5 - 45;
+  Int  offset     = ((initValue&15)<<3)-16;
+  Int  initState  =  min( max( 1, ( ( ( slope * qp ) >> 4 ) + offset ) ), 126 );
+  UInt mpState    = (initState >= 64 );
+  m_ucState       = ( (mpState? (initState - 64):(63 - initState)) <<1) + mpState;
+}
+
+const UChar ContextModel::m_aucNextStateMPS[ ContextModel::m_totalStates ] =
+{
+  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[ ContextModel::m_totalStates ] =
+{
+  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[ ContextModel::m_totalStates ][2 /*MPS = [0|1]*/];
+
+Void ContextModel::buildNextStateTable()
+{
+  for (Int i = 0; i < ContextModel::m_totalStates; 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[ ContextModel::m_totalStates ] =
+{
+#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: /tags/SHM-9.0/source/Lib/TLibCommon/ContextModel.h
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibCommon/ContextModel.h	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibCommon/ContextModel.h	(revision 1088)
@@ -0,0 +1,108 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+
+/** \file     ContextModel.h
+    \brief    context model class (header)
+*/
+
+#ifndef __CONTEXTMODEL__
+#define __CONTEXTMODEL__
+
+#if _MSC_VER > 1000
+#pragma once
+#endif // _MSC_VER > 1000
+
+#include "CommonDef.h"
+#include "TComRom.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  UInt  m_totalStates = (1 << CONTEXT_STATE_BITS) * 2; //*2 for MPS = [0|1]
+  static const  UChar m_aucNextStateMPS[m_totalStates];
+  static const  UChar m_aucNextStateLPS[m_totalStates];
+  static const  Int   m_entropyBits    [m_totalStates];
+#if FAST_BIT_EST
+  static UChar m_nextState[m_totalStates][2 /*MPS = [0|1]*/];
+#endif
+  UInt          m_binsCoded;
+};
+
+//! \}
+
+#endif
+
Index: /tags/SHM-9.0/source/Lib/TLibCommon/ContextModel3DBuffer.cpp
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibCommon/ContextModel3DBuffer.cpp	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibCommon/ContextModel3DBuffer.cpp	(revision 1088)
@@ -0,0 +1,120 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     ContextModel3DBuffer.cpp
+    \brief    context model 3D buffer class
+*/
+
+#include "ContextModel3DBuffer.h"
+
+//! \ingroup TLibCommon
+//! \{
+
+// ====================================================================================================================
+// Constructor / destructor / initialization / destroy
+// ====================================================================================================================
+
+ContextModel3DBuffer::ContextModel3DBuffer( UInt uiSizeZ, UInt uiSizeY, UInt uiSizeX, ContextModel *basePtr, Int &count )
+: m_sizeX  ( uiSizeX )
+, m_sizeXY ( uiSizeX * uiSizeY )
+, m_sizeXYZ( uiSizeX * uiSizeY * uiSizeZ )
+{
+  // allocate 3D buffer
+  m_contextModel = basePtr;
+  count += m_sizeXYZ;
+}
+
+// ====================================================================================================================
+// Public member functions
+// ====================================================================================================================
+
+/**
+ * Initialize 3D buffer with respect to slicetype, QP and given initial probability table
+ *
+ * \param  eSliceType      slice type
+ * \param  iQp             input QP value
+ * \param  psCtxModel      given probability table
+ */
+Void ContextModel3DBuffer::initBuffer( SliceType sliceType, Int qp, UChar* ctxModel )
+{
+  ctxModel += sliceType * m_sizeXYZ;
+  
+  for ( Int n = 0; n < m_sizeXYZ; n++ )
+  {
+    m_contextModel[ n ].init( qp, ctxModel[ n ] );
+    m_contextModel[ n ].setBinsCoded( 0 );
+  }
+}
+
+/**
+ * Calculate the cost of choosing a probability table based on the current probability of CABAC at encoder
+ *
+ * \param  sliceType      slice type
+ * \param  qp             input QP value
+ * \param  ctxModel      given probability table
+ */
+UInt ContextModel3DBuffer::calcCost( SliceType sliceType, Int qp, UChar* ctxModel )
+{
+  UInt cost = 0;
+  ctxModel += sliceType * m_sizeXYZ;
+
+  for ( Int n = 0; n < m_sizeXYZ; n++ )
+  {
+    ContextModel tmpContextModel;
+    tmpContextModel.init( qp, ctxModel[ n ] );
+
+    // Map the 64 CABAC states to their corresponding probability values
+    static Double aStateToProbLPS[] = {0.50000000, 0.47460857, 0.45050660, 0.42762859, 0.40591239, 0.38529900, 0.36573242, 0.34715948, 0.32952974, 0.31279528, 0.29691064, 0.28183267, 0.26752040, 0.25393496, 0.24103941, 0.22879875, 0.21717969, 0.20615069, 0.19568177, 0.18574449, 0.17631186, 0.16735824, 0.15885931, 0.15079198, 0.14313433, 0.13586556, 0.12896592, 0.12241667, 0.11620000, 0.11029903, 0.10469773, 0.09938088, 0.09433404, 0.08954349, 0.08499621, 0.08067986, 0.07658271, 0.07269362, 0.06900203, 0.06549791, 0.06217174, 0.05901448, 0.05601756, 0.05317283, 0.05047256, 0.04790942, 0.04547644, 0.04316702, 0.04097487, 0.03889405, 0.03691890, 0.03504406, 0.03326442, 0.03157516, 0.02997168, 0.02844963, 0.02700488, 0.02563349, 0.02433175, 0.02309612, 0.02192323, 0.02080991, 0.01975312, 0.01875000};
+
+    Double probLPS          = aStateToProbLPS[ m_contextModel[ n ].getState() ];
+    Double prob0, prob1;
+    if (m_contextModel[ n ].getMps()==1)
+    {
+      prob0 = probLPS;
+      prob1 = 1.0-prob0;
+    }
+    else
+    {
+      prob1 = probLPS;
+      prob0 = 1.0-prob1;
+    }
+
+    if (m_contextModel[ n ].getBinsCoded()>0)
+    {
+      cost += (UInt) (prob0 * tmpContextModel.getEntropyBits( 0 ) + prob1 * tmpContextModel.getEntropyBits( 1 ));
+    }
+  }
+
+  return cost;
+}
+//! \}
Index: /tags/SHM-9.0/source/Lib/TLibCommon/ContextModel3DBuffer.h
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibCommon/ContextModel3DBuffer.h	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibCommon/ContextModel3DBuffer.h	(revision 1088)
@@ -0,0 +1,98 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     ContextModel3DBuffer.h
+    \brief    context model 3D buffer class (header)
+*/
+
+#ifndef __CONTEXTMODEL3DBUFFER__
+#define __CONTEXTMODEL3DBUFFER__
+
+#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( const 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: /tags/SHM-9.0/source/Lib/TLibCommon/ContextTables.h
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibCommon/ContextTables.h	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibCommon/ContextTables.h	(revision 1088)
@@ -0,0 +1,502 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     ContextTables.h
+    \brief    Defines constants and tables for SBAC
+    \todo     number of context models is not matched to actual use, should be fixed
+*/
+
+#ifndef __CONTEXTTABLES__
+#define __CONTEXTTABLES__
+
+//! \ingroup TLibCommon
+//! \{
+
+// ====================================================================================================================
+// Constants
+// ====================================================================================================================
+
+#define MAX_NUM_CTX_MOD             512       ///< maximum number of supported contexts
+
+#define NUM_SPLIT_FLAG_CTX            3       ///< number of context models for split flag
+#define NUM_SKIP_FLAG_CTX             3       ///< number of context models for skip flag
+
+#define NUM_MERGE_FLAG_EXT_CTX        1       ///< number of context models for merge flag of merge extended
+#define NUM_MERGE_IDX_EXT_CTX         1       ///< number of context models for merge index of merge extended
+
+#define NUM_PART_SIZE_CTX             4       ///< number of context models for partition size
+#define NUM_PRED_MODE_CTX             1       ///< number of context models for prediction mode
+
+#define NUM_ADI_CTX                   1       ///< number of context models for intra prediction
+
+#define NUM_CHROMA_PRED_CTX           2       ///< number of context models for intra prediction (chroma)
+#define NUM_INTER_DIR_CTX             5       ///< number of context models for inter prediction direction
+#define NUM_MV_RES_CTX                2       ///< number of context models for motion vector difference
+#define NUM_CHROMA_QP_ADJ_FLAG_CTX    1       ///< number of context models for chroma_qp_adjustment_flag
+#define NUM_CHROMA_QP_ADJ_IDC_CTX     1       ///< number of context models for chroma_qp_adjustment_idc
+
+#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_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_EXPLICIT_RDPCM_FLAG_CTX   1       ///< number of context models for the flag which specifies whether to use RDPCM on inter coded residues
+#define NUM_EXPLICIT_RDPCM_DIR_CTX    1       ///< number of context models for the flag which specifies which RDPCM direction is used on inter coded residues
+
+//--------------------------------------------------------------------------------------------------
+
+// context size definitions for significance map
+
+#define NUM_SIG_FLAG_CTX_LUMA        28       ///< number of context models for luma sig flag
+#define NUM_SIG_FLAG_CTX_CHROMA      16       ///< number of context models for chroma sig flag
+
+//                                                                                                           |----Luma-----|  |---Chroma----|
+static const UInt significanceMapContextSetStart         [MAX_NUM_CHANNEL_TYPE][CONTEXT_NUMBER_OF_TYPES] = { {0,  9, 21, 27}, {0,  9, 12, 15} };
+static const UInt significanceMapContextSetSize          [MAX_NUM_CHANNEL_TYPE][CONTEXT_NUMBER_OF_TYPES] = { {9, 12,  6,  1}, {9,  3,  3,  1} };
+static const UInt nonDiagonalScan8x8ContextOffset        [MAX_NUM_CHANNEL_TYPE]                          = {  6,               0              };
+static const UInt notFirstGroupNeighbourhoodContextOffset[MAX_NUM_CHANNEL_TYPE]                          = {  3,               0              };
+
+//------------------
+
+#define NEIGHBOURHOOD_00_CONTEXT_1_THRESHOLD_4x4  3
+#define NEIGHBOURHOOD_00_CONTEXT_2_THRESHOLD_4x4  1
+
+//------------------
+
+#define FIRST_SIG_FLAG_CTX_LUMA                   0
+#define FIRST_SIG_FLAG_CTX_CHROMA     (FIRST_SIG_FLAG_CTX_LUMA + NUM_SIG_FLAG_CTX_LUMA)
+
+#define NUM_SIG_FLAG_CTX              (NUM_SIG_FLAG_CTX_LUMA + NUM_SIG_FLAG_CTX_CHROMA)       ///< number of context models for sig flag
+
+//--------------------------------------------------------------------------------------------------
+
+// context size definitions for last significant coefficient position
+
+#define NUM_CTX_LAST_FLAG_SETS         2
+
+#define NUM_CTX_LAST_FLAG_XY          15      ///< number of context models for last coefficient position
+
+//--------------------------------------------------------------------------------------------------
+
+// context size definitions for greater-than-one and greater-than-two maps
+
+#define NUM_ONE_FLAG_CTX_PER_SET       4      ///< number of context models for greater than 1 flag in a set
+#define NUM_ABS_FLAG_CTX_PER_SET       1      ///< number of context models for greater than 2 flag in a set
+
+//------------------
+
+#define NUM_CTX_SETS_LUMA              4      ///< number of context model sets for luminance
+#define NUM_CTX_SETS_CHROMA            2      ///< number of context model sets for combined chrominance
+
+#define FIRST_CTX_SET_LUMA             0      ///< index of first luminance context set
+
+//------------------
+
+#define NUM_ONE_FLAG_CTX_LUMA         (NUM_ONE_FLAG_CTX_PER_SET * NUM_CTX_SETS_LUMA)           ///< number of context models for greater than 1 flag of luma
+#define NUM_ONE_FLAG_CTX_CHROMA       (NUM_ONE_FLAG_CTX_PER_SET * NUM_CTX_SETS_CHROMA)         ///< number of context models for greater than 1 flag of chroma
+
+#define NUM_ABS_FLAG_CTX_LUMA         (NUM_ABS_FLAG_CTX_PER_SET * NUM_CTX_SETS_LUMA)           ///< number of context models for greater than 2 flag of luma
+#define NUM_ABS_FLAG_CTX_CHROMA       (NUM_ABS_FLAG_CTX_PER_SET * NUM_CTX_SETS_CHROMA)         ///< number of context models for greater than 2 flag of chroma
+
+#define NUM_ONE_FLAG_CTX              (NUM_ONE_FLAG_CTX_LUMA + NUM_ONE_FLAG_CTX_CHROMA)        ///< number of context models for greater than 1 flag
+#define NUM_ABS_FLAG_CTX              (NUM_ABS_FLAG_CTX_LUMA + NUM_ABS_FLAG_CTX_CHROMA)        ///< number of context models for greater than 2 flag
+
+#define FIRST_CTX_SET_CHROMA          (FIRST_CTX_SET_LUMA + NUM_CTX_SETS_LUMA)                 ///< index of first chrominance context set
+
+//--------------------------------------------------------------------------------------------------
+
+// context size definitions for CBF
+
+#define NUM_QT_CBF_CTX_SETS           2
+
+#define NUM_QT_CBF_CTX_PER_SET        5       ///< number of context models for QT CBF
+
+#define FIRST_CBF_CTX_LUMA            0       ///< index of first luminance CBF context
+
+#define FIRST_CBF_CTX_CHROMA          (FIRST_CBF_CTX_LUMA + NUM_QT_CBF_CTX_PER_SET)  ///< index of first chrominance CBF context
+
+
+//--------------------------------------------------------------------------------------------------
+
+#define NUM_MVP_IDX_CTX               1       ///< number of context models for MVP index
+
+#define NUM_SAO_MERGE_FLAG_CTX        1       ///< number of context models for SAO merge flags
+#define NUM_SAO_TYPE_IDX_CTX          1       ///< number of context models for SAO type index
+
+#define NUM_TRANSFORMSKIP_FLAG_CTX    1       ///< number of context models for transform skipping 
+
+#define NUM_CU_TRANSQUANT_BYPASS_FLAG_CTX  1 
+
+#define NUM_CROSS_COMPONENT_PREDICTION_CTX 10
+
+#define CNU                          154      ///< dummy initialization value for unused context models 'Context model Not Used'
+
+
+// ====================================================================================================================
+// Tables
+// ====================================================================================================================
+
+// initial probability for cu_transquant_bypass flag
+static const UChar
+INIT_CU_TRANSQUANT_BYPASS_FLAG[NUMBER_OF_SLICE_TYPES][NUM_CU_TRANSQUANT_BYPASS_FLAG_CTX] =
+{
+  { 154 }, 
+  { 154 }, 
+  { 154 }, 
+};
+
+// initial probability for split flag
+static const UChar 
+INIT_SPLIT_FLAG[NUMBER_OF_SLICE_TYPES][NUM_SPLIT_FLAG_CTX] =
+{
+  { 107,  139,  126, },
+  { 107,  139,  126, }, 
+  { 139,  141,  157, }, 
+};
+
+static const UChar 
+INIT_SKIP_FLAG[NUMBER_OF_SLICE_TYPES][NUM_SKIP_FLAG_CTX] =
+{
+  { 197,  185,  201, }, 
+  { 197,  185,  201, }, 
+  { CNU,  CNU,  CNU, }, 
+};
+
+static const UChar
+INIT_MERGE_FLAG_EXT[NUMBER_OF_SLICE_TYPES][NUM_MERGE_FLAG_EXT_CTX] =
+{
+  { 154, }, 
+  { 110, }, 
+  { CNU, }, 
+};
+
+static const UChar 
+INIT_MERGE_IDX_EXT[NUMBER_OF_SLICE_TYPES][NUM_MERGE_IDX_EXT_CTX] =
+{
+  { 137, }, 
+  { 122, }, 
+  { CNU, }, 
+};
+
+static const UChar 
+INIT_PART_SIZE[NUMBER_OF_SLICE_TYPES][NUM_PART_SIZE_CTX] =
+{
+  { 154,  139,  154,  154 },
+  { 154,  139,  154,  154 },
+  { 184,  CNU,  CNU,  CNU },
+};
+
+static const UChar 
+INIT_PRED_MODE[NUMBER_OF_SLICE_TYPES][NUM_PRED_MODE_CTX] =
+{
+  { 134, }, 
+  { 149, }, 
+  { CNU, }, 
+};
+
+static const UChar 
+INIT_INTRA_PRED_MODE[NUMBER_OF_SLICE_TYPES][NUM_ADI_CTX] =
+{
+  { 183, }, 
+  { 154, }, 
+  { 184, }, 
+};
+
+static const UChar 
+INIT_CHROMA_PRED_MODE[NUMBER_OF_SLICE_TYPES][NUM_CHROMA_PRED_CTX] =
+{
+  { 152,  139, }, 
+  { 152,  139, }, 
+  {  63,  139, }, 
+};
+
+static const UChar 
+INIT_INTER_DIR[NUMBER_OF_SLICE_TYPES][NUM_INTER_DIR_CTX] =
+{
+  {  95,   79,   63,   31,  31, }, 
+  {  95,   79,   63,   31,  31, }, 
+  { CNU,  CNU,  CNU,  CNU, CNU, }, 
+};
+
+static const UChar 
+INIT_MVD[NUMBER_OF_SLICE_TYPES][NUM_MV_RES_CTX] =
+{
+  { 169,  198, }, 
+  { 140,  198, }, 
+  { CNU,  CNU, }, 
+};
+
+static const UChar 
+INIT_REF_PIC[NUMBER_OF_SLICE_TYPES][NUM_REF_NO_CTX] =
+{
+  { 153,  153 }, 
+  { 153,  153 }, 
+  { CNU,  CNU }, 
+};
+
+static const UChar 
+INIT_DQP[NUMBER_OF_SLICE_TYPES][NUM_DELTA_QP_CTX] =
+{
+  { 154,  154,  154, }, 
+  { 154,  154,  154, }, 
+  { 154,  154,  154, }, 
+};
+
+static const UChar 
+INIT_CHROMA_QP_ADJ_FLAG[NUMBER_OF_SLICE_TYPES][NUM_CHROMA_QP_ADJ_FLAG_CTX] =
+{
+  { 154, },
+  { 154, },
+  { 154, },
+};
+
+static const UChar
+INIT_CHROMA_QP_ADJ_IDC[NUMBER_OF_SLICE_TYPES][NUM_CHROMA_QP_ADJ_IDC_CTX] =
+{
+  { 154, },
+  { 154, },
+  { 154, },
+};
+
+//--------------------------------------------------------------------------------------------------
+
+//Initialisation for CBF
+
+//                                 |---------Luminance---------|
+#define BSLICE_LUMA_CBF_CONTEXT     153,  111,  CNU,  CNU,  CNU
+#define PSLICE_LUMA_CBF_CONTEXT     153,  111,  CNU,  CNU,  CNU
+#define ISLICE_LUMA_CBF_CONTEXT     111,  141,  CNU,  CNU,  CNU
+//                                 |--------Chrominance--------|
+#define BSLICE_CHROMA_CBF_CONTEXT   149,   92,  167,  154,  154
+#define PSLICE_CHROMA_CBF_CONTEXT   149,  107,  167,  154,  154
+#define ISLICE_CHROMA_CBF_CONTEXT    94,  138,  182,  154,  154
+
+
+static const UChar 
+INIT_QT_CBF[NUMBER_OF_SLICE_TYPES][NUM_QT_CBF_CTX_SETS * NUM_QT_CBF_CTX_PER_SET] =
+{
+  { BSLICE_LUMA_CBF_CONTEXT, BSLICE_CHROMA_CBF_CONTEXT },
+  { PSLICE_LUMA_CBF_CONTEXT, PSLICE_CHROMA_CBF_CONTEXT },
+  { ISLICE_LUMA_CBF_CONTEXT, ISLICE_CHROMA_CBF_CONTEXT },
+};
+
+
+//--------------------------------------------------------------------------------------------------
+
+static const UChar
+INIT_QT_ROOT_CBF[NUMBER_OF_SLICE_TYPES][NUM_QT_ROOT_CBF_CTX] =
+{
+  {  79, }, 
+  {  79, }, 
+  { CNU, }, 
+};
+
+
+//--------------------------------------------------------------------------------------------------
+
+//Initialisation for last-significant-position
+
+//                                           |------------------------------Luminance----------------------------------|
+#define BSLICE_LUMA_LAST_POSITION_CONTEXT     125, 110, 124, 110,  95,  94, 125, 111, 111,  79, 125, 126, 111, 111,  79
+#define PSLICE_LUMA_LAST_POSITION_CONTEXT     125, 110,  94, 110,  95,  79, 125, 111, 110,  78, 110, 111, 111,  95,  94
+#define ISLICE_LUMA_LAST_POSITION_CONTEXT     110, 110, 124, 125, 140, 153, 125, 127, 140, 109, 111, 143, 127, 111,  79
+//                                           |------------------------------Chrominance--------------------------------|
+#define BSLICE_CHROMA_LAST_POSITION_CONTEXT   108, 123,  93, CNU, CNU, CNU, CNU, CNU, CNU, CNU, CNU, CNU, CNU, CNU, CNU
+#define PSLICE_CHROMA_LAST_POSITION_CONTEXT   108, 123, 108, CNU, CNU, CNU, CNU, CNU, CNU, CNU, CNU, CNU, CNU, CNU, CNU
+#define ISLICE_CHROMA_LAST_POSITION_CONTEXT   108, 123,  63, CNU, CNU, CNU, CNU, CNU, CNU, CNU, CNU, CNU, CNU, CNU, CNU
+
+
+static const UChar 
+INIT_LAST[NUMBER_OF_SLICE_TYPES][NUM_CTX_LAST_FLAG_SETS * NUM_CTX_LAST_FLAG_XY] =
+{
+  { BSLICE_LUMA_LAST_POSITION_CONTEXT, BSLICE_CHROMA_LAST_POSITION_CONTEXT },
+  { PSLICE_LUMA_LAST_POSITION_CONTEXT, PSLICE_CHROMA_LAST_POSITION_CONTEXT },
+  { ISLICE_LUMA_LAST_POSITION_CONTEXT, ISLICE_CHROMA_LAST_POSITION_CONTEXT },
+};
+
+
+//--------------------------------------------------------------------------------------------------
+
+static const UChar 
+INIT_SIG_CG_FLAG[NUMBER_OF_SLICE_TYPES][2 * NUM_SIG_CG_FLAG_CTX] =
+{
+  { 121,  140,  
+    61,  154, 
+  }, 
+  { 121,  140, 
+    61,  154, 
+  }, 
+  {  91,  171,  
+    134,  141, 
+  }, 
+};
+
+
+//--------------------------------------------------------------------------------------------------
+
+//Initialisation for significance map
+
+//                                          |-DC-|  |-----------------4x4------------------|  |------8x8 Diagonal Scan------|  |----8x8 Non-Diagonal Scan----|  |-NxN First group-|  |-NxN Other group-| |-Single context-|
+//                                          |    |  |                                      |  |-First Group-| |-Other Group-|  |-First Group-| |-Other Group-|  |                 |  |                 | |                |
+#define BSLICE_LUMA_SIGNIFICANCE_CONTEXT     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,        140
+#define PSLICE_LUMA_SIGNIFICANCE_CONTEXT     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,        140
+#define ISLICE_LUMA_SIGNIFICANCE_CONTEXT     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,        141
+
+//                                          |-DC-|  |-----------------4x4------------------|  |-8x8 Any group-|  |-NxN Any group-| |-Single context-|
+#define BSLICE_CHROMA_SIGNIFICANCE_CONTEXT   170,    153, 138, 138, 122, 121, 122, 121, 167,   151,  183,  140,   151,  183,  140,        140
+#define PSLICE_CHROMA_SIGNIFICANCE_CONTEXT   170,    153, 123, 123, 107, 121, 107, 121, 167,   151,  183,  140,   151,  183,  140,        140
+#define ISLICE_CHROMA_SIGNIFICANCE_CONTEXT   140,    139, 182, 182, 152, 136, 152, 136, 153,   136,  139,  111,   136,  139,  111,        111
+
+//------------------------------------------------
+
+static const UChar 
+INIT_SIG_FLAG[NUMBER_OF_SLICE_TYPES][NUM_SIG_FLAG_CTX] =
+{
+  { BSLICE_LUMA_SIGNIFICANCE_CONTEXT, BSLICE_CHROMA_SIGNIFICANCE_CONTEXT },
+  { PSLICE_LUMA_SIGNIFICANCE_CONTEXT, PSLICE_CHROMA_SIGNIFICANCE_CONTEXT },
+  { ISLICE_LUMA_SIGNIFICANCE_CONTEXT, ISLICE_CHROMA_SIGNIFICANCE_CONTEXT },
+};
+
+
+//--------------------------------------------------------------------------------------------------
+
+//Initialisation for greater-than-one flags and greater-than-two flags
+
+//                                 |------Set 0-------| |------Set 1-------| |------Set 2-------| |------Set 3-------|
+#define BSLICE_LUMA_ONE_CONTEXT     154, 196, 167, 167,  154, 152, 167, 182,  182, 134, 149, 136,  153, 121, 136, 122
+#define PSLICE_LUMA_ONE_CONTEXT     154, 196, 196, 167,  154, 152, 167, 182,  182, 134, 149, 136,  153, 121, 136, 137
+#define ISLICE_LUMA_ONE_CONTEXT     140,  92, 137, 138,  140, 152, 138, 139,  153,  74, 149,  92,  139, 107, 122, 152
+
+#define BSLICE_LUMA_ABS_CONTEXT     107,                 167,                  91,                 107
+#define PSLICE_LUMA_ABS_CONTEXT     107,                 167,                  91,                 122
+#define ISLICE_LUMA_ABS_CONTEXT     138,                 153,                 136,                 167
+
+//                                 |------Set 4-------| |------Set 5-------|
+#define BSLICE_CHROMA_ONE_CONTEXT   169, 208, 166, 167,  154, 152, 167, 182
+#define PSLICE_CHROMA_ONE_CONTEXT   169, 194, 166, 167,  154, 167, 137, 182
+#define ISLICE_CHROMA_ONE_CONTEXT   140, 179, 166, 182,  140, 227, 122, 197
+
+#define BSLICE_CHROMA_ABS_CONTEXT   107,                 167
+#define PSLICE_CHROMA_ABS_CONTEXT   107,                 167
+#define ISLICE_CHROMA_ABS_CONTEXT   152,                 152
+
+
+//------------------------------------------------
+
+static const UChar 
+INIT_ONE_FLAG[NUMBER_OF_SLICE_TYPES][NUM_ONE_FLAG_CTX] =
+{
+  { BSLICE_LUMA_ONE_CONTEXT, BSLICE_CHROMA_ONE_CONTEXT },
+  { PSLICE_LUMA_ONE_CONTEXT, PSLICE_CHROMA_ONE_CONTEXT },
+  { ISLICE_LUMA_ONE_CONTEXT, ISLICE_CHROMA_ONE_CONTEXT },
+};
+
+static const UChar 
+INIT_ABS_FLAG[NUMBER_OF_SLICE_TYPES][NUM_ABS_FLAG_CTX] =
+{
+  { BSLICE_LUMA_ABS_CONTEXT, BSLICE_CHROMA_ABS_CONTEXT },
+  { PSLICE_LUMA_ABS_CONTEXT, PSLICE_CHROMA_ABS_CONTEXT },
+  { ISLICE_LUMA_ABS_CONTEXT, ISLICE_CHROMA_ABS_CONTEXT },
+};
+
+
+//--------------------------------------------------------------------------------------------------
+
+static const UChar 
+INIT_MVP_IDX[NUMBER_OF_SLICE_TYPES][NUM_MVP_IDX_CTX] =
+{
+  { 168, },
+  { 168, },
+  { CNU, },
+};
+
+static const UChar 
+INIT_SAO_MERGE_FLAG[NUMBER_OF_SLICE_TYPES][NUM_SAO_MERGE_FLAG_CTX] =
+{
+  { 153,  }, 
+  { 153,  }, 
+  { 153,  }, 
+};
+
+static const UChar 
+INIT_SAO_TYPE_IDX[NUMBER_OF_SLICE_TYPES][NUM_SAO_TYPE_IDX_CTX] =
+{
+  { 160, },
+  { 185, },
+  { 200, },
+};
+
+static const UChar
+INIT_TRANS_SUBDIV_FLAG[NUMBER_OF_SLICE_TYPES][NUM_TRANS_SUBDIV_FLAG_CTX] =
+{
+  { 224,  167,  122, },
+  { 124,  138,   94, },
+  { 153,  138,  138, },
+};
+
+static const UChar
+INIT_TRANSFORMSKIP_FLAG[NUMBER_OF_SLICE_TYPES][2*NUM_TRANSFORMSKIP_FLAG_CTX] =
+{
+  { 139,  139}, 
+  { 139,  139}, 
+  { 139,  139}, 
+};
+
+static const UChar
+INIT_EXPLICIT_RDPCM_FLAG[NUMBER_OF_SLICE_TYPES][2*NUM_EXPLICIT_RDPCM_FLAG_CTX] =
+{
+  {139, 139},
+  {139, 139},
+  {CNU, CNU}
+};
+
+static const UChar
+INIT_EXPLICIT_RDPCM_DIR[NUMBER_OF_SLICE_TYPES][2*NUM_EXPLICIT_RDPCM_DIR_CTX] =
+{
+  {139, 139},
+  {139, 139},
+  {CNU, CNU}
+};
+
+static const UChar
+INIT_CROSS_COMPONENT_PREDICTION[NUMBER_OF_SLICE_TYPES][NUM_CROSS_COMPONENT_PREDICTION_CTX] =
+{
+  { 154, 154, 154, 154, 154, 154, 154, 154, 154, 154 },
+  { 154, 154, 154, 154, 154, 154, 154, 154, 154, 154 },
+  { 154, 154, 154, 154, 154, 154, 154, 154, 154, 154 },
+};
+
+//! \}
+
+#endif
Index: /tags/SHM-9.0/source/Lib/TLibCommon/Debug.cpp
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibCommon/Debug.cpp	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibCommon/Debug.cpp	(revision 1088)
@@ -0,0 +1,449 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     Debug.cpp
+    \brief    Defines types and objects for environment-variable-based debugging and feature control
+*/
+
+#include "Debug.h"
+#include <algorithm>
+#include <math.h>
+#include "TComDataCU.h"
+#include "TComPic.h"
+#include "TComYuv.h"
+
+static const UInt settingNameWidth  = 66;
+static const UInt settingHelpWidth  = 84;
+static const UInt settingValueWidth = 3;
+
+#ifdef DEBUG_STRING
+// these strings are used to reorder the debug output so that the encoder and decoder match.
+const Char *debug_reorder_data_inter_token[MAX_NUM_COMPONENT+1]
+ = {"Start of channel 0 inter debug\n", "Start of channel 1 inter debug\n", "Start of channel 2 inter debug\n", "End of inter residual debug\n"} ;
+const Char *partSizeToString[NUMBER_OF_PART_SIZES]={"2Nx2N(0)", "2NxN(1)", "Nx2N(2)", "NxN(3)", "2Nx(N/2+3N/2)(4)", "2Nx(3N/2+N/2)(5)", "(N/2+3N/2)x2N(6)", "(3N/2+N/2)x2N(7)"};
+#endif
+
+// --------------------------------------------------------------------------------------------------------------------- //
+
+//EnvVar definition
+
+std::list<std::pair<std::string, std::string> > &EnvVar::getEnvVarList()
+{
+  static std::list<std::pair<std::string, std::string> > varInfoList;
+  return varInfoList;
+}
+
+std::list<EnvVar*> &EnvVar::getEnvVarInUse()
+{
+  static std::list<EnvVar*> varInUseList;
+  return varInUseList;
+}
+
+static inline Void printPair(const std::pair<std::string, std::string> &p)
+{
+  if (p.second=="")
+  {
+    std::cout << "\n" << std::setw(settingNameWidth) << p.first << "\n" << std::endl;
+  }
+  else
+  {
+    std::cout << std::setw(settingNameWidth) << p.first << ":   " << p.second << "\n" << std::endl;
+  }
+}
+
+static inline Void printVal(const EnvVar* env)
+{
+  std::cout << std::setw(settingNameWidth) << env->getName() << " = " << std::setw(settingValueWidth) << env->getInt() << " (string = " << std::setw(15) << env->getString() << ")" << std::endl;
+}
+
+//static inline Bool sameEnvName( const std::pair<std::string, std::string> &a,
+//                                const std::pair<std::string, std::string> &b )
+//{
+//  // only check env name
+//  return (a.first==b.first);
+//}
+
+Void EnvVar::printEnvVar()
+{
+//  getEnvVarList().unique(sameEnvName);
+  if (getEnvVarList().size()!=0)
+  {
+    std::cout << "--- Environment variables:\n" << std::endl;
+    for_each(getEnvVarList().begin(), getEnvVarList().end(), printPair);
+  }
+  std::cout << std::endl;
+}
+
+Void EnvVar::printEnvVarInUse()
+{
+  if (getEnvVarInUse().size()!=0)
+  {
+    std::cout << "RExt Environment variables set as follows: \n" << std::endl;
+    for_each(getEnvVarInUse().begin(), getEnvVarInUse().end(), printVal);
+  }
+  std::cout << std::endl;
+}
+
+EnvVar::EnvVar(const std::string &sName, const std::string &sDefault, const std::string &sHelp) :
+                                                                m_sName(sName),
+                                                                m_sHelp(sHelp),
+                                                                m_sVal(),
+                                                                m_dVal(0),
+                                                                m_iVal(0),
+                                                                m_bSet(false)
+{
+  if (getenv(m_sName.c_str()))
+  {
+    m_sVal = getenv(m_sName.c_str());
+    m_bSet = true;
+    getEnvVarInUse().push_back(this);
+  }
+  else m_sVal = sDefault;
+
+  m_dVal = strtod(m_sVal.c_str(), 0);
+  m_iVal = Int(m_dVal);
+
+  getEnvVarList().push_back( std::pair<std::string, std::string>(m_sName, indentNewLines(lineWrap(splitOnSettings(m_sHelp), settingHelpWidth), (settingNameWidth + 4))) );
+}
+
+
+// --------------------------------------------------------------------------------------------------------------------- //
+
+// Debug environment variables:
+
+EnvVar Debug("-- Debugging","","");
+
+EnvVar DebugOptionList::DebugSBAC             ("DEBUG_SBAC",        "0", "Output debug data from SBAC entropy coder (coefficient data etc.)"                              );
+EnvVar DebugOptionList::DebugRQT              ("DEBUG_RQT",         "0", "Output RQT debug data from entropy coder"                                                       );
+EnvVar DebugOptionList::DebugPred             ("DEBUG_PRED",        "0", "Output prediction debug"                                                                        );
+EnvVar DebugOptionList::ForceLumaMode         ("FORCE_LUMA_MODE",   "0", "Force a particular intra direction for Luma (0-34)"                                             );
+EnvVar DebugOptionList::ForceChromaMode       ("FORCE_CHROMA_MODE", "0", "Force a particular intra direction for chroma (0-5)"                                            );
+
+#ifdef DEBUG_STRING
+EnvVar DebugOptionList::DebugString_Structure ("DEBUG_STRUCTURE",   "0", "Produce output on chosen structure                        bit0=intra, bit1=inter");
+EnvVar DebugOptionList::DebugString_Pred      ("DEBUG_PRED",        "0", "Produce output on prediction data.                        bit0=intra, bit1=inter");
+EnvVar DebugOptionList::DebugString_Resi      ("DEBUG_RESI",        "0", "Produce output on residual data.                          bit0=intra, bit1=inter");
+EnvVar DebugOptionList::DebugString_Reco      ("DEBUG_RECO",        "0", "Produce output on reconstructed data.                     bit0=intra, bit1=inter");
+EnvVar DebugOptionList::DebugString_InvTran   ("DEBUG_INV_QT",      "0", "Produce output on inverse-quantiser and transform stages. bit0=intra, bit1=inter");
+#endif
+
+// --------------------------------------------------------------------------------------------------------------------- //
+
+//macro value printing function
+
+Void printMacroSettings()
+{
+  std::cout << "Non-environment-variable-controlled macros set as follows: \n" << std::endl;
+
+  //------------------------------------------------
+
+  //setting macros
+
+  PRINT_CONSTANT(RExt__DECODER_DEBUG_BIT_STATISTICS,                                settingNameWidth, settingValueWidth);
+  PRINT_CONSTANT(RExt__HIGH_BIT_DEPTH_SUPPORT,                                      settingNameWidth, settingValueWidth);
+  PRINT_CONSTANT(RExt__HIGH_PRECISION_FORWARD_TRANSFORM,                            settingNameWidth, settingValueWidth);
+
+  PRINT_CONSTANT(O0043_BEST_EFFORT_DECODING,                                        settingNameWidth, settingValueWidth);
+
+  PRINT_CONSTANT(RD_TEST_SAO_DISABLE_AT_PICTURE_LEVEL,                              settingNameWidth, settingValueWidth);
+
+  //------------------------------------------------
+
+  std::cout << std::endl;
+}
+
+
+// --------------------------------------------------------------------------------------------------------------------- //
+
+//Debugging
+
+UInt  g_debugCounter  = 0;
+Bool  g_printDebug    = false;
+Void* g_debugAddr     = NULL;
+
+#ifdef DEBUG_ENCODER_SEARCH_BINS
+const UInt debugEncoderSearchBinTargetLine = 0;
+const UInt debugEncoderSearchBinWindow     = 1000000;
+#endif
+
+#ifdef DEBUG_CABAC_BINS
+const UInt debugCabacBinTargetLine = 0;
+const UInt debugCabacBinWindow     = 1000000;
+#endif
+
+Void printSBACCoeffData(  const UInt          lastX,
+                          const UInt          lastY,
+                          const UInt          width,
+                          const UInt          height,
+                          const UInt          chan,
+                          const UInt          absPart,
+                          const UInt          scanIdx,
+                          const TCoeff *const pCoeff,
+                          const Bool          finalEncode
+                        )
+{
+  if (DebugOptionList::DebugSBAC.getInt()!=0 && finalEncode)
+  {
+    std::cout << "Size: " << width << "x" << height << ", Last X/Y: (" << lastX << ", " << lastY << "), absPartIdx: " << absPart << ", scanIdx: " << scanIdx << ", chan: " << chan << std::endl;
+    for (Int i=0; i<width*height; i++)
+    {
+      std::cout << std::setw(3) << pCoeff[i];// + dcVal;
+      if (i%width == width-1) std::cout << std::endl;
+      else                    std::cout << ",";
+    }
+    std::cout << std::endl;
+  }
+}
+
+Void printCbfArray( TComDataCU* pcCU  )
+{
+  const UInt CUSizeInParts = pcCU->getWidth(0)/4;
+  const UInt numValidComp=pcCU->getPic()->getNumberValidComponents();
+  for (UInt ch=0; ch<numValidComp; ch++)
+  {
+    const ComponentID compID=ComponentID(ch);
+    printf("channel: %d\n", ch);
+    for (Int y=0; y<CUSizeInParts; y++)
+    {
+      for (Int x=0; x<CUSizeInParts; x++)
+      {
+        printf(x+1==CUSizeInParts?"%3d\n":"%3d, ", pcCU->getCbf(compID)[g_auiRasterToZscan[y*CUSizeInParts + x]]);
+      }
+    }
+  }
+}
+
+UInt getDecimalWidth(const Double value)
+{
+  return (value == 0) ? 1 : (UInt(floor(log10(fabs(value)))) + ((value < 0) ? 2 : 1));
+                                                               //for the minus sign
+}
+
+UInt getZScanIndex(const UInt x, const UInt y)
+{
+  UInt remainingX = x;
+  UInt remainingY = y;
+  UInt offset     = 0;
+  UInt result     = 0;
+
+  while ((remainingX != 0) || (remainingY != 0))
+  {
+    result |= ((remainingX & 0x1) << offset) | ((remainingY & 0x1) << (offset + 1));
+
+    remainingX >>= 1;
+    remainingY >>= 1;
+    offset      += 2;
+  }
+
+  return result;
+}
+
+
+// --------------------------------------------------------------------------------------------------------------------- //
+
+//String manipulation functions for aligning and wrapping printed text
+
+
+std::string splitOnSettings(const std::string &input)
+{
+  std::string result = input;
+
+  std::string::size_type searchFromPosition = 0;
+
+  while (searchFromPosition < result.length())
+  {
+    //find the " = " that is used to define each setting
+    std::string::size_type equalsPosition = result.find(" = ", searchFromPosition);
+
+    if (equalsPosition == std::string::npos) break;
+
+    //then find the end of the numeric characters
+    std::string::size_type splitPosition = result.find_last_of("1234567890", equalsPosition);
+
+    //then find the last space before the first numeric character...
+    if (splitPosition != std::string::npos) splitPosition = result.find_last_of(' ', splitPosition);
+
+    //...and replace it with a new line
+    if (splitPosition != std::string::npos) result.replace(splitPosition, 1, 1, '\n');
+
+    //start the next search from the end of the " = " string
+    searchFromPosition = (equalsPosition + 3);
+  }
+
+  return result;
+}
+
+
+std::string lineWrap(const std::string &input, const UInt maximumLineLength)
+{
+  if (maximumLineLength == 0) return input;
+  std::string result = input;
+
+  std::string::size_type lineStartPosition = result.find_first_not_of(' '); //don't wrap any leading spaces in the string
+
+  while (lineStartPosition != std::string::npos)
+  {
+    //------------------------------------------------
+
+    const std::string::size_type searchFromPosition = lineStartPosition + maximumLineLength;
+
+    if (searchFromPosition >= result.length()) break;
+
+    //------------------------------------------------
+
+    //first check to see if there is another new line character before the maximum line length
+    //we can't use find for this unfortunately because it doesn't take both a beginning and an end for its search range
+    std::string::size_type nextLineStartPosition = std::string::npos;
+    for (std::string::size_type currentPosition = lineStartPosition; currentPosition <= searchFromPosition; currentPosition++)
+    {
+      if (result[currentPosition] == '\n') { nextLineStartPosition = currentPosition + 1; break; }
+    }
+
+    //------------------------------------------------
+
+    //if there ia another new line character before the maximum line length, we need to start this loop again from that position
+    if (nextLineStartPosition != std::string::npos) lineStartPosition = nextLineStartPosition;
+    else
+    {
+      std::string::size_type spacePosition = std::string::npos;
+
+      //search backwards for the last space character (must use signed Int because lineStartPosition can be 0)
+      for (Int currentPosition = Int(searchFromPosition); currentPosition >= Int(lineStartPosition); currentPosition--)
+      {
+        if (result[currentPosition] == ' ') { spacePosition = currentPosition; break; }
+      }
+
+      //if we didn't find a space searching backwards, we must hyphenate
+      if (spacePosition == std::string::npos)
+      {
+        result.insert(searchFromPosition, "-\n");
+        lineStartPosition = searchFromPosition + 2; //make sure the next search ignores the hyphen
+      }
+      else //if we found a space to split on, replace it with a new line character
+      {
+        result.replace(spacePosition, 1, 1, '\n');
+        lineStartPosition = spacePosition + 1;
+      }
+    }
+
+    //------------------------------------------------
+  }
+
+  return result;
+}
+
+
+std::string indentNewLines(const std::string &input, const UInt indentBy)
+{
+  std::string result = input;
+
+  const std::string indentString(indentBy, ' ');
+  std::string::size_type offset = 0;
+
+  while ((offset = result.find('\n', offset)) != std::string::npos)
+  {
+    if ((++offset) >= result.length()) break; //increment offset so we don't find the same \n again and do no indentation at the end
+    result.insert(offset, indentString);
+  }
+
+  return result;
+}
+
+
+// --------------------------------------------------------------------------------------------------------------------- //
+
+
+Void printBlockToStream( std::ostream &ss, const Char *pLinePrefix, TComYuv &src, const UInt numSubBlocksAcross, const UInt numSubBlocksUp, const UInt defWidth )
+{
+  const UInt numValidComp=src.getNumberValidComponents();
+
+  for (UInt ch=0; ch<numValidComp ; ch++)
+  {
+    const ComponentID compID = ComponentID(ch);
+    const UInt width  = src.getWidth(compID);
+    const UInt height = src.getHeight(compID);
+    const UInt stride = src.getStride(compID);
+    const Pel* blkSrc = src.getAddr(compID);
+    const UInt subBlockWidth=width/numSubBlocksAcross;
+    const UInt subBlockHeight=height/numSubBlocksUp;
+
+    ss << pLinePrefix << " compID: " << compID << "\n";
+    for (UInt y=0; y<height; y++)
+    {
+      if ((y%subBlockHeight)==0 && y!=0)
+        ss << pLinePrefix << '\n';
+
+      ss << pLinePrefix;
+      for (UInt x=0; x<width; x++)
+      {
+        if ((x%subBlockWidth)==0 && x!=0)
+          ss << std::setw(defWidth+2) << "";
+
+        ss << std::setw(defWidth) << blkSrc[y*stride + x] << ' ';
+      }
+      ss << '\n';
+    }
+    ss << pLinePrefix << " --- \n";
+  }
+}
+
+#ifdef DEBUG_STRING
+Int DebugStringGetPredModeMask(PredMode mode)
+{
+  return (mode==MODE_INTRA)?1:2;
+}
+
+Void DebugInterPredResiReco(std::string &sDebug, TComYuv &pred, TComYuv &resi, TComYuv &reco, Int predmode_mask)
+{
+  if (DebugOptionList::DebugString_Pred.getInt()&predmode_mask)
+  {
+    std::stringstream ss(std::stringstream::out);
+    printBlockToStream(ss, "###inter-pred: ", pred);
+    std::string debugTmp;
+    debugTmp=ss.str();
+    sDebug=debugTmp+sDebug;
+  }
+  if (DebugOptionList::DebugString_Resi.getInt()&predmode_mask)
+  {
+    std::stringstream ss(std::stringstream::out);
+    printBlockToStream(ss, "###inter-resi: ", resi);
+    sDebug+=ss.str();
+  }
+  if (DebugOptionList::DebugString_Reco.getInt()&predmode_mask)
+  {
+    std::stringstream ss(std::stringstream::out);
+    printBlockToStream(ss, "###inter-reco: ", reco);
+    sDebug+=ss.str();
+  }
+}
+#endif
Index: /tags/SHM-9.0/source/Lib/TLibCommon/Debug.h
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibCommon/Debug.h	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibCommon/Debug.h	(revision 1088)
@@ -0,0 +1,266 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     Debug.h
+    \brief    Defines types and objects for environment-variable-based debugging and feature control
+*/
+
+#ifndef __DEBUG__
+#define __DEBUG__
+
+#include <iostream>
+#include <iomanip>
+#include <string>
+#include <list>
+#include <stdlib.h>
+#include <sstream>
+#include <TLibCommon/CommonDef.h>
+
+#ifdef DEBUG_STRING
+extern const Char *debug_reorder_data_inter_token[MAX_NUM_COMPONENT+1];
+extern const Char *partSizeToString[NUMBER_OF_PART_SIZES];
+#endif
+
+// ---------------------------------------------------------------------------------------------- //
+
+//constant print-out macro
+
+#define PRINT_CONSTANT(NAME, NAME_WIDTH, VALUE_WIDTH) std::cout << std::setw(NAME_WIDTH) << #NAME << " = " << std::setw(VALUE_WIDTH) << NAME << std::endl;
+
+// ---------------------------------------------------------------------------------------------- //
+
+// ---- Environment variables for test/debug ---- //
+
+class EnvVar
+{
+private:
+  std::string m_sName;
+  std::string m_sHelp;
+  std::string m_sVal;
+  Double      m_dVal;
+  Int         m_iVal;
+  Bool        m_bSet;
+
+public:
+
+  static std::list< std::pair<std::string, std::string> > &getEnvVarList();
+  static std::list<EnvVar*>                               &getEnvVarInUse();
+  static Void printEnvVar();
+  static Void printEnvVarInUse();
+
+  EnvVar(const std::string &sName, const std::string &sDefault, const std::string &sHelp);
+
+  Double              getDouble()   const       { return m_dVal;    }
+  Int                 getInt()      const       { return m_iVal;    }
+  const std::string  &getString()   const       { return m_sVal;    }
+  Bool                isSet()       const       { return m_bSet;    }
+  Bool                isTrue()      const       { return m_iVal!=0; }
+  const std::string  &getName()     const       { return m_sName;   }
+
+};
+
+
+// ---------------------------------------------------------------------------------------------- //
+
+// ---- Control switches for debugging and feature control ---- //
+
+namespace DebugOptionList
+{
+  extern EnvVar DebugSBAC;
+  extern EnvVar DebugRQT;
+  extern EnvVar DebugPred;
+  extern EnvVar ForceLumaMode;
+  extern EnvVar ForceChromaMode;
+
+#ifdef DEBUG_STRING
+  extern EnvVar DebugString_Structure;
+  extern EnvVar DebugString_Pred;
+  extern EnvVar DebugString_Resi;
+  extern EnvVar DebugString_Reco;
+  extern EnvVar DebugString_InvTran;
+#endif
+}
+
+// ---------------------------------------------------------------------------------------------- //
+
+Void printMacroSettings();
+
+// ---------------------------------------------------------------------------------------------- //
+
+//Debugging
+
+extern Bool g_bFinalEncode;
+extern UInt g_debugCounter;
+extern Bool g_printDebug;
+extern Void* g_debugAddr;
+
+#ifdef DEBUG_ENCODER_SEARCH_BINS
+extern const UInt debugEncoderSearchBinTargetLine;
+extern const UInt debugEncoderSearchBinWindow;
+#endif
+
+#ifdef DEBUG_CABAC_BINS
+extern const UInt debugCabacBinTargetLine;
+extern const UInt debugCabacBinWindow;
+#endif
+
+
+Void printSBACCoeffData(  const UInt          lastX,
+                          const UInt          lastY,
+                          const UInt          width,
+                          const UInt          height,
+                          const UInt          chan,
+                          const UInt          absPart,
+                          const UInt          scanIdx,
+                          const TCoeff *const pCoeff,
+                          const Bool          finalEncode=true
+                        );
+
+
+Void printCbfArray( class TComDataCU* pcCU  );
+
+UInt getDecimalWidth(const Double value);
+UInt getZScanIndex(const UInt x, const UInt y);
+
+//template specialisation for Char types to get it to render as a number
+template <typename ValueType> inline Void writeValueToStream       (const ValueType &value, std::ostream &stream, const UInt outputWidth) { stream << std::setw(outputWidth) <<      value;  }
+template <>                   inline Void writeValueToStream<Char >(const Char      &value, std::ostream &stream, const UInt outputWidth) { stream << std::setw(outputWidth) <<  Int(value); }
+template <>                   inline Void writeValueToStream<UChar>(const UChar     &value, std::ostream &stream, const UInt outputWidth) { stream << std::setw(outputWidth) << UInt(value); }
+
+template <typename ValueType>
+Void printBlock(const ValueType    *const source,
+                const UInt                width,
+                const UInt                height,
+                const UInt                stride,
+                const UInt                outputValueWidth = 0,         //if set to 0, the maximum output width will be calculated and used
+                const Bool                onlyPrintEdges   = false,     //print only the top row and left column for printing prediction reference samples
+                const Bool                printInZScan     = false,     //output values in Z-scan format (useful for values addressed by AbsPartIdxes)
+                const Int                 shiftLeftBy      = 0,         //set a negative value to right-shift instead
+                const Bool                printAverage     = false,     //also print the average of the values in the block
+                      std::ostream      & stream           = std::cout)
+{
+  //find the maximum output width
+  UInt outputWidth = outputValueWidth;
+
+  if (outputWidth == 0)
+  {
+    ValueType minimumValue = leftShift(source[0], shiftLeftBy);
+    ValueType maximumValue = minimumValue;
+
+    for (UInt y = 0; y < height; y++)
+      for (UInt x = 0; x < width; x++)
+      {
+        ValueType value = 0;
+
+        if (!onlyPrintEdges || (x == 0) || (y == 0))
+        {
+          value = leftShift(source[printInZScan ? getZScanIndex(x, y) : ((y * stride) + x)], shiftLeftBy);
+        }
+
+        if      (value < minimumValue) minimumValue = value;
+        else if (value > maximumValue) maximumValue = value;
+      }
+
+    outputWidth = std::max<UInt>(getDecimalWidth(Double(minimumValue)), getDecimalWidth(Double(maximumValue))) + 1; //+1 so the numbers don't run into each other
+  }
+
+  //------------------
+  //print out the block
+
+  ValueType valueSum = 0;
+
+  for (UInt y = 0; y < height; y++)
+  {
+    for (UInt x = 0; x < width; x++)
+    {
+      ValueType value = 0;
+
+      if (!onlyPrintEdges || (x == 0) || (y == 0))
+      {
+        value     = leftShift(source[printInZScan ? getZScanIndex(x, y) : ((y * stride) + x)], shiftLeftBy);
+        valueSum += value;
+      }
+
+      writeValueToStream(value, stream, outputWidth);
+    }
+    stream << "\n";
+  }
+
+  const Int valueCount = onlyPrintEdges ? Int((width + height) - 1) : Int(width * height);
+  if (printAverage) stream << "Average: " << (valueSum / valueCount) << "\n";
+  stream << "\n";
+}
+
+
+template <typename T>
+Void printBlockToStream( std::ostream &ss, const Char *pLinePrefix, const T * blkSrc, const UInt width, const UInt height, const UInt stride, const UInt subBlockWidth=0, const UInt subBlockHeight=0, const UInt defWidth=3 )
+{
+  for (UInt y=0; y<height; y++)
+  {
+    if (subBlockHeight!=0 && (y%subBlockHeight)==0 && y!=0)
+      ss << pLinePrefix << '\n';
+
+    ss << pLinePrefix;
+    for (UInt x=0; x<width; x++)
+    {
+      if (subBlockWidth!=0 && (x%subBlockWidth)==0 && x!=0)
+        ss << std::setw(defWidth+2) << "";
+
+      ss << std::setw(defWidth) << blkSrc[y*stride + x] << ' ';
+    }
+    ss << '\n';
+  }
+}
+
+class TComYuv;
+Void printBlockToStream( std::ostream &ss, const Char *pLinePrefix, TComYuv &src, const UInt numSubBlocksAcross=1, const UInt numSubBlocksUp=1, const UInt defWidth=3 );
+
+// ---------------------------------------------------------------------------------------------- //
+
+//String manipulation functions for aligning and wrapping printed text
+
+std::string splitOnSettings(const std::string &input);
+
+std::string lineWrap(const std::string &input, const UInt maximumLineLength);
+
+std::string indentNewLines(const std::string &input, const UInt indentBy);
+
+// ---------------------------------------------------------------------------------------------- //
+
+#ifdef DEBUG_STRING
+  Int DebugStringGetPredModeMask(PredMode mode);
+  Void DebugInterPredResiReco(std::string &sDebug, TComYuv &pred, TComYuv &resi, TComYuv &reco, Int predmode_mask);
+#endif
+
+
+#endif /* __DEBUG__ */
Index: /tags/SHM-9.0/source/Lib/TLibCommon/NAL.h
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibCommon/NAL.h	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibCommon/NAL.h	(revision 1088)
@@ -0,0 +1,127 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#pragma once
+
+#ifndef __NAL__
+#define __NAL__
+
+#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 SVC_EXTENSION
+  UInt        m_layerId;   ///< layer id
+#endif
+  UInt        m_reservedZero6Bits; ///< reserved_zero_6bits
+
+  /** construct an NALunit structure with given header values. */
+  NALUnit(
+    NalUnitType nalUnitType,
+    Int         temporalId = 0,
+#if SVC_EXTENSION
+    UInt        layerId = 0,
+#endif
+    Int         reservedZero6Bits = 0)
+    :m_nalUnitType (nalUnitType)
+    ,m_temporalId  (temporalId)
+#if SVC_EXTENSION
+    ,m_layerId   (layerId)
+#endif
+    ,m_reservedZero6Bits(reservedZero6Bits)
+  {}
+
+  /** default constructor - no initialization; must be perfomed by user */
+  NALUnit() {}
+
+  /** returns true if the NALunit is a slice NALunit */
+  Bool isSlice()
+  {
+    return m_nalUnitType == NAL_UNIT_CODED_SLICE_TRAIL_R
+        || m_nalUnitType == NAL_UNIT_CODED_SLICE_TRAIL_N
+        || m_nalUnitType == NAL_UNIT_CODED_SLICE_TSA_R
+        || m_nalUnitType == NAL_UNIT_CODED_SLICE_TSA_N
+        || m_nalUnitType == NAL_UNIT_CODED_SLICE_STSA_R
+        || m_nalUnitType == NAL_UNIT_CODED_SLICE_STSA_N
+        || m_nalUnitType == NAL_UNIT_CODED_SLICE_BLA_W_LP
+        || m_nalUnitType == NAL_UNIT_CODED_SLICE_BLA_W_RADL
+        || m_nalUnitType == NAL_UNIT_CODED_SLICE_BLA_N_LP
+        || m_nalUnitType == NAL_UNIT_CODED_SLICE_IDR_W_RADL
+        || m_nalUnitType == NAL_UNIT_CODED_SLICE_IDR_N_LP
+        || m_nalUnitType == NAL_UNIT_CODED_SLICE_CRA
+        || m_nalUnitType == NAL_UNIT_CODED_SLICE_RADL_N
+        || m_nalUnitType == NAL_UNIT_CODED_SLICE_RADL_R
+        || m_nalUnitType == NAL_UNIT_CODED_SLICE_RASL_N
+        || m_nalUnitType == NAL_UNIT_CODED_SLICE_RASL_R;
+  }
+  Bool isSei()
+  {
+    return m_nalUnitType == NAL_UNIT_PREFIX_SEI 
+        || m_nalUnitType == NAL_UNIT_SUFFIX_SEI;
+  }
+
+  Bool isVcl()
+  {
+    return ( (UInt)m_nalUnitType < 32 );
+  }
+};
+
+struct OutputNALUnit;
+
+/**
+ * A single NALunit, with complete payload in EBSP format.
+ */
+struct NALUnitEBSP : public NALUnit
+{
+  std::ostringstream m_nalUnitData;
+
+  /**
+   * convert the OutputNALUnit #nalu# into EBSP format by writing out
+   * the NALUnit header, then the rbsp_bytes including any
+   * emulation_prevention_three_byte symbols.
+   */
+  NALUnitEBSP(OutputNALUnit& nalu);
+};
+//! \}
+//! \}
+
+#endif
Index: /tags/SHM-9.0/source/Lib/TLibCommon/SEI.cpp
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibCommon/SEI.cpp	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibCommon/SEI.cpp	(revision 1088)
@@ -0,0 +1,170 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     SEI.cpp
+    \brief    helper functions for SEI handling
+*/
+
+#include "CommonDef.h"
+#include "SEI.h"
+
+//Table D-7 Meaning of camera iso sensitivity indicator and exposure index rating indicator
+Int  Table_exp_indicator[32] = {0, 10, 12, 16, 20, 25, 32, 40, 50, 64, 80, 100, 125, 160, 200, 250, 320, 400, 500, 640, 800, 1000, 1250, 1600, 2000, 2500, 3200, 4000, 5000, 6400, 8000, -1};
+
+#if SUB_BITSTREAM_PROPERTY_SEI
+SEISubBitstreamProperty::SEISubBitstreamProperty()
+{
+  m_activeVpsId             = -1;
+  m_numAdditionalSubStreams = 0;
+  ::memset(m_subBitstreamMode       , 0, sizeof(m_subBitstreamMode));
+  ::memset(m_outputLayerSetIdxToVps , 0, sizeof(m_outputLayerSetIdxToVps));
+  ::memset(m_highestSublayerId      , 0, sizeof(m_highestSublayerId));
+  ::memset(m_avgBitRate             , 0, sizeof(m_avgBitRate));
+  ::memset(m_maxBitRate             , 0, sizeof(m_maxBitRate));
+}
+#endif
+
+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();
+}
+
+
+// Static member
+const Char *SEI::getSEIMessageString(SEI::PayloadType payloadType)
+{
+  switch (payloadType)
+  {
+    case SEI::BUFFERING_PERIOD:                     return "Buffering period";
+    case SEI::PICTURE_TIMING:                       return "Picture timing";
+    case SEI::PAN_SCAN_RECT:                        return "Pan-scan rectangle";                   // not currently decoded
+    case SEI::FILLER_PAYLOAD:                       return "Filler payload";                       // not currently decoded
+    case SEI::USER_DATA_REGISTERED_ITU_T_T35:       return "User data registered";                 // not currently decoded
+    case SEI::USER_DATA_UNREGISTERED:               return "User data unregistered";
+    case SEI::RECOVERY_POINT:                       return "Recovery point";
+    case SEI::SCENE_INFO:                           return "Scene information";                    // not currently decoded
+    case SEI::FULL_FRAME_SNAPSHOT:                  return "Picture snapshot";                     // not currently decoded
+    case SEI::PROGRESSIVE_REFINEMENT_SEGMENT_START: return "Progressive refinement segment start"; // not currently decoded
+    case SEI::PROGRESSIVE_REFINEMENT_SEGMENT_END:   return "Progressive refinement segment end";   // not currently decoded
+    case SEI::FILM_GRAIN_CHARACTERISTICS:           return "Film grain characteristics";           // not currently decoded
+    case SEI::POST_FILTER_HINT:                     return "Post filter hint";                     // not currently decoded
+    case SEI::TONE_MAPPING_INFO:                    return "Tone mapping information";
+    case SEI::KNEE_FUNCTION_INFO:                   return "Knee function information";
+    case SEI::FRAME_PACKING:                        return "Frame packing arrangement";
+    case SEI::DISPLAY_ORIENTATION:                  return "Display orientation";
+    case SEI::SOP_DESCRIPTION:                      return "Structure of pictures information";
+    case SEI::ACTIVE_PARAMETER_SETS:                return "Active parameter sets";
+    case SEI::DECODING_UNIT_INFO:                   return "Decoding unit information";
+    case SEI::TEMPORAL_LEVEL0_INDEX:                return "Temporal sub-layer zero index";
+    case SEI::DECODED_PICTURE_HASH:                 return "Decoded picture hash";
+    case SEI::SCALABLE_NESTING:                     return "Scalable nesting";
+    case SEI::REGION_REFRESH_INFO:                  return "Region refresh information";
+    case SEI::NO_DISPLAY:                           return "No display";
+    case SEI::TIME_CODE:                            return "Time code";
+    case SEI::MASTERING_DISPLAY_COLOUR_VOLUME:      return "Mastering display colour volume";
+    case SEI::SEGM_RECT_FRAME_PACKING:              return "Segmented rectangular frame packing arrangement";
+    case SEI::TEMP_MOTION_CONSTRAINED_TILE_SETS:    return "Temporal motion constrained tile sets";
+    case SEI::CHROMA_SAMPLING_FILTER_HINT:          return "Chroma sampling filter hint";
+#if Q0074_COLOUR_REMAPPING_SEI
+    case SEI::COLOUR_REMAPPING_INFO:                return "Colour Remapping Information";
+#endif
+#if SVC_EXTENSION
+#if LAYERS_NOT_PRESENT_SEI
+    case SEI::LAYERS_NOT_PRESENT:                   return "Layers Present";
+#endif
+#if N0383_IL_CONSTRAINED_TILE_SETS_SEI
+    case SEI::INTER_LAYER_CONSTRAINED_TILE_SETS:    return "Inter Layer Constrained Tile Sets";
+#endif
+#if SUB_BITSTREAM_PROPERTY_SEI
+    case SEI::SUB_BITSTREAM_PROPERTY:               return "Sub-bitstream property";
+#endif
+#if O0164_MULTI_LAYER_HRD
+    case SEI::BSP_NESTING:                          return "Bitstream parition nesting";
+    case SEI::BSP_INITIAL_ARRIVAL_TIME:             return "Bitstream parition initial arrival time";
+#if !REMOVE_BSP_HRD_SEI
+    case SEI::BSP_HRD:                              return "Bitstream parition HRD parameters";
+#endif
+#endif
+#if Q0078_ADD_LAYER_SETS
+    case SEI::OUTPUT_LAYER_SET_NESTING:             return "Output layer set nesting";
+    case SEI::VPS_REWRITING:                        return "VPS rewriting";
+#endif
+#if Q0096_OVERLAY_SEI
+    case SEI::OVERLAY_INFO:                         return "Overlay Information";
+#endif
+#if P0123_ALPHA_CHANNEL_SEI
+    case SEI::ALPHA_CHANNEL_INFO:                   return "Alpha Channel Information";
+#endif
+#endif
+    default:                                        return "Unknown";
+  }
+}
Index: /tags/SHM-9.0/source/Lib/TLibCommon/SEI.h
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibCommon/SEI.h	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibCommon/SEI.h	(revision 1088)
@@ -0,0 +1,936 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef __SEI__
+#define __SEI__
+
+#pragma once
+#include <list>
+#include <vector>
+#include <cstring>
+
+#include "TypeDef.h"
+#include "libmd5/MD5.h"
+#if Q0078_ADD_LAYER_SETS
+#include "TLibCommon/NAL.h"
+#endif
+
+//! \ingroup TLibCommon
+//! \{
+class TComSPS;
+#if O0164_MULTI_LAYER_HRD
+class TComHRD;
+#endif
+
+/**
+ * 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,
+    NO_DISPLAY                           = 135,
+    TIME_CODE                            = 136,
+    MASTERING_DISPLAY_COLOUR_VOLUME      = 137,
+    SEGM_RECT_FRAME_PACKING              = 138,
+    TEMP_MOTION_CONSTRAINED_TILE_SETS    = 139,
+    CHROMA_SAMPLING_FILTER_HINT          = 140,
+    KNEE_FUNCTION_INFO                   = 141,
+#if LAYERS_NOT_PRESENT_SEI
+    LAYERS_NOT_PRESENT                   = 142,
+#endif
+#if N0383_IL_CONSTRAINED_TILE_SETS_SEI
+    INTER_LAYER_CONSTRAINED_TILE_SETS    = 143,
+#endif
+#if SUB_BITSTREAM_PROPERTY_SEI
+    SUB_BITSTREAM_PROPERTY               = 144,    // Final PayloadType to be defined after finalization
+#endif
+#if O0164_MULTI_LAYER_HRD
+    BSP_NESTING                          = 145,
+    BSP_INITIAL_ARRIVAL_TIME             = 146,
+#if !REMOVE_BSP_HRD_SEI
+    BSP_HRD                              = 147,
+#endif
+#endif
+#if Q0074_COLOUR_REMAPPING_SEI
+    COLOUR_REMAPPING_INFO                = 148,
+#endif
+#if Q0078_ADD_LAYER_SETS
+    OUTPUT_LAYER_SET_NESTING             = 149,
+    VPS_REWRITING                        = 150,
+#endif
+#if Q0189_TMVP_CONSTRAINTS
+    TMVP_CONSTRAINTS                     = 151,
+#endif
+#if Q0247_FRAME_FIELD_INFO
+    FRAME_FIELD_INFO                     = 152,
+#endif
+#if Q0096_OVERLAY_SEI
+    OVERLAY_INFO                         = 153,
+#endif
+#if P0123_ALPHA_CHANNEL_SEI
+    ALPHA_CHANNEL_INFO                   = 165,
+#endif
+  };
+  
+  SEI() {}
+  virtual ~SEI() {}
+  
+  static const Char *getSEIMessageString(SEI::PayloadType payloadType);
+
+  virtual PayloadType payloadType() const = 0;
+};
+
+static const UInt ISO_IEC_11578_LEN=16;
+
+class SEIuserDataUnregistered : public SEI
+{
+public:
+  PayloadType payloadType() const { return USER_DATA_UNREGISTERED; }
+
+  SEIuserDataUnregistered()
+    : userData(0)
+    {}
+
+  virtual ~SEIuserDataUnregistered()
+  {
+    delete userData;
+  }
+
+  UChar uuid_iso_iec_11578[ISO_IEC_11578_LEN];
+  UInt userDataLength;
+  UChar *userData;
+};
+
+class SEIDecodedPictureHash : public SEI
+{
+public:
+  PayloadType payloadType() const { return DECODED_PICTURE_HASH; }
+
+  SEIDecodedPictureHash() {}
+  virtual ~SEIDecodedPictureHash() {}
+  
+  enum Method
+  {
+    MD5,
+    CRC,
+    CHECKSUM,
+    RESERVED,
+  } method;
+
+  TComDigest m_digest;
+};
+
+class SEIActiveParameterSets : public SEI 
+{
+public:
+  PayloadType payloadType() const { return ACTIVE_PARAMETER_SETS; }
+
+  SEIActiveParameterSets() 
+    : activeVPSId            (0)
+    , m_selfContainedCvsFlag (false)
+    , m_noParameterSetUpdateFlag (false)
+    , numSpsIdsMinus1        (0)
+  {}
+  virtual ~SEIActiveParameterSets() {}
+
+  Int activeVPSId; 
+  Bool m_selfContainedCvsFlag;
+  Bool m_noParameterSetUpdateFlag;
+  Int numSpsIdsMinus1;
+  std::vector<Int> activeSeqParameterSetId; 
+#if R0247_SEI_ACTIVE
+  std::vector<Int> layerSpsIdx; 
+#endif
+};
+
+class SEIBufferingPeriod : public SEI
+{
+public:
+  PayloadType payloadType() const { return BUFFERING_PERIOD; }
+
+  SEIBufferingPeriod()
+  : m_bpSeqParameterSetId (0)
+  , m_rapCpbParamsPresentFlag (false)
+  , m_cpbDelayOffset      (0)
+  , m_dpbDelayOffset      (0)
+#if P0138_USE_ALT_CPB_PARAMS_FLAG
+  , m_useAltCpbParamsFlagPresent(false)
+  , m_useAltCpbParamsFlag (false)
+#endif
+  {
+    ::memset(m_initialCpbRemovalDelay, 0, sizeof(m_initialCpbRemovalDelay));
+    ::memset(m_initialCpbRemovalDelayOffset, 0, sizeof(m_initialCpbRemovalDelayOffset));
+    ::memset(m_initialAltCpbRemovalDelay, 0, sizeof(m_initialAltCpbRemovalDelay));
+    ::memset(m_initialAltCpbRemovalDelayOffset, 0, sizeof(m_initialAltCpbRemovalDelayOffset));
+  }
+  virtual ~SEIBufferingPeriod() {}
+
+  UInt m_bpSeqParameterSetId;
+  Bool m_rapCpbParamsPresentFlag;
+  UInt m_cpbDelayOffset;
+  UInt m_dpbDelayOffset;
+  UInt m_initialCpbRemovalDelay         [MAX_CPB_CNT][2];
+  UInt m_initialCpbRemovalDelayOffset   [MAX_CPB_CNT][2];
+  UInt m_initialAltCpbRemovalDelay      [MAX_CPB_CNT][2];
+  UInt m_initialAltCpbRemovalDelayOffset[MAX_CPB_CNT][2];
+  Bool m_concatenationFlag;
+  UInt m_auCpbRemovalDelayDelta;
+#if P0138_USE_ALT_CPB_PARAMS_FLAG
+  Bool m_useAltCpbParamsFlagPresent;
+  Bool m_useAltCpbParamsFlag;
+#endif
+};
+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 SEISegmentedRectFramePacking : public SEI
+{
+public:
+  PayloadType payloadType() const { return SEGM_RECT_FRAME_PACKING; }
+
+  SEISegmentedRectFramePacking() {}
+  virtual ~SEISegmentedRectFramePacking() {}
+
+  Bool m_arrangementCancelFlag;
+  Int  m_contentInterpretationType;
+  Bool m_arrangementPersistenceFlag;
+};
+
+class SEIDisplayOrientation : public SEI
+{
+public:
+  PayloadType payloadType() const { return DISPLAY_ORIENTATION; }
+
+  SEIDisplayOrientation()
+    : cancelFlag(true)
+    , persistenceFlag(0)
+    , extensionFlag(false)
+    {}
+  virtual ~SEIDisplayOrientation() {}
+
+  Bool cancelFlag;
+  Bool horFlip;
+  Bool verFlip;
+
+  UInt anticlockwiseRotation;
+  Bool persistenceFlag;
+  Bool extensionFlag;
+};
+
+class SEITemporalLevel0Index : public SEI
+{
+public:
+  PayloadType payloadType() const { return TEMPORAL_LEVEL0_INDEX; }
+
+  SEITemporalLevel0Index()
+    : tl0Idx(0)
+    , rapIdx(0)
+    {}
+  virtual ~SEITemporalLevel0Index() {}
+
+  UInt tl0Idx;
+  UInt rapIdx;
+};
+
+class SEIGradualDecodingRefreshInfo : public SEI
+{
+public:
+  PayloadType payloadType() const { return REGION_REFRESH_INFO; }
+
+  SEIGradualDecodingRefreshInfo()
+    : m_gdrForegroundFlag(0)
+  {}
+  virtual ~SEIGradualDecodingRefreshInfo() {}
+
+  Bool m_gdrForegroundFlag;
+};
+
+class SEINoDisplay : public SEI
+{
+public:
+  PayloadType payloadType() const { return NO_DISPLAY; }
+
+  SEINoDisplay()
+    : m_noDisplay(false)
+  {}
+  virtual ~SEINoDisplay() {}
+
+  Bool m_noDisplay;
+};
+
+class SEISOPDescription : public SEI
+{
+public:
+  PayloadType payloadType() const { return SOP_DESCRIPTION; }
+
+  SEISOPDescription() {}
+  virtual ~SEISOPDescription() {}
+
+  UInt m_sopSeqParameterSetId;
+  UInt m_numPicsInSopMinus1;
+
+  UInt m_sopDescVclNaluType[MAX_NUM_PICS_IN_SOP];
+  UInt m_sopDescTemporalId[MAX_NUM_PICS_IN_SOP];
+  UInt m_sopDescStRpsIdx[MAX_NUM_PICS_IN_SOP];
+  Int m_sopDescPocDelta[MAX_NUM_PICS_IN_SOP];
+};
+
+class SEIToneMappingInfo : public SEI
+{
+public:
+  PayloadType payloadType() const { return TONE_MAPPING_INFO; }
+  SEIToneMappingInfo() {}
+  virtual ~SEIToneMappingInfo() {}
+
+  Int    m_toneMapId;
+  Bool   m_toneMapCancelFlag;
+  Bool   m_toneMapPersistenceFlag;
+  Int    m_codedDataBitDepth;
+  Int    m_targetBitDepth;
+  Int    m_modelId;
+  Int    m_minValue;
+  Int    m_maxValue;
+  Int    m_sigmoidMidpoint;
+  Int    m_sigmoidWidth;
+  std::vector<Int> m_startOfCodedInterval;
+  Int    m_numPivots;
+  std::vector<Int> m_codedPivotValue;
+  std::vector<Int> m_targetPivotValue;
+  Int    m_cameraIsoSpeedIdc;
+  Int    m_cameraIsoSpeedValue;
+  Int    m_exposureIndexIdc;
+  Int    m_exposureIndexValue;
+  Int    m_exposureCompensationValueSignFlag;
+  Int    m_exposureCompensationValueNumerator;
+  Int    m_exposureCompensationValueDenomIdc;
+  Int    m_refScreenLuminanceWhite;
+  Int    m_extendedRangeWhiteLevel;
+  Int    m_nominalBlackLevelLumaCodeValue;
+  Int    m_nominalWhiteLevelLumaCodeValue;
+  Int    m_extendedWhiteLevelLumaCodeValue;
+};
+
+class SEIKneeFunctionInfo : public SEI
+{
+public:
+  PayloadType payloadType() const { return KNEE_FUNCTION_INFO; }
+  SEIKneeFunctionInfo() {}
+  virtual ~SEIKneeFunctionInfo() {}
+
+  Int   m_kneeId;
+  Bool  m_kneeCancelFlag;
+  Bool  m_kneePersistenceFlag;
+  Int   m_kneeInputDrange;
+  Int   m_kneeInputDispLuminance;
+  Int   m_kneeOutputDrange;
+  Int   m_kneeOutputDispLuminance;
+  Int   m_kneeNumKneePointsMinus1;
+  std::vector<Int> m_kneeInputKneePoint;
+  std::vector<Int> m_kneeOutputKneePoint;
+};
+
+class SEIChromaSamplingFilterHint : public SEI
+{
+public:
+  PayloadType payloadType() const {return CHROMA_SAMPLING_FILTER_HINT;}
+  SEIChromaSamplingFilterHint() {}
+  virtual ~SEIChromaSamplingFilterHint() {
+    if(m_verChromaFilterIdc == 1)
+    {
+      for(Int i = 0; i < m_numVerticalFilters; i ++)
+      {
+        free(m_verFilterCoeff[i]);
+      }
+      free(m_verFilterCoeff);
+      free(m_verTapLengthMinus1);
+    }
+    if(m_horChromaFilterIdc == 1)
+    {
+      for(Int i = 0; i < m_numHorizontalFilters; i ++)
+      {
+        free(m_horFilterCoeff[i]);
+      }
+      free(m_horFilterCoeff);
+      free(m_horTapLengthMinus1);
+    }
+  }
+
+  Int   m_verChromaFilterIdc;
+  Int   m_horChromaFilterIdc;
+  Bool  m_verFilteringProcessFlag;
+  Int   m_targetFormatIdc;
+  Bool  m_perfectReconstructionFlag;
+  Int   m_numVerticalFilters;
+  Int*  m_verTapLengthMinus1;
+  Int** m_verFilterCoeff;
+  Int   m_numHorizontalFilters;
+  Int*  m_horTapLengthMinus1;
+  Int** m_horFilterCoeff;
+};
+
+class SEIMasteringDisplayColourVolume : public SEI
+{
+public:
+    PayloadType payloadType() const { return MASTERING_DISPLAY_COLOUR_VOLUME; }
+    SEIMasteringDisplayColourVolume() {}
+    virtual ~SEIMasteringDisplayColourVolume(){}
+    
+    TComSEIMasteringDisplay values;
+};
+
+typedef std::list<SEI*> SEIMessages;
+
+/// output a selection of SEI messages by payload type. Ownership stays in original message list.
+SEIMessages getSeisByType(SEIMessages &seiList, SEI::PayloadType seiType);
+
+/// remove a selection of SEI messages by payload type from the original list and return them in a new list. 
+SEIMessages extractSeisByType(SEIMessages &seiList, SEI::PayloadType seiType);
+
+/// delete list of SEI messages (freeing the referenced objects)
+Void deleteSEIs (SEIMessages &seiList);
+
+class SEIScalableNesting : public SEI
+{
+public:
+  PayloadType payloadType() const { return SCALABLE_NESTING; }
+
+  SEIScalableNesting()
+    : m_callerOwnsSEIs(false)
+  {}
+  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 UChar values
+
+  Bool  m_callerOwnsSEIs;
+  SEIMessages m_nestedSEIs;
+};
+
+class SEITimeCode : public SEI
+{
+public:
+  PayloadType payloadType() const { return TIME_CODE; }
+  SEITimeCode() {}
+  virtual ~SEITimeCode(){}
+
+  UInt numClockTs;
+  TComSEITimeSet timeSetArray[MAX_TIMECODE_SEI_SETS];
+};
+
+//definition according to P1005_v1;
+class SEITempMotionConstrainedTileSets: public SEI
+{
+  struct TileSetData
+  {
+    protected:
+      std::vector<Int> m_top_left_tile_index;  //[tileSetIdx][tileIdx];
+      std::vector<Int> m_bottom_right_tile_index;
+
+    public:
+      Int     m_mcts_id;  
+      Bool    m_display_tile_set_flag;
+      Int     m_num_tile_rects_in_set; //_minus1;
+      Bool    m_exact_sample_value_match_flag;
+      Bool    m_mcts_tier_level_idc_present_flag;
+      Bool    m_mcts_tier_flag;
+      Int     m_mcts_level_idc;
+
+      Void setNumberOfTileRects(const Int number)
+      {
+        m_top_left_tile_index    .resize(number);
+        m_bottom_right_tile_index.resize(number);
+      }
+
+      Int  getNumberOfTileRects() const
+      {
+        assert(m_top_left_tile_index.size() == m_bottom_right_tile_index.size());
+        return Int(m_top_left_tile_index.size());
+      }
+
+            Int &topLeftTileIndex    (const Int tileRectIndex)       { return m_top_left_tile_index    [tileRectIndex]; }
+            Int &bottomRightTileIndex(const Int tileRectIndex)       { return m_bottom_right_tile_index[tileRectIndex]; }
+      const Int &topLeftTileIndex    (const Int tileRectIndex) const { return m_top_left_tile_index    [tileRectIndex]; }
+      const Int &bottomRightTileIndex(const Int tileRectIndex) const { return m_bottom_right_tile_index[tileRectIndex]; }
+  };
+
+protected:
+  std::vector<TileSetData> m_tile_set_data;
+
+public:
+
+  Bool    m_mc_all_tiles_exact_sample_value_match_flag;
+  Bool    m_each_tile_one_tile_set_flag;
+  Bool    m_limited_tile_set_display_flag;
+  Bool    m_max_mcs_tier_level_idc_present_flag;
+  Bool    m_max_mcts_tier_flag;
+  Int     m_max_mcts_level_idc;
+
+  PayloadType payloadType() const { return TEMP_MOTION_CONSTRAINED_TILE_SETS; }
+
+  Void setNumberOfTileSets(const Int number)       { m_tile_set_data.resize(number);     }
+  Int  getNumberOfTileSets()                 const { return Int(m_tile_set_data.size()); }
+
+        TileSetData &tileSetData (const Int index)       { return m_tile_set_data[index]; }
+  const TileSetData &tileSetData (const Int index) const { return m_tile_set_data[index]; }
+
+};
+
+#if Q0078_ADD_LAYER_SETS
+class SEIOutputLayerSetNesting : public SEI
+{
+public:
+  PayloadType payloadType() const { return OUTPUT_LAYER_SET_NESTING; }
+
+  SEIOutputLayerSetNesting()
+    : m_callerOwnsSEIs(false)
+  {}
+
+  virtual ~SEIOutputLayerSetNesting()
+  {
+    if (!m_callerOwnsSEIs)
+    {
+      deleteSEIs(m_nestedSEIs);
+    }
+  }
+
+  Bool m_olsFlag;
+  UInt m_numOlsIndicesMinus1;
+  UInt m_olsIdx[1024];
+  Bool  m_callerOwnsSEIs;
+  SEIMessages m_nestedSEIs;
+};
+
+class SEIVPSRewriting : public SEI
+{
+public:
+  PayloadType payloadType() const { return VPS_REWRITING; }
+
+  SEIVPSRewriting() {}
+  virtual ~SEIVPSRewriting() {}
+
+  NALUnit* nalu;
+};
+#endif
+
+#if P0123_ALPHA_CHANNEL_SEI
+class SEIAlphaChannelInfo : public SEI
+{
+public:
+  PayloadType payloadType() const { return ALPHA_CHANNEL_INFO; }
+  SEIAlphaChannelInfo() {}
+  virtual ~SEIAlphaChannelInfo() {}
+  Bool m_alphaChannelCancelFlag;
+  UInt m_alphaChannelUseIdc;
+  UInt m_alphaChannelBitDepthMinus8;
+  UInt m_alphaTransparentValue;
+  UInt m_alphaOpaqueValue;
+  Bool m_alphaChannelIncrFlag;
+  Bool m_alphaChannelClipFlag;
+  Bool m_alphaChannelClipTypeFlag;
+};
+#endif
+
+#if Q0096_OVERLAY_SEI
+class SEIOverlayInfo : public SEI
+{
+public:
+  PayloadType payloadType() const { return OVERLAY_INFO; }
+  SEIOverlayInfo() 
+    :  m_numOverlaysMinus1(-1) 
+    {}
+
+  virtual ~SEIOverlayInfo() 
+  {
+    for (Int i=0 ; i<=m_numOverlaysMinus1 ; i++)
+    { 
+      delete [] m_overlayLanguage[i];          
+      delete [] m_overlayName[i];
+      for (Int j=0 ; j<=m_numOverlayElementsMinus1[i] ; j++)
+      {
+        delete [] m_overlayElementName[i][j];
+      }
+    }
+  }
+
+  Bool                                m_overlayInfoCancelFlag;
+  UInt                                m_overlayContentAuxIdMinus128;
+  UInt                                m_overlayLabelAuxIdMinus128;
+  UInt                                m_overlayAlphaAuxIdMinus128;
+  UInt                                m_overlayElementLabelValueLengthMinus8;
+  UInt                                m_numOverlaysMinus1;
+  std::vector<UInt>                   m_overlayIdx;
+  std::vector<Bool>                   m_languageOverlayPresentFlag;
+  std::vector<UInt>                   m_overlayContentLayerId;
+  std::vector<Bool>                   m_overlayLabelPresentFlag;
+  std::vector<UInt>                   m_overlayLabelLayerId;
+  std::vector<Bool>                   m_overlayAlphaPresentFlag;
+  std::vector<UInt>                   m_overlayAlphaLayerId;
+  std::vector<UInt>                   m_numOverlayElementsMinus1;
+  std::vector< std::vector<UInt> >    m_overlayElementLabelMin;
+  std::vector< std::vector<UInt> >    m_overlayElementLabelMax;
+  std::vector<UChar*>                 m_overlayLanguage;
+  std::vector<UInt>                   m_overlayLanguageLength;
+  std::vector<UChar*>                 m_overlayName;
+  std::vector<UInt>                   m_overlayNameLength;
+  std::vector< std::vector<UChar*> >  m_overlayElementName;
+  std::vector< std::vector<UInt> >    m_overlayElementNameLength;
+  Bool                                m_overlayInfoPersistenceFlag;
+};
+#endif
+
+#if LAYERS_NOT_PRESENT_SEI
+class SEILayersNotPresent : public SEI
+{
+public:
+  PayloadType payloadType() const { return LAYERS_NOT_PRESENT; }
+
+  SEILayersNotPresent() {}
+  virtual ~SEILayersNotPresent() {}
+
+  UInt m_activeVpsId;
+  UInt m_vpsMaxLayers;
+  Bool m_layerNotPresentFlag[MAX_LAYERS];
+};
+#endif
+
+#if Q0074_COLOUR_REMAPPING_SEI
+class SEIColourRemappingInfo : public SEI
+{
+public:
+  PayloadType payloadType() const { return COLOUR_REMAPPING_INFO; }
+  SEIColourRemappingInfo() {}
+  ~SEIColourRemappingInfo() {}
+ 
+  Int   m_colourRemapId;
+  Bool  m_colourRemapCancelFlag;
+  Bool  m_colourRemapPersistenceFlag;
+  Bool  m_colourRemapVideoSignalInfoPresentFlag;
+  Bool  m_colourRemapFullRangeFlag;
+  Int   m_colourRemapPrimaries;
+  Int   m_colourRemapTransferFunction;
+  Int   m_colourRemapMatrixCoefficients;
+  Int   m_colourRemapInputBitDepth;
+  Int   m_colourRemapBitDepth;
+  Int   m_preLutNumValMinus1[3];
+  std::vector<Int> m_preLutCodedValue[3];
+  std::vector<Int> m_preLutTargetValue[3];
+  Bool  m_colourRemapMatrixPresentFlag;
+  Int   m_log2MatrixDenom;
+  Int   m_colourRemapCoeffs[3][3];
+  Int   m_postLutNumValMinus1[3];
+  std::vector<Int> m_postLutCodedValue[3];
+  std::vector<Int> m_postLutTargetValue[3];
+};
+#endif
+
+#if N0383_IL_CONSTRAINED_TILE_SETS_SEI
+class SEIInterLayerConstrainedTileSets : public SEI
+{
+public:
+  PayloadType payloadType() const { return INTER_LAYER_CONSTRAINED_TILE_SETS; }
+
+  SEIInterLayerConstrainedTileSets() {}
+  virtual ~SEIInterLayerConstrainedTileSets() {}
+
+  Bool m_ilAllTilesExactSampleValueMatchFlag;
+  Bool m_ilOneTilePerTileSetFlag;
+  UInt m_ilNumSetsInMessageMinus1;
+  Bool m_skippedTileSetPresentFlag;
+  UInt m_ilctsId[256];
+  UInt m_ilNumTileRectsInSetMinus1[256];
+  UInt m_ilTopLeftTileIndex[256][440];
+  UInt m_ilBottomRightTileIndex[256][440];
+  UInt m_ilcIdc[256];
+  Bool m_ilExactSampleValueMatchFlag[256];
+  UInt m_allTilesIlcIdc;
+};
+#endif
+
+#if SUB_BITSTREAM_PROPERTY_SEI
+class SEISubBitstreamProperty : public SEI
+{
+public:
+  PayloadType payloadType() const { return SUB_BITSTREAM_PROPERTY; }
+
+  SEISubBitstreamProperty();
+  virtual ~SEISubBitstreamProperty() {}
+
+  Int  m_activeVpsId;
+  Int  m_numAdditionalSubStreams;
+  Int  m_subBitstreamMode       [MAX_SUB_STREAMS];
+  Int  m_outputLayerSetIdxToVps [MAX_SUB_STREAMS];
+  Int  m_highestSublayerId      [MAX_SUB_STREAMS];
+  Int  m_avgBitRate             [MAX_SUB_STREAMS];
+  Int  m_maxBitRate             [MAX_SUB_STREAMS];
+};
+#endif
+
+#if Q0189_TMVP_CONSTRAINTS
+class SEITMVPConstrains : public SEI
+{
+public:
+  PayloadType payloadType() const { return TMVP_CONSTRAINTS; }
+
+  SEITMVPConstrains()
+    : prev_pics_not_used_flag(0),no_intra_layer_col_pic_flag(0)
+    {}
+
+  virtual ~SEITMVPConstrains()
+  {
+  }
+
+  UInt prev_pics_not_used_flag;
+  UInt no_intra_layer_col_pic_flag;
+};
+#endif
+
+#if Q0247_FRAME_FIELD_INFO 
+class SEIFrameFieldInfo: public SEI
+{
+public:
+  PayloadType payloadType() const { return FRAME_FIELD_INFO; }
+
+  SEIFrameFieldInfo()
+    : m_ffinfo_picStruct(0),m_ffinfo_sourceScanType(0), m_ffinfo_duplicateFlag(false)
+    {}
+
+  virtual ~SEIFrameFieldInfo()
+  {
+  }
+
+  UInt  m_ffinfo_picStruct;
+  UInt  m_ffinfo_sourceScanType;
+  Bool  m_ffinfo_duplicateFlag;
+};
+#endif
+
+#if O0164_MULTI_LAYER_HRD
+class SEIBspNesting : public SEI
+{
+public:
+  PayloadType payloadType() const { return BSP_NESTING; }
+
+  SEIBspNesting()
+    : m_callerOwnsSEIs(false)
+  {}
+  virtual ~SEIBspNesting()
+  {
+    if (!m_callerOwnsSEIs)
+    {
+      deleteSEIs(m_nestedSEIs);
+    }
+  }
+
+  Int  m_bspIdx;
+  Bool  m_callerOwnsSEIs;
+  SEIMessages m_nestedSEIs;
+#if VPS_VUI_BSP_HRD_PARAMS
+  Int  m_seiPartitioningSchemeIdx;
+  Int  m_seiOlsIdx;
+#endif
+};
+
+class SEIBspInitialArrivalTime : public SEI
+{
+public:
+  PayloadType payloadType() const { return BSP_INITIAL_ARRIVAL_TIME; }
+
+  SEIBspInitialArrivalTime () {}
+  virtual ~SEIBspInitialArrivalTime () {}
+
+  UInt m_nalInitialArrivalDelay[256];
+  UInt m_vclInitialArrivalDelay[256];
+};
+
+#if !REMOVE_BSP_HRD_SEI
+class SEIBspHrd : public SEI
+{
+public:
+  PayloadType payloadType() const { return BSP_HRD; }
+
+  SEIBspHrd () {}
+  virtual ~SEIBspHrd () {}
+
+  UInt m_seiNumBspHrdParametersMinus1;
+  Bool m_seiBspCprmsPresentFlag[MAX_VPS_LAYER_SETS_PLUS1];
+  UInt m_seiNumBitstreamPartitionsMinus1[MAX_VPS_LAYER_SETS_PLUS1];
+  Bool m_seiLayerInBspFlag[MAX_VPS_LAYER_SETS_PLUS1][8][MAX_LAYERS];
+  UInt m_seiNumBspSchedCombinationsMinus1[MAX_VPS_LAYER_SETS_PLUS1];
+  UInt m_seiBspCombHrdIdx[MAX_VPS_LAYER_SETS_PLUS1][16][16];
+  UInt m_seiBspCombScheddx[MAX_VPS_LAYER_SETS_PLUS1][16][16];
+  UInt m_vpsMaxLayers;
+  Bool m_layerIdIncludedFlag[MAX_VPS_LAYER_SETS_PLUS1][MAX_VPS_LAYER_IDX_PLUS1];
+
+  TComHRD *hrd;
+};
+#endif
+
+#endif
+
+#endif
+//! \}
Index: /tags/SHM-9.0/source/Lib/TLibCommon/TCom3DAsymLUT.cpp
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibCommon/TCom3DAsymLUT.cpp	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibCommon/TCom3DAsymLUT.cpp	(revision 1088)
@@ -0,0 +1,481 @@
+#include <cstdio>
+#include <cstdlib>
+#include <cstring>
+#include <cmath>
+#include <algorithm>
+
+#include "TypeDef.h"
+#include "TCom3DAsymLUT.h"
+#include "TComPicYuv.h"
+
+#if Q0048_CGS_3D_ASYMLUT
+
+const Int TCom3DAsymLUT::m_nVertexIdxOffset[4][3] = { { 0 , 0 , 0 } , { 0 , 1 , 0 } , { 0 , 1 , 1 } , { 1 , 1 , 1 } };
+
+TCom3DAsymLUT::TCom3DAsymLUT()
+{
+  m_pCuboid = NULL;
+  m_nResQuanBit = 0;
+#if R0164_CGS_LUT_BUGFIX_CHECK
+  m_pCuboidExplicit = NULL;
+  m_pCuboidFilled = NULL;
+#endif
+}
+
+TCom3DAsymLUT::~TCom3DAsymLUT()
+{
+  destroy();
+}
+
+Void TCom3DAsymLUT::create( Int nMaxOctantDepth , Int nInputBitDepth , Int nInputBitDepthC , Int nOutputBitDepth , Int nOutputBitDepthC , Int nMaxYPartNumLog2 
+#if R0151_CGS_3D_ASYMLUT_IMPROVE
+  , Int nAdaptCThresholdU , Int nAdaptCThresholdV
+#endif
+  )
+{
+  m_nMaxOctantDepth = nMaxOctantDepth;
+  m_nInputBitDepthY = nInputBitDepth;
+  m_nOutputBitDepthY = nOutputBitDepth;
+  m_nInputBitDepthC = nInputBitDepthC;
+  m_nOutputBitDepthC = nOutputBitDepthC;
+  m_nDeltaBitDepthC = m_nOutputBitDepthC - m_nInputBitDepthC;
+  m_nDeltaBitDepth = m_nOutputBitDepthY - m_nInputBitDepthY;
+  m_nMaxYPartNumLog2 = nMaxYPartNumLog2;
+  m_nMaxPartNumLog2 = 3 * m_nMaxOctantDepth + m_nMaxYPartNumLog2;
+
+  xUpdatePartitioning( nMaxOctantDepth , nMaxYPartNumLog2 
+#if R0151_CGS_3D_ASYMLUT_IMPROVE
+    , nAdaptCThresholdU , nAdaptCThresholdV
+#endif
+    );
+
+  m_nYSize = 1 << ( m_nMaxOctantDepth + m_nMaxYPartNumLog2 );
+  m_nUSize = 1 << m_nMaxOctantDepth;
+  m_nVSize = 1 << m_nMaxOctantDepth;
+  assert( m_nYSize > 0 && m_nUSize > 0 && m_nVSize > 0 );
+
+  if( m_pCuboid != NULL )
+  {
+    destroy();
+  }
+  xAllocate3DArray( m_pCuboid , m_nYSize , m_nUSize , m_nVSize );
+
+#if R0164_CGS_LUT_BUGFIX_CHECK
+  xAllocate3DArray( m_pCuboidExplicit , m_nYSize , m_nUSize , m_nVSize );
+  xAllocate3DArray( m_pCuboidFilled   , m_nYSize , m_nUSize , m_nVSize );
+#endif
+}
+
+Void TCom3DAsymLUT::destroy()
+{
+  xFree3DArray( m_pCuboid );
+#if R0164_CGS_LUT_BUGFIX_CHECK
+  xFree3DArray( m_pCuboidExplicit );
+  xFree3DArray( m_pCuboidFilled   );
+#endif
+}
+
+
+Void TCom3DAsymLUT::xUpdatePartitioning( Int nCurOctantDepth , Int nCurYPartNumLog2 
+#if R0151_CGS_3D_ASYMLUT_IMPROVE
+  , Int nAdaptCThresholdU , Int nAdaptCThresholdV
+#endif
+  )
+{
+  assert( nCurOctantDepth <= m_nMaxOctantDepth );
+#if R0179_CGS_SIZE_8x1x1
+  assert( nCurYPartNumLog2 + nCurOctantDepth <= m_nMaxYPartNumLog2 + m_nMaxOctantDepth );
+#else
+  assert( nCurYPartNumLog2 <= m_nMaxYPartNumLog2 );
+#endif 
+
+  m_nCurOctantDepth = nCurOctantDepth;
+  m_nCurYPartNumLog2 = nCurYPartNumLog2;
+  m_nYShift2Idx = m_nInputBitDepthY - m_nCurOctantDepth - m_nCurYPartNumLog2;
+  m_nUShift2Idx = m_nVShift2Idx = m_nInputBitDepthC - m_nCurOctantDepth;
+#if R0151_CGS_3D_ASYMLUT_IMPROVE
+  m_nMappingShift = 10 + m_nInputBitDepthY - m_nOutputBitDepthY; 
+  m_nAdaptCThresholdU = nAdaptCThresholdU;
+  m_nAdaptCThresholdV = nAdaptCThresholdV;
+#else
+  m_nMappingShift = m_nYShift2Idx + m_nUShift2Idx;
+#endif
+  m_nMappingOffset = 1 << ( m_nMappingShift - 1 );
+
+#if R0179_ENC_OPT_3DLUT_SIZE
+  m_nYSize = 1 << ( m_nCurOctantDepth + m_nCurYPartNumLog2 );
+  m_nUSize = 1 << m_nCurOctantDepth;
+  m_nVSize = 1 << m_nCurOctantDepth;
+#endif
+}
+
+Void TCom3DAsymLUT::colorMapping( TComPicYuv * pcPic, TComPicYuv * pcPicDst )
+{
+  Int nWidth = pcPic->getWidth(COMPONENT_Y);
+  Int nHeight = pcPic->getHeight(COMPONENT_Y);
+  Int nStrideY = pcPic->getStride(COMPONENT_Y);
+  Int nStrideC = pcPic->getStride(COMPONENT_Cb);
+  Pel * pY = pcPic->getAddr(COMPONENT_Y);
+  Pel * pU = pcPic->getAddr(COMPONENT_Cb);
+  Pel * pV = pcPic->getAddr(COMPONENT_Cr);
+
+  Int nDstStrideY = pcPicDst->getStride(COMPONENT_Y);
+  Int nDstStrideC = pcPicDst->getStride(COMPONENT_Cb);
+  Pel * pYDst = pcPicDst->getAddr(COMPONENT_Y);
+  Pel * pUDst = pcPicDst->getAddr(COMPONENT_Cb);
+  Pel * pVDst = pcPicDst->getAddr(COMPONENT_Cr);
+
+  Pel *pUPrev = pU;
+  Pel *pVPrev = pV;
+  Pel *pUNext = pU+nStrideC;
+  Pel *pVNext = pV+nStrideC;
+
+  // alignment padding
+  pcPic->setBorderExtension( false );
+  pcPic->extendPicBorder();
+
+  Pel iMaxValY = (1<<getOutputBitDepthY())-1;
+  Pel iMaxValC = (1<<getOutputBitDepthC())-1;
+  for( Int y = 0 ; y < nHeight ; y += 2 )
+  {
+    for( Int xY = 0 , xC = 0 ; xY < nWidth ; xY += 2 , xC++ )
+    {
+      Pel srcY00 = pY[xY];
+      Pel srcY01 = pY[xY+1];
+      Pel srcY10 = pY[xY+nStrideY];
+      Pel srcY11 = pY[xY+nStrideY+1];
+      Pel srcYaver;
+      Pel srcU = pU[xC];
+      Pel srcV = pV[xC];
+      Pel dstY00, dstY01, dstY10, dstY11;
+
+      // alignment
+      srcYaver =  (srcY00 + srcY10 + 1 ) >> 1;
+      Pel srcUP0 = pUPrev[xC];
+      Pel srcVP0 = pVPrev[xC];        
+      Pel tmpU =  (srcUP0 + srcU + (srcU<<1) + 2 ) >> 2;
+      Pel tmpV =  (srcVP0 + srcV + (srcV<<1) + 2 ) >> 2;
+      dstY00 = xMapY( srcY00 , tmpU , tmpV );
+      Pel a = pU[xC+1] + srcU;
+      tmpU =  ((a<<1) + a + srcUP0 + pUPrev[xC+1] + 4 ) >> 3;
+      Pel b = pV[xC+1] + srcV;
+      tmpV =  ((b<<1) + b + srcVP0 + pVPrev[xC+1] + 4 ) >> 3;
+      dstY01 = xMapY( srcY01 , tmpU , tmpV );
+
+      srcUP0 = pUNext[xC];
+      srcVP0 = pVNext[xC];
+      tmpU =  (srcUP0 + srcU + (srcU<<1) + 2 ) >> 2;
+      tmpV =  (srcVP0 + srcV + (srcV<<1) + 2 ) >> 2;
+      dstY10 = xMapY( srcY10 , tmpU , tmpV );
+      tmpU =  ((a<<1) + a + srcUP0 + pUNext[xC+1] + 4 ) >> 3;
+      tmpV =  ((b<<1) + b + srcVP0 + pVNext[xC+1] + 4 ) >> 3;
+      dstY11 = xMapY( srcY11 , tmpU , tmpV );
+
+      SYUVP dstUV = xMapUV( srcYaver , srcU , srcV );
+      pYDst[xY] = Clip3((Pel)0, iMaxValY, dstY00 );
+      pYDst[xY+1] = Clip3((Pel)0, iMaxValY, dstY01 );
+      pYDst[xY+nDstStrideY] = Clip3((Pel)0, iMaxValY, dstY10 );
+      pYDst[xY+nDstStrideY+1] = Clip3((Pel)0, iMaxValY, dstY11 );
+      pUDst[xC] = Clip3((Pel)0, iMaxValC, dstUV.U );
+      pVDst[xC] = Clip3((Pel)0, iMaxValC, dstUV.V );
+    }
+    pY += nStrideY + nStrideY;
+
+    // alignment
+    pUPrev = pU;
+    pVPrev = pV;
+    pU = pUNext;
+    pV = pVNext;
+    pUNext += nStrideC;
+    pVNext += nStrideC;
+
+    pYDst += nDstStrideY + nDstStrideY;
+    pUDst += nDstStrideC;
+    pVDst += nDstStrideC;
+  }
+}
+
+SYUVP TCom3DAsymLUT::xGetCuboidVertexPredA( Int yIdx , Int uIdx , Int vIdx , Int nVertexIdx )
+{
+  assert( nVertexIdx < 4 );
+  
+  SYUVP sPred;
+#if R0151_CGS_3D_ASYMLUT_IMPROVE
+  sPred.Y = sPred.U = sPred.V = 0;
+  if( nVertexIdx == 0 )
+    sPred.Y = xGetNormCoeffOne() << ( m_nOutputBitDepthY - m_nInputBitDepthY );
+  else if( nVertexIdx == 1 )
+    sPred.U = xGetNormCoeffOne() << ( m_nOutputBitDepthY - m_nInputBitDepthY );
+  else if( nVertexIdx == 2 )
+    sPred.V = xGetNormCoeffOne() << ( m_nOutputBitDepthY - m_nInputBitDepthY );
+#else
+  sPred.Y = ( yIdx + m_nVertexIdxOffset[nVertexIdx][0] ) << ( m_nYShift2Idx + m_nDeltaBitDepth );
+  sPred.U = ( uIdx + m_nVertexIdxOffset[nVertexIdx][1] ) << ( m_nUShift2Idx + m_nDeltaBitDepthC );
+  sPred.V = ( vIdx + m_nVertexIdxOffset[nVertexIdx][2] ) << ( m_nVShift2Idx + m_nDeltaBitDepthC );
+#endif
+  return( sPred );
+}
+
+SYUVP  TCom3DAsymLUT::xGetCuboidVertexPredAll( Int yIdx , Int uIdx , Int vIdx , Int nVertexIdx , SCuboid *** pCurCuboid )
+{
+  SCuboid***  pCuboid = pCurCuboid ? pCurCuboid : m_pCuboid ;
+
+#if R0151_CGS_3D_ASYMLUT_IMPROVE
+  SYUVP sPred;
+  if( yIdx == 0 )
+  {
+    sPred.Y = nVertexIdx == 0 ? 1024 : 0;
+    sPred.U = nVertexIdx == 1 ? 1024 : 0;
+    sPred.V = nVertexIdx == 2 ? 1024 : 0;
+  }
+  else
+  {
+    sPred = pCuboid[yIdx-1][uIdx][vIdx].P[nVertexIdx];
+  }
+#else
+  // PredA
+  SYUVP sPredA = xGetCuboidVertexPredA( yIdx , uIdx , vIdx , nVertexIdx );
+
+  // PredB
+  SYUVP sPredB; 
+  memset( &sPredB , 0 , sizeof( sPredB ) );
+  if( yIdx > 0 )
+  {
+    SYUVP & recNeighborP = pCuboid[yIdx-1][uIdx][vIdx].P[nVertexIdx];
+    SYUVP sPredNeighbor = xGetCuboidVertexPredA( yIdx - 1 , uIdx , vIdx , nVertexIdx );
+    sPredB.Y += recNeighborP.Y - sPredNeighbor.Y ;
+    sPredB.U += recNeighborP.U - sPredNeighbor.U ;
+    sPredB.V += recNeighborP.V - sPredNeighbor.V ;
+
+    Pel min = - ( 1 << ( getOutputBitDepthY() - 2 ) );
+    Pel max =  - min;
+    sPredB.Y = Clip3( min , max , sPredB.Y );
+    min = - ( 1 << ( getOutputBitDepthC() - 2 ) );
+    max =  - min;
+    sPredB.U = Clip3( min , max , sPredB.U );
+    sPredB.V = Clip3( min , max , sPredB.V );
+  }
+
+  SYUVP sPred;
+  sPred.Y = sPredA.Y + sPredB.Y;
+  sPred.U = sPredA.U + sPredB.U;
+  sPred.V = sPredA.V + sPredB.V;
+#endif
+  return sPred ;
+}
+
+SYUVP TCom3DAsymLUT::getCuboidVertexResTree( Int yIdx , Int uIdx , Int vIdx , Int nVertexIdx )
+{
+  const SYUVP & rYUVP = m_pCuboid[yIdx][uIdx][vIdx].P[nVertexIdx];
+  SYUVP sPred = xGetCuboidVertexPredAll( yIdx , uIdx , vIdx , nVertexIdx );
+
+  SYUVP sResidue;
+  sResidue.Y = ( rYUVP.Y - sPred.Y ) >> m_nResQuanBit;
+  sResidue.U = ( rYUVP.U - sPred.U ) >> m_nResQuanBit;
+  sResidue.V = ( rYUVP.V - sPred.V ) >> m_nResQuanBit;
+  return( sResidue );
+}
+
+Void TCom3DAsymLUT::setCuboidVertexResTree( Int yIdx , Int uIdx , Int vIdx , Int nVertexIdx , Int deltaY , Int deltaU , Int deltaV )
+{
+  SYUVP & rYUVP = m_pCuboid[yIdx][uIdx][vIdx].P[nVertexIdx];
+  SYUVP sPred = xGetCuboidVertexPredAll( yIdx , uIdx , vIdx , nVertexIdx );
+
+  rYUVP.Y = sPred.Y + ( deltaY << m_nResQuanBit );
+  rYUVP.U = sPred.U + ( deltaU << m_nResQuanBit );
+  rYUVP.V = sPred.V + ( deltaV << m_nResQuanBit );
+#if R0150_CGS_SIGNAL_CONSTRAINTS
+  // LUT coefficients are less than 12-bit
+  assert( -2048 <= rYUVP.Y && rYUVP.Y <= 2047 );
+  assert( -2048 <= rYUVP.U && rYUVP.U <= 2047 );
+  assert( -2048 <= rYUVP.V && rYUVP.V <= 2047 );
+#endif
+}
+
+Pel TCom3DAsymLUT::xMapY( Pel y , Pel u , Pel v )
+{
+#if R0151_CGS_3D_ASYMLUT_IMPROVE
+  const SCuboid & rCuboid = m_pCuboid[xGetYIdx(y)][xGetUIdx(u)][xGetVIdx(v)];
+  Pel dstY = ( ( rCuboid.P[0].Y * y + rCuboid.P[1].Y * u + rCuboid.P[2].Y * v + m_nMappingOffset ) >> m_nMappingShift ) + rCuboid.P[3].Y;
+#else
+  const SCuboid & rCuboid = m_pCuboid[y>>m_nYShift2Idx][u>>m_nUShift2Idx][v>>m_nVShift2Idx];
+  Pel dstY = rCuboid.P[0].Y;
+  Int deltaY = y - ( y >> m_nYShift2Idx << m_nYShift2Idx );
+  Int deltaU = u - ( u >> m_nUShift2Idx << m_nUShift2Idx );
+  Int deltaV = v - ( v >> m_nVShift2Idx << m_nVShift2Idx );
+  dstY += ( Pel )( ( ( ( deltaY * ( rCuboid.P[3].Y - rCuboid.P[2].Y ) ) << m_nUShift2Idx ) 
+                   + ( ( deltaU * ( rCuboid.P[1].Y - rCuboid.P[0].Y ) ) << m_nYShift2Idx )
+                   + ( ( deltaV * ( rCuboid.P[2].Y - rCuboid.P[1].Y ) ) << m_nYShift2Idx ) 
+                   + m_nMappingOffset ) >> m_nMappingShift );
+#endif
+  return( dstY );
+}
+
+SYUVP TCom3DAsymLUT::xMapUV( Pel y , Pel u , Pel v )
+{
+#if R0151_CGS_3D_ASYMLUT_IMPROVE
+  const SCuboid & rCuboid = m_pCuboid[xGetYIdx(y)][xGetUIdx(u)][xGetVIdx(v)];
+  SYUVP dst;
+  dst.Y = 0;
+  dst.U = ( ( rCuboid.P[0].U * y + rCuboid.P[1].U * u + rCuboid.P[2].U * v + m_nMappingOffset ) >> m_nMappingShift ) + rCuboid.P[3].U;
+  dst.V = ( ( rCuboid.P[0].V * y + rCuboid.P[1].V * u + rCuboid.P[2].V * v + m_nMappingOffset ) >> m_nMappingShift ) + rCuboid.P[3].V;
+#else
+  const SCuboid & rCuboid = m_pCuboid[y>>m_nYShift2Idx][u>>m_nUShift2Idx][v>>m_nVShift2Idx];
+  SYUVP dst = rCuboid.P[0];
+  Int deltaY = y - ( y >> m_nYShift2Idx << m_nYShift2Idx );
+  Int deltaU = u - ( u >> m_nUShift2Idx << m_nUShift2Idx );
+  Int deltaV = v - ( v >> m_nVShift2Idx << m_nVShift2Idx );
+  dst.U += ( Pel )( ( ( ( deltaY * ( rCuboid.P[3].U - rCuboid.P[2].U ) ) << m_nUShift2Idx ) 
+                    + ( ( deltaU * ( rCuboid.P[1].U - rCuboid.P[0].U ) ) << m_nYShift2Idx )
+                    + ( ( deltaV * ( rCuboid.P[2].U - rCuboid.P[1].U ) ) << m_nYShift2Idx ) 
+                    + m_nMappingOffset ) >> m_nMappingShift );
+  dst.V += ( Pel )( ( ( ( deltaY * ( rCuboid.P[3].V - rCuboid.P[2].V ) ) << m_nUShift2Idx ) 
+                    + ( ( deltaU * ( rCuboid.P[1].V - rCuboid.P[0].V ) ) << m_nYShift2Idx )
+                    + ( ( deltaV * ( rCuboid.P[2].V - rCuboid.P[1].V ) ) << m_nYShift2Idx ) 
+                    + m_nMappingOffset ) >> m_nMappingShift );
+#endif
+  return( dst );
+}
+
+Void TCom3DAsymLUT::xSaveCuboids( SCuboid *** pSrcCuboid )
+{
+#if R0179_ENC_OPT_3DLUT_SIZE
+  memcpy( m_pCuboid[0][0] , pSrcCuboid[0][0] , sizeof( SCuboid ) * getMaxYSize() * getMaxCSize() * getMaxCSize() );
+#else
+  memcpy( m_pCuboid[0][0] , pSrcCuboid[0][0] , sizeof( SCuboid ) * m_nYSize * m_nUSize * m_nVSize );
+#endif 
+}
+
+Void TCom3DAsymLUT::copy3DAsymLUT( TCom3DAsymLUT * pSrc )
+{
+  assert( pSrc->getMaxOctantDepth() == getMaxOctantDepth() && pSrc->getMaxYPartNumLog2() == getMaxYPartNumLog2() );
+  xUpdatePartitioning( pSrc->getCurOctantDepth() , pSrc->getCurYPartNumLog2() 
+#if R0151_CGS_3D_ASYMLUT_IMPROVE
+    , pSrc->getAdaptChromaThresholdU() , pSrc->getAdaptChromaThresholdV()
+#endif
+    );
+  setResQuantBit( pSrc->getResQuantBit() );
+  xSaveCuboids( pSrc->m_pCuboid );
+}
+
+#if R0164_CGS_LUT_BUGFIX_CHECK
+Void TCom3DAsymLUT::xInitCuboids( )
+{
+  // All vertices are initialized as non-exlicitly-encoded
+  for( Int yIdx = 0 ; yIdx < m_nYSize ; yIdx++ )
+  {
+    for( Int uIdx = 0 ; uIdx < m_nUSize ; uIdx++ )
+    {
+      for( Int vIdx = 0 ; vIdx < m_nVSize ; vIdx++ )
+      { 
+        m_pCuboidExplicit[yIdx][uIdx][vIdx] = false;
+        m_pCuboidFilled[yIdx][uIdx][vIdx]   = false;
+      }
+    }
+  }
+}
+
+Void TCom3DAsymLUT::xCuboidsFilledCheck( Int yIdx , Int uIdx , Int vIdx )
+{
+  if ( m_pCuboidFilled[yIdx][uIdx][vIdx] == false )
+  {
+    if( yIdx > 0) 
+      assert ( m_pCuboidFilled[yIdx-1][uIdx][vIdx] );
+
+    for ( Int nVertexIdx=0 ; nVertexIdx<4 ; nVertexIdx++ )
+      m_pCuboid[yIdx][uIdx][vIdx].P[nVertexIdx] = yIdx == 0 ? xGetCuboidVertexPredA( yIdx , uIdx , vIdx , nVertexIdx ): xGetCuboidVertexPredAll( yIdx , uIdx , vIdx , nVertexIdx );
+
+    m_pCuboidFilled[yIdx][uIdx][vIdx] = true ;
+  }
+}
+
+
+Void TCom3DAsymLUT::xCuboidsFilledCheck( Bool bDecode )
+{
+  Int ySize = 1 << ( getCurOctantDepth() + getCurYPartNumLog2() );
+  Int uSize = 1 << getCurOctantDepth();
+  Int vSize = 1 << getCurOctantDepth();
+  for( Int yIdx = 0 ; yIdx < ySize ; yIdx++ )
+  {
+    for( Int uIdx = 0 ; uIdx < uSize ; uIdx++ )
+    {
+      for( Int vIdx = 0 ; vIdx < vSize ; vIdx++ )
+      { 
+        if ( bDecode )
+          xCuboidsFilledCheck( yIdx , uIdx , vIdx );
+
+        assert( m_pCuboidFilled[yIdx][uIdx][vIdx] );
+      }
+    }
+  }
+
+}
+#endif
+
+#if R0150_CGS_SIGNAL_CONSTRAINTS
+Bool TCom3DAsymLUT::isRefLayer( UInt uiRefLayerId )
+{
+  Bool bIsRefLayer = false;
+  for( UInt i = 0 ; i < m_vRefLayerId.size() ; i++ )
+  {
+    if( m_vRefLayerId[i] == uiRefLayerId )
+    {
+      bIsRefLayer = true;
+      break;
+    }
+  }
+
+  return( bIsRefLayer );
+}
+#endif
+
+#if R0164_CGS_LUT_BUGFIX_CHECK
+Void  TCom3DAsymLUT::display( Bool bFilled )
+{
+  Int ySize = 1 << ( getCurOctantDepth() + getCurYPartNumLog2() );
+  Int uSize = 1 << getCurOctantDepth();
+  Int vSize = 1 << getCurOctantDepth();
+  Int vIdx=0;
+
+  printf("\n");
+  printf("3DLut Explicit flag:\n");
+  for( Int uIdx = 0 ; uIdx < uSize ; uIdx++ )
+  {
+    for( Int yIdx = 0 ; yIdx < ySize ; yIdx++ )
+    {
+      printf("%d\t", m_pCuboidExplicit[yIdx][uIdx][vIdx] );
+    }
+    printf("\n");
+  }
+
+  printf("3DLut values (explicit):\n");
+  for( Int uIdx = 0 ; uIdx < uSize ; uIdx++ )
+  {
+    for( Int yIdx = 0 ; yIdx < ySize ; yIdx++ )
+    {
+      if ( m_pCuboidExplicit[yIdx][uIdx][vIdx] )  printf("%d\t", m_pCuboid[yIdx][uIdx][vIdx].P[0].Y );
+      else                                        printf("?\t", m_pCuboid[yIdx][uIdx][vIdx].P[0].Y );
+    }
+    printf("\n");
+  }
+
+  printf("3DLut values (all):\n");
+  for( Int uIdx = 0 ; uIdx < uSize ; uIdx++ )
+  {
+    for( Int yIdx = 0 ; yIdx < ySize ; yIdx++ )
+    {
+      if ( bFilled ) {
+        if ( m_pCuboidFilled[yIdx][uIdx][vIdx] )  printf("%d\t"  , m_pCuboid[yIdx][uIdx][vIdx].P[0].Y );
+        else                                      printf("unk\t" , m_pCuboid[yIdx][uIdx][vIdx].P[0].Y );
+      }
+      else
+        printf("%d\t"  , m_pCuboid[yIdx][uIdx][vIdx].P[0].Y );
+    }
+    printf("\n");
+  }
+
+}
+#endif
+
+#endif
+
Index: /tags/SHM-9.0/source/Lib/TLibCommon/TCom3DAsymLUT.h
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibCommon/TCom3DAsymLUT.h	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibCommon/TCom3DAsymLUT.h	(revision 1088)
@@ -0,0 +1,206 @@
+
+#ifndef __TCOM3DASYMLUT__
+#define __TCOM3DASYMLUT__
+
+#include "TypeDef.h"
+#if R0150_CGS_SIGNAL_CONSTRAINTS
+#include <cassert>
+#include <vector>
+#endif
+
+#if Q0048_CGS_3D_ASYMLUT
+
+typedef struct _SYUVP
+{
+  Pel   Y , U , V;
+}SYUVP;
+
+typedef struct _SCuboid // vertexes for tetrahedral interpolation
+{
+  SYUVP P[4];     // YUV: P0(0,0,0), P1(0,1,0), P3(0,1,1), P7(1,1,1)
+}SCuboid;
+
+class TComPicYuv;
+
+class TCom3DAsymLUT
+{
+public:
+  TCom3DAsymLUT();
+  virtual ~TCom3DAsymLUT();
+
+  virtual Void  create( Int nMaxOctantDepth , Int nInputBitDepth , Int nInputBitDepthC , Int nOutputBitDepth , Int nOutputBitDepthC , Int nMaxYPartNumLog2 
+#if R0151_CGS_3D_ASYMLUT_IMPROVE
+  , Int nAdaptCThresholdU , Int nAdaptCThresholdV
+#endif
+    );
+  virtual Void  destroy();
+
+  Int   getMaxOctantDepth() { return m_nMaxOctantDepth; }
+  Int   getCurOctantDepth() { return m_nCurOctantDepth; }
+  Int   getInputBitDepthY()  { return m_nInputBitDepthY;  }
+  Int   getOutputBitDepthY()  { return m_nOutputBitDepthY;  }
+  Int   getInputBitDepthC()  { return m_nInputBitDepthC;  }
+  Int   getOutputBitDepthC()  { return m_nOutputBitDepthC;  }
+  Int   getResQuantBit()     { return m_nResQuanBit; }
+  Void  setResQuantBit(Int n){ m_nResQuanBit = n; }
+#if R0300_CGS_RES_COEFF_CODING 
+  Int   getMappingShift()     { return m_nMappingShift; }
+  Int   getDeltaBits()        { return m_nDeltaBits; }
+  Void  setDeltaBits(Int n)   { m_nDeltaBits = n; }
+#endif 
+  Int   getMaxYPartNumLog2() { return m_nMaxYPartNumLog2; }
+  Int   getCurYPartNumLog2() { return m_nCurYPartNumLog2; }
+#if R0150_CGS_SIGNAL_CONSTRAINTS
+  Void  addRefLayerId( UInt uiRefLayerId )  
+  { 
+    if( !isRefLayer( uiRefLayerId ) )
+      m_vRefLayerId.push_back( uiRefLayerId ); 
+  }
+  size_t  getRefLayerNum()     { return m_vRefLayerId.size();  }
+  UInt  getRefLayerId( UInt n )  { assert( n < m_vRefLayerId.size() ); return m_vRefLayerId[n];   }
+  Bool  isRefLayer( UInt uiRefLayerId );
+#endif
+#if R0151_CGS_3D_ASYMLUT_IMPROVE
+  Void  setAdaptChromaThresholdU( Int n ) { m_nAdaptCThresholdU = n; }
+  Int   getAdaptChromaThresholdU()        { return m_nAdaptCThresholdU; }
+  Void  setAdaptChromaThresholdV( Int n ) { m_nAdaptCThresholdV = n;  }
+  Int   getAdaptChromaThresholdV()        { return m_nAdaptCThresholdV; }
+#endif
+#if R0179_ENC_OPT_3DLUT_SIZE
+  Int   getMaxYSize() { return 1<<(m_nMaxOctantDepth+m_nMaxYPartNumLog2); }
+  Int   getMaxCSize() { return 1<<m_nMaxOctantDepth; }
+#endif 
+
+  Void  colorMapping( TComPicYuv * pcPicSrc,  TComPicYuv * pcPicDst );
+  Void  copy3DAsymLUT( TCom3DAsymLUT * pSrc );
+
+  SYUVP xGetCuboidVertexPredAll( Int yIdx , Int uIdx , Int vIdx , Int nVertexIdx , SCuboid *** pCurCuboid=NULL );
+  SYUVP getCuboidVertexResTree( Int yIdx , Int uIdx , Int vIdx , Int nVertexIdx );
+  Void  setCuboidVertexResTree( Int yIdx , Int uIdx , Int vIdx , Int nVertexIdx , Int deltaY , Int deltaU , Int deltaV );
+#if R0164_CGS_LUT_BUGFIX_CHECK
+  Void  xInitCuboids( );
+  Void  xCuboidsFilledCheck( Int yIdx , Int uIdx , Int vIdx );
+  Void  xCuboidsFilledCheck( Bool bDecode );
+  Void  display( Bool bFilled=true );
+  Void  xSetExplicit( Int yIdx , Int uIdx , Int vIdx )  { m_pCuboidExplicit[yIdx][uIdx][vIdx] = true ; xSetFilled(yIdx,uIdx,vIdx); }
+  Void  xSetFilled( Int yIdx , Int uIdx , Int vIdx )    { m_pCuboidFilled[yIdx][uIdx][vIdx] = true ; }
+#endif
+
+private:
+  Int   m_nMaxOctantDepth;
+  Int   m_nCurOctantDepth;
+  Int   m_nInputBitDepthY;
+  Int   m_nOutputBitDepthY;
+  Int   m_nInputBitDepthC;
+  Int   m_nOutputBitDepthC;
+  Int   m_nDeltaBitDepthC;
+  Int   m_nDeltaBitDepth;
+  Int   m_nMaxYPartNumLog2;
+  Int   m_nCurYPartNumLog2;
+  Int   m_nMaxPartNumLog2;
+  Int   m_nYSize;
+  Int   m_nUSize;
+  Int   m_nVSize;
+  Int   m_nYShift2Idx;
+  Int   m_nUShift2Idx;
+  Int   m_nVShift2Idx;
+  Int   m_nMappingShift;
+  Int   m_nMappingOffset;
+  Int   m_nResQuanBit;
+#if R0300_CGS_RES_COEFF_CODING
+  Int   m_nDeltaBits;
+#endif
+  SCuboid *** m_pCuboid;
+  const static Int m_nVertexIdxOffset[4][3];
+#if R0150_CGS_SIGNAL_CONSTRAINTS
+  std::vector<UInt> m_vRefLayerId;
+#endif
+#if R0151_CGS_3D_ASYMLUT_IMPROVE
+  Int   m_nAdaptCThresholdU;
+  Int   m_nAdaptCThresholdV;
+#endif
+#if R0164_CGS_LUT_BUGFIX_CHECK
+  Bool  *** m_pCuboidExplicit;
+  Bool  *** m_pCuboidFilled;
+#endif
+
+protected:
+  template <class T> 
+  Void xAllocate3DArray( T*** &p , Int xSize , Int ySize , Int zSize );
+  template <class T> 
+  Void xReset3DArray( T*** &p , Int xSize , Int ySize , Int zSize );
+  template <class T>
+  Void xFree3DArray( T *** &p );
+
+  Void  xUpdatePartitioning( Int nCurOctantDepth , Int nCurYPartNumLog2 
+#if R0151_CGS_3D_ASYMLUT_IMPROVE
+    , Int nAdaptCThresholdU , Int nAdaptCThreshodV
+#endif
+    );
+  SYUVP xGetCuboidVertexPredA( Int yIdx , Int uIdx , Int vIdx , Int nVertexIdx );
+  Pel   xMapY( Pel y , Pel u , Pel v );
+  SYUVP xMapUV( Pel y , Pel u , Pel v );
+  Int   xGetMaxPartNumLog2()  { return m_nMaxPartNumLog2; }
+  Int   xGetYSize()  { return m_nYSize;  }
+  Int   xGetUSize()  { return m_nUSize;  }
+  Int   xGetVSize()  { return m_nVSize;  }
+#if R0151_CGS_3D_ASYMLUT_IMPROVE
+  Int   xGetYIdx(Pel y)  { return( y >> m_nYShift2Idx ); }
+  Int   xGetUIdx(Pel u)  { return( m_nCurOctantDepth == 1 ? u >= m_nAdaptCThresholdU : u >> m_nUShift2Idx ); }
+  Int   xGetVIdx(Pel v)  { return( m_nCurOctantDepth == 1 ? v >= m_nAdaptCThresholdV : v >> m_nVShift2Idx ); }
+  Int   xGetNormCoeffOne()    { return( 1 << m_nMappingShift ); }
+#else
+  Int   xGetYShift2Idx() { return m_nYShift2Idx; }
+  Int   xGetUShift2Idx() { return m_nUShift2Idx; }
+  Int   xGetVShift2Idx() { return m_nVShift2Idx; } 
+#endif
+  SCuboid & xGetCuboid( Int yIdx , Int uIdx , Int vIdx ){ return m_pCuboid[yIdx][uIdx][vIdx];  }
+  Void  xSaveCuboids( SCuboid *** pSrcCuboid );
+};
+
+template <class T> 
+Void TCom3DAsymLUT::xAllocate3DArray( T *** &p , Int xSize , Int ySize , Int zSize )
+{
+  p = new T**[xSize];
+  p[0] = new T*[xSize*ySize];
+  for( Int x = 1 ; x < xSize ; x++ )
+  {
+    p[x] = p[x-1] + ySize;
+  }
+  p[0][0] = new T[xSize*ySize*zSize];
+  for( Int x = 0 ; x < xSize ; x++ )
+  {
+    for( Int y = 0 ; y < ySize ; y++ )
+    {
+      p[x][y] = p[0][0] + x * ySize * zSize + y * zSize;
+    }
+  }
+}
+
+template <class T>
+Void TCom3DAsymLUT::xFree3DArray( T *** &p )
+{
+  if( p != NULL )
+  {
+    if( p[0] != NULL )
+    {
+      if( p[0][0] != NULL )
+      {
+        delete [] p[0][0];
+      }
+      delete [] p[0];
+    }
+    delete [] p;
+    p = NULL;
+  }
+}
+
+template <class T>
+Void TCom3DAsymLUT::xReset3DArray( T*** &p , Int xSize , Int ySize , Int zSize )
+{
+  memset( p[0][0] , 0 , sizeof( T ) * xSize * ySize * zSize );
+}
+
+#endif
+
+#endif
Index: /tags/SHM-9.0/source/Lib/TLibCommon/TComBitCounter.h
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibCommon/TComBitCounter.h	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibCommon/TComBitCounter.h	(revision 1088)
@@ -0,0 +1,71 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TComBitCounter.h
+    \brief    Class for counting bits (header)
+*/
+
+#ifndef __TCOMBITCOUNTER__
+#define __TCOMBITCOUNTER__
+
+#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: /tags/SHM-9.0/source/Lib/TLibCommon/TComBitStream.cpp
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibCommon/TComBitStream.cpp	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibCommon/TComBitStream.cpp	(revision 1088)
@@ -0,0 +1,396 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TComBitStream.cpp
+    \brief    class for handling bitstream
+*/
+
+#include <stdint.h>
+#include <vector>
+#include "TComBitStream.h"
+#include <string.h>
+#include <memory.h>
+
+using namespace std;
+
+//! \ingroup TLibCommon
+//! \{
+
+// ====================================================================================================================
+// Constructor / destructor / create / destroy
+// ====================================================================================================================
+
+TComOutputBitstream::TComOutputBitstream()
+{
+  clear();
+}
+
+TComOutputBitstream::~TComOutputBitstream()
+{
+}
+
+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;
+#if P0138_USE_ALT_CPB_PARAMS_FLAG
+  UInt saved_numBitsRead = m_numBitsRead;
+#endif
+
+  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;
+#if P0138_USE_ALT_CPB_PARAMS_FLAG
+  m_numBitsRead = saved_numBitsRead;
+#endif
+}
+
+
+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 = m_fifo.begin() + pos;
+  m_fifo.insert(at, src.m_fifo.begin(), src.m_fifo.end());
+}
+
+UInt TComInputBitstream::readOutTrailingBits ()
+{
+  UInt count=0;
+  UInt uiBits = 0;
+
+  while ( ( getNumBitsLeft() > 0 ) && (getNumBitsUntilByteAligned()!=0) )
+  {
+    count++;
+    read ( 1, uiBits );
+  }
+  return count;
+}
+//
+//TComOutputBitstream& TComOutputBitstream::operator= (const TComOutputBitstream& src)
+//{
+//  vector<uint8_t>::iterator at = m_fifo.begin();
+//  m_fifo.insert(at, src.m_fifo.begin(), src.m_fifo.end());
+//
+//  m_num_held_bits             = src.m_num_held_bits;
+//  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;
+}
+
+UInt 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);
+  }
+  return numBits+1;
+}
+
+//! \}
Index: /tags/SHM-9.0/source/Lib/TLibCommon/TComBitStream.h
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibCommon/TComBitStream.h	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibCommon/TComBitStream.h	(revision 1088)
@@ -0,0 +1,228 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TComBitStream.h
+    \brief    class for handling bitstream (header)
+*/
+
+#ifndef __TCOMBITSTREAM__
+#define __TCOMBITSTREAM__
+
+#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 */
+  const 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];
+  }
+  
+  UInt        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; }
+  UInt 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: /tags/SHM-9.0/source/Lib/TLibCommon/TComCABACTables.cpp
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibCommon/TComCABACTables.cpp	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibCommon/TComCABACTables.cpp	(revision 1088)
@@ -0,0 +1,123 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TComCABACTables.cpp
+ *  \brief    static class for CABAC tables
+ */
+
+#include "TComCABACTables.h"
+
+//! \ingroup TLibCommon
+//! \{
+
+const UChar TComCABACTables::sm_aucLPSTable[1 << CONTEXT_STATE_BITS][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: /tags/SHM-9.0/source/Lib/TLibCommon/TComCABACTables.h
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibCommon/TComCABACTables.h	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibCommon/TComCABACTables.h	(revision 1088)
@@ -0,0 +1,61 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TComCABACTables.h
+    \brief    static class for CABAC tables
+*/
+
+#ifndef __TCOMCABACTABLES__
+#define __TCOMCABACTABLES__
+
+#include "TLibCommon/CommonDef.h"
+#include "TLibCommon/TComRom.h"
+
+//! \ingroup TLibCommon
+//! \{
+
+/**
+ * \brief static class for CABAC tables
+ */
+
+class TComCABACTables
+{
+public:
+  const static UChar  sm_aucLPSTable[1 << CONTEXT_STATE_BITS][4];
+  const static UChar  sm_aucRenormTable[32];
+};
+
+
+//! \}
+
+#endif
Index: /tags/SHM-9.0/source/Lib/TLibCommon/TComChromaFormat.cpp
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibCommon/TComChromaFormat.cpp	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibCommon/TComChromaFormat.cpp	(revision 1088)
@@ -0,0 +1,142 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+
+#include "TComChromaFormat.h"
+#include "TComPic.h"
+#include "TComDataCU.h"
+#include "TComTrQuant.h"
+#include "TComTU.h"
+
+
+
+
+//----------------------------------------------------------------------------------------------------------------------
+
+InputColourSpaceConversion stringToInputColourSpaceConvert(const std::string &value, const Bool bIsForward)
+{
+  if (value.empty() || value=="UNCHANGED") return IPCOLOURSPACE_UNCHANGED;
+  if (bIsForward)
+  {
+    if (value=="YCbCrtoYYY")                 return IPCOLOURSPACE_YCbCrtoYYY;
+    if (value=="YCbCrtoYCrCb")               return IPCOLOURSPACE_YCbCrtoYCrCb;
+    if (value=="RGBtoGBR")                   return IPCOLOURSPACE_RGBtoGBR;
+  }
+  else
+  {
+    if (value=="YCrCbtoYCbCr")               return IPCOLOURSPACE_YCbCrtoYCrCb;
+    if (value=="GBRtoRGB")                   return IPCOLOURSPACE_RGBtoGBR;
+  }
+  return NUMBER_INPUT_COLOUR_SPACE_CONVERSIONS;
+}
+
+std::string getListOfColourSpaceConverts(const Bool bIsForward)
+{
+  if (bIsForward)
+  {
+    return "UNCHANGED, YCbCrtoYCrCb, YCbCrtoYYY or RGBtoGBR";
+  }
+  else
+  {
+    return "UNCHANGED, YCrCbtoYCbCr or GBRtoRGB";
+  }
+}
+
+
+//----------------------------------------------------------------------------------------------------------------------
+
+Void getTUEntropyCodingParameters(      TUEntropyCodingParameters &result,
+                                        TComTU                    &rTu,
+                                  const ComponentID                component)
+{
+  //------------------------------------------------
+
+  //set the local parameters
+
+        TComDataCU    *const pcCU            = rTu.getCU();
+  const TComRectangle &      area            = rTu.getRect(component);
+  const UInt                 uiAbsPartIdx    = rTu.GetAbsPartIdxTU(component);
+  const UInt                 log2BlockWidth  = g_aucConvertToBit[area.width]  + 2;
+  const UInt                 log2BlockHeight = g_aucConvertToBit[area.height] + 2;
+  const ChannelType          channelType     = toChannelType(component);
+
+  result.scanType = COEFF_SCAN_TYPE(pcCU->getCoefScanIdx(uiAbsPartIdx, area.width, area.height, component));
+
+  //------------------------------------------------
+
+  //set the group layout
+
+  result.widthInGroups  = area.width  >> MLS_CG_LOG2_WIDTH;
+  result.heightInGroups = area.height >> MLS_CG_LOG2_HEIGHT;
+
+  //------------------------------------------------
+
+  //set the scan orders
+
+  const UInt log2WidthInGroups  = g_aucConvertToBit[result.widthInGroups  * 4];
+  const UInt log2HeightInGroups = g_aucConvertToBit[result.heightInGroups * 4];
+
+  result.scan   = g_scanOrder[ SCAN_GROUPED_4x4 ][ result.scanType ][ log2BlockWidth    ][ log2BlockHeight    ];
+  result.scanCG = g_scanOrder[ SCAN_UNGROUPED   ][ result.scanType ][ log2WidthInGroups ][ log2HeightInGroups ];
+
+  //------------------------------------------------
+
+  //set the significance map context selection parameters
+
+  if (pcCU->getSlice()->getSPS()->getUseSingleSignificanceMapContext()
+      && (pcCU->getCUTransquantBypass(uiAbsPartIdx) || (pcCU->getTransformSkip(uiAbsPartIdx, component) != 0)))
+  {
+    result.firstSignificanceMapContext = significanceMapContextSetStart[channelType][CONTEXT_TYPE_SINGLE];
+  }
+  else
+  {
+    if ((area.width == 4) && (area.height == 4))
+    {
+      result.firstSignificanceMapContext = significanceMapContextSetStart[channelType][CONTEXT_TYPE_4x4];
+    }
+    else if ((area.width == 8) && (area.height == 8))
+    {
+      result.firstSignificanceMapContext = significanceMapContextSetStart[channelType][CONTEXT_TYPE_8x8];
+      if (result.scanType != SCAN_DIAG) result.firstSignificanceMapContext += nonDiagonalScan8x8ContextOffset[channelType];
+    }
+    else
+    {
+      result.firstSignificanceMapContext = significanceMapContextSetStart[channelType][CONTEXT_TYPE_NxN];
+    }
+  }
+
+  //------------------------------------------------
+}
+
+
+//----------------------------------------------------------------------------------------------------------------------
Index: /tags/SHM-9.0/source/Lib/TLibCommon/TComChromaFormat.h
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibCommon/TComChromaFormat.h	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibCommon/TComChromaFormat.h	(revision 1088)
@@ -0,0 +1,277 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef __TCOMCHROMAFORMAT__
+#define __TCOMCHROMAFORMAT__
+
+#include "CommonDef.h"
+#include "TComRectangle.h"
+#include "ContextTables.h"
+#include "TComRom.h"
+#include <iostream>
+#include <vector>
+#include <assert.h>
+#include "Debug.h"
+
+//======================================================================================================================
+//Chroma format utility functions  =====================================================================================
+//======================================================================================================================
+
+class TComDataCU;
+
+
+static inline ChannelType toChannelType             (const ComponentID id)                         { return (id==COMPONENT_Y)? CHANNEL_TYPE_LUMA : CHANNEL_TYPE_CHROMA; }
+static inline Bool        isLuma                    (const ComponentID id)                         { return (id==COMPONENT_Y);                                          }
+static inline Bool        isLuma                    (const ChannelType id)                         { return (id==CHANNEL_TYPE_LUMA);                                    }
+static inline Bool        isChroma                  (const ComponentID id)                         { return (id!=COMPONENT_Y);                                          }
+static inline Bool        isChroma                  (const ChannelType id)                         { return (id!=CHANNEL_TYPE_LUMA);                                    }
+static inline UInt        getChannelTypeScaleX      (const ChannelType id, const ChromaFormat fmt) { return (isLuma(id) || (fmt==CHROMA_444)) ? 0 : 1;                  }
+static inline UInt        getChannelTypeScaleY      (const ChannelType id, const ChromaFormat fmt) { return (isLuma(id) || (fmt!=CHROMA_420)) ? 0 : 1;                  }
+static inline UInt        getComponentScaleX        (const ComponentID id, const ChromaFormat fmt) { return getChannelTypeScaleX(toChannelType(id), fmt);               }
+static inline UInt        getComponentScaleY        (const ComponentID id, const ChromaFormat fmt) { return getChannelTypeScaleY(toChannelType(id), fmt);               }
+static inline UInt        getNumberValidChannelTypes(const ChromaFormat fmt)                       { return (fmt==CHROMA_400) ? 1 : MAX_NUM_CHANNEL_TYPE;               }
+static inline UInt        getNumberValidComponents  (const ChromaFormat fmt)                       { return (fmt==CHROMA_400) ? 1 : MAX_NUM_COMPONENT;                  }
+static inline Bool        isChromaEnabled           (const ChromaFormat fmt)                       { return  fmt!=CHROMA_400;                                           }
+static inline ComponentID getFirstComponentOfChannel(const ChannelType id)                         { return (isLuma(id) ? COMPONENT_Y : COMPONENT_Cb);                  }
+
+InputColourSpaceConversion stringToInputColourSpaceConvert(const std::string &value, const Bool bIsForward);
+std::string getListOfColourSpaceConverts(const Bool bIsForward);
+
+//------------------------------------------------
+
+static inline UInt getTotalSamples(const UInt width, const UInt height, const ChromaFormat format)
+{
+  const UInt samplesPerChannel = width * height;
+
+  switch (format)
+  {
+    case CHROMA_400: return  samplesPerChannel;           break;
+    case CHROMA_420: return (samplesPerChannel * 3) >> 1; break;
+    case CHROMA_422: return  samplesPerChannel * 2;       break;
+    case CHROMA_444: return  samplesPerChannel * 3;       break;
+    default:
+      std::cerr << "ERROR: Unrecognised chroma format in getTotalSamples()" << std::endl;
+      exit(1);
+      break;
+  }
+
+  return MAX_UINT;
+}
+
+//------------------------------------------------
+
+static inline UInt getTotalBits(const UInt width, const UInt height, const ChromaFormat format, const Int bitDepths[MAX_NUM_CHANNEL_TYPE])
+{
+  const UInt samplesPerChannel = width * height;
+
+  switch (format)
+  {
+    case CHROMA_400: return  samplesPerChannel *  bitDepths[CHANNEL_TYPE_LUMA];                                              break;
+    case CHROMA_420: return (samplesPerChannel * (bitDepths[CHANNEL_TYPE_LUMA]*2 +   bitDepths[CHANNEL_TYPE_CHROMA]) ) >> 1; break;
+    case CHROMA_422: return  samplesPerChannel * (bitDepths[CHANNEL_TYPE_LUMA]   +   bitDepths[CHANNEL_TYPE_CHROMA]);        break;
+    case CHROMA_444: return  samplesPerChannel * (bitDepths[CHANNEL_TYPE_LUMA]   + 2*bitDepths[CHANNEL_TYPE_CHROMA]);        break;
+    default:
+      std::cerr << "ERROR: Unrecognised chroma format in getTotalSamples()" << std::endl;
+      exit(1);
+      break;
+  }
+
+  return MAX_UINT;
+}
+
+
+//------------------------------------------------
+
+// In HM, a CU only has one chroma intra prediction direction, that corresponds to the top left luma intra prediction
+// even if the NxN PU split occurs when 4 sub-TUs exist for chroma.
+// Use this function to allow NxN PU splitting for chroma.
+
+static inline Bool enable4ChromaPUsInIntraNxNCU(const ChromaFormat chFmt)
+{
+  return (chFmt == CHROMA_444);
+}
+
+
+//------------------------------------------------
+
+//returns the part index of the luma region that is co-located with the specified chroma region
+
+static inline UInt getChromasCorrespondingPULumaIdx(const UInt lumaZOrderIdxInCtu, const ChromaFormat chFmt)
+{
+  return enable4ChromaPUsInIntraNxNCU(chFmt) ? lumaZOrderIdxInCtu : lumaZOrderIdxInCtu & (~((1<<(2*g_uiAddCUDepth))-1)); //(lumaZOrderIdxInCtu/numParts)*numParts;
+}
+
+//------------------------------------------------
+
+// If chroma format is 4:2:2 and a chroma-square-sub-tu is possible for the smallest TU, then increase the depth by 1 to allow for more parts.
+
+static inline UInt getMaxCUDepthOffset(const ChromaFormat chFmt, const UInt quadtreeTULog2MinSize)
+{
+  return (chFmt==CHROMA_422 && quadtreeTULog2MinSize>2) ? 1 : 0;
+}
+
+//======================================================================================================================
+//Intra prediction  ====================================================================================================
+//======================================================================================================================
+
+static inline Bool filterIntraReferenceSamples (const ChannelType chType, const ChromaFormat chFmt, const Bool intraReferenceSmoothingDisabled)
+{
+  return (!intraReferenceSmoothingDisabled) && (isLuma(chType) || (chFmt == CHROMA_444));
+}
+
+
+//======================================================================================================================
+//Transform and Quantisation  ==========================================================================================
+//======================================================================================================================
+
+static inline Bool TUCompRectHasAssociatedTransformSkipFlag(const TComRectangle &rectSamples, const UInt transformSkipLog2MaxSize)
+{
+  return (rectSamples.width <= (1<<transformSkipLog2MaxSize));
+}
+
+
+//------------------------------------------------
+
+static inline Int getTransformShift(const ChannelType type, const UInt uiLog2TrSize)
+{
+#if O0043_BEST_EFFORT_DECODING
+  return g_maxTrDynamicRange[type] - g_bitDepthInStream[type] - uiLog2TrSize;
+#else
+  return g_maxTrDynamicRange[type] - g_bitDepth[type] - uiLog2TrSize;
+#endif
+}
+
+
+//------------------------------------------------
+
+static inline Int getScaledChromaQP(Int unscaledChromaQP, const ChromaFormat chFmt)
+{
+  return g_aucChromaScale[chFmt][Clip3(0, (chromaQPMappingTableSize - 1), unscaledChromaQP)];
+}
+
+
+//======================================================================================================================
+//Scaling lists  =======================================================================================================
+//======================================================================================================================
+
+static inline Int getScalingListType(const PredMode predMode, const ComponentID compID)
+{
+  return ((predMode != MODE_INTER) ? 0 : MAX_NUM_COMPONENT) + compID;
+}
+
+
+//------------------------------------------------
+
+
+//======================================================================================================================
+//Context variable selection  ==========================================================================================
+//======================================================================================================================
+
+//context variable source tables
+
+static const UInt significanceMapContextStartTable[MAX_NUM_CHANNEL_TYPE] = {FIRST_SIG_FLAG_CTX_LUMA, FIRST_SIG_FLAG_CTX_CHROMA};
+static const UInt contextSetStartTable            [MAX_NUM_CHANNEL_TYPE] = {FIRST_CTX_SET_LUMA,      FIRST_CTX_SET_CHROMA     };
+static const UInt CBFContextStartTable            [MAX_NUM_CHANNEL_TYPE] = {FIRST_CBF_CTX_LUMA,      FIRST_CBF_CTX_CHROMA     };
+
+
+//------------------------------------------------
+
+//Function for last-significant-coefficient context selection parameters
+
+static inline Void getLastSignificantContextParameters (const ComponentID  component,
+                                                        const Int          width,
+                                                        const Int          height,
+                                                              Int         &result_offsetX,
+                                                              Int         &result_offsetY,
+                                                              Int         &result_shiftX,
+                                                              Int         &result_shiftY)
+{
+  const UInt convertedWidth  = g_aucConvertToBit[width];
+  const UInt convertedHeight = g_aucConvertToBit[height];
+
+  result_offsetX = (isChroma(component)) ? 0               : ((convertedWidth  * 3) + ((convertedWidth  + 1) >> 2));
+  result_offsetY = (isChroma(component)) ? 0               : ((convertedHeight * 3) + ((convertedHeight + 1) >> 2));
+  result_shiftX  = (isChroma(component)) ? convertedWidth  : ((convertedWidth  + 3) >> 2);
+  result_shiftY  = (isChroma(component)) ? convertedHeight : ((convertedHeight + 3) >> 2);
+}
+
+
+//------------------------------------------------
+
+//Function for significance map context index offset selection
+
+static inline UInt getSignificanceMapContextOffset (const ComponentID component)
+{
+  return significanceMapContextStartTable[toChannelType(component)];
+}
+
+
+//------------------------------------------------
+
+// Function for greater-than-one map/greater-than-two map context set selection
+
+static inline UInt getContextSetIndex (const ComponentID  component,
+                                       const UInt         subsetIndex,
+                                       const Bool         foundACoefficientGreaterThan1)
+{
+  const UInt notFirstSubsetOffset     = (isLuma(component) && (subsetIndex > 0)) ? 2 : 0;
+  const UInt foundAGreaterThan1Offset = foundACoefficientGreaterThan1            ? 1 : 0;
+
+  return contextSetStartTable[toChannelType(component)] + notFirstSubsetOffset + foundAGreaterThan1Offset;
+}
+
+
+//------------------------------------------------
+
+//Function for CBF context index offset
+
+static inline UInt getCBFContextOffset (const ComponentID component)
+{
+  return CBFContextStartTable[toChannelType(component)];
+}
+
+
+//======================================================================================================================
+//Entropy coding parameters ============================================================================================
+//======================================================================================================================
+
+Void getTUEntropyCodingParameters(      TUEntropyCodingParameters &result,
+                                  class TComTU                    &rTu,
+                                  const ComponentID                component);
+
+
+//======================================================================================================================
+//End  =================================================================================================================
+//======================================================================================================================
+
+#endif
Index: /tags/SHM-9.0/source/Lib/TLibCommon/TComCodingStatistics.h
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibCommon/TComCodingStatistics.h	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibCommon/TComCodingStatistics.h	(revision 1088)
@@ -0,0 +1,470 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef __TCOMCODINGSTATISTICS__
+#define __TCOMCODINGSTATISTICS__
+
+#include "TypeDef.h"
+#include <stdio.h>
+#include <string>
+#include <map>
+#include <math.h>
+#include "TComChromaFormat.h"
+
+static const Int64 TCOMCODINGSTATISTICS_ENTROPYSCALE=32768;
+
+
+enum TComCodingStatisticsType
+{
+  STATS__NAL_UNIT_TOTAL_BODY,// This is a special case and is not included in the total sums.
+  STATS__NAL_UNIT_PACKING,
+  STATS__EMULATION_PREVENTION_3_BYTES,
+  STATS__NAL_UNIT_HEADER_BITS,
+  STATS__CABAC_INITIALISATION,
+  STATS__CABAC_BITS__TQ_BYPASS_FLAG,
+  STATS__CABAC_BITS__SKIP_FLAG,
+  STATS__CABAC_BITS__MERGE_FLAG,
+  STATS__CABAC_BITS__MERGE_INDEX,
+  STATS__CABAC_BITS__MVP_IDX,
+  STATS__CABAC_BITS__SPLIT_FLAG,
+  STATS__CABAC_BITS__PART_SIZE,
+  STATS__CABAC_BITS__PRED_MODE,
+  STATS__CABAC_BITS__INTRA_DIR_ANG,
+  STATS__CABAC_BITS__INTER_DIR,
+  STATS__CABAC_BITS__REF_FRM_IDX,
+  STATS__CABAC_BITS__MVD,
+  STATS__CABAC_BITS__MVD_EP,
+  STATS__CABAC_BITS__TRANSFORM_SUBDIV_FLAG,
+  STATS__CABAC_BITS__QT_ROOT_CBF,
+  STATS__CABAC_BITS__DELTA_QP_EP,
+  STATS__CABAC_BITS__CHROMA_QP_ADJUSTMENT,
+  STATS__CABAC_BITS__QT_CBF,
+  STATS__CABAC_BITS__CROSS_COMPONENT_PREDICTION,
+  STATS__CABAC_BITS__TRANSFORM_SKIP_FLAGS,
+
+  STATS__CABAC_BITS__LAST_SIG_X_Y,
+  STATS__CABAC_BITS__SIG_COEFF_GROUP_FLAG,
+  STATS__CABAC_BITS__SIG_COEFF_MAP_FLAG,
+  STATS__CABAC_BITS__GT1_FLAG,
+  STATS__CABAC_BITS__GT2_FLAG,
+  STATS__CABAC_BITS__SIGN_BIT,
+  STATS__CABAC_BITS__ESCAPE_BITS,
+
+  STATS__CABAC_BITS__SAO,
+  STATS__CABAC_TRM_BITS,
+  STATS__CABAC_FIXED_BITS,
+  STATS__CABAC_PCM_ALIGN_BITS,
+  STATS__CABAC_PCM_CODE_BITS,
+  STATS__BYTE_ALIGNMENT_BITS,
+  STATS__TRAILING_BITS,
+  STATS__EXPLICIT_RDPCM_BITS,
+  STATS__CABAC_EP_BIT_ALIGNMENT,
+  STATS__CABAC_BITS__ALIGNED_SIGN_BIT,
+  STATS__CABAC_BITS__ALIGNED_ESCAPE_BITS,
+  STATS__NUM_STATS
+};
+
+static inline const Char* getName(TComCodingStatisticsType name)
+{
+  static const Char *statNames[]=
+  {
+    "NAL_UNIT_TOTAL_BODY", // This is a special case and is not included in the total sums.
+    "NAL_UNIT_PACKING",
+    "EMULATION_PREVENTION_3_BYTES",
+    "NAL_UNIT_HEADER_BITS",
+    "CABAC_INITIALISATION-and-rounding",
+    "CABAC_BITS__TQ_BYPASS_FLAG",
+    "CABAC_BITS__SKIP_FLAG",
+    "CABAC_BITS__MERGE_FLAG",
+    "CABAC_BITS__MERGE_INDEX",
+    "CABAC_BITS__MVP_IDX",
+    "CABAC_BITS__SPLIT_FLAG",
+    "CABAC_BITS__PART_SIZE",
+    "CABAC_BITS__PRED_MODE",
+    "CABAC_BITS__INTRA_DIR_ANG",
+    "CABAC_BITS__INTER_DIR",
+    "CABAC_BITS__REF_FRM_IDX",
+    "CABAC_BITS__MVD",
+    "CABAC_BITS__MVD_EP",
+    "CABAC_BITS__TRANSFORM_SUBDIV_FLAG",
+    "CABAC_BITS__QT_ROOT_CBF",
+    "CABAC_BITS__DELTA_QP_EP",
+    "CABAC_BITS__CHROMA_QP_ADJUSTMENT",
+    "CABAC_BITS__QT_CBF",
+    "CABAC_BITS__CROSS_COMPONENT_PREDICTION",
+    "CABAC_BITS__TRANSFORM_SKIP_FLAGS",
+    "CABAC_BITS__LAST_SIG_X_Y",
+    "CABAC_BITS__SIG_COEFF_GROUP_FLAG",
+    "CABAC_BITS__SIG_COEFF_MAP_FLAG",
+    "CABAC_BITS__GT1_FLAG",
+    "CABAC_BITS__GT2_FLAG",
+    "CABAC_BITS__SIGN_BIT",
+    "CABAC_BITS__ESCAPE_BITS",
+    "CABAC_BITS__SAO",
+    "CABAC_TRM_BITS",
+    "CABAC_FIXED_BITS",
+    "CABAC_PCM_ALIGN_BITS",
+    "CABAC_PCM_CODE_BITS",
+    "BYTE_ALIGNMENT_BITS",
+    "TRAILING_BITS",
+    "EXPLICIT_RDPCM_BITS",
+    "CABAC_EP_BIT_ALIGNMENT",
+    "CABAC_BITS__ALIGNED_SIGN_BIT",
+    "CABAC_BITS__ALIGNED_ESCAPE_BITS"
+  };
+  assert(STATS__NUM_STATS == sizeof(statNames)/sizeof(Char *) && name < STATS__NUM_STATS);
+  return statNames[name];
+}
+
+static inline Bool isAlignedBins(TComCodingStatisticsType statT) { return statT==STATS__CABAC_BITS__ALIGNED_SIGN_BIT || statT==STATS__CABAC_BITS__ALIGNED_ESCAPE_BITS; }
+
+static const UInt CODING_STATS_NUM_WIDTHS=7;
+static const UInt CODING_STATS_NUM_SUBCLASSES=CODING_STATS_NUM_WIDTHS*(1+MAX_NUM_COMPONENT+MAX_NUM_CHANNEL_TYPE);
+
+class TComCodingStatisticsClassType
+{
+public:
+
+  TComCodingStatisticsClassType(const TComCodingStatisticsType t)
+    : type(t), subClass(0)
+  { }
+  TComCodingStatisticsClassType(const TComCodingStatisticsType t, const UInt log2w )
+    : type(t), subClass(log2w)
+  { }
+  TComCodingStatisticsClassType(const TComCodingStatisticsType t, const Int log2w )
+    : type(t), subClass(log2w)
+  { }
+  TComCodingStatisticsClassType(const TComCodingStatisticsType t, const ComponentID cid )
+    : type(t), subClass((cid+1)*CODING_STATS_NUM_WIDTHS)
+  { }
+  TComCodingStatisticsClassType(const TComCodingStatisticsType t, const ChannelType chid )
+    : type(t), subClass((chid+MAX_NUM_COMPONENT+1)*CODING_STATS_NUM_WIDTHS)
+  { }
+  TComCodingStatisticsClassType(const TComCodingStatisticsType t, const UInt log2w, const ComponentID cid )
+    : type(t), subClass((cid+1)*CODING_STATS_NUM_WIDTHS + log2w)
+  { }
+  TComCodingStatisticsClassType(const TComCodingStatisticsType t, const UInt log2w, const ChannelType chid )
+    : type(t), subClass((chid+MAX_NUM_COMPONENT+1)*CODING_STATS_NUM_WIDTHS + log2w)
+  { }
+
+  static UInt GetSubClassWidth(const UInt subClass)
+  {
+    return subClass%CODING_STATS_NUM_WIDTHS;
+  }
+
+  static const Char *GetSubClassString(const UInt subClass)
+  {
+    assert (subClass<CODING_STATS_NUM_SUBCLASSES);
+    static const Char *strings[1+MAX_NUM_COMPONENT+MAX_NUM_CHANNEL_TYPE]={"-", "Y", "Cb", "Cr", "Luma", "Chroma"};
+    return strings[subClass/CODING_STATS_NUM_WIDTHS];
+  }
+
+  TComCodingStatisticsType type;
+  UInt subClass;
+};
+
+
+
+class TComCodingStatistics
+{
+  public:
+
+
+    struct StatLogValue
+    {
+      UInt values[512+1];
+      StatLogValue()
+      {
+        const Double es=Double(TCOMCODINGSTATISTICS_ENTROPYSCALE);
+        values[0]=0;
+        for(UInt i=1; i<sizeof(values)/sizeof(UInt); i++)
+        {
+          values[i]=UInt(    log(Double(i))*es/log(2.0)  );
+        }
+      }
+    };
+
+    struct SStat
+    {
+      SStat() : bits(0), count(0), sum(0) { }
+      Int64 bits;
+      Int64 count;
+      Int64 sum;
+      Void clear() { bits=0; count=0; sum=0; }
+
+      SStat &operator+=(const SStat &src)
+      { bits+=src.bits; count+=src.count; sum+=src.sum; return *this; }
+    };
+
+    class TComCodingStatisticsData
+    {
+      private:
+        SStat statistics[STATS__NUM_STATS+1][CODING_STATS_NUM_SUBCLASSES];
+        SStat statistics_ep[STATS__NUM_STATS+1][CODING_STATS_NUM_SUBCLASSES ];
+        std::map<std::string, SStat> mappings_ep;
+        friend class TComCodingStatistics;
+    };
+
+  private:
+
+    TComCodingStatisticsData data;
+
+    TComCodingStatistics() : data()
+    { }
+
+    static Void OutputLine(const Char *pName, const Char sep, UInt width, const Char *pSubClassStr, const SStat &sCABAC, const SStat &sEP)
+    {
+      if (width==0)
+        OutputLine(pName, sep, "-", pSubClassStr, sCABAC, sEP);
+      else
+        printf("%c%-45s%c  %6d %6s %12lld %12lld %12lld %12lld %12lld %12lld %12lld (%12lld)%c\n",
+          sep=='~'?'[':' ', pName, sep, 1<<width, pSubClassStr,
+              sCABAC.count, sCABAC.sum, sCABAC.bits, sEP.count, sEP.sum, sEP.bits, sCABAC.bits+sEP.bits, (sCABAC.bits+sEP.bits)/8, sep=='~'?']':' ');
+    }
+    static Void OutputLine(const Char *pName, const Char sep, const Char *pWidthString, const Char *pSubClassStr, const SStat &sCABAC, const SStat &sEP)
+    {
+      printf("%c%-45s%c  %6s %6s %12lld %12lld %12lld %12lld %12lld %12lld %12lld (%12lld)%c\n",
+          sep=='~'?'[':' ', pName, sep, pWidthString, pSubClassStr,
+              sCABAC.count, sCABAC.sum, sCABAC.bits, sEP.count, sEP.sum, sEP.bits, sCABAC.bits+sEP.bits, (sCABAC.bits+sEP.bits)/8, sep=='~'?']':' ');
+    }
+    static Void OutputLine(const Char *pName, const Char sep, const Char *pWidthString, const Char *pSubClassStr,  const SStat &sEP)
+    {
+      printf("%c%-45s%c  %6s %6s %12s %12s %12s %12lld %12lld %12lld %12lld (%12lld)%c\n",
+          sep=='~'?'[':' ', pName, sep, pWidthString, pSubClassStr,
+              "", "", "", sEP.count, sEP.sum, sEP.bits, sEP.bits, (sEP.bits)/8, sep=='~'?']':' ');
+    }
+
+    static Void OutputDashedLine(const Char *pText)
+    {
+      printf("--%s",pText);
+      UInt tot=0;
+      for(;pText[tot]!=0; tot++);
+      tot+=2;
+      for (; tot<168; tot++)
+      {
+        printf("-");
+      }
+      printf("\n");
+    }
+
+    ~TComCodingStatistics()
+    {
+      const Int64 es=TCOMCODINGSTATISTICS_ENTROPYSCALE;
+
+      Int64 cr=0; // CABAC remainder, which is added to "STATS__CABAC_INITIALISATION"
+      {
+        Int64 totalCABACbits=0, roundedCABACbits=0;
+        for(Int i=STATS__NAL_UNIT_PACKING; i<STATS__NUM_STATS; i++)
+        {
+          for(UInt c=0; c<CODING_STATS_NUM_SUBCLASSES; c++)
+          {
+            totalCABACbits+=data.statistics[i][c].bits;
+            roundedCABACbits+=data.statistics[i][c].bits/es;
+          }
+        }
+        Int64 remainder=totalCABACbits - roundedCABACbits*es;
+        cr=(remainder+es/2)/es;
+      }
+
+      printf("Note %s will be excluded from the total as it should be the sum of all the other entries (except for %s)\n", getName(STATS__NAL_UNIT_TOTAL_BODY), getName(STATS__NAL_UNIT_PACKING));
+      printf(" %-45s-   Width   Type  CABAC Count    CABAC Sum   CABAC bits     EP Count       EP Sum      EP bits   Total bits ( Total bytes)\n", "Decoder statistics");
+
+      OutputDashedLine("");
+      SStat cabacTotalBits, epTotalBits;
+      SStat statTotals_cabac[CODING_STATS_NUM_SUBCLASSES];
+      SStat statTotals_ep[CODING_STATS_NUM_SUBCLASSES];
+
+      for(Int i=0; i<STATS__NUM_STATS; i++)
+      {
+        SStat cabacSubTotal, epSubTotal;
+        Bool bHadClassifiedEntry=false;
+        const Char *pName=getName(TComCodingStatisticsType(i));
+
+        for(UInt c=0; c<CODING_STATS_NUM_SUBCLASSES; c++)
+        {
+          SStat &sCABACorig=data.statistics[i][c];
+          SStat &sEP=data.statistics_ep[i][c];
+
+          if (sCABACorig.bits==0 && sEP.bits==0) continue;
+
+          SStat sCABAC;
+          {
+            Int64 thisCABACbits=sCABACorig.bits/es; if (i==STATS__CABAC_INITIALISATION && sCABACorig.bits!=0) { thisCABACbits+=cr; cr=0; }
+            sCABAC.bits=thisCABACbits; sCABAC.count=sCABACorig.count; sCABAC.sum=sCABACorig.sum;
+          }
+          UInt width=TComCodingStatisticsClassType::GetSubClassWidth(c);
+          OutputLine(pName, ':', width, TComCodingStatisticsClassType::GetSubClassString(c), sCABAC, sEP);
+          cabacSubTotal+=sCABAC;
+          epSubTotal+=sEP;
+          if (i!=STATS__NAL_UNIT_TOTAL_BODY)
+          {
+            cabacTotalBits+=sCABAC;
+            epTotalBits+=sEP;
+            statTotals_cabac[c]+=sCABAC;
+            statTotals_ep[c]+=sEP;
+          }
+          bHadClassifiedEntry=bHadClassifiedEntry||(c!=0);
+        }
+        if (bHadClassifiedEntry)
+        {
+          OutputLine(pName, '~', "~~ST~~", "~~ST~~", cabacSubTotal, epSubTotal);
+        }
+        if (i==STATS__NAL_UNIT_TOTAL_BODY)
+        {
+          OutputDashedLine("");
+        }
+      }
+      OutputDashedLine("");
+      OutputLine("CABAC Sub-total", '~', "~~ST~~", "~~ST~~", cabacTotalBits, epTotalBits);
+
+      OutputDashedLine("CAVLC HEADER BITS");
+      SStat cavlcTotalBits;
+      for(std::map<std::string, SStat>::iterator it=data.mappings_ep.begin(); it!=data.mappings_ep.end(); it++)
+      {
+        SStat s=it->second;
+        cavlcTotalBits+=s;
+        OutputLine(it->first.c_str(), ':', "-", "-", s);
+      }
+
+      OutputDashedLine("");
+      OutputLine("CAVLC Header Sub-total", '~', "~~ST~~", "~~ST~~", cavlcTotalBits);
+
+      // Now output the breakdowns
+      OutputDashedLine("CABAC Break down by size");
+      for(UInt s=0; s<CODING_STATS_NUM_WIDTHS; s++)
+      {
+        SStat subTotalCabac, subTotalEP;
+        for(UInt c=0; c<CODING_STATS_NUM_SUBCLASSES; c+=CODING_STATS_NUM_WIDTHS)
+        {
+          subTotalCabac+=statTotals_cabac[c+s];
+          subTotalEP+=statTotals_ep[c+s];
+        }
+        if (subTotalCabac.bits!=0 || subTotalEP.bits!=0)
+        {
+          OutputLine("CABAC by size Sub-total", '=', s, "All", subTotalCabac, subTotalEP);
+        }
+      }
+      OutputDashedLine("Break down by component/Channel type");
+      for(UInt c=0; c<CODING_STATS_NUM_SUBCLASSES; c+=CODING_STATS_NUM_WIDTHS)
+      {
+        SStat subTotalCabac, subTotalEP;
+        for(UInt s=0; s<CODING_STATS_NUM_WIDTHS; s++)
+        {
+          subTotalCabac+=statTotals_cabac[c+s];
+          subTotalEP+=statTotals_ep[c+s];
+        }
+        if (subTotalCabac.bits!=0 || subTotalEP.bits!=0)
+        {
+          OutputLine("CABAC by type Sub-total", '=', "-", TComCodingStatisticsClassType::GetSubClassString(c), subTotalCabac, subTotalEP);
+        }
+      }
+      OutputDashedLine("Break down by size and component/Channel type");
+      for(UInt c=0; c<CODING_STATS_NUM_SUBCLASSES; c+=CODING_STATS_NUM_WIDTHS)
+      {
+        for(UInt s=0; s<CODING_STATS_NUM_WIDTHS; s++)
+        {
+          SStat subTotalCabac, subTotalEP;
+          subTotalCabac+=statTotals_cabac[c+s];
+          subTotalEP+=statTotals_ep[c+s];
+          if (subTotalCabac.bits!=0 || subTotalEP.bits!=0)
+          {
+            OutputLine("CABAC by size and type Sub-total", '=', s, TComCodingStatisticsClassType::GetSubClassString(c), subTotalCabac, subTotalEP);
+          }
+        }
+      }
+
+      OutputDashedLine("");
+      OutputLine("CABAC Sub-total", '~', "~~ST~~", "~~ST~~", cabacTotalBits, epTotalBits);
+      OutputLine("CAVLC Header Sub-total", '~', "~~ST~~", "~~ST~~", cavlcTotalBits);
+      OutputDashedLine("GRAND TOTAL");
+      epTotalBits+=cavlcTotalBits;
+      OutputLine("TOTAL", '~', "~~GT~~", "~~GT~~", cabacTotalBits, epTotalBits);
+    }
+
+
+  public:
+    static TComCodingStatistics& GetSingletonInstance()
+    {
+      static TComCodingStatistics inst;
+      return inst;
+    }
+
+    static const TComCodingStatisticsData &GetStatistics()         { return GetSingletonInstance().data; }
+    static Void SetStatistics(const TComCodingStatisticsData &src) { GetSingletonInstance().data=src; }
+
+    static SStat &GetStatisticEP(const TComCodingStatisticsClassType &stat) { return GetSingletonInstance().data.statistics_ep[stat.type][stat.subClass]; }
+
+    static SStat &GetStatisticEP(const std::string &str) { return GetSingletonInstance().data.mappings_ep[str]; }
+
+    static SStat &GetStatisticEP(const Char *pKey) {return GetStatisticEP(std::string(pKey)); }
+
+    static Void IncrementStatisticEP(const TComCodingStatisticsClassType &stat, const Int numBits, const Int value)
+    {
+      SStat &s=GetStatisticEP(stat);
+      s.bits+=numBits;
+      s.count++;
+      s.sum+=value;
+    }
+
+    static Void IncrementStatisticEP(const std::string &str, const Int numBits, const Int value)
+    {
+      SStat &s=GetStatisticEP(str);
+      s.bits+=numBits;
+      s.count++;
+      s.sum+=value;
+    }
+
+    static Void IncrementStatisticEP(const Char *pKey, const Int numBits, const Int value)
+    {
+      SStat &s=GetStatisticEP(pKey);
+      s.bits+=numBits;
+      s.count++;
+      s.sum+=value;
+    }
+
+    StatLogValue values;
+
+    static Void UpdateCABACStat(const TComCodingStatisticsClassType &stat, UInt uiRangeBefore, UInt uiRangeAfter, Int val)
+    {
+      TComCodingStatistics &inst=GetSingletonInstance();
+      // doing rangeBefore*p(x)=rangeAfter
+      // p(x)=rangeAfter/rangeBefore
+      // entropy = -log2(p(x))=-log(p(x))/log(2) = -(log rangeAfter - log rangeBefore) / log(2) = (log rangeBefore / log 2 - log rangeAfter / log 2)
+      SStat &s=inst.data.statistics[stat.type][stat.subClass];
+      s.bits+=inst.values.values[uiRangeBefore]-inst.values.values[uiRangeAfter];
+      s.count++;
+      s.sum+=val;
+    }
+};
+
+#endif
Index: /tags/SHM-9.0/source/Lib/TLibCommon/TComDataCU.cpp
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibCommon/TComDataCU.cpp	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibCommon/TComDataCU.cpp	(revision 1088)
@@ -0,0 +1,3660 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TComDataCU.cpp
+    \brief    CU data structure
+    \todo     not all entities are documented
+*/
+
+#include "TComDataCU.h"
+#include "TComTU.h"
+#include "TComPic.h"
+
+//! \ingroup TLibCommon
+//! \{
+
+#if ADAPTIVE_QP_SELECTION
+  TCoeff * TComDataCU::m_pcGlbArlCoeff[MAX_NUM_COMPONENT] = { NULL, NULL, 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_ChromaQpAdj        = NULL;
+  m_pbMergeFlag        = NULL;
+  m_puhMergeIndex      = NULL;
+  for(UInt i=0; i<MAX_NUM_CHANNEL_TYPE; i++)
+  {
+    m_puhIntraDir[i]     = NULL;
+  }
+  m_puhInterDir        = NULL;
+  m_puhTrIdx           = NULL;
+
+  for (UInt comp=0; comp<MAX_NUM_COMPONENT; comp++)
+  {
+    m_puhCbf[comp]                        = NULL;
+    m_crossComponentPredictionAlpha[comp] = NULL;
+    m_puhTransformSkip[comp]              = NULL;
+    m_pcTrCoeff[comp]                     = NULL;
+#if ADAPTIVE_QP_SELECTION
+    m_pcArlCoeff[comp]                    = NULL;
+#endif
+    m_pcIPCMSample[comp]                  = NULL;
+    m_explicitRdpcmMode[comp]             = NULL;
+  }
+#if ADAPTIVE_QP_SELECTION
+  m_ArlCoeffIsAliasedAllocation = false;
+#endif
+  m_pbIPCMFlag         = NULL;
+
+  m_pCtuAboveLeft      = NULL;
+  m_pCtuAboveRight     = NULL;
+  m_pCtuAbove          = NULL;
+  m_pCtuLeft           = NULL;
+
+  for(UInt i=0; i<NUM_REF_PIC_LIST_01; i++)
+  {
+    m_apcCUColocated[i]  = NULL;
+    m_apiMVPIdx[i]       = NULL;
+    m_apiMVPNum[i]       = NULL;
+  }
+
+  m_bDecSubCu          = false;
+}
+
+TComDataCU::~TComDataCU()
+{
+}
+
+Void TComDataCU::create( ChromaFormat chromaFormatIDC, 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_ChromaQpAdj        = new UChar[ uiNumPartition ];
+    m_skipFlag           = new Bool[ uiNumPartition ];
+    m_pePartSize         = new Char[ uiNumPartition ];
+    memset( m_pePartSize, NUMBER_OF_PART_SIZES,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);
+
+    for (UInt ch=0; ch<MAX_NUM_CHANNEL_TYPE; ch++)
+    {
+      m_puhIntraDir[ch] = (UChar* )xMalloc(UChar,  uiNumPartition);
+    }
+    m_puhInterDir        = (UChar* )xMalloc(UChar,  uiNumPartition);
+
+    m_puhTrIdx           = (UChar* )xMalloc(UChar,  uiNumPartition);
+
+    for(UInt i=0; i<NUM_REF_PIC_LIST_01; i++)
+    {
+      const RefPicList rpl=RefPicList(i);
+      m_apiMVPIdx[rpl]       = new Char[ uiNumPartition ];
+      m_apiMVPNum[rpl]       = new Char[ uiNumPartition ];
+      memset( m_apiMVPIdx[rpl], -1,uiNumPartition * sizeof( Char ) );
+    }
+
+    for (UInt comp=0; comp<MAX_NUM_COMPONENT; comp++)
+    {
+      const ComponentID compID = ComponentID(comp);
+      const UInt chromaShift = getComponentScaleX(compID, chromaFormatIDC) + getComponentScaleY(compID, chromaFormatIDC);
+      const UInt totalSize   = (uiWidth * uiHeight) >> chromaShift;
+
+      m_crossComponentPredictionAlpha[compID] = (Char*  )xMalloc(Char,   uiNumPartition);
+      m_puhTransformSkip[compID]              = (UChar* )xMalloc(UChar,  uiNumPartition);
+      m_explicitRdpcmMode[compID]             = (UChar* )xMalloc(UChar,  uiNumPartition);
+      m_puhCbf[compID]                        = (UChar* )xMalloc(UChar,  uiNumPartition);
+      m_pcTrCoeff[compID]                     = (TCoeff*)xMalloc(TCoeff, totalSize);
+      memset( m_pcTrCoeff[compID], 0, (totalSize * sizeof( TCoeff )) );
+
+#if ADAPTIVE_QP_SELECTION
+      if( bGlobalRMARLBuffer )
+      {
+#if LAYER_CTB
+        if (m_pcGlbArlCoeff[compID] == NULL) m_pcGlbArlCoeff[compID] = (TCoeff*)xMalloc(TCoeff, MAX_CU_SIZE * MAX_CU_SIZE);
+#else
+        if (m_pcGlbArlCoeff[compID] == NULL) m_pcGlbArlCoeff[compID] = (TCoeff*)xMalloc(TCoeff, totalSize);
+#endif
+
+        m_pcArlCoeff[compID] = m_pcGlbArlCoeff[compID];
+        m_ArlCoeffIsAliasedAllocation = true;
+      }
+      else
+      {
+         m_pcArlCoeff[compID] = (TCoeff*)xMalloc(TCoeff, totalSize);
+      }
+#endif
+      m_pcIPCMSample[compID] = (Pel*   )xMalloc(Pel , totalSize);
+    }
+
+    m_pbIPCMFlag         = (Bool*  )xMalloc(Bool, uiNumPartition);
+
+    for(UInt i=0; i<NUM_REF_PIC_LIST_01; i++)
+    {
+      m_acCUMvField[i].create( uiNumPartition );
+    }
+
+  }
+  else
+  {
+    for(UInt i=0; i<NUM_REF_PIC_LIST_01; i++)
+    {
+      m_acCUMvField[i].setNumPartition(uiNumPartition );
+    }
+  }
+
+  // create motion vector fields
+
+  m_pCtuAboveLeft      = NULL;
+  m_pCtuAboveRight     = NULL;
+  m_pCtuAbove          = NULL;
+  m_pCtuLeft           = NULL;
+
+  for(UInt i=0; i<NUM_REF_PIC_LIST_01; i++)
+  {
+    m_apcCUColocated[i]  = NULL;
+  }
+}
+
+Void TComDataCU::destroy()
+{
+  // 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_ChromaQpAdj        ) { delete[] m_ChromaQpAdj;       m_ChromaQpAdj        = NULL; }
+    if ( m_CUTransquantBypass ) { delete[] m_CUTransquantBypass;m_CUTransquantBypass = 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; }
+
+    for (UInt ch=0; ch<MAX_NUM_CHANNEL_TYPE; ch++)
+    {
+      xFree(m_puhIntraDir[ch]);
+      m_puhIntraDir[ch] = NULL;
+    }
+
+    if ( m_puhTrIdx           ) { xFree(m_puhTrIdx);            m_puhTrIdx          = NULL; }
+
+    for (UInt comp=0; comp<MAX_NUM_COMPONENT; comp++)
+    {
+      if ( m_crossComponentPredictionAlpha[comp] ) { xFree(m_crossComponentPredictionAlpha[comp]); m_crossComponentPredictionAlpha[comp] = NULL; }
+      if ( m_puhTransformSkip[comp]              ) { xFree(m_puhTransformSkip[comp]);              m_puhTransformSkip[comp]              = NULL; }
+      if ( m_puhCbf[comp]                        ) { xFree(m_puhCbf[comp]);                        m_puhCbf[comp]                        = NULL; }
+      if ( m_pcTrCoeff[comp]                     ) { xFree(m_pcTrCoeff[comp]);                     m_pcTrCoeff[comp]                     = NULL; }
+      if ( m_explicitRdpcmMode[comp]             ) { xFree(m_explicitRdpcmMode[comp]);             m_explicitRdpcmMode[comp]             = NULL; }
+
+#if ADAPTIVE_QP_SELECTION
+      if (!m_ArlCoeffIsAliasedAllocation)
+      {
+        if ( m_pcArlCoeff[comp]     ) { xFree(m_pcArlCoeff[comp]);      m_pcArlCoeff[comp]    = NULL; }
+      }
+
+      if ( m_pcGlbArlCoeff[comp]  ) { xFree(m_pcGlbArlCoeff[comp]);   m_pcGlbArlCoeff[comp] = NULL; }
+#endif
+
+      if ( m_pcIPCMSample[comp]   ) { xFree(m_pcIPCMSample[comp]);    m_pcIPCMSample[comp]  = NULL; }
+    }
+    if ( m_pbIPCMFlag         ) { xFree(m_pbIPCMFlag   );       m_pbIPCMFlag        = NULL; }
+
+    for(UInt i=0; i<NUM_REF_PIC_LIST_01; i++)
+    {
+      const RefPicList rpl=RefPicList(i);
+      if ( m_apiMVPIdx[rpl]       ) { delete[] m_apiMVPIdx[rpl];      m_apiMVPIdx[rpl]      = NULL; }
+      if ( m_apiMVPNum[rpl]       ) { delete[] m_apiMVPNum[rpl];      m_apiMVPNum[rpl]      = NULL; }
+    }
+
+    for(UInt i=0; i<NUM_REF_PIC_LIST_01; i++)
+    {
+      const RefPicList rpl=RefPicList(i);
+      m_acCUMvField[rpl].destroy();
+    }
+  }
+
+  m_pcPic              = NULL;
+  m_pcSlice            = NULL;
+
+  m_pCtuAboveLeft      = NULL;
+  m_pCtuAboveRight     = NULL;
+  m_pCtuAbove          = NULL;
+  m_pCtuLeft           = NULL;
+
+
+  for(UInt i=0; i<NUM_REF_PIC_LIST_01; i++)
+  {
+    m_apcCUColocated[i]  = NULL;
+  }
+
+}
+
+Bool TComDataCU::CUIsFromSameTile            ( const TComDataCU *pCU /* Can be NULL */) const
+{
+  return pCU!=NULL &&
+         pCU->getSlice() != NULL &&
+         m_pcPic->getPicSym()->getTileIdxMap( pCU->getCtuRsAddr() ) == m_pcPic->getPicSym()->getTileIdxMap(getCtuRsAddr());
+}
+
+Bool TComDataCU::CUIsFromSameSliceAndTile    ( const TComDataCU *pCU /* Can be NULL */) const
+{
+  return pCU!=NULL &&
+         pCU->getSlice() != NULL &&
+         pCU->getSlice()->getSliceCurStartCtuTsAddr() == getSlice()->getSliceCurStartCtuTsAddr() &&
+         m_pcPic->getPicSym()->getTileIdxMap( pCU->getCtuRsAddr() ) == m_pcPic->getPicSym()->getTileIdxMap(getCtuRsAddr())
+         ;
+}
+
+Bool TComDataCU::CUIsFromSameSliceTileAndWavefrontRow( const TComDataCU *pCU /* Can be NULL */) const
+{
+  return CUIsFromSameSliceAndTile(pCU)
+         && (!getSlice()->getPPS()->getEntropyCodingSyncEnabledFlag() || getPic()->getCtu(getCtuRsAddr())->getCUPelY() == getPic()->getCtu(pCU->getCtuRsAddr())->getCUPelY());
+}
+
+Bool TComDataCU::isLastSubCUOfCtu(const UInt absPartIdx)
+{
+  TComPic* pcPic = getPic();
+  TComSlice * pcSlice = pcPic->getSlice(pcPic->getCurrSliceIdx());
+
+#if REPN_FORMAT_IN_VPS
+  const UInt picWidth = pcSlice->getPicWidthInLumaSamples();
+  const UInt picHeight = pcSlice->getPicHeightInLumaSamples();
+#else
+  const UInt picWidth = pcSlice->getSPS()->getPicWidthInLumaSamples();
+  const UInt picHeight = pcSlice->getSPS()->getPicHeightInLumaSamples();
+#endif
+  const UInt granularityWidth = g_uiMaxCUWidth;
+
+  const UInt cuPosX = getCUPelX() + g_auiRasterToPelX[ g_auiZscanToRaster[absPartIdx] ];
+  const UInt cuPosY = getCUPelY() + g_auiRasterToPelY[ g_auiZscanToRaster[absPartIdx] ];
+
+  return (((cuPosX+getWidth( absPartIdx))%granularityWidth==0||(cuPosX+getWidth( absPartIdx)==picWidth ))
+       && ((cuPosY+getHeight(absPartIdx))%granularityWidth==0||(cuPosY+getHeight(absPartIdx)==picHeight)));
+}
+
+// ====================================================================================================================
+// 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::initCtu( TComPic* pcPic, UInt ctuRsAddr )
+{
+
+  m_pcPic              = pcPic;
+  m_pcSlice            = pcPic->getSlice(pcPic->getCurrSliceIdx());
+  m_ctuRsAddr          = ctuRsAddr;
+  m_uiCUPelX           = ( ctuRsAddr % pcPic->getFrameWidthInCtus() ) * g_uiMaxCUWidth;
+  m_uiCUPelY           = ( ctuRsAddr / pcPic->getFrameWidthInCtus() ) * g_uiMaxCUHeight;
+  m_absZIdxInCtu       = 0;
+  m_dTotalCost         = MAX_DOUBLE;
+  m_uiTotalDistortion  = 0;
+  m_uiTotalBits        = 0;
+  m_uiTotalBins        = 0;
+  m_uiNumPartition     = pcPic->getNumPartitionsInCtu();
+
+  memset( m_skipFlag          , false,                      m_uiNumPartition * sizeof( *m_skipFlag ) );
+
+#if SVC_EXTENSION
+  m_layerId           = pcPic->getLayerId();
+#endif
+
+  memset( m_pePartSize        , NUMBER_OF_PART_SIZES,       m_uiNumPartition * sizeof( *m_pePartSize ) );
+  memset( m_pePredMode        , NUMBER_OF_PREDICTION_MODES, m_uiNumPartition * sizeof( *m_pePredMode ) );
+  memset( m_CUTransquantBypass, false,                      m_uiNumPartition * sizeof( *m_CUTransquantBypass) );
+  memset( m_puhDepth          , 0,                          m_uiNumPartition * sizeof( *m_puhDepth ) );
+  memset( m_puhTrIdx          , 0,                          m_uiNumPartition * sizeof( *m_puhTrIdx ) );
+  memset( m_puhWidth          , g_uiMaxCUWidth,             m_uiNumPartition * sizeof( *m_puhWidth ) );
+  memset( m_puhHeight         , g_uiMaxCUHeight,            m_uiNumPartition * sizeof( *m_puhHeight ) );
+  for(UInt i=0; i<NUM_REF_PIC_LIST_01; i++)
+  {
+    const RefPicList rpl=RefPicList(i);
+    memset( m_apiMVPIdx[rpl]  , -1,                         m_uiNumPartition * sizeof( *m_apiMVPIdx[rpl] ) );
+    memset( m_apiMVPNum[rpl]  , -1,                         m_uiNumPartition * sizeof( *m_apiMVPNum[rpl] ) );
+  }
+  memset( m_phQP              , getSlice()->getSliceQp(),   m_uiNumPartition * sizeof( *m_phQP ) );
+  memset( m_ChromaQpAdj       , 0,                          m_uiNumPartition * sizeof( *m_ChromaQpAdj ) );
+  for(UInt comp=0; comp<MAX_NUM_COMPONENT; comp++)
+  {
+    memset( m_crossComponentPredictionAlpha[comp] , 0,                     m_uiNumPartition * sizeof( *m_crossComponentPredictionAlpha[comp] ) );
+    memset( m_puhTransformSkip[comp]              , 0,                     m_uiNumPartition * sizeof( *m_puhTransformSkip[comp]) );
+    memset( m_puhCbf[comp]                        , 0,                     m_uiNumPartition * sizeof( *m_puhCbf[comp] ) );
+    memset( m_explicitRdpcmMode[comp]             , NUMBER_OF_RDPCM_MODES, m_uiNumPartition * sizeof( *m_explicitRdpcmMode[comp] ) );
+  }
+  memset( m_pbMergeFlag       , false,                    m_uiNumPartition * sizeof( *m_pbMergeFlag ) );
+  memset( m_puhMergeIndex     , 0,                        m_uiNumPartition * sizeof( *m_puhMergeIndex ) );
+  for (UInt ch=0; ch<MAX_NUM_CHANNEL_TYPE; ch++)
+  {
+    memset( m_puhIntraDir[ch] , ((ch==0) ? DC_IDX : 0),   m_uiNumPartition * sizeof( *(m_puhIntraDir[ch]) ) );
+  }
+  memset( m_puhInterDir       , 0,                        m_uiNumPartition * sizeof( *m_puhInterDir ) );
+  memset( m_pbIPCMFlag        , false,                    m_uiNumPartition * sizeof( *m_pbIPCMFlag ) );
+
+  const UInt numCoeffY    = g_uiMaxCUWidth*g_uiMaxCUHeight;
+  for (UInt comp=0; comp<MAX_NUM_COMPONENT; comp++)
+  {
+    const UInt componentShift = m_pcPic->getComponentScaleX(ComponentID(comp)) + m_pcPic->getComponentScaleY(ComponentID(comp));
+    memset( m_pcTrCoeff[comp], 0, sizeof(TCoeff)* numCoeffY>>componentShift );
+#if ADAPTIVE_QP_SELECTION
+    memset( m_pcArlCoeff[comp], 0, sizeof(TCoeff)* numCoeffY>>componentShift );
+#endif
+  }
+
+  for(UInt i=0; i<NUM_REF_PIC_LIST_01; i++)
+  {
+    m_acCUMvField[i].clearMvField();
+  }
+
+  // Setting neighbor CU
+  m_pCtuLeft        = NULL;
+  m_pCtuAbove       = NULL;
+  m_pCtuAboveLeft   = NULL;
+  m_pCtuAboveRight  = NULL;
+
+
+  for(UInt i=0; i<NUM_REF_PIC_LIST_01; i++)
+  {
+    m_apcCUColocated[i]  = NULL;
+  }
+
+  UInt frameWidthInCtus = pcPic->getFrameWidthInCtus();
+  if ( m_ctuRsAddr % frameWidthInCtus )
+  {
+    m_pCtuLeft = pcPic->getCtu( m_ctuRsAddr - 1 );
+  }
+
+  if ( m_ctuRsAddr / frameWidthInCtus )
+  {
+    m_pCtuAbove = pcPic->getCtu( m_ctuRsAddr - frameWidthInCtus );
+  }
+
+  if ( m_pCtuLeft && m_pCtuAbove )
+  {
+    m_pCtuAboveLeft = pcPic->getCtu( m_ctuRsAddr - frameWidthInCtus - 1 );
+  }
+
+  if ( m_pCtuAbove && ( (m_ctuRsAddr%frameWidthInCtus) < (frameWidthInCtus-1) )  )
+  {
+    m_pCtuAboveRight = pcPic->getCtu( m_ctuRsAddr - frameWidthInCtus + 1 );
+  }
+
+  for(UInt i=0; i<NUM_REF_PIC_LIST_01; i++)
+  {
+    const RefPicList rpl=RefPicList(i);
+    if ( getSlice()->getNumRefIdx( rpl ) > 0 )
+    {
+      m_apcCUColocated[rpl] = getSlice()->getRefPic( rpl, 0)->getCtu( m_ctuRsAddr );
+    }
+  }
+}
+
+
+/** initialize prediction data with enabling sub-CTU-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( const UInt uiDepth, const Int qp, const Bool bTransquantBypass )
+{
+  m_dTotalCost         = MAX_DOUBLE;
+  m_uiTotalDistortion  = 0;
+  m_uiTotalBits        = 0;
+  m_uiTotalBins        = 0;
+
+  UChar uhWidth  = g_uiMaxCUWidth  >> uiDepth;
+  UChar uhHeight = g_uiMaxCUHeight >> uiDepth;
+
+  for (UInt ui = 0; ui < m_uiNumPartition; ui++)
+  {
+    for(UInt i=0; i<NUM_REF_PIC_LIST_01; i++)
+    {
+      const RefPicList rpl=RefPicList(i);
+      m_apiMVPIdx[rpl][ui]  = -1;
+      m_apiMVPNum[rpl][ui]  = -1;
+    }
+    m_puhDepth  [ui]    = uiDepth;
+    m_puhWidth  [ui]    = uhWidth;
+    m_puhHeight [ui]    = uhHeight;
+    m_puhTrIdx  [ui]    = 0;
+    for(UInt comp=0; comp<MAX_NUM_COMPONENT; comp++)
+    {
+      m_crossComponentPredictionAlpha[comp][ui] = 0;
+      m_puhTransformSkip             [comp][ui] = 0;
+      m_explicitRdpcmMode            [comp][ui] = NUMBER_OF_RDPCM_MODES;
+    }
+    m_skipFlag[ui]      = false;
+    m_pePartSize[ui]    = NUMBER_OF_PART_SIZES;
+    m_pePredMode[ui]    = NUMBER_OF_PREDICTION_MODES;
+    m_CUTransquantBypass[ui] = bTransquantBypass;
+    m_pbIPCMFlag[ui]    = 0;
+    m_phQP[ui]          = qp;
+    m_ChromaQpAdj[ui]   = 0;
+    m_pbMergeFlag[ui]   = 0;
+    m_puhMergeIndex[ui] = 0;
+
+    for (UInt ch=0; ch<MAX_NUM_CHANNEL_TYPE; ch++)
+    {
+      m_puhIntraDir[ch][ui] = ((ch==0) ? DC_IDX : 0);
+    }
+
+    m_puhInterDir[ui] = 0;
+    for (UInt comp=0; comp<MAX_NUM_COMPONENT; comp++)
+    {
+      m_puhCbf[comp][ui] = 0;
+    }
+  }
+
+  for(UInt i=0; i<NUM_REF_PIC_LIST_01; i++)
+  {
+    m_acCUMvField[i].clearMvField();
+  }
+
+  const UInt numCoeffY = uhWidth*uhHeight;
+
+  for (UInt comp=0; comp<MAX_NUM_COMPONENT; comp++)
+  {
+    const ComponentID component = ComponentID(comp);
+    const UInt numCoeff = numCoeffY >> (getPic()->getComponentScaleX(component) + getPic()->getComponentScaleY(component));
+    memset( m_pcTrCoeff[comp],    0, numCoeff * sizeof( TCoeff ) );
+#if ADAPTIVE_QP_SELECTION
+    memset( m_pcArlCoeff[comp],   0, numCoeff * sizeof( TCoeff ) );
+#endif
+    memset( m_pcIPCMSample[comp], 0, numCoeff * sizeof( Pel) );
+  }
+}
+
+
+// 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_ctuRsAddr          = pcCU->getCtuRsAddr();
+  m_absZIdxInCtu       = pcCU->getZorderIdxInCtu() + 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 );
+  for (UInt ch=0; ch<MAX_NUM_CHANNEL_TYPE; ch++)
+  {
+    memset( m_puhIntraDir[ch],  ((ch==0) ? DC_IDX : 0), iSizeInUchar );
+  }
+
+  memset( m_puhInterDir,        0, iSizeInUchar );
+  memset( m_puhTrIdx,           0, iSizeInUchar );
+
+  for(UInt comp=0; comp<MAX_NUM_COMPONENT; comp++)
+  {
+    memset( m_crossComponentPredictionAlpha[comp], 0, iSizeInUchar );
+    memset( m_puhTransformSkip[comp],              0, iSizeInUchar );
+    memset( m_puhCbf[comp],                        0, iSizeInUchar );
+    memset( m_explicitRdpcmMode[comp],             NUMBER_OF_RDPCM_MODES, iSizeInUchar );
+  }
+
+  memset( m_puhDepth,     uiDepth, iSizeInUchar );
+
+  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  );
+  for (UInt ui = 0; ui < m_uiNumPartition; ui++)
+  {
+    m_skipFlag[ui]   = false;
+    m_pePartSize[ui] = NUMBER_OF_PART_SIZES;
+    m_pePredMode[ui] = NUMBER_OF_PREDICTION_MODES;
+    m_CUTransquantBypass[ui] = false;
+    m_ChromaQpAdj[ui] = 0;
+
+    for(UInt i=0; i<NUM_REF_PIC_LIST_01; i++)
+    {
+      const RefPicList rpl=RefPicList(i);
+      m_apiMVPIdx[rpl][ui] = -1;
+      m_apiMVPNum[rpl][ui] = -1;
+    }
+  }
+
+  const UInt numCoeffY    = uhWidth*uhHeight;
+  for (UInt ch=0; ch<MAX_NUM_COMPONENT; ch++)
+  {
+    const UInt componentShift = m_pcPic->getComponentScaleX(ComponentID(ch)) + m_pcPic->getComponentScaleY(ComponentID(ch));
+    memset( m_pcTrCoeff[ch],  0, sizeof(TCoeff)*(numCoeffY>>componentShift) );
+#if ADAPTIVE_QP_SELECTION
+    memset( m_pcArlCoeff[ch], 0, sizeof(TCoeff)*(numCoeffY>>componentShift) );
+#endif
+    memset( m_pcIPCMSample[ch], 0, sizeof(Pel)* (numCoeffY>>componentShift) );
+  }
+
+  for(UInt i=0; i<NUM_REF_PIC_LIST_01; i++)
+  {
+    m_acCUMvField[i].clearMvField();
+  }
+
+  m_pCtuLeft        = pcCU->getCtuLeft();
+  m_pCtuAbove       = pcCU->getCtuAbove();
+  m_pCtuAboveLeft   = pcCU->getCtuAboveLeft();
+  m_pCtuAboveRight  = pcCU->getCtuAboveRight();
+
+  for(UInt i=0; i<NUM_REF_PIC_LIST_01; i++)
+  {
+    m_apcCUColocated[i] = pcCU->getCUColocated(RefPicList(i));
+  }
+}
+
+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_ctuRsAddr          = pcCU->getCtuRsAddr();
+  m_absZIdxInCtu       = 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_ChromaQpAdj = pcCU->getChromaQpAdj()  + uiPart;
+  m_pePartSize = pcCU->getPartitionSize() + uiPart;
+  m_pePredMode=pcCU->getPredictionMode()  + uiPart;
+  m_CUTransquantBypass  = pcCU->getCUTransquantBypass()+uiPart;
+
+  m_pbMergeFlag         = pcCU->getMergeFlag()        + uiPart;
+  m_puhMergeIndex       = pcCU->getMergeIndex()       + uiPart;
+
+  for (UInt ch=0; ch<MAX_NUM_CHANNEL_TYPE; ch++)
+  {
+    m_puhIntraDir[ch]   = pcCU->getIntraDir(ChannelType(ch)) + uiPart;
+  }
+
+  m_puhInterDir         = pcCU->getInterDir()         + uiPart;
+  m_puhTrIdx            = pcCU->getTransformIdx()     + uiPart;
+
+  for(UInt comp=0; comp<MAX_NUM_COMPONENT; comp++)
+  {
+    m_crossComponentPredictionAlpha[comp] = pcCU->getCrossComponentPredictionAlpha(ComponentID(comp)) + uiPart;
+    m_puhTransformSkip[comp]              = pcCU->getTransformSkip(ComponentID(comp))                 + uiPart;
+    m_puhCbf[comp]                        = pcCU->getCbf(ComponentID(comp))                           + uiPart;
+    m_explicitRdpcmMode[comp]             = pcCU->getExplicitRdpcmMode(ComponentID(comp))             + uiPart;
+  }
+
+  m_puhDepth=pcCU->getDepth()                     + uiPart;
+  m_puhWidth=pcCU->getWidth()                     + uiPart;
+  m_puhHeight=pcCU->getHeight()                   + uiPart;
+
+  m_pbIPCMFlag         = pcCU->getIPCMFlag()        + uiPart;
+
+  m_pCtuAboveLeft      = pcCU->getCtuAboveLeft();
+  m_pCtuAboveRight     = pcCU->getCtuAboveRight();
+  m_pCtuAbove          = pcCU->getCtuAbove();
+  m_pCtuLeft           = pcCU->getCtuLeft();
+
+  for(UInt i=0; i<NUM_REF_PIC_LIST_01; i++)
+  {
+    const RefPicList rpl=RefPicList(i);
+    m_apcCUColocated[rpl] = pcCU->getCUColocated(rpl);
+    m_apiMVPIdx[rpl]=pcCU->getMVPIdx(rpl)  + uiPart;
+    m_apiMVPNum[rpl]=pcCU->getMVPNum(rpl)  + uiPart;
+  }
+
+  for(UInt i=0; i<NUM_REF_PIC_LIST_01; i++)
+  {
+    const RefPicList rpl=RefPicList(i);
+    m_acCUMvField[rpl].linkToWithOffset( pcCU->getCUMvField(rpl), uiPart );
+  }
+
+  UInt uiMaxCuWidth=pcCU->getSlice()->getSPS()->getMaxCUWidth();
+  UInt uiMaxCuHeight=pcCU->getSlice()->getSPS()->getMaxCUHeight();
+
+  UInt uiCoffOffset = uiMaxCuWidth*uiMaxCuHeight*uiAbsPartIdx/pcCU->getPic()->getNumPartitionsInCtu();
+
+  for (UInt ch=0; ch<MAX_NUM_COMPONENT; ch++)
+  {
+    const ComponentID component = ComponentID(ch);
+    const UInt componentShift   = m_pcPic->getComponentScaleX(component) + m_pcPic->getComponentScaleY(component);
+    const UInt offset           = uiCoffOffset >> componentShift;
+    m_pcTrCoeff[ch] = pcCU->getCoeff(component) + offset;
+#if ADAPTIVE_QP_SELECTION
+    m_pcArlCoeff[ch] = pcCU->getArlCoeff(component) + offset;
+#endif
+    m_pcIPCMSample[ch] = pcCU->getPCMSample(component) + offset;
+  }
+}
+
+// Copy inter prediction info from the biggest CU
+Void TComDataCU::copyInterPredInfoFrom    ( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefPicList )
+{
+  m_pcPic              = pcCU->getPic();
+  m_pcSlice            = pcCU->getSlice();
+  m_ctuRsAddr          = pcCU->getCtuRsAddr();
+  m_absZIdxInCtu       = uiAbsPartIdx;
+
+  Int iRastPartIdx     = g_auiZscanToRaster[uiAbsPartIdx];
+  m_uiCUPelX           = pcCU->getCUPelX() + m_pcPic->getMinCUWidth ()*( iRastPartIdx % m_pcPic->getNumPartInCtuWidth() );
+  m_uiCUPelY           = pcCU->getCUPelY() + m_pcPic->getMinCUHeight()*( iRastPartIdx / m_pcPic->getNumPartInCtuWidth() );
+
+  m_pCtuAboveLeft      = pcCU->getCtuAboveLeft();
+  m_pCtuAboveRight     = pcCU->getCtuAboveRight();
+  m_pCtuAbove          = pcCU->getCtuAbove();
+  m_pCtuLeft           = pcCU->getCtuLeft();
+
+  for(UInt i=0; i<NUM_REF_PIC_LIST_01; i++)
+  {
+    m_apcCUColocated[i]  = pcCU->getCUColocated(RefPicList(i));
+  }
+
+  m_skipFlag           = pcCU->getSkipFlag ()             + uiAbsPartIdx;
+
+  m_pePartSize         = pcCU->getPartitionSize ()        + uiAbsPartIdx;
+  m_pePredMode         = pcCU->getPredictionMode()        + uiAbsPartIdx;
+  m_ChromaQpAdj        = pcCU->getChromaQpAdj()           + uiAbsPartIdx;
+  m_CUTransquantBypass = pcCU->getCUTransquantBypass()    + uiAbsPartIdx;
+  m_puhInterDir        = pcCU->getInterDir      ()        + uiAbsPartIdx;
+
+  m_puhDepth           = pcCU->getDepth ()                + uiAbsPartIdx;
+  m_puhWidth           = pcCU->getWidth ()                + uiAbsPartIdx;
+  m_puhHeight          = pcCU->getHeight()                + uiAbsPartIdx;
+
+  m_pbMergeFlag        = pcCU->getMergeFlag()             + uiAbsPartIdx;
+  m_puhMergeIndex      = pcCU->getMergeIndex()            + uiAbsPartIdx;
+
+  m_apiMVPIdx[eRefPicList] = pcCU->getMVPIdx(eRefPicList) + uiAbsPartIdx;
+  m_apiMVPNum[eRefPicList] = pcCU->getMVPNum(eRefPicList) + uiAbsPartIdx;
+
+  m_acCUMvField[ eRefPicList ].linkToWithOffset( pcCU->getCUMvField(eRefPicList), uiAbsPartIdx );
+}
+
+// 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;
+  const UInt numValidComp=pcCU->getPic()->getNumberValidComponents();
+  const UInt numValidChan=pcCU->getPic()->getChromaFormat()==CHROMA_400 ? 1:2;
+
+  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_ChromaQpAdj + uiOffset, pcCU->getChromaQpAdj(),   sizeof( *m_ChromaQpAdj ) * 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 );
+
+  for (UInt ch=0; ch<numValidChan; ch++)
+  {
+    memcpy( m_puhIntraDir[ch]   + uiOffset, pcCU->getIntraDir(ChannelType(ch)), iSizeInUchar );
+  }
+
+  memcpy( m_puhInterDir         + uiOffset, pcCU->getInterDir(),          iSizeInUchar );
+  memcpy( m_puhTrIdx            + uiOffset, pcCU->getTransformIdx(),      iSizeInUchar );
+
+  for(UInt comp=0; comp<numValidComp; comp++)
+  {
+    memcpy( m_crossComponentPredictionAlpha[comp] + uiOffset, pcCU->getCrossComponentPredictionAlpha(ComponentID(comp)), iSizeInUchar );
+    memcpy( m_puhTransformSkip[comp]              + uiOffset, pcCU->getTransformSkip(ComponentID(comp))                , iSizeInUchar );
+    memcpy( m_puhCbf[comp]                        + uiOffset, pcCU->getCbf(ComponentID(comp))                          , iSizeInUchar );
+    memcpy( m_explicitRdpcmMode[comp]             + uiOffset, pcCU->getExplicitRdpcmMode(ComponentID(comp))            , iSizeInUchar );
+  }
+
+  memcpy( m_puhDepth  + uiOffset, pcCU->getDepth(),  iSizeInUchar );
+  memcpy( m_puhWidth  + uiOffset, pcCU->getWidth(),  iSizeInUchar );
+  memcpy( m_puhHeight + uiOffset, pcCU->getHeight(), iSizeInUchar );
+
+  memcpy( m_pbIPCMFlag + uiOffset, pcCU->getIPCMFlag(), iSizeInBool );
+
+  m_pCtuAboveLeft      = pcCU->getCtuAboveLeft();
+  m_pCtuAboveRight     = pcCU->getCtuAboveRight();
+  m_pCtuAbove          = pcCU->getCtuAbove();
+  m_pCtuLeft           = pcCU->getCtuLeft();
+
+  for(UInt i=0; i<NUM_REF_PIC_LIST_01; i++)
+  {
+    const RefPicList rpl=RefPicList(i);
+    memcpy( m_apiMVPIdx[rpl] + uiOffset, pcCU->getMVPIdx(rpl), iSizeInUchar );
+    memcpy( m_apiMVPNum[rpl] + uiOffset, pcCU->getMVPNum(rpl), iSizeInUchar );
+    m_apcCUColocated[rpl] = pcCU->getCUColocated(rpl);
+  }
+
+  for(UInt i=0; i<NUM_REF_PIC_LIST_01; i++)
+  {
+    const RefPicList rpl=RefPicList(i);
+    m_acCUMvField[rpl].copyFrom( pcCU->getCUMvField( rpl ), pcCU->getTotalNumPart(), uiOffset );
+  }
+
+  const UInt numCoeffY = g_uiMaxCUWidth*g_uiMaxCUHeight >> (uiDepth<<1);
+  const UInt offsetY   = uiPartUnitIdx*numCoeffY;
+  for (UInt ch=0; ch<numValidComp; ch++)
+  {
+    const ComponentID component = ComponentID(ch);
+    const UInt componentShift   = m_pcPic->getComponentScaleX(component) + m_pcPic->getComponentScaleY(component);
+    const UInt offset           = offsetY>>componentShift;
+    memcpy( m_pcTrCoeff [ch] + offset, pcCU->getCoeff(component),    sizeof(TCoeff)*(numCoeffY>>componentShift) );
+#if ADAPTIVE_QP_SELECTION
+    memcpy( m_pcArlCoeff[ch] + offset, pcCU->getArlCoeff(component), sizeof(TCoeff)*(numCoeffY>>componentShift) );
+#endif
+    memcpy( m_pcIPCMSample[ch] + offset, pcCU->getPCMSample(component), sizeof(Pel)*(numCoeffY>>componentShift) );
+  }
+
+  m_uiTotalBins += pcCU->getTotalBins();
+}
+
+// Copy current predicted part to a CU in picture.
+// It is used to predict for next part
+Void TComDataCU::copyToPic( UChar uhDepth )
+{
+  TComDataCU* pCtu = m_pcPic->getCtu( m_ctuRsAddr );
+  const UInt numValidComp=pCtu->getPic()->getNumberValidComponents();
+  const UInt numValidChan=pCtu->getPic()->getChromaFormat()==CHROMA_400 ? 1:2;
+
+  pCtu->getTotalCost()       = m_dTotalCost;
+  pCtu->getTotalDistortion() = m_uiTotalDistortion;
+  pCtu->getTotalBits()       = m_uiTotalBits;
+
+  Int iSizeInUchar  = sizeof( UChar ) * m_uiNumPartition;
+  Int iSizeInBool   = sizeof( Bool  ) * m_uiNumPartition;
+  Int sizeInChar  = sizeof( Char ) * m_uiNumPartition;
+
+  memcpy( pCtu->getSkipFlag() + m_absZIdxInCtu, m_skipFlag, sizeof( *m_skipFlag ) * m_uiNumPartition );
+
+  memcpy( pCtu->getQP() + m_absZIdxInCtu, m_phQP, sizeInChar  );
+
+  memcpy( pCtu->getPartitionSize()  + m_absZIdxInCtu, m_pePartSize, sizeof( *m_pePartSize ) * m_uiNumPartition );
+  memcpy( pCtu->getPredictionMode() + m_absZIdxInCtu, m_pePredMode, sizeof( *m_pePredMode ) * m_uiNumPartition );
+  memcpy( pCtu->getChromaQpAdj() + m_absZIdxInCtu, m_ChromaQpAdj, sizeof( *m_ChromaQpAdj ) * m_uiNumPartition );
+  memcpy( pCtu->getCUTransquantBypass()+ m_absZIdxInCtu, m_CUTransquantBypass, sizeof( *m_CUTransquantBypass ) * m_uiNumPartition );
+  memcpy( pCtu->getMergeFlag()         + m_absZIdxInCtu, m_pbMergeFlag,         iSizeInBool  );
+  memcpy( pCtu->getMergeIndex()        + m_absZIdxInCtu, m_puhMergeIndex,       iSizeInUchar );
+  for (UInt ch=0; ch<numValidChan; ch++)
+  {
+    memcpy( pCtu->getIntraDir(ChannelType(ch)) + m_absZIdxInCtu, m_puhIntraDir[ch], iSizeInUchar);
+  }
+
+  memcpy( pCtu->getInterDir()          + m_absZIdxInCtu, m_puhInterDir,         iSizeInUchar );
+  memcpy( pCtu->getTransformIdx()      + m_absZIdxInCtu, m_puhTrIdx,            iSizeInUchar );
+
+  for(UInt comp=0; comp<numValidComp; comp++)
+  {
+    memcpy( pCtu->getCrossComponentPredictionAlpha(ComponentID(comp)) + m_absZIdxInCtu, m_crossComponentPredictionAlpha[comp], iSizeInUchar );
+    memcpy( pCtu->getTransformSkip(ComponentID(comp))                 + m_absZIdxInCtu, m_puhTransformSkip[comp],              iSizeInUchar );
+    memcpy( pCtu->getCbf(ComponentID(comp))                           + m_absZIdxInCtu, m_puhCbf[comp],                        iSizeInUchar );
+    memcpy( pCtu->getExplicitRdpcmMode(ComponentID(comp))             + m_absZIdxInCtu, m_explicitRdpcmMode[comp],             iSizeInUchar );
+  }
+
+  memcpy( pCtu->getDepth()  + m_absZIdxInCtu, m_puhDepth,  iSizeInUchar );
+  memcpy( pCtu->getWidth()  + m_absZIdxInCtu, m_puhWidth,  iSizeInUchar );
+  memcpy( pCtu->getHeight() + m_absZIdxInCtu, m_puhHeight, iSizeInUchar );
+
+  for(UInt i=0; i<NUM_REF_PIC_LIST_01; i++)
+  {
+    const RefPicList rpl=RefPicList(i);
+    memcpy( pCtu->getMVPIdx(rpl) + m_absZIdxInCtu, m_apiMVPIdx[rpl], iSizeInUchar );
+    memcpy( pCtu->getMVPNum(rpl) + m_absZIdxInCtu, m_apiMVPNum[rpl], iSizeInUchar );
+  }
+
+  for(UInt i=0; i<NUM_REF_PIC_LIST_01; i++)
+  {
+    const RefPicList rpl=RefPicList(i);
+    m_acCUMvField[rpl].copyTo( pCtu->getCUMvField( rpl ), m_absZIdxInCtu );
+  }
+
+  memcpy( pCtu->getIPCMFlag() + m_absZIdxInCtu, m_pbIPCMFlag,         iSizeInBool  );
+
+  const UInt numCoeffY    = (g_uiMaxCUWidth*g_uiMaxCUHeight)>>(uhDepth<<1);
+  const UInt offsetY      = m_absZIdxInCtu*m_pcPic->getMinCUWidth()*m_pcPic->getMinCUHeight();
+  for (UInt comp=0; comp<numValidComp; comp++)
+  {
+    const ComponentID component = ComponentID(comp);
+    const UInt componentShift   = m_pcPic->getComponentScaleX(component) + m_pcPic->getComponentScaleY(component);
+    memcpy( pCtu->getCoeff(component)   + (offsetY>>componentShift), m_pcTrCoeff[component], sizeof(TCoeff)*(numCoeffY>>componentShift) );
+#if ADAPTIVE_QP_SELECTION
+    memcpy( pCtu->getArlCoeff(component) + (offsetY>>componentShift), m_pcArlCoeff[component], sizeof(TCoeff)*(numCoeffY>>componentShift) );
+#endif
+    memcpy( pCtu->getPCMSample(component) + (offsetY>>componentShift), m_pcIPCMSample[component], sizeof(Pel)*(numCoeffY>>componentShift) );
+  }
+
+  pCtu->getTotalBins() = m_uiTotalBins;
+}
+
+Void TComDataCU::copyToPic( UChar uhDepth, UInt uiPartIdx, UInt uiPartDepth )
+{
+  TComDataCU*   pCtu       = m_pcPic->getCtu( m_ctuRsAddr );
+  UInt          uiQNumPart  = m_uiNumPartition>>(uiPartDepth<<1);
+
+  UInt uiPartStart          = uiPartIdx*uiQNumPart;
+  UInt uiPartOffset         = m_absZIdxInCtu + uiPartStart;
+
+  const UInt numValidComp=pCtu->getPic()->getNumberValidComponents();
+  const UInt numValidChan=pCtu->getPic()->getChromaFormat()==CHROMA_400 ? 1:2;
+
+  pCtu->getTotalCost()       = m_dTotalCost;
+  pCtu->getTotalDistortion() = m_uiTotalDistortion;
+  pCtu->getTotalBits()       = m_uiTotalBits;
+
+  Int iSizeInUchar  = sizeof( UChar  ) * uiQNumPart;
+  Int iSizeInBool   = sizeof( Bool   ) * uiQNumPart;
+  Int sizeInChar  = sizeof( Char ) * uiQNumPart;
+
+  memcpy( pCtu->getSkipFlag()       + uiPartOffset, m_skipFlag,   sizeof( *m_skipFlag )   * uiQNumPart );
+
+  memcpy( pCtu->getQP() + uiPartOffset, m_phQP, sizeInChar );
+  memcpy( pCtu->getPartitionSize()  + uiPartOffset, m_pePartSize, sizeof( *m_pePartSize ) * uiQNumPart );
+  memcpy( pCtu->getPredictionMode() + uiPartOffset, m_pePredMode, sizeof( *m_pePredMode ) * uiQNumPart );
+
+  memcpy( pCtu->getCUTransquantBypass()+ uiPartOffset, m_CUTransquantBypass, sizeof( *m_CUTransquantBypass ) * uiQNumPart );
+  memcpy( pCtu->getMergeFlag()         + uiPartOffset, m_pbMergeFlag,         iSizeInBool  );
+  memcpy( pCtu->getMergeIndex()        + uiPartOffset, m_puhMergeIndex,       iSizeInUchar );
+  for (UInt ch=0; ch<numValidChan; ch++)
+  {
+    memcpy( pCtu->getIntraDir(ChannelType(ch)) + uiPartOffset, m_puhIntraDir[ch], iSizeInUchar );
+  }
+
+  memcpy( pCtu->getInterDir()          + uiPartOffset, m_puhInterDir,         iSizeInUchar );
+  memcpy( pCtu->getTransformIdx()      + uiPartOffset, m_puhTrIdx,            iSizeInUchar );
+
+  for(UInt comp=0; comp<numValidComp; comp++)
+  {
+    memcpy( pCtu->getCrossComponentPredictionAlpha(ComponentID(comp)) + uiPartOffset, m_crossComponentPredictionAlpha[comp], iSizeInUchar );
+    memcpy( pCtu->getTransformSkip(ComponentID(comp) )                + uiPartOffset, m_puhTransformSkip[comp],   iSizeInUchar );
+    memcpy( pCtu->getCbf(ComponentID(comp))                           + uiPartOffset, m_puhCbf[comp],             iSizeInUchar );
+    memcpy( pCtu->getExplicitRdpcmMode(ComponentID(comp) )            + uiPartOffset, m_explicitRdpcmMode[comp],  iSizeInUchar );
+  }
+
+  memcpy( pCtu->getDepth()  + uiPartOffset, m_puhDepth,  iSizeInUchar );
+  memcpy( pCtu->getWidth()  + uiPartOffset, m_puhWidth,  iSizeInUchar );
+  memcpy( pCtu->getHeight() + uiPartOffset, m_puhHeight, iSizeInUchar );
+
+  for(UInt i=0; i<NUM_REF_PIC_LIST_01; i++)
+  {
+    const RefPicList rpl=RefPicList(i);
+    memcpy( pCtu->getMVPIdx(rpl) + uiPartOffset, m_apiMVPIdx[rpl], iSizeInUchar );
+    memcpy( pCtu->getMVPNum(rpl) + uiPartOffset, m_apiMVPNum[rpl], iSizeInUchar );
+  }
+
+  for(UInt i=0; i<NUM_REF_PIC_LIST_01; i++)
+  {
+    const RefPicList rpl=RefPicList(i);
+    m_acCUMvField[rpl].copyTo( pCtu->getCUMvField( rpl ), m_absZIdxInCtu, uiPartStart, uiQNumPart );
+  }
+
+  memcpy( pCtu->getIPCMFlag() + uiPartOffset, m_pbIPCMFlag,         iSizeInBool  );
+
+  const UInt numCoeffY    = (g_uiMaxCUWidth*g_uiMaxCUHeight)>>((uhDepth+uiPartDepth)<<1);
+  const UInt offsetY      = uiPartOffset*m_pcPic->getMinCUWidth()*m_pcPic->getMinCUHeight();
+  for (UInt comp=0; comp<numValidComp; comp++)
+  {
+    UInt componentShift = m_pcPic->getComponentScaleX(ComponentID(comp)) + m_pcPic->getComponentScaleY(ComponentID(comp));
+    memcpy( pCtu->getCoeff(ComponentID(comp)) + (offsetY>>componentShift), m_pcTrCoeff[comp], sizeof(TCoeff)*(numCoeffY>>componentShift) );
+#if ADAPTIVE_QP_SELECTION
+    memcpy( pCtu->getArlCoeff(ComponentID(comp)) + (offsetY>>componentShift), m_pcArlCoeff[comp], sizeof(TCoeff)*(numCoeffY>>componentShift) );
+#endif
+    memcpy( pCtu->getPCMSample(ComponentID(comp)) + (offsetY>>componentShift), m_pcIPCMSample[comp], sizeof(Pel)*(numCoeffY>>componentShift) );
+  }
+
+  pCtu->getTotalBins() = m_uiTotalBins;
+}
+
+// --------------------------------------------------------------------------------------------------------------------
+// Other public functions
+// --------------------------------------------------------------------------------------------------------------------
+
+TComDataCU* TComDataCU::getPULeft( UInt& uiLPartUnitIdx,
+                                   UInt uiCurrPartUnitIdx,
+                                   Bool bEnforceSliceRestriction,
+                                   Bool bEnforceTileRestriction )
+{
+  UInt uiAbsPartIdx       = g_auiZscanToRaster[uiCurrPartUnitIdx];
+  UInt uiAbsZorderCUIdx   = g_auiZscanToRaster[m_absZIdxInCtu];
+  const UInt numPartInCtuWidth = m_pcPic->getNumPartInCtuWidth();
+
+  if ( !RasterAddress::isZeroCol( uiAbsPartIdx, numPartInCtuWidth ) )
+  {
+    uiLPartUnitIdx = g_auiRasterToZscan[ uiAbsPartIdx - 1 ];
+    if ( RasterAddress::isEqualCol( uiAbsPartIdx, uiAbsZorderCUIdx, numPartInCtuWidth ) )
+    {
+      return m_pcPic->getCtu( getCtuRsAddr() );
+    }
+    else
+    {
+      uiLPartUnitIdx -= m_absZIdxInCtu;
+      return this;
+    }
+  }
+
+  uiLPartUnitIdx = g_auiRasterToZscan[ uiAbsPartIdx + numPartInCtuWidth - 1 ];
+  if ( (bEnforceSliceRestriction && !CUIsFromSameSlice(m_pCtuLeft)) || (bEnforceTileRestriction && !CUIsFromSameTile(m_pCtuLeft)) )
+  {
+    return NULL;
+  }
+  return m_pCtuLeft;
+}
+
+
+TComDataCU* TComDataCU::getPUAbove( UInt& uiAPartUnitIdx,
+                                    UInt uiCurrPartUnitIdx,
+                                    Bool bEnforceSliceRestriction,
+                                    Bool planarAtCtuBoundary,
+                                    Bool bEnforceTileRestriction )
+{
+  UInt uiAbsPartIdx       = g_auiZscanToRaster[uiCurrPartUnitIdx];
+  UInt uiAbsZorderCUIdx   = g_auiZscanToRaster[m_absZIdxInCtu];
+  const UInt numPartInCtuWidth = m_pcPic->getNumPartInCtuWidth();
+
+  if ( !RasterAddress::isZeroRow( uiAbsPartIdx, numPartInCtuWidth ) )
+  {
+    uiAPartUnitIdx = g_auiRasterToZscan[ uiAbsPartIdx - numPartInCtuWidth ];
+    if ( RasterAddress::isEqualRow( uiAbsPartIdx, uiAbsZorderCUIdx, numPartInCtuWidth ) )
+    {
+      return m_pcPic->getCtu( getCtuRsAddr() );
+    }
+    else
+    {
+      uiAPartUnitIdx -= m_absZIdxInCtu;
+      return this;
+    }
+  }
+
+  if(planarAtCtuBoundary)
+  {
+    return NULL;
+  }
+
+  uiAPartUnitIdx = g_auiRasterToZscan[ uiAbsPartIdx + m_pcPic->getNumPartitionsInCtu() - numPartInCtuWidth ];
+
+  if ( (bEnforceSliceRestriction && !CUIsFromSameSlice(m_pCtuAbove)) || (bEnforceTileRestriction && !CUIsFromSameTile(m_pCtuAbove)) )
+  {
+    return NULL;
+  }
+  return m_pCtuAbove;
+}
+
+TComDataCU* TComDataCU::getPUAboveLeft( UInt& uiALPartUnitIdx, UInt uiCurrPartUnitIdx, Bool bEnforceSliceRestriction )
+{
+  UInt uiAbsPartIdx       = g_auiZscanToRaster[uiCurrPartUnitIdx];
+  UInt uiAbsZorderCUIdx   = g_auiZscanToRaster[m_absZIdxInCtu];
+  const UInt numPartInCtuWidth = m_pcPic->getNumPartInCtuWidth();
+
+  if ( !RasterAddress::isZeroCol( uiAbsPartIdx, numPartInCtuWidth ) )
+  {
+    if ( !RasterAddress::isZeroRow( uiAbsPartIdx, numPartInCtuWidth ) )
+    {
+      uiALPartUnitIdx = g_auiRasterToZscan[ uiAbsPartIdx - numPartInCtuWidth - 1 ];
+      if ( RasterAddress::isEqualRowOrCol( uiAbsPartIdx, uiAbsZorderCUIdx, numPartInCtuWidth ) )
+      {
+        return m_pcPic->getCtu( getCtuRsAddr() );
+      }
+      else
+      {
+        uiALPartUnitIdx -= m_absZIdxInCtu;
+        return this;
+      }
+    }
+    uiALPartUnitIdx = g_auiRasterToZscan[ uiAbsPartIdx + getPic()->getNumPartitionsInCtu() - numPartInCtuWidth - 1 ];
+    if ( bEnforceSliceRestriction && !CUIsFromSameSliceAndTile(m_pCtuAbove) )
+    {
+      return NULL;
+    }
+    return m_pCtuAbove;
+  }
+
+  if ( !RasterAddress::isZeroRow( uiAbsPartIdx, numPartInCtuWidth ) )
+  {
+    uiALPartUnitIdx = g_auiRasterToZscan[ uiAbsPartIdx - 1 ];
+    if ( bEnforceSliceRestriction && !CUIsFromSameSliceAndTile(m_pCtuLeft) )
+    {
+      return NULL;
+    }
+    return m_pCtuLeft;
+  }
+
+  uiALPartUnitIdx = g_auiRasterToZscan[ m_pcPic->getNumPartitionsInCtu() - 1 ];
+  if ( bEnforceSliceRestriction && !CUIsFromSameSliceAndTile(m_pCtuAboveLeft) )
+  {
+    return NULL;
+  }
+  return m_pCtuAboveLeft;
+}
+
+TComDataCU* TComDataCU::getPUAboveRight( UInt& uiARPartUnitIdx, UInt uiCurrPartUnitIdx, Bool bEnforceSliceRestriction )
+{
+  UInt uiAbsPartIdxRT     = g_auiZscanToRaster[uiCurrPartUnitIdx];
+  UInt uiAbsZorderCUIdx   = g_auiZscanToRaster[ m_absZIdxInCtu ] + m_puhWidth[0] / m_pcPic->getMinCUWidth() - 1;
+  const UInt numPartInCtuWidth = m_pcPic->getNumPartInCtuWidth();
+  
+#if REPN_FORMAT_IN_VPS
+  if( ( m_pcPic->getCtu(m_ctuRsAddr)->getCUPelX() + g_auiRasterToPelX[uiAbsPartIdxRT] + m_pcPic->getMinCUWidth() ) >= m_pcSlice->getPicWidthInLumaSamples() )
+#else
+  if( ( m_pcPic->getCtu(m_ctuRsAddr)->getCUPelX() + g_auiRasterToPelX[uiAbsPartIdxRT] + m_pcPic->getMinCUWidth() ) >= m_pcSlice->getSPS()->getPicWidthInLumaSamples() )
+#endif
+  {
+    uiARPartUnitIdx = MAX_UINT;
+    return NULL;
+  }
+
+  if ( RasterAddress::lessThanCol( uiAbsPartIdxRT, numPartInCtuWidth - 1, numPartInCtuWidth ) )
+  {
+    if ( !RasterAddress::isZeroRow( uiAbsPartIdxRT, numPartInCtuWidth ) )
+    {
+      if ( uiCurrPartUnitIdx > g_auiRasterToZscan[ uiAbsPartIdxRT - numPartInCtuWidth + 1 ] )
+      {
+        uiARPartUnitIdx = g_auiRasterToZscan[ uiAbsPartIdxRT - numPartInCtuWidth + 1 ];
+        if ( RasterAddress::isEqualRowOrCol( uiAbsPartIdxRT, uiAbsZorderCUIdx, numPartInCtuWidth ) )
+        {
+          return m_pcPic->getCtu( getCtuRsAddr() );
+        }
+        else
+        {
+          uiARPartUnitIdx -= m_absZIdxInCtu;
+          return this;
+        }
+      }
+      uiARPartUnitIdx = MAX_UINT;
+      return NULL;
+    }
+    uiARPartUnitIdx = g_auiRasterToZscan[ uiAbsPartIdxRT + m_pcPic->getNumPartitionsInCtu() - numPartInCtuWidth + 1 ];
+
+    if ( bEnforceSliceRestriction && !CUIsFromSameSliceAndTile(m_pCtuAbove) )
+    {
+      return NULL;
+    }
+    return m_pCtuAbove;
+  }
+
+  if ( !RasterAddress::isZeroRow( uiAbsPartIdxRT, numPartInCtuWidth ) )
+  {
+    uiARPartUnitIdx = MAX_UINT;
+    return NULL;
+  }
+
+  uiARPartUnitIdx = g_auiRasterToZscan[ m_pcPic->getNumPartitionsInCtu() - numPartInCtuWidth ];
+
+  if ( bEnforceSliceRestriction && !CUIsFromSameSliceAndTile(m_pCtuAboveRight) )
+  {
+    return NULL;
+  }
+  return m_pCtuAboveRight;
+}
+
+TComDataCU* TComDataCU::getPUBelowLeft( UInt& uiBLPartUnitIdx, UInt uiCurrPartUnitIdx, Bool bEnforceSliceRestriction )
+{
+  UInt uiAbsPartIdxLB     = g_auiZscanToRaster[uiCurrPartUnitIdx];
+  const UInt numPartInCtuWidth = m_pcPic->getNumPartInCtuWidth();
+  UInt uiAbsZorderCUIdxLB = g_auiZscanToRaster[ m_absZIdxInCtu ] + (m_puhHeight[0] / m_pcPic->getMinCUHeight() - 1)*numPartInCtuWidth;
+
+#if REPN_FORMAT_IN_VPS
+  if( ( m_pcPic->getCtu(m_ctuRsAddr)->getCUPelY() + g_auiRasterToPelY[uiAbsPartIdxLB] + m_pcPic->getMinCUHeight() ) >= m_pcSlice->getPicHeightInLumaSamples() )
+#else
+  if( ( m_pcPic->getCtu(m_ctuRsAddr)->getCUPelY() + g_auiRasterToPelY[uiAbsPartIdxLB] + m_pcPic->getMinCUHeight() ) >= m_pcSlice->getSPS()->getPicHeightInLumaSamples() )
+#endif
+  {
+    uiBLPartUnitIdx = MAX_UINT;
+    return NULL;
+  }
+
+  if ( RasterAddress::lessThanRow( uiAbsPartIdxLB, m_pcPic->getNumPartInCtuHeight() - 1, numPartInCtuWidth ) )
+  {
+    if ( !RasterAddress::isZeroCol( uiAbsPartIdxLB, numPartInCtuWidth ) )
+    {
+      if ( uiCurrPartUnitIdx > g_auiRasterToZscan[ uiAbsPartIdxLB + numPartInCtuWidth - 1 ] )
+      {
+        uiBLPartUnitIdx = g_auiRasterToZscan[ uiAbsPartIdxLB + numPartInCtuWidth - 1 ];
+        if ( RasterAddress::isEqualRowOrCol( uiAbsPartIdxLB, uiAbsZorderCUIdxLB, numPartInCtuWidth ) )
+        {
+          return m_pcPic->getCtu( getCtuRsAddr() );
+        }
+        else
+        {
+          uiBLPartUnitIdx -= m_absZIdxInCtu;
+          return this;
+        }
+      }
+      uiBLPartUnitIdx = MAX_UINT;
+      return NULL;
+    }
+    uiBLPartUnitIdx = g_auiRasterToZscan[ uiAbsPartIdxLB + numPartInCtuWidth*2 - 1 ];
+    if ( bEnforceSliceRestriction && !CUIsFromSameSliceAndTile(m_pCtuLeft) )
+    {
+      return NULL;
+    }
+    return m_pCtuLeft;
+  }
+
+  uiBLPartUnitIdx = MAX_UINT;
+  return NULL;
+}
+
+TComDataCU* TComDataCU::getPUBelowLeftAdi(UInt& uiBLPartUnitIdx,  UInt uiCurrPartUnitIdx, UInt uiPartUnitOffset, Bool bEnforceSliceRestriction)
+{
+  UInt uiAbsPartIdxLB     = g_auiZscanToRaster[uiCurrPartUnitIdx];
+  const UInt numPartInCtuWidth = m_pcPic->getNumPartInCtuWidth();
+  UInt uiAbsZorderCUIdxLB = g_auiZscanToRaster[ m_absZIdxInCtu ] + ((m_puhHeight[0] / m_pcPic->getMinCUHeight()) - 1)*numPartInCtuWidth;
+  
+#if REPN_FORMAT_IN_VPS
+  if( ( m_pcPic->getCtu(m_ctuRsAddr)->getCUPelY() + g_auiRasterToPelY[uiAbsPartIdxLB] + (m_pcPic->getPicSym()->getMinCUHeight() * uiPartUnitOffset)) >= m_pcSlice->getPicHeightInLumaSamples())
+#else
+  if( ( m_pcPic->getCtu(m_ctuRsAddr)->getCUPelY() + g_auiRasterToPelY[uiAbsPartIdxLB] + (m_pcPic->getPicSym()->getMinCUHeight() * uiPartUnitOffset)) >= m_pcSlice->getSPS()->getPicHeightInLumaSamples())
+#endif
+  {
+    uiBLPartUnitIdx = MAX_UINT;
+    return NULL;
+  }
+
+  if ( RasterAddress::lessThanRow( uiAbsPartIdxLB, m_pcPic->getNumPartInCtuHeight() - uiPartUnitOffset, numPartInCtuWidth ) )
+  {
+    if ( !RasterAddress::isZeroCol( uiAbsPartIdxLB, numPartInCtuWidth ) )
+    {
+      if ( uiCurrPartUnitIdx > g_auiRasterToZscan[ uiAbsPartIdxLB + uiPartUnitOffset * numPartInCtuWidth - 1 ] )
+      {
+        uiBLPartUnitIdx = g_auiRasterToZscan[ uiAbsPartIdxLB + uiPartUnitOffset * numPartInCtuWidth - 1 ];
+        if ( RasterAddress::isEqualRowOrCol( uiAbsPartIdxLB, uiAbsZorderCUIdxLB, numPartInCtuWidth ) )
+        {
+          return m_pcPic->getCtu( getCtuRsAddr() );
+        }
+        else
+        {
+          uiBLPartUnitIdx -= m_absZIdxInCtu;
+          return this;
+        }
+      }
+      uiBLPartUnitIdx = MAX_UINT;
+      return NULL;
+    }
+    uiBLPartUnitIdx = g_auiRasterToZscan[ uiAbsPartIdxLB + (1+uiPartUnitOffset) * numPartInCtuWidth - 1 ];
+    if ( bEnforceSliceRestriction && !CUIsFromSameSliceAndTile(m_pCtuLeft) )
+    {
+      return NULL;
+    }
+    return m_pCtuLeft;
+  }
+
+  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_absZIdxInCtu ] + (m_puhWidth[0] / m_pcPic->getMinCUWidth()) - 1;
+  const UInt numPartInCtuWidth = m_pcPic->getNumPartInCtuWidth();
+  
+#if REPN_FORMAT_IN_VPS
+  if( ( m_pcPic->getCtu(m_ctuRsAddr)->getCUPelX() + g_auiRasterToPelX[uiAbsPartIdxRT] + (m_pcPic->getPicSym()->getMinCUHeight() * uiPartUnitOffset)) >= m_pcSlice->getPicWidthInLumaSamples() )
+#else
+  if( ( m_pcPic->getCtu(m_ctuRsAddr)->getCUPelX() + g_auiRasterToPelX[uiAbsPartIdxRT] + (m_pcPic->getPicSym()->getMinCUHeight() * uiPartUnitOffset)) >= m_pcSlice->getSPS()->getPicWidthInLumaSamples() )
+#endif
+  {
+    uiARPartUnitIdx = MAX_UINT;
+    return NULL;
+  }
+
+  if ( RasterAddress::lessThanCol( uiAbsPartIdxRT, numPartInCtuWidth - uiPartUnitOffset, numPartInCtuWidth ) )
+  {
+    if ( !RasterAddress::isZeroRow( uiAbsPartIdxRT, numPartInCtuWidth ) )
+    {
+      if ( uiCurrPartUnitIdx > g_auiRasterToZscan[ uiAbsPartIdxRT - numPartInCtuWidth + uiPartUnitOffset ] )
+      {
+        uiARPartUnitIdx = g_auiRasterToZscan[ uiAbsPartIdxRT - numPartInCtuWidth + uiPartUnitOffset ];
+        if ( RasterAddress::isEqualRowOrCol( uiAbsPartIdxRT, uiAbsZorderCUIdx, numPartInCtuWidth ) )
+        {
+          return m_pcPic->getCtu( getCtuRsAddr() );
+        }
+        else
+        {
+          uiARPartUnitIdx -= m_absZIdxInCtu;
+          return this;
+        }
+      }
+      uiARPartUnitIdx = MAX_UINT;
+      return NULL;
+    }
+
+    uiARPartUnitIdx = g_auiRasterToZscan[ uiAbsPartIdxRT + m_pcPic->getNumPartitionsInCtu() - numPartInCtuWidth + uiPartUnitOffset ];
+    if ( bEnforceSliceRestriction && !CUIsFromSameSliceAndTile(m_pCtuAbove) )
+    {
+      return NULL;
+    }
+    return m_pCtuAbove;
+  }
+
+  if ( !RasterAddress::isZeroRow( uiAbsPartIdxRT, numPartInCtuWidth ) )
+  {
+    uiARPartUnitIdx = MAX_UINT;
+    return NULL;
+  }
+
+  uiARPartUnitIdx = g_auiRasterToZscan[ m_pcPic->getNumPartitionsInCtu() - numPartInCtuWidth + uiPartUnitOffset-1 ];
+  if ( bEnforceSliceRestriction && !CUIsFromSameSliceAndTile(m_pCtuAboveRight) )
+  {
+    return NULL;
+  }
+  return m_pCtuAboveRight;
+}
+
+/** Get left QpMinCu
+*\param   uiLPartUnitIdx
+*\param   uiCurrAbsIdxInCtu
+*\returns TComDataCU*   point of TComDataCU of left QpMinCu
+*/
+TComDataCU* TComDataCU::getQpMinCuLeft( UInt& uiLPartUnitIdx, UInt uiCurrAbsIdxInCtu )
+{
+  const UInt numPartInCtuWidth = m_pcPic->getNumPartInCtuWidth();
+  UInt absZorderQpMinCUIdx = (uiCurrAbsIdxInCtu>>((g_uiMaxCUDepth - getSlice()->getPPS()->getMaxCuDQPDepth())<<1))<<((g_uiMaxCUDepth -getSlice()->getPPS()->getMaxCuDQPDepth())<<1);
+  UInt absRorderQpMinCUIdx = g_auiZscanToRaster[absZorderQpMinCUIdx];
+
+  // check for left CTU boundary
+  if ( RasterAddress::isZeroCol(absRorderQpMinCUIdx, numPartInCtuWidth) )
+  {
+    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 CTU
+  return m_pcPic->getCtu( getCtuRsAddr() );
+}
+
+/** Get Above QpMinCu
+*\param   uiAPartUnitIdx
+*\param   uiCurrAbsIdxInCtu
+*\returns TComDataCU*   point of TComDataCU of above QpMinCu
+*/
+TComDataCU* TComDataCU::getQpMinCuAbove( UInt& uiAPartUnitIdx, UInt uiCurrAbsIdxInCtu )
+{
+  const UInt numPartInCtuWidth = m_pcPic->getNumPartInCtuWidth();
+  UInt absZorderQpMinCUIdx = (uiCurrAbsIdxInCtu>>((g_uiMaxCUDepth - getSlice()->getPPS()->getMaxCuDQPDepth())<<1))<<((g_uiMaxCUDepth - getSlice()->getPPS()->getMaxCuDQPDepth())<<1);
+  UInt absRorderQpMinCUIdx = g_auiZscanToRaster[absZorderQpMinCUIdx];
+
+  // check for top CTU boundary
+  if ( RasterAddress::isZeroRow( absRorderQpMinCUIdx, numPartInCtuWidth) )
+  {
+    return NULL;
+  }
+
+  // get index of top-CU relative to top-left corner of current quantization group
+  uiAPartUnitIdx = g_auiRasterToZscan[absRorderQpMinCUIdx - numPartInCtuWidth];
+
+  // return pointer to current CTU
+  return m_pcPic->getCtu( getCtuRsAddr() );
+}
+
+
+
+/** Get reference QP from left QpMinCu or latest coded QP
+*\param   uiCurrAbsIdxInCtu
+*\returns Char   reference QP value
+*/
+Char TComDataCU::getRefQP( UInt uiCurrAbsIdxInCtu )
+{
+  UInt lPartIdx = MAX_UINT;
+  UInt aPartIdx = MAX_UINT;
+  TComDataCU* cULeft  = getQpMinCuLeft ( lPartIdx, m_absZIdxInCtu + uiCurrAbsIdxInCtu );
+  TComDataCU* cUAbove = getQpMinCuAbove( aPartIdx, m_absZIdxInCtu + uiCurrAbsIdxInCtu );
+  return (((cULeft? cULeft->getQP( lPartIdx ): getLastCodedQP( uiCurrAbsIdxInCtu )) + (cUAbove? cUAbove->getQP( aPartIdx ): getLastCodedQP( uiCurrAbsIdxInCtu )) + 1) >> 1);
+}
+
+Int TComDataCU::getLastValidPartIdx( Int iAbsPartIdx )
+{
+  Int iLastValidPartIdx = iAbsPartIdx-1;
+  while ( iLastValidPartIdx >= 0
+       && getPredictionMode( iLastValidPartIdx ) == NUMBER_OF_PREDICTION_MODES )
+  {
+    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 ); // A idx will be invalid if it is off the right or bottom edge of the picture.
+  // If this CU is in the first CTU of the slice and there is no valid part before this one, use slice QP
+  if ( getPic()->getPicSym()->getCtuTsToRsAddrMap(getSlice()->getSliceCurStartCtuTsAddr()) == getCtuRsAddr() && Int(getZorderIdxInCtu())+iLastValidPartIdx<0)
+  {
+    return getSlice()->getSliceQp();
+  }
+  else if ( iLastValidPartIdx >= 0 )
+  {
+    // If there is a valid part within the current Sub-CU, use it
+    return getQP( iLastValidPartIdx );
+  }
+  else
+  {
+    if ( getZorderIdxInCtu() > 0 )
+    {
+      // If this wasn't the first sub-cu within the Ctu, explore the CTU itself.
+      return getPic()->getCtu( getCtuRsAddr() )->getLastCodedQP( getZorderIdxInCtu() ); // TODO - remove this recursion
+    }
+    else if ( getPic()->getPicSym()->getCtuRsToTsAddrMap(getCtuRsAddr()) > 0
+      && CUIsFromSameSliceTileAndWavefrontRow(getPic()->getCtu(getPic()->getPicSym()->getCtuTsToRsAddrMap(getPic()->getPicSym()->getCtuRsToTsAddrMap(getCtuRsAddr())-1))) )
+    {
+      // If this isn't the first Ctu (how can it be due to the first 'if'?), and the previous Ctu is from the same tile, examine the previous Ctu.
+      return getPic()->getCtu( getPic()->getPicSym()->getCtuTsToRsAddrMap(getPic()->getPicSym()->getCtuRsToTsAddrMap(getCtuRsAddr())-1) )->getLastCodedQP( getPic()->getNumPartitionsInCtu() );  // TODO - remove this recursion
+    }
+    else
+    {
+      // No other options available - use the slice-level QP.
+      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[NUM_CHROMA_MODE] )
+{
+  uiModeList[0] = PLANAR_IDX;
+  uiModeList[1] = VER_IDX;
+  uiModeList[2] = HOR_IDX;
+  uiModeList[3] = DC_IDX;
+  uiModeList[4] = DM_CHROMA_IDX;
+  assert(4<NUM_CHROMA_MODE);
+
+  UInt uiLumaMode = getIntraDir( CHANNEL_TYPE_LUMA, 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::getIntraDirPredictor( UInt uiAbsPartIdx, Int uiIntraDirPred[NUM_MOST_PROBABLE_MODES], const ComponentID compID, Int* piMode  )
+{
+  TComDataCU* pcCULeft, *pcCUAbove;
+  UInt        LeftPartIdx  = MAX_UINT;
+  UInt        AbovePartIdx = MAX_UINT;
+  Int         iLeftIntraDir, iAboveIntraDir;
+  Int         uiPredNum = 0;
+
+  const ChannelType chType = toChannelType(compID);
+  const ChromaFormat chForm = getPic()->getChromaFormat();
+  // Get intra direction of left PU
+  pcCULeft = getPULeft( LeftPartIdx, m_absZIdxInCtu + uiAbsPartIdx );
+
+  if (isChroma(compID)) LeftPartIdx = getChromasCorrespondingPULumaIdx(LeftPartIdx, chForm);
+  iLeftIntraDir  = pcCULeft ? ( pcCULeft->isIntra( LeftPartIdx ) ? pcCULeft->getIntraDir( chType, LeftPartIdx ) : DC_IDX ) : DC_IDX;
+
+  // Get intra direction of above PU
+  pcCUAbove = getPUAbove( AbovePartIdx, m_absZIdxInCtu + uiAbsPartIdx, true, true );
+
+  if (isChroma(compID)) AbovePartIdx = getChromasCorrespondingPULumaIdx(AbovePartIdx, chForm);
+  iAboveIntraDir = pcCUAbove ? ( pcCUAbove->isIntra( AbovePartIdx ) ? pcCUAbove->getIntraDir( chType, AbovePartIdx ) : DC_IDX ) : DC_IDX;
+
+  if (isChroma(chType))
+  {
+    if (iLeftIntraDir  == DM_CHROMA_IDX) iLeftIntraDir  = pcCULeft-> getIntraDir( CHANNEL_TYPE_LUMA, LeftPartIdx  );
+    if (iAboveIntraDir == DM_CHROMA_IDX) iAboveIntraDir = pcCUAbove->getIntraDir( CHANNEL_TYPE_LUMA, AbovePartIdx );
+  }
+
+  assert (2<NUM_MOST_PROBABLE_MODES);
+  uiPredNum = NUM_MOST_PROBABLE_MODES;
+  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;
+    }
+  }
+  for (Int i=0; i<uiPredNum; i++)
+    assert(uiIntraDirPred[i] < 35);
+
+  return uiPredNum;
+}
+
+UInt TComDataCU::getCtxSplitFlag( UInt uiAbsPartIdx, UInt uiDepth )
+{
+  TComDataCU* pcTempCU;
+  UInt        uiTempPartIdx;
+  UInt        uiCtx;
+  // Get left split flag
+  pcTempCU = getPULeft( uiTempPartIdx, m_absZIdxInCtu + uiAbsPartIdx );
+  uiCtx  = ( pcTempCU ) ? ( ( pcTempCU->getDepth( uiTempPartIdx ) > uiDepth ) ? 1 : 0 ) : 0;
+
+  // Get above split flag
+  pcTempCU = getPUAbove( uiTempPartIdx, m_absZIdxInCtu + uiAbsPartIdx );
+  uiCtx += ( pcTempCU ) ? ( ( pcTempCU->getDepth( uiTempPartIdx ) > uiDepth ) ? 1 : 0 ) : 0;
+
+  return uiCtx;
+}
+
+UInt TComDataCU::getCtxQtCbf( TComTU &rTu, const ChannelType chType )
+{
+  const UInt transformDepth = rTu.GetTransformDepthRel();
+
+  if (isChroma(chType))
+  {
+    return transformDepth;
+  }
+  else
+  {
+    const UInt uiCtx = ( transformDepth == 0 ? 1 : 0 );
+    return uiCtx;
+  }
+}
+
+UInt TComDataCU::getQuadtreeTULog2MinSizeInCU( UInt absPartIdx )
+{
+  UInt log2CbSize = g_aucConvertToBit[getWidth( absPartIdx )] + 2;
+  PartSize  partSize  = getPartitionSize( absPartIdx );
+  UInt quadtreeTUMaxDepth = isIntra( absPartIdx ) ? m_pcSlice->getSPS()->getQuadtreeTUMaxDepthIntra() : m_pcSlice->getSPS()->getQuadtreeTUMaxDepthInter();
+  Int intraSplitFlag = ( isIntra( absPartIdx ) && partSize == SIZE_NxN ) ? 1 : 0;
+  Int interSplitFlag = ((quadtreeTUMaxDepth == 1) && isInter( absPartIdx ) && (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_absZIdxInCtu + uiAbsPartIdx );
+  uiCtx    = ( pcTempCU ) ? pcTempCU->isSkipped( uiTempPartIdx ) : 0;
+
+  // Get BCBP of above PU
+  pcTempCU = getPUAbove( uiTempPartIdx, m_absZIdxInCtu + uiAbsPartIdx );
+  uiCtx   += ( pcTempCU ) ? pcTempCU->isSkipped( uiTempPartIdx ) : 0;
+
+  return uiCtx;
+}
+
+UInt TComDataCU::getCtxInterDir( UInt uiAbsPartIdx )
+{
+  return getDepth( uiAbsPartIdx );
+}
+
+
+UChar TComDataCU::getQtRootCbf( UInt uiIdx )
+{
+  const UInt numberValidComponents = getPic()->getNumberValidComponents();
+  return getCbf( uiIdx, COMPONENT_Y, 0 )
+          || ((numberValidComponents > COMPONENT_Cb) && getCbf( uiIdx, COMPONENT_Cb, 0 ))
+          || ((numberValidComponents > COMPONENT_Cr) && getCbf( uiIdx, COMPONENT_Cr, 0 ));
+}
+
+Void TComDataCU::setCbfSubParts( const UInt uiCbf[MAX_NUM_COMPONENT], UInt uiAbsPartIdx, UInt uiDepth )
+{
+  UInt uiCurrPartNumb = m_pcPic->getNumPartitionsInCtu() >> (uiDepth << 1);
+  for(UInt comp=0; comp<MAX_NUM_COMPONENT; comp++)
+  {
+    memset( m_puhCbf[comp] + uiAbsPartIdx, uiCbf[comp], sizeof( UChar ) * uiCurrPartNumb );
+  }
+}
+
+Void TComDataCU::setCbfSubParts( UInt uiCbf, ComponentID compID, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  UInt uiCurrPartNumb = m_pcPic->getNumPartitionsInCtu() >> (uiDepth << 1);
+  memset( m_puhCbf[compID] + 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, ComponentID compID, UInt uiAbsPartIdx, UInt uiPartIdx, UInt uiDepth )
+{
+  setSubPart<UChar>( uiCbf, m_puhCbf[compID], uiAbsPartIdx, uiDepth, uiPartIdx );
+}
+
+Void TComDataCU::setCbfPartRange ( UInt uiCbf, ComponentID compID, UInt uiAbsPartIdx, UInt uiCoveredPartIdxes )
+{
+  memset((m_puhCbf[compID] + uiAbsPartIdx), uiCbf, (sizeof(UChar) * uiCoveredPartIdxes));
+}
+
+Void TComDataCU::bitwiseOrCbfPartRange( UInt uiCbf, ComponentID compID, UInt uiAbsPartIdx, UInt uiCoveredPartIdxes )
+{
+  const UInt stopAbsPartIdx = uiAbsPartIdx + uiCoveredPartIdxes;
+
+  for (UInt subPartIdx = uiAbsPartIdx; subPartIdx < stopAbsPartIdx; subPartIdx++)
+  {
+    m_puhCbf[compID][subPartIdx] |= uiCbf;
+  }
+}
+
+Void TComDataCU::setDepthSubParts( UInt uiDepth, UInt uiAbsPartIdx )
+{
+  UInt uiCurrPartNumb = m_pcPic->getNumPartitionsInCtu() >> (uiDepth << 1);
+  memset( m_puhDepth + uiAbsPartIdx, uiDepth, sizeof(UChar)*uiCurrPartNumb );
+}
+
+Bool TComDataCU::isFirstAbsZorderIdxInDepth (UInt uiAbsPartIdx, UInt uiDepth)
+{
+  UInt uiPartNumb = m_pcPic->getNumPartitionsInCtu() >> (uiDepth << 1);
+  return (((m_absZIdxInCtu + uiAbsPartIdx)% uiPartNumb) == 0);
+}
+
+Void TComDataCU::setPartSizeSubParts( PartSize eMode, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  assert( sizeof( *m_pePartSize) == 1 );
+  memset( m_pePartSize + uiAbsPartIdx, eMode, m_pcPic->getNumPartitionsInCtu() >> ( 2 * uiDepth ) );
+}
+
+Void TComDataCU::setCUTransquantBypassSubParts( Bool flag, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  memset( m_CUTransquantBypass + uiAbsPartIdx, flag, m_pcPic->getNumPartitionsInCtu() >> ( 2 * uiDepth ) );
+}
+
+Void TComDataCU::setSkipFlagSubParts( Bool skip, UInt absPartIdx, UInt depth )
+{
+  assert( sizeof( *m_skipFlag) == 1 );
+  memset( m_skipFlag + absPartIdx, skip, m_pcPic->getNumPartitionsInCtu() >> ( 2 * depth ) );
+}
+
+Void TComDataCU::setPredModeSubParts( PredMode eMode, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  assert( sizeof( *m_pePredMode) == 1 );
+  memset( m_pePredMode + uiAbsPartIdx, eMode, m_pcPic->getNumPartitionsInCtu() >> ( 2 * uiDepth ) );
+}
+
+Void TComDataCU::setChromaQpAdjSubParts( UChar val, Int absPartIdx, Int depth )
+{
+  assert( sizeof(*m_ChromaQpAdj) == 1 );
+  memset( m_ChromaQpAdj + absPartIdx, val, m_pcPic->getNumPartitionsInCtu() >> ( 2 * depth ) );
+}
+
+Void TComDataCU::setQPSubCUs( Int qp, UInt absPartIdx, UInt depth, Bool &foundNonZeroCbf )
+{
+  UInt currPartNumb = m_pcPic->getNumPartitionsInCtu() >> (depth << 1);
+  UInt currPartNumQ = currPartNumb >> 2;
+  const UInt numValidComp = m_pcPic->getNumberValidComponents();
+
+  if(!foundNonZeroCbf)
+  {
+    if(getDepth(absPartIdx) > depth)
+    {
+      for ( UInt partUnitIdx = 0; partUnitIdx < 4; partUnitIdx++ )
+      {
+        setQPSubCUs( qp, absPartIdx+partUnitIdx*currPartNumQ, depth+1, foundNonZeroCbf );
+      }
+    }
+    else
+    {
+      if(getCbf( absPartIdx, COMPONENT_Y ) || (numValidComp>COMPONENT_Cb && getCbf( absPartIdx, COMPONENT_Cb )) || (numValidComp>COMPONENT_Cr && getCbf( absPartIdx, COMPONENT_Cr) ) )
+      {
+        foundNonZeroCbf = true;
+      }
+      else
+      {
+        setQPSubParts(qp, absPartIdx, depth);
+      }
+    }
+  }
+}
+
+Void TComDataCU::setQPSubParts( Int qp, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  const UInt numPart = m_pcPic->getNumPartitionsInCtu() >> (uiDepth << 1);
+  memset(m_phQP+uiAbsPartIdx, qp, numPart);
+}
+
+Void TComDataCU::setIntraDirSubParts( const ChannelType channelType, const UInt dir, const UInt absPartIdx, const UInt depth )
+{
+  UInt numPart = m_pcPic->getNumPartitionsInCtu() >> (depth << 1);
+  memset( m_puhIntraDir[channelType] + absPartIdx, dir,sizeof(UChar)*numPart );
+}
+
+template<typename T>
+Void TComDataCU::setSubPart( T uiParameter, T* puhBaseCtu, UInt uiCUAddr, UInt uiCUDepth, UInt uiPUIdx )
+{
+  assert( sizeof(T) == 1 ); // Using memset() works only for types of size 1
+
+  UInt uiCurrPartNumQ = (m_pcPic->getNumPartitionsInCtu() >> (2 * uiCUDepth)) >> 2;
+  switch ( m_pePartSize[ uiCUAddr ] )
+  {
+    case SIZE_2Nx2N:
+      memset( puhBaseCtu + uiCUAddr, uiParameter, 4 * uiCurrPartNumQ );
+      break;
+    case SIZE_2NxN:
+      memset( puhBaseCtu + uiCUAddr, uiParameter, 2 * uiCurrPartNumQ );
+      break;
+    case SIZE_Nx2N:
+      memset( puhBaseCtu + uiCUAddr, uiParameter, uiCurrPartNumQ );
+      memset( puhBaseCtu + uiCUAddr + 2 * uiCurrPartNumQ, uiParameter, uiCurrPartNumQ );
+      break;
+    case SIZE_NxN:
+      memset( puhBaseCtu + uiCUAddr, uiParameter, uiCurrPartNumQ );
+      break;
+    case SIZE_2NxnU:
+      if ( uiPUIdx == 0 )
+      {
+        memset( puhBaseCtu + uiCUAddr, uiParameter, (uiCurrPartNumQ >> 1) );
+        memset( puhBaseCtu + uiCUAddr + uiCurrPartNumQ, uiParameter, (uiCurrPartNumQ >> 1) );
+      }
+      else if ( uiPUIdx == 1 )
+      {
+        memset( puhBaseCtu + uiCUAddr, uiParameter, (uiCurrPartNumQ >> 1) );
+        memset( puhBaseCtu + uiCUAddr + uiCurrPartNumQ, uiParameter, ((uiCurrPartNumQ >> 1) + (uiCurrPartNumQ << 1)) );
+      }
+      else
+      {
+        assert(0);
+      }
+      break;
+    case SIZE_2NxnD:
+      if ( uiPUIdx == 0 )
+      {
+        memset( puhBaseCtu + uiCUAddr, uiParameter, ((uiCurrPartNumQ << 1) + (uiCurrPartNumQ >> 1)) );
+        memset( puhBaseCtu + uiCUAddr + (uiCurrPartNumQ << 1) + uiCurrPartNumQ, uiParameter, (uiCurrPartNumQ >> 1) );
+      }
+      else if ( uiPUIdx == 1 )
+      {
+        memset( puhBaseCtu + uiCUAddr, uiParameter, (uiCurrPartNumQ >> 1) );
+        memset( puhBaseCtu + uiCUAddr + uiCurrPartNumQ, uiParameter, (uiCurrPartNumQ >> 1) );
+      }
+      else
+      {
+        assert(0);
+      }
+      break;
+    case SIZE_nLx2N:
+      if ( uiPUIdx == 0 )
+      {
+        memset( puhBaseCtu + uiCUAddr, uiParameter, (uiCurrPartNumQ >> 2) );
+        memset( puhBaseCtu + uiCUAddr + (uiCurrPartNumQ >> 1), uiParameter, (uiCurrPartNumQ >> 2) );
+        memset( puhBaseCtu + uiCUAddr + (uiCurrPartNumQ << 1), uiParameter, (uiCurrPartNumQ >> 2) );
+        memset( puhBaseCtu + uiCUAddr + (uiCurrPartNumQ << 1) + (uiCurrPartNumQ >> 1), uiParameter, (uiCurrPartNumQ >> 2) );
+      }
+      else if ( uiPUIdx == 1 )
+      {
+        memset( puhBaseCtu + uiCUAddr, uiParameter, (uiCurrPartNumQ >> 2) );
+        memset( puhBaseCtu + uiCUAddr + (uiCurrPartNumQ >> 1), uiParameter, (uiCurrPartNumQ + (uiCurrPartNumQ >> 2)) );
+        memset( puhBaseCtu + uiCUAddr + (uiCurrPartNumQ << 1), uiParameter, (uiCurrPartNumQ >> 2) );
+        memset( puhBaseCtu + uiCUAddr + (uiCurrPartNumQ << 1) + (uiCurrPartNumQ >> 1), uiParameter, (uiCurrPartNumQ + (uiCurrPartNumQ >> 2)) );
+      }
+      else
+      {
+        assert(0);
+      }
+      break;
+    case SIZE_nRx2N:
+      if ( uiPUIdx == 0 )
+      {
+        memset( puhBaseCtu + uiCUAddr, uiParameter, (uiCurrPartNumQ + (uiCurrPartNumQ >> 2)) );
+        memset( puhBaseCtu + uiCUAddr + uiCurrPartNumQ + (uiCurrPartNumQ >> 1), uiParameter, (uiCurrPartNumQ >> 2) );
+        memset( puhBaseCtu + uiCUAddr + (uiCurrPartNumQ << 1), uiParameter, (uiCurrPartNumQ + (uiCurrPartNumQ >> 2)) );
+        memset( puhBaseCtu + uiCUAddr + (uiCurrPartNumQ << 1) + uiCurrPartNumQ + (uiCurrPartNumQ >> 1), uiParameter, (uiCurrPartNumQ >> 2) );
+      }
+      else if ( uiPUIdx == 1 )
+      {
+        memset( puhBaseCtu + uiCUAddr, uiParameter, (uiCurrPartNumQ >> 2) );
+        memset( puhBaseCtu + uiCUAddr + (uiCurrPartNumQ >> 1), uiParameter, (uiCurrPartNumQ >> 2) );
+        memset( puhBaseCtu + uiCUAddr + (uiCurrPartNumQ << 1), uiParameter, (uiCurrPartNumQ >> 2) );
+        memset( puhBaseCtu + uiCUAddr + (uiCurrPartNumQ << 1) + (uiCurrPartNumQ >> 1), uiParameter, (uiCurrPartNumQ >> 2) );
+      }
+      else
+      {
+        assert(0);
+      }
+      break;
+    default:
+      assert( 0 );
+      break;
+  }
+}
+
+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 );
+}
+
+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->getNumPartitionsInCtu() >> (uiDepth << 1);
+
+  memset( m_puhTrIdx + uiAbsPartIdx, uiTrIdx, sizeof(UChar)*uiCurrPartNumb );
+}
+
+Void TComDataCU::setTransformSkipSubParts( const UInt useTransformSkip[MAX_NUM_COMPONENT], UInt uiAbsPartIdx, UInt uiDepth )
+{
+  UInt uiCurrPartNumb = m_pcPic->getNumPartitionsInCtu() >> (uiDepth << 1);
+
+  for(UInt i=0; i<MAX_NUM_COMPONENT; i++)
+  {
+    memset( m_puhTransformSkip[i] + uiAbsPartIdx, useTransformSkip[i], sizeof( UChar ) * uiCurrPartNumb );
+  }
+}
+
+Void TComDataCU::setTransformSkipSubParts( UInt useTransformSkip, ComponentID compID, UInt uiAbsPartIdx, UInt uiDepth)
+{
+  UInt uiCurrPartNumb = m_pcPic->getNumPartitionsInCtu() >> (uiDepth << 1);
+
+  memset( m_puhTransformSkip[compID] + uiAbsPartIdx, useTransformSkip, sizeof( UChar ) * uiCurrPartNumb );
+}
+
+Void TComDataCU::setTransformSkipPartRange ( UInt useTransformSkip, ComponentID compID, UInt uiAbsPartIdx, UInt uiCoveredPartIdxes )
+{
+  memset((m_puhTransformSkip[compID] + uiAbsPartIdx), useTransformSkip, (sizeof(UChar) * uiCoveredPartIdxes));
+}
+
+Void TComDataCU::setCrossComponentPredictionAlphaPartRange( Char alphaValue, ComponentID compID, UInt uiAbsPartIdx, UInt uiCoveredPartIdxes )
+{
+  memset((m_crossComponentPredictionAlpha[compID] + uiAbsPartIdx), alphaValue, (sizeof(Char) * uiCoveredPartIdxes));
+}
+
+Void TComDataCU::setExplicitRdpcmModePartRange ( UInt rdpcmMode, ComponentID compID, UInt uiAbsPartIdx, UInt uiCoveredPartIdxes )
+{
+  memset((m_explicitRdpcmMode[compID] + uiAbsPartIdx), rdpcmMode, (sizeof(UChar) * uiCoveredPartIdxes));
+}
+
+Void TComDataCU::setSizeSubParts( UInt uiWidth, UInt uiHeight, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  UInt uiCurrPartNumb = m_pcPic->getNumPartitionsInCtu() >> (uiDepth << 1);
+
+  memset( m_puhWidth  + uiAbsPartIdx, uiWidth,  sizeof(UChar)*uiCurrPartNumb );
+  memset( m_puhHeight + uiAbsPartIdx, uiHeight, sizeof(UChar)*uiCurrPartNumb );
+}
+
+UChar TComDataCU::getNumPartitions(const UInt uiAbsPartIdx)
+{
+  UChar iNumPart = 0;
+
+  switch ( m_pePartSize[uiAbsPartIdx] )
+  {
+    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;
+}
+
+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;
+  }
+}
+
+
+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_absZIdxInCtu + 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_absZIdxInCtu + uiAbsPartIdx ] + ((uiPUHeight / m_pcPic->getMinCUHeight()) - 1)*m_pcPic->getNumPartInCtuWidth()];
+}
+
+Void TComDataCU::deriveLeftRightTopIdx ( UInt uiPartIdx, UInt& ruiPartIdxLT, UInt& ruiPartIdxRT )
+{
+  ruiPartIdxLT = m_absZIdxInCtu;
+  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_absZIdxInCtu ] + ( ((m_puhHeight[0] / m_pcPic->getMinCUHeight())>>1) - 1)*m_pcPic->getNumPartInCtuWidth()];
+
+  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_absZIdxInCtu ] + ( ((m_puhHeight[0] / m_pcPic->getMinCUHeight())>>1) - 1)*m_pcPic->getNumPartInCtuWidth() +  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_absZIdxInCtu + 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        = getZorderIdxInCtu()+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;
+}
+
+/** Constructs a list of merging candidates
+ * \param uiAbsPartIdx
+ * \param uiPUIdx
+ * \param uiDepth
+ * \param pcMvFieldNeighbours
+ * \param puhInterDirNeighbours
+ * \param numValidMergeCand
+ */
+Void TComDataCU::getInterMergeCandidates( UInt uiAbsPartIdx, UInt uiPUIdx, TComMvField* pcMvFieldNeighbours, UChar* puhInterDirNeighbours, Int& numValidMergeCand, Int mrgCandIdx )
+{
+  UInt uiAbsPartAddr = m_absZIdxInCtu + uiAbsPartIdx;
+  Bool abCandIsInter[ MRG_MAX_NUM_CANDS ];
+  for( UInt ui = 0; ui < getSlice()->getMaxNumMergeCand(); ++ui )
+  {
+    abCandIsInter[ui] = false;
+    pcMvFieldNeighbours[ ( ui << 1 )     ].setRefIdx(NOT_VALID);
+    pcMvFieldNeighbours[ ( ui << 1 ) + 1 ].setRefIdx(NOT_VALID);
+  }
+  numValidMergeCand = getSlice()->getMaxNumMergeCand();
+  // compute the location of the current PU
+  Int xP, yP, nPSW, nPSH;
+  this->getPartPosition(uiPUIdx, xP, yP, nPSW, nPSH);
+
+  Int iCount = 0;
+
+  UInt uiPartIdxLT, uiPartIdxRT, uiPartIdxLB;
+  PartSize cCurPS = getPartitionSize( uiAbsPartIdx );
+  deriveLeftRightTopIdxGeneral( uiAbsPartIdx, uiPUIdx, uiPartIdxLT, uiPartIdxRT );
+  deriveLeftBottomIdxGeneral( uiAbsPartIdx, uiPUIdx, uiPartIdxLB );
+
+  //left
+  UInt uiLeftPartIdx = 0;
+  TComDataCU* pcCULeft = 0;
+  pcCULeft = getPULeft( uiLeftPartIdx, uiPartIdxLB );
+
+  Bool isAvailableA1 = pcCULeft &&
+                       pcCULeft->isDiffMER(xP -1, yP+nPSH-1, xP, yP) &&
+                       !( uiPUIdx == 1 && (cCurPS == SIZE_Nx2N || cCurPS == SIZE_nLx2N || cCurPS == SIZE_nRx2N) ) &&
+                       pcCULeft->isInter( uiLeftPartIdx ) ;
+
+  if ( isAvailableA1 )
+  {
+    abCandIsInter[iCount] = true;
+    // get Inter Dir
+    puhInterDirNeighbours[iCount] = pcCULeft->getInterDir( uiLeftPartIdx );
+    // get Mv from Left
+    pcCULeft->getMvField( pcCULeft, uiLeftPartIdx, REF_PIC_LIST_0, pcMvFieldNeighbours[iCount<<1] );
+    if ( getSlice()->isInterB() )
+    {
+      pcCULeft->getMvField( pcCULeft, uiLeftPartIdx, REF_PIC_LIST_1, pcMvFieldNeighbours[(iCount<<1)+1] );
+    }
+    if ( mrgCandIdx == iCount )
+    {
+      return;
+    }
+    iCount ++;
+  }
+
+  // early termination
+  if (iCount == getSlice()->getMaxNumMergeCand())
+  {
+    return;
+  }
+  // above
+  UInt uiAbovePartIdx = 0;
+  TComDataCU* pcCUAbove = 0;
+  pcCUAbove = getPUAbove( uiAbovePartIdx, uiPartIdxRT );
+
+  Bool isAvailableB1 = pcCUAbove &&
+                       pcCUAbove->isDiffMER(xP+nPSW-1, yP-1, xP, yP) &&
+                       !( uiPUIdx == 1 && (cCurPS == SIZE_2NxN || cCurPS == SIZE_2NxnU || cCurPS == SIZE_2NxnD) ) &&
+                       pcCUAbove->isInter( uiAbovePartIdx );
+
+  if ( isAvailableB1 && (!isAvailableA1 || !pcCULeft->hasEqualMotion( uiLeftPartIdx, pcCUAbove, uiAbovePartIdx ) ) )
+  {
+    abCandIsInter[iCount] = true;
+    // get Inter Dir
+    puhInterDirNeighbours[iCount] = pcCUAbove->getInterDir( uiAbovePartIdx );
+    // get Mv from Left
+    pcCUAbove->getMvField( pcCUAbove, uiAbovePartIdx, REF_PIC_LIST_0, pcMvFieldNeighbours[iCount<<1] );
+    if ( getSlice()->isInterB() )
+    {
+      pcCUAbove->getMvField( pcCUAbove, uiAbovePartIdx, REF_PIC_LIST_1, pcMvFieldNeighbours[(iCount<<1)+1] );
+    }
+    if ( mrgCandIdx == iCount )
+    {
+      return;
+    }
+    iCount ++;
+  }
+  // early termination
+  if (iCount == getSlice()->getMaxNumMergeCand())
+  {
+    return;
+  }
+
+  // above right
+  UInt uiAboveRightPartIdx = 0;
+  TComDataCU* pcCUAboveRight = 0;
+  pcCUAboveRight = getPUAboveRight( uiAboveRightPartIdx, uiPartIdxRT );
+
+  Bool isAvailableB0 = pcCUAboveRight &&
+                       pcCUAboveRight->isDiffMER(xP+nPSW, yP-1, xP, yP) &&
+                       pcCUAboveRight->isInter( uiAboveRightPartIdx );
+
+  if ( isAvailableB0 && ( !isAvailableB1 || !pcCUAbove->hasEqualMotion( uiAbovePartIdx, pcCUAboveRight, uiAboveRightPartIdx ) ) )
+  {
+    abCandIsInter[iCount] = true;
+    // get Inter Dir
+    puhInterDirNeighbours[iCount] = pcCUAboveRight->getInterDir( uiAboveRightPartIdx );
+    // get Mv from Left
+    pcCUAboveRight->getMvField( pcCUAboveRight, uiAboveRightPartIdx, REF_PIC_LIST_0, pcMvFieldNeighbours[iCount<<1] );
+    if ( getSlice()->isInterB() )
+    {
+      pcCUAboveRight->getMvField( pcCUAboveRight, uiAboveRightPartIdx, REF_PIC_LIST_1, pcMvFieldNeighbours[(iCount<<1)+1] );
+    }
+    if ( mrgCandIdx == iCount )
+    {
+      return;
+    }
+    iCount ++;
+  }
+  // early termination
+  if (iCount == getSlice()->getMaxNumMergeCand())
+  {
+    return;
+  }
+
+  //left bottom
+  UInt uiLeftBottomPartIdx = 0;
+  TComDataCU* pcCULeftBottom = 0;
+  pcCULeftBottom = this->getPUBelowLeft( uiLeftBottomPartIdx, uiPartIdxLB );
+
+  Bool isAvailableA0 = pcCULeftBottom &&
+                       pcCULeftBottom->isDiffMER(xP-1, yP+nPSH, xP, yP) &&
+                       pcCULeftBottom->isInter( uiLeftBottomPartIdx ) ;
+
+  if ( isAvailableA0 && ( !isAvailableA1 || !pcCULeft->hasEqualMotion( uiLeftPartIdx, pcCULeftBottom, uiLeftBottomPartIdx ) ) )
+  {
+    abCandIsInter[iCount] = true;
+    // get Inter Dir
+    puhInterDirNeighbours[iCount] = pcCULeftBottom->getInterDir( uiLeftBottomPartIdx );
+    // get Mv from Left
+    pcCULeftBottom->getMvField( pcCULeftBottom, uiLeftBottomPartIdx, REF_PIC_LIST_0, pcMvFieldNeighbours[iCount<<1] );
+    if ( getSlice()->isInterB() )
+    {
+      pcCULeftBottom->getMvField( pcCULeftBottom, uiLeftBottomPartIdx, REF_PIC_LIST_1, pcMvFieldNeighbours[(iCount<<1)+1] );
+    }
+    if ( mrgCandIdx == iCount )
+    {
+      return;
+    }
+    iCount ++;
+  }
+  // early termination
+  if (iCount == getSlice()->getMaxNumMergeCand())
+  {
+    return;
+  }
+
+  // above left
+  if( iCount < 4 )
+  {
+    UInt uiAboveLeftPartIdx = 0;
+    TComDataCU* pcCUAboveLeft = 0;
+    pcCUAboveLeft = getPUAboveLeft( uiAboveLeftPartIdx, uiAbsPartAddr );
+
+    Bool isAvailableB2 = pcCUAboveLeft &&
+                         pcCUAboveLeft->isDiffMER(xP-1, yP-1, xP, yP) &&
+                         pcCUAboveLeft->isInter( uiAboveLeftPartIdx );
+
+    if ( isAvailableB2 && ( !isAvailableA1 || !pcCULeft->hasEqualMotion( uiLeftPartIdx, pcCUAboveLeft, uiAboveLeftPartIdx ) )
+        && ( !isAvailableB1 || !pcCUAbove->hasEqualMotion( uiAbovePartIdx, pcCUAboveLeft, uiAboveLeftPartIdx ) ) )
+    {
+      abCandIsInter[iCount] = true;
+      // get Inter Dir
+      puhInterDirNeighbours[iCount] = pcCUAboveLeft->getInterDir( uiAboveLeftPartIdx );
+      // get Mv from Left
+      pcCUAboveLeft->getMvField( pcCUAboveLeft, uiAboveLeftPartIdx, REF_PIC_LIST_0, pcMvFieldNeighbours[iCount<<1] );
+      if ( getSlice()->isInterB() )
+      {
+        pcCUAboveLeft->getMvField( pcCUAboveLeft, uiAboveLeftPartIdx, REF_PIC_LIST_1, pcMvFieldNeighbours[(iCount<<1)+1] );
+      }
+      if ( mrgCandIdx == iCount )
+      {
+        return;
+      }
+      iCount ++;
+    }
+  }
+  // early termination
+  if (iCount == getSlice()->getMaxNumMergeCand())
+  {
+    return;
+  }
+
+  if ( getSlice()->getEnableTMVPFlag() )
+  {
+    //>> MTK colocated-RightBottom
+    UInt uiPartIdxRB;
+
+    deriveRightBottomIdx( uiPUIdx, uiPartIdxRB );
+
+    UInt uiAbsPartIdxTmp = g_auiZscanToRaster[uiPartIdxRB];
+    const UInt numPartInCtuWidth  = m_pcPic->getNumPartInCtuWidth();
+    const UInt numPartInCtuHeight = m_pcPic->getNumPartInCtuHeight();
+
+    TComMv cColMv;
+    Int iRefIdx;
+    Int ctuRsAddr = -1;
+
+#if REPN_FORMAT_IN_VPS
+    if (   ( ( m_pcPic->getCtu(m_ctuRsAddr)->getCUPelX() + g_auiRasterToPelX[uiAbsPartIdxTmp] + m_pcPic->getMinCUWidth () ) < m_pcSlice->getPicWidthInLumaSamples() )  // image boundary check
+        && ( ( m_pcPic->getCtu(m_ctuRsAddr)->getCUPelY() + g_auiRasterToPelY[uiAbsPartIdxTmp] + m_pcPic->getMinCUHeight() ) < m_pcSlice->getPicHeightInLumaSamples() ) )
+#else
+    if (   ( ( m_pcPic->getCtu(m_ctuRsAddr)->getCUPelX() + g_auiRasterToPelX[uiAbsPartIdxTmp] + m_pcPic->getMinCUWidth () ) < m_pcSlice->getSPS()->getPicWidthInLumaSamples () )  // image boundary check
+        && ( ( m_pcPic->getCtu(m_ctuRsAddr)->getCUPelY() + g_auiRasterToPelY[uiAbsPartIdxTmp] + m_pcPic->getMinCUHeight() ) < m_pcSlice->getSPS()->getPicHeightInLumaSamples() ) )
+#endif    
+    {
+      if ( ( uiAbsPartIdxTmp % numPartInCtuWidth < numPartInCtuWidth - 1 ) &&           // is not at the last column of CTU
+        ( uiAbsPartIdxTmp / numPartInCtuWidth < numPartInCtuHeight - 1 ) )              // is not at the last row    of CTU
+      {
+        uiAbsPartAddr = g_auiRasterToZscan[ uiAbsPartIdxTmp + numPartInCtuWidth + 1 ];
+        ctuRsAddr = getCtuRsAddr();
+      }
+      else if ( uiAbsPartIdxTmp % numPartInCtuWidth < numPartInCtuWidth - 1 )           // is not at the last column of CTU But is last row of CTU
+      {
+        uiAbsPartAddr = g_auiRasterToZscan[ (uiAbsPartIdxTmp + numPartInCtuWidth + 1) % m_pcPic->getNumPartitionsInCtu() ];
+      }
+      else if ( uiAbsPartIdxTmp / numPartInCtuWidth < numPartInCtuHeight - 1 )          // is not at the last row of CTU But is last column of CTU
+      {
+        uiAbsPartAddr = g_auiRasterToZscan[ uiAbsPartIdxTmp + 1 ];
+        ctuRsAddr = getCtuRsAddr() + 1;
+      }
+      else //is the right bottom corner of CTU
+      {
+        uiAbsPartAddr = 0;
+      }
+    }
+
+    iRefIdx = 0;
+
+    Bool bExistMV = false;
+    UInt uiPartIdxCenter;
+    Int dir = 0;
+    UInt uiArrayAddr = iCount;
+    xDeriveCenterIdx( uiPUIdx, uiPartIdxCenter );
+    bExistMV = ctuRsAddr >= 0 && xGetColMVP( REF_PIC_LIST_0, ctuRsAddr, uiAbsPartAddr, cColMv, iRefIdx );
+    if( bExistMV == false )
+    {
+      bExistMV = xGetColMVP( REF_PIC_LIST_0, getCtuRsAddr(), uiPartIdxCenter,  cColMv, iRefIdx );
+    }
+    if( bExistMV )
+    {
+      dir |= 1;
+      pcMvFieldNeighbours[ 2 * uiArrayAddr ].setMvField( cColMv, iRefIdx );
+    }
+
+    if ( getSlice()->isInterB() )
+    {
+      bExistMV = ctuRsAddr >= 0 && xGetColMVP( REF_PIC_LIST_1, ctuRsAddr, uiAbsPartAddr, cColMv, iRefIdx);
+      if( bExistMV == false )
+      {
+        bExistMV = xGetColMVP( REF_PIC_LIST_1, getCtuRsAddr(), uiPartIdxCenter, cColMv, iRefIdx );
+      }
+      if( bExistMV )
+      {
+        dir |= 2;
+        pcMvFieldNeighbours[ 2 * uiArrayAddr + 1 ].setMvField( cColMv, iRefIdx );
+      }
+    }
+
+    if (dir != 0)
+    {
+      puhInterDirNeighbours[uiArrayAddr] = dir;
+      abCandIsInter[uiArrayAddr] = true;
+
+      if ( mrgCandIdx == iCount )
+      {
+        return;
+      }
+      iCount++;
+    }
+  }
+  // early termination
+  if (iCount == getSlice()->getMaxNumMergeCand())
+  {
+    return;
+  }
+
+  UInt uiArrayAddr = iCount;
+  UInt uiCutoff = uiArrayAddr;
+
+  if ( getSlice()->isInterB() )
+  {
+    static const UInt NUM_PRIORITY_LIST=12;
+    static const UInt uiPriorityList0[NUM_PRIORITY_LIST] = {0 , 1, 0, 2, 1, 2, 0, 3, 1, 3, 2, 3};
+    static const UInt uiPriorityList1[NUM_PRIORITY_LIST] = {1 , 0, 2, 0, 2, 1, 3, 0, 3, 1, 3, 2};
+
+    for (Int idx=0; idx<uiCutoff*(uiCutoff-1) && uiArrayAddr!= getSlice()->getMaxNumMergeCand(); idx++)
+    {
+      assert(idx<NUM_PRIORITY_LIST);
+      Int i = uiPriorityList0[idx];
+      Int j = uiPriorityList1[idx];
+      if (abCandIsInter[i] && abCandIsInter[j]&& (puhInterDirNeighbours[i]&0x1)&&(puhInterDirNeighbours[j]&0x2))
+      {
+        abCandIsInter[uiArrayAddr] = true;
+        puhInterDirNeighbours[uiArrayAddr] = 3;
+
+        // get Mv from cand[i] and cand[j]
+        pcMvFieldNeighbours[uiArrayAddr << 1].setMvField(pcMvFieldNeighbours[i<<1].getMv(), pcMvFieldNeighbours[i<<1].getRefIdx());
+        pcMvFieldNeighbours[( uiArrayAddr << 1 ) + 1].setMvField(pcMvFieldNeighbours[(j<<1)+1].getMv(), pcMvFieldNeighbours[(j<<1)+1].getRefIdx());
+
+        Int iRefPOCL0 = m_pcSlice->getRefPOC( REF_PIC_LIST_0, pcMvFieldNeighbours[(uiArrayAddr<<1)].getRefIdx() );
+        Int iRefPOCL1 = m_pcSlice->getRefPOC( REF_PIC_LIST_1, pcMvFieldNeighbours[(uiArrayAddr<<1)+1].getRefIdx() );
+        if (iRefPOCL0 == iRefPOCL1 && pcMvFieldNeighbours[(uiArrayAddr<<1)].getMv() == pcMvFieldNeighbours[(uiArrayAddr<<1)+1].getMv())
+        {
+          abCandIsInter[uiArrayAddr] = false;
+        }
+        else
+        {
+          uiArrayAddr++;
+        }
+      }
+    }
+  }
+  // early termination
+  if (uiArrayAddr == getSlice()->getMaxNumMergeCand())
+  {
+    return;
+  }
+
+  Int iNumRefIdx = (getSlice()->isInterB()) ? min(m_pcSlice->getNumRefIdx(REF_PIC_LIST_0), m_pcSlice->getNumRefIdx(REF_PIC_LIST_1)) : m_pcSlice->getNumRefIdx(REF_PIC_LIST_0);
+
+  Int r = 0;
+  Int refcnt = 0;
+  while (uiArrayAddr < getSlice()->getMaxNumMergeCand())
+  {
+    abCandIsInter[uiArrayAddr] = true;
+    puhInterDirNeighbours[uiArrayAddr] = 1;
+    pcMvFieldNeighbours[uiArrayAddr << 1].setMvField( TComMv(0, 0), r);
+
+    if ( getSlice()->isInterB() )
+    {
+      puhInterDirNeighbours[uiArrayAddr] = 3;
+      pcMvFieldNeighbours[(uiArrayAddr << 1) + 1].setMvField(TComMv(0, 0), r);
+    }
+    uiArrayAddr++;
+
+    if ( refcnt == iNumRefIdx - 1 )
+    {
+      r = 0;
+    }
+    else
+    {
+      ++r;
+      ++refcnt;
+    }
+  }
+  numValidMergeCand = uiArrayAddr;
+}
+
+/** 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;
+  const UInt numPartInCtuWidth  = m_pcPic->getNumPartInCtuWidth();
+  const UInt numPartInCtuHeight = m_pcPic->getNumPartInCtuHeight();
+  Bool bAdded = false;
+
+  deriveLeftRightTopIdx( uiPartIdx, uiPartIdxLT, uiPartIdxRT );
+  deriveLeftBottomIdx( uiPartIdx, uiPartIdxLB );
+
+  TComDataCU* tmpCU = NULL;
+  UInt idx;
+  tmpCU = getPUBelowLeft(idx, uiPartIdxLB);
+  bAddedSmvp = (tmpCU != NULL) && (tmpCU->isInter(idx));
+
+  if (!bAddedSmvp)
+  {
+    tmpCU = getPULeft(idx, uiPartIdxLB);
+    bAddedSmvp = (tmpCU != NULL) && (tmpCU->isInter(idx));
+  }
+
+  // Left predictor search
+  bAdded = xAddMVPCand( pInfo, eRefPicList, iRefIdx, uiPartIdxLB, MD_BELOW_LEFT);
+  if (!bAdded)
+  {
+    bAdded = xAddMVPCand( pInfo, eRefPicList, iRefIdx, uiPartIdxLB, MD_LEFT );
+  }
+
+  if(!bAdded)
+  {
+    bAdded = xAddMVPCandOrder( pInfo, eRefPicList, iRefIdx, uiPartIdxLB, MD_BELOW_LEFT);
+    if (!bAdded)
+    {
+      xAddMVPCandOrder( pInfo, eRefPicList, iRefIdx, uiPartIdxLB, MD_LEFT );
+    }
+  }
+
+  // Above predictor search
+  bAdded = xAddMVPCand( pInfo, eRefPicList, iRefIdx, uiPartIdxRT, MD_ABOVE_RIGHT);
+
+  if (!bAdded)
+  {
+    bAdded = xAddMVPCand( pInfo, eRefPicList, iRefIdx, uiPartIdxRT, MD_ABOVE);
+  }
+
+  if(!bAdded)
+  {
+    xAddMVPCand( pInfo, eRefPicList, iRefIdx, uiPartIdxLT, MD_ABOVE_LEFT);
+  }
+
+  if(!bAddedSmvp)
+  {
+    bAdded = xAddMVPCandOrder( pInfo, eRefPicList, iRefIdx, uiPartIdxRT, MD_ABOVE_RIGHT);
+    if (!bAdded)
+    {
+      bAdded = xAddMVPCandOrder( pInfo, eRefPicList, iRefIdx, uiPartIdxRT, MD_ABOVE);
+    }
+
+    if(!bAdded)
+    {
+      xAddMVPCandOrder( pInfo, eRefPicList, iRefIdx, uiPartIdxLT, MD_ABOVE_LEFT);
+    }
+  }
+
+  if ( pInfo->iN == 2 )
+  {
+    if ( pInfo->m_acMvCand[ 0 ] == pInfo->m_acMvCand[ 1 ] )
+    {
+      pInfo->iN = 1;
+    }
+  }
+
+  if ( getSlice()->getEnableTMVPFlag() )
+  {
+    // Get Temporal Motion Predictor
+    Int iRefIdx_Col = iRefIdx;
+    TComMv cColMv;
+    UInt uiPartIdxRB;
+    UInt uiAbsPartIdx;
+    UInt uiAbsPartAddr;
+
+    deriveRightBottomIdx( uiPartIdx, uiPartIdxRB );
+    uiAbsPartAddr = m_absZIdxInCtu + uiPartAddr;
+
+    //----  co-located RightBottom Temporal Predictor (H) ---//
+    uiAbsPartIdx = g_auiZscanToRaster[uiPartIdxRB];
+    Int ctuRsAddr = -1;
+#if REPN_FORMAT_IN_VPS
+    if (  ( ( m_pcPic->getCtu(m_ctuRsAddr)->getCUPelX() + g_auiRasterToPelX[uiAbsPartIdx] + m_pcPic->getMinCUWidth () ) < m_pcSlice->getPicWidthInLumaSamples())   // image boundary check
+       && ( ( m_pcPic->getCtu(m_ctuRsAddr)->getCUPelY() + g_auiRasterToPelY[uiAbsPartIdx] + m_pcPic->getMinCUHeight() ) < m_pcSlice->getPicHeightInLumaSamples() ) )    
+#else
+    if (  ( ( m_pcPic->getCtu(m_ctuRsAddr)->getCUPelX() + g_auiRasterToPelX[uiAbsPartIdx] + m_pcPic->getMinCUWidth () ) < m_pcSlice->getSPS()->getPicWidthInLumaSamples () )  // image boundary check
+       && ( ( m_pcPic->getCtu(m_ctuRsAddr)->getCUPelY() + g_auiRasterToPelY[uiAbsPartIdx] + m_pcPic->getMinCUHeight() ) < m_pcSlice->getSPS()->getPicHeightInLumaSamples() ) )
+#endif    
+    {
+      if ( ( uiAbsPartIdx % numPartInCtuWidth < numPartInCtuWidth - 1 ) &&  // is not at the last column of CTU
+           ( uiAbsPartIdx / numPartInCtuWidth < numPartInCtuHeight - 1 ) )  // is not at the last row    of CTU
+      {
+        uiAbsPartAddr = g_auiRasterToZscan[ uiAbsPartIdx + numPartInCtuWidth + 1 ];
+        ctuRsAddr = getCtuRsAddr();
+      }
+      else if ( uiAbsPartIdx % numPartInCtuWidth < numPartInCtuWidth - 1 )  // is not at the last column of CTU But is last row of CTU
+      {
+        uiAbsPartAddr = g_auiRasterToZscan[ (uiAbsPartIdx + numPartInCtuWidth + 1) % m_pcPic->getNumPartitionsInCtu() ];
+      }
+      else if ( uiAbsPartIdx / numPartInCtuWidth < numPartInCtuHeight - 1 ) // is not at the last row of CTU But is last column of CTU
+      {
+        uiAbsPartAddr = g_auiRasterToZscan[ uiAbsPartIdx + 1 ];
+        ctuRsAddr = getCtuRsAddr() + 1;
+      }
+      else //is the right bottom corner of CTU
+      {
+        uiAbsPartAddr = 0;
+      }
+    }
+    if ( ctuRsAddr >= 0 && xGetColMVP( eRefPicList, ctuRsAddr, uiAbsPartAddr, cColMv, iRefIdx_Col ) )
+    {
+      pInfo->m_acMvCand[pInfo->iN++] = cColMv;
+    }
+    else
+    {
+      UInt uiPartIdxCenter;
+      xDeriveCenterIdx( uiPartIdx, uiPartIdxCenter );
+      if (xGetColMVP( eRefPicList, getCtuRsAddr(), uiPartIdxCenter,  cColMv, iRefIdx_Col ))
+      {
+        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;
+  Int iOffset = 8;
+#if REPN_FORMAT_IN_VPS
+  Int iHorMax = ( m_pcSlice->getPicWidthInLumaSamples() + iOffset - m_uiCUPelX - 1 ) << iMvShift;
+#else
+  Int iHorMax = ( m_pcSlice->getSPS()->getPicWidthInLumaSamples() + iOffset - m_uiCUPelX - 1 ) << iMvShift;
+#endif
+  Int iHorMin = (       -(Int)g_uiMaxCUWidth - iOffset - (Int)m_uiCUPelX + 1 ) << iMvShift;
+  
+#if REPN_FORMAT_IN_VPS
+  Int iVerMax = ( m_pcSlice->getPicHeightInLumaSamples() + iOffset - m_uiCUPelY - 1 ) << iMvShift;
+#else
+  Int iVerMax = ( m_pcSlice->getSPS()->getPicHeightInLumaSamples() + iOffset - m_uiCUPelY - 1 ) << iMvShift;
+#endif
+  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, ComponentID compID, UInt uiNumParts )
+{
+  memset( &m_puhCbf[compID][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->getNumPartitionsInCtu() >> (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 ctuRsAddr, Int uiPartUnitIdx, TComMv& rcMv, Int& riRefIdx )
+{
+  UInt uiAbsPartAddr = uiPartUnitIdx;
+
+  RefPicList  eColRefPicList;
+  Int iColPOC, iColRefPOC, iCurrPOC, iCurrRefPOC, iScale;
+  TComMv cColMv;
+
+  // use coldir.
+  TComPic *pColPic = getSlice()->getRefPic( RefPicList(getSlice()->isInterB() ? 1-getSlice()->getColFromL0Flag() : 0), getSlice()->getColRefIdx());
+  TComDataCU *pColCtu = pColPic->getCtu( ctuRsAddr );
+  if(pColCtu->getPic()==0||pColCtu->getPartitionSize(uiPartUnitIdx)==NUMBER_OF_PART_SIZES)
+  {
+    return false;
+  }
+  iCurrPOC = m_pcSlice->getPOC();
+  iColPOC = pColCtu->getSlice()->getPOC();
+
+  if (!pColCtu->isInter(uiAbsPartAddr))
+  {
+    return false;
+  }
+
+  eColRefPicList = getSlice()->getCheckLDC() ? eRefPicList : RefPicList(getSlice()->getColFromL0Flag());
+
+  Int iColRefIdx = pColCtu->getCUMvField(RefPicList(eColRefPicList))->getRefIdx(uiAbsPartAddr);
+
+  if (iColRefIdx < 0 )
+  {
+    eColRefPicList = RefPicList(1 - eColRefPicList);
+    iColRefIdx = pColCtu->getCUMvField(RefPicList(eColRefPicList))->getRefIdx(uiAbsPartAddr);
+
+    if (iColRefIdx < 0 )
+    {
+      return false;
+    }
+  }
+
+  // Scale the vector.
+  iColRefPOC = pColCtu->getSlice()->getRefPOC(eColRefPicList, iColRefIdx);
+  cColMv = pColCtu->getCUMvField(eColRefPicList)->getMv(uiAbsPartAddr);
+
+  iCurrRefPOC = m_pcSlice->getRefPic(eRefPicList, riRefIdx)->getPOC();
+
+  Bool bIsCurrRefLongTerm = m_pcSlice->getRefPic(eRefPicList, riRefIdx)->getIsLongTerm();
+  Bool bIsColRefLongTerm = pColCtu->getSlice()->getIsUsedAsLongTerm(eColRefPicList, iColRefIdx);
+
+  if ( bIsCurrRefLongTerm != bIsColRefLongTerm )
+  {
+    return false;
+  }
+
+  if ( bIsCurrRefLongTerm || bIsColRefLongTerm )
+  {
+    rcMv = cColMv;
+  }
+  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_absZIdxInCtu+uiPartAddr; // partition origin.
+  ruiPartIdxCenter = g_auiRasterToZscan[ g_auiZscanToRaster[ ruiPartIdxCenter ]
+                                        + ( iPartHeight/m_pcPic->getMinCUHeight()  )/2*m_pcPic->getNumPartInCtuWidth()
+                                        + ( iPartWidth/m_pcPic->getMinCUWidth()  )/2];
+}
+
+Void TComDataCU::compressMV()
+{
+  Int scaleFactor = 4 * AMVP_DECIMATION_FACTOR / m_unitSize;
+  if (scaleFactor > 0)
+  {
+    for(UInt i=0; i<NUM_REF_PIC_LIST_01; i++)
+    {
+      m_acCUMvField[i].compress(m_pePredMode, scaleFactor);
+    }
+  }
+}
+
+UInt TComDataCU::getCoefScanIdx(const UInt uiAbsPartIdx, const UInt uiWidth, const UInt uiHeight, const ComponentID compID) const
+{
+  //------------------------------------------------
+
+  //this mechanism is available for intra only
+
+  if (!isIntra(uiAbsPartIdx)) return SCAN_DIAG;
+
+  //------------------------------------------------
+
+  //check that MDCS can be used for this TU
+
+  const ChromaFormat format = getPic()->getChromaFormat();
+
+  const UInt maximumWidth  = MDCS_MAXIMUM_WIDTH  >> getComponentScaleX(compID, format);
+  const UInt maximumHeight = MDCS_MAXIMUM_HEIGHT >> getComponentScaleY(compID, format);
+
+  if ((uiWidth > maximumWidth) || (uiHeight > maximumHeight)) return SCAN_DIAG;
+
+  //------------------------------------------------
+
+  //otherwise, select the appropriate mode
+
+  UInt uiDirMode  = getIntraDir(toChannelType(compID), uiAbsPartIdx);
+
+  if (uiDirMode==DM_CHROMA_IDX)
+  {
+    uiDirMode = getIntraDir(CHANNEL_TYPE_LUMA, getChromasCorrespondingPULumaIdx(uiAbsPartIdx, getPic()->getChromaFormat()));
+  }
+
+  if (isChroma(compID) && (format == CHROMA_422))
+  {
+    uiDirMode = g_chroma422IntraAngleMappingTable[uiDirMode];
+  }
+
+  //------------------
+
+  if      (abs((Int)uiDirMode - VER_IDX) <= MDCS_ANGLE_LIMIT) return SCAN_HOR;
+  else if (abs((Int)uiDirMode - HOR_IDX) <= MDCS_ANGLE_LIMIT) return SCAN_VER;
+  else return SCAN_DIAG;
+}
+
+#if SVC_EXTENSION
+TComDataCU* TComDataCU::getBaseColCU( UInt refLayerIdc, UInt uiCuAbsPartIdx, UInt &uiCUAddrBase, UInt &uiAbsPartIdxBase, Bool motionMapping )
+{
+  UInt uiPelX = getCUPelX() + g_auiRasterToPelX[ g_auiZscanToRaster[uiCuAbsPartIdx] ];
+  UInt uiPelY = getCUPelY() + g_auiRasterToPelY[ g_auiZscanToRaster[uiCuAbsPartIdx] ];
+
+  return getBaseColCU( refLayerIdc, uiPelX, uiPelY, uiCUAddrBase, uiAbsPartIdxBase, motionMapping );
+}
+
+TComDataCU* TComDataCU::getBaseColCU( UInt refLayerIdc, UInt pelX, UInt pelY, UInt &uiCUAddrBase, UInt &uiAbsPartIdxBase, Bool motionMapping )
+{
+  TComPic* baseColPic = m_pcSlice->getBaseColPic(refLayerIdc);
+
+  Int iPelX = Clip3<Int>(0, m_pcPic->getPicYuvRec()->getWidth(COMPONENT_Y)  - 1, pelX);
+  Int iPelY = Clip3<Int>(0, m_pcPic->getPicYuvRec()->getHeight(COMPONENT_Y) - 1, pelY);
+
+#if REF_IDX_MFM
+  // centre of the collocated 16x16 block for motion mapping
+  if( motionMapping )
+  {
+    iPelX = pelX + 8;
+    iPelY = pelY + 8;
+  }
+#endif
+
+#if !LAYER_CTB
+  UInt uiMinUnitSize = m_pcPic->getMinCUWidth();
+#endif
+
+#if MOVE_SCALED_OFFSET_TO_PPS
+#if O0098_SCALED_REF_LAYER_ID
+  Int leftStartL = m_pcSlice->getPPS()->getScaledRefLayerWindowForLayer(baseColPic->getSlice(0)->getVPS()->getRefLayerId(getSlice()->getLayerId(), refLayerIdc)).getWindowLeftOffset();
+  Int topStartL  = m_pcSlice->getPPS()->getScaledRefLayerWindowForLayer(baseColPic->getSlice(0)->getVPS()->getRefLayerId(getSlice()->getLayerId(), refLayerIdc)).getWindowTopOffset();
+#else
+  Int leftStartL = baseColPic->getSlice(0)->getPPS()->getScaledRefLayerWindow(refLayerIdc).getWindowLeftOffset();
+  Int topStartL  = baseColPic->getSlice(0)->getPPS()->getScaledRefLayerWindow(refLayerIdc).getWindowTopOffset();
+#endif
+#else
+#if O0098_SCALED_REF_LAYER_ID
+  Int leftStartL = baseColPic->getSlice(0)->getSPS()->getScaledRefLayerWindowForLayer(baseColPic->getSlice(0)->getVPS()->getRefLayerId(getSlice()->getLayerId(), refLayerIdc)).getWindowLeftOffset();
+  Int topStartL  = baseColPic->getSlice(0)->getSPS()->getScaledRefLayerWindowForLayer(baseColPic->getSlice(0)->getVPS()->getRefLayerId(getSlice()->getLayerId(), refLayerIdc)).getWindowTopOffset();
+#else
+  Int leftStartL = baseColPic->getSlice(0)->getSPS()->getScaledRefLayerWindow(refLayerIdc).getWindowLeftOffset();
+  Int topStartL  = baseColPic->getSlice(0)->getSPS()->getScaledRefLayerWindow(refLayerIdc).getWindowTopOffset();
+#endif
+#endif
+
+#if REF_REGION_OFFSET
+  const Window &windowRL = m_pcSlice->getPPS()->getRefLayerWindowForLayer(baseColPic->getSlice(0)->getVPS()->getRefLayerId(getSlice()->getLayerId(), refLayerIdc));
+  Int iBX = (((iPelX - leftStartL)*g_posScalingFactor[refLayerIdc][0] + (1<<15)) >> 16) + windowRL.getWindowLeftOffset();
+  Int iBY = (((iPelY - topStartL )*g_posScalingFactor[refLayerIdc][1] + (1<<15)) >> 16) + windowRL.getWindowTopOffset();
+#else
+#if Q0200_CONFORMANCE_BL_SIZE
+  Int chromaFormatIdc = baseColPic->getSlice(0)->getChromaFormatIdc();
+  Int iBX = (((iPelX - leftStartL)*g_posScalingFactor[refLayerIdc][0] + (1<<15)) >> 16) + baseColPic->getConformanceWindow().getWindowLeftOffset() * TComSPS::getWinUnitX( chromaFormatIdc );
+  Int iBY = (((iPelY - topStartL )*g_posScalingFactor[refLayerIdc][1] + (1<<15)) >> 16) + baseColPic->getConformanceWindow().getWindowTopOffset() * TComSPS::getWinUnitY( chromaFormatIdc );
+#else
+  Int iBX = ((iPelX - leftStartL)*g_posScalingFactor[refLayerIdc][0] + (1<<15)) >> 16;
+  Int iBY = ((iPelY - topStartL )*g_posScalingFactor[refLayerIdc][1] + (1<<15)) >> 16;
+#endif
+#endif
+
+#if REF_IDX_MFM
+  // offset for collocated block in the motion mapping
+  if( motionMapping )
+  {
+    if( m_pcPic->equalPictureSizeAndOffsetFlag(refLayerIdc) )
+    {
+      // copy motion field from the same sample position for the case of 1x scaling ratio and same offset value between the current and reference layers
+      iBX = pelX;
+      iBY = pelY;
+    }
+    else
+    {
+      // actually, motion field compression is performed in the Void TComPic::compressMotion() function, but with (+4) the rounding may have effect on the picture boundary check.
+      iBX = ( ( iBX + 4 ) >> 4 ) << 4;
+      iBY = ( ( iBY + 4 ) >> 4 ) << 4;
+    }
+  }
+#endif
+
+  if ( iBX < 0 || iBX >= baseColPic->getPicYuvRec()->getWidth(COMPONENT_Y) || iBY < 0 || iBY >= baseColPic->getPicYuvRec()->getHeight(COMPONENT_Y) )
+  {
+    return NULL;
+  }
+
+#if LAYER_CTB
+  UInt baseMaxCUHeight = baseColPic->getPicSym()->getMaxCUHeight();
+  UInt baseMaxCUWidth  = baseColPic->getPicSym()->getMaxCUWidth();
+  UInt baseMinUnitSize = baseColPic->getMinCUWidth();
+  
+  uiCUAddrBase = ( iBY / baseMaxCUHeight ) * baseColPic->getFrameWidthInCtus() + ( iBX / baseMaxCUWidth );
+#else
+  uiCUAddrBase = (iBY/g_uiMaxCUHeight)*baseColPic->getFrameWidthInCtus() + (iBX/g_uiMaxCUWidth);
+#endif
+
+  assert(uiCUAddrBase < baseColPic->getNumberOfCtusInFrame());
+
+#if LAYER_CTB
+  UInt uiRasterAddrBase = ( iBY - (iBY/baseMaxCUHeight)*baseMaxCUHeight ) / baseMinUnitSize * baseColPic->getNumPartInCtuWidth() + ( iBX - (iBX/baseMaxCUWidth)*baseMaxCUWidth ) / baseMinUnitSize;
+  
+  uiAbsPartIdxBase = g_auiLayerRasterToZscan[baseColPic->getLayerId()][uiRasterAddrBase];
+#else
+  UInt uiRasterAddrBase = (iBY - (iBY/g_uiMaxCUHeight)*g_uiMaxCUHeight)/uiMinUnitSize*baseColPic->getNumPartInCtuWidth() + (iBX - (iBX/g_uiMaxCUWidth)*g_uiMaxCUWidth)/uiMinUnitSize;
+
+  uiAbsPartIdxBase = g_auiRasterToZscan[uiRasterAddrBase];
+#endif
+
+  return baseColPic->getCtu(uiCUAddrBase);
+}
+
+Void TComDataCU::scaleBaseMV( UInt refLayerIdc, TComMvField& rcMvFieldEnhance, TComMvField& rcMvFieldBase )
+{
+  TComMvField cMvFieldBase;
+  TComMv cMv;
+
+  cMv = rcMvFieldBase.getMv().scaleMv( g_mvScalingFactor[refLayerIdc][0], g_mvScalingFactor[refLayerIdc][1] );
+
+  rcMvFieldEnhance.setMvField( cMv, rcMvFieldBase.getRefIdx() );
+}
+
+#if FAST_INTRA_SHVC
+/** generate limited set of remaining modes
+*\param   uiAbsPartIdx
+*\param   uiIntraDirPred  pointer to the array for MPM storage
+*\returns Number of intra coding modes (nb of remaining modes + 3 MPMs)
+*/
+Int TComDataCU::reduceSetOfIntraModes( UInt uiAbsPartIdx, Int* uiIntraDirPred, Int &fullSetOfModes )
+{
+  // check BL mode
+  UInt uiCUAddrBase = 0, uiAbsPartAddrBase = 0;
+  // the right reference layerIdc should be specified, currently it is set to m_layerId-1
+  TComDataCU* pcTempCU = getBaseColCU(m_layerId - 1, uiAbsPartIdx, uiCUAddrBase, uiAbsPartAddrBase, false );
+
+  if( pcTempCU->getPredictionMode( uiAbsPartAddrBase ) != MODE_INTRA )
+  {
+    return( NUM_INTRA_MODE-1 );
+  }
+
+  // compute set of enabled modes g_reducedSetIntraModes[...]
+  Int authorizedMode[NUM_INTRA_MODE-1]={1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1};
+  Int nbModes;
+  for (nbModes=0; nbModes<3; nbModes++)  // add 3 MPMs 1st
+  {
+    g_reducedSetIntraModes[nbModes] = uiIntraDirPred[nbModes];
+    authorizedMode[ uiIntraDirPred[nbModes] ] = 0;
+  }
+
+  Int iColBaseDir = pcTempCU->getIntraDir( CHANNEL_TYPE_LUMA, uiAbsPartAddrBase );
+  if ( authorizedMode[iColBaseDir] )  //possibly add BL mode
+  {
+    g_reducedSetIntraModes[nbModes++] = iColBaseDir;
+    authorizedMode[ iColBaseDir ] = 0;
+  }
+
+  Int iRefMode = ( iColBaseDir > 1 ) ? iColBaseDir : uiIntraDirPred[0];
+  if ( iRefMode > 1 )    //add neighboring modes of refMode
+  {
+    UInt Left  = iRefMode;
+    UInt Right = iRefMode;
+    while ( nbModes < NB_REMAIN_MODES+3 )
+    {
+      Left = ((Left + 29) % 32) + 2;
+      Right = ((Right - 1 ) % 32) + 2;
+      if ( authorizedMode[Left] )   g_reducedSetIntraModes[nbModes++] = Left;
+      if ( authorizedMode[Right] )  g_reducedSetIntraModes[nbModes++] = Right;
+    }
+  }
+  else      //add pre-defined modes
+  {
+    Int  idx = 0;
+    while ( nbModes < NB_REMAIN_MODES+3 )
+    {
+      UInt mode = g_predefSetIntraModes[idx++];
+      if ( authorizedMode[mode] )   g_reducedSetIntraModes[nbModes++] = mode;
+    }
+  }
+
+  fullSetOfModes = 0;
+  return ( nbModes );
+}
+#endif
+
+#if REF_IDX_ME_ZEROMV
+Bool TComDataCU::xCheckZeroMVILRMerge(UChar uhInterDir, TComMvField& cMvFieldL0, TComMvField& cMvFieldL1)
+{
+  Bool checkZeroMVILR = true;
+
+  if(uhInterDir&0x1)  //list0
+  {
+    Int refIdxL0 = cMvFieldL0.getRefIdx();
+    TComPic* refPic = m_pcSlice->getRefPic(REF_PIC_LIST_0, refIdxL0);
+
+    if(refPic->isILR(m_layerId))
+    {
+      checkZeroMVILR &= (cMvFieldL0.getHor() == 0 && cMvFieldL0.getVer() == 0);
+
+      // It is a requirement of bitstream conformance that when the reference picture represented by the variable refIdxLX is an inter-layer reference picture, 
+      // VpsInterLayerSamplePredictionEnabled[ LayerIdxInVps[ currLayerId ] ][ LayerIdxInVps[ rLId ] ] shall be equal to 1, where rLId is set equal to nuh_layer_id of the inter-layer picture
+      checkZeroMVILR &= m_pcSlice->getVPS()->isSamplePredictionType( getLayerIdx(), refPic->getLayerIdx() );
+    }
+  }
+  if(uhInterDir&0x2)  //list1
+  {
+    Int refIdxL1  = cMvFieldL1.getRefIdx();
+    TComPic* refPic = m_pcSlice->getRefPic(REF_PIC_LIST_1, refIdxL1);
+
+    if(refPic->isILR(m_layerId))
+    {
+      checkZeroMVILR &= (cMvFieldL1.getHor() == 0 && cMvFieldL1.getVer() == 0);
+
+      // It is a requirement of bitstream conformance that when the reference picture represented by the variable refIdxLX is an inter-layer reference picture, 
+      // VpsInterLayerSamplePredictionEnabled[ LayerIdxInVps[ currLayerId ] ][ LayerIdxInVps[ rLId ] ] shall be equal to 1, where rLId is set equal to nuh_layer_id of the inter-layer picture
+      checkZeroMVILR &= m_pcSlice->getVPS()->isSamplePredictionType( getLayerIdx(), refPic->getLayerIdx() );
+    }
+  }
+
+  return checkZeroMVILR;
+}
+
+Bool TComDataCU::xCheckZeroMVILRMvdL1Zero(Int iRefList, Int iRefIdx, Int MvpIdx)
+{
+  RefPicList eRefPicList = iRefList > 0? REF_PIC_LIST_1: REF_PIC_LIST_0;
+  assert(eRefPicList == REF_PIC_LIST_1);
+
+  Bool checkZeroMVILR = true;
+
+  if(getSlice()->getRefPic(eRefPicList, iRefIdx)->isILR(m_layerId))
+  {
+    AMVPInfo* pcAMVPInfo = getCUMvField(eRefPicList)->getAMVPInfo();
+    TComMv    cMv        = pcAMVPInfo->m_acMvCand[MvpIdx];
+    checkZeroMVILR &= (cMv.getHor() == 0 && cMv.getVer() == 0);
+  }
+
+  return checkZeroMVILR;
+}
+#endif
+
+#if N0383_IL_CONSTRAINED_TILE_SETS_SEI
+Bool TComDataCU::isInterLayerReference(UChar uhInterDir, TComMvField& cMvFieldL0, TComMvField& cMvFieldL1)
+{
+  Bool checkILR = false;
+
+  if(uhInterDir&0x1)  //list0
+  {
+    Int refIdxL0 = cMvFieldL0.getRefIdx();
+    checkILR = getSlice()->getRefPic(REF_PIC_LIST_0, refIdxL0)->isILR(m_layerId);
+  }
+  if(uhInterDir&0x2)  //list1
+  {
+    Int refIdxL1  = cMvFieldL1.getRefIdx();
+    checkILR = checkILR || getSlice()->getRefPic(REF_PIC_LIST_1, refIdxL1)->isILR(m_layerId);
+  }
+
+  return checkILR;
+}
+#endif
+
+#endif //SVC_EXTENSION
+//! \}
Index: /tags/SHM-9.0/source/Lib/TLibCommon/TComDataCU.h
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibCommon/TComDataCU.h	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibCommon/TComDataCU.h	(revision 1088)
@@ -0,0 +1,592 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TComDataCU.h
+    \brief    CU data structure (header)
+    \todo     not all entities are documented
+*/
+
+#ifndef __TCOMDATACU__
+#define __TCOMDATACU__
+
+#include <assert.h>
+
+// Include files
+#include "CommonDef.h"
+#include "TComMotionInfo.h"
+#include "TComSlice.h"
+#include "TComRdCost.h"
+#include "TComPattern.h"
+
+#include <algorithm>
+#include <vector>
+
+//! \ingroup TLibCommon
+//! \{
+
+class TComTU; // forward declaration
+
+static const UInt NUM_MOST_PROBABLE_MODES=3;
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// CU data structure class
+class TComDataCU
+{
+private:
+
+  // -------------------------------------------------------------------------------------------------------------------
+  // class pointers
+  // -------------------------------------------------------------------------------------------------------------------
+
+  TComPic*      m_pcPic;              ///< picture class pointer
+  TComSlice*    m_pcSlice;            ///< slice header pointer
+
+  // -------------------------------------------------------------------------------------------------------------------
+  // CU description
+  // -------------------------------------------------------------------------------------------------------------------
+
+  UInt          m_ctuRsAddr;          ///< CTU (also known as LCU) address in a slice (Raster-scan address, as opposed to tile-scan/encoding order).
+  UInt          m_absZIdxInCtu;       ///< absolute address in a CTU. 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"
+  
+#if SVC_EXTENSION
+  UInt          m_layerId;          ///< layer id
+#endif
+
+  // -------------------------------------------------------------------------------------------------------------------
+  // CU data
+  // -------------------------------------------------------------------------------------------------------------------
+
+  Bool*          m_skipFlag;           ///< array of skip flags
+  Char*          m_pePartSize;         ///< array of partition sizes
+  Char*          m_pePredMode;         ///< array of prediction modes
+  Char*          m_crossComponentPredictionAlpha[MAX_NUM_COMPONENT]; ///< array of cross-component prediction alpha values
+  Bool*          m_CUTransquantBypass;   ///< array of cu_transquant_bypass flags
+  Char*          m_phQP;               ///< array of QP values
+  UChar*         m_ChromaQpAdj;        ///< array of chroma QP adjustments (indexed)
+  UInt           m_codedChromaQpAdj;
+  UChar*         m_puhTrIdx;           ///< array of transform indices
+  UChar*         m_puhTransformSkip[MAX_NUM_COMPONENT];///< array of transform skipping flags
+  UChar*         m_puhCbf[MAX_NUM_COMPONENT];          ///< array of coded block flags (CBF)
+  TComCUMvField  m_acCUMvField[NUM_REF_PIC_LIST_01];    ///< array of motion vectors.
+  TCoeff*        m_pcTrCoeff[MAX_NUM_COMPONENT];       ///< array of transform coefficient buffers (0->Y, 1->Cb, 2->Cr)
+#if ADAPTIVE_QP_SELECTION
+  TCoeff*        m_pcArlCoeff[MAX_NUM_COMPONENT];  // ARL coefficient buffer (0->Y, 1->Cb, 2->Cr)
+  static TCoeff* m_pcGlbArlCoeff[MAX_NUM_COMPONENT]; // global ARL buffer
+  Bool           m_ArlCoeffIsAliasedAllocation;  ///< ARL coefficient buffer is an alias of the global buffer and must not be free()'d
+#endif
+
+  Pel*           m_pcIPCMSample[MAX_NUM_COMPONENT];    ///< PCM sample buffer (0->Y, 1->Cb, 2->Cr)
+
+  // -------------------------------------------------------------------------------------------------------------------
+  // neighbour access variables
+  // -------------------------------------------------------------------------------------------------------------------
+
+  TComDataCU*   m_pCtuAboveLeft;      ///< pointer of above-left CTU.
+  TComDataCU*   m_pCtuAboveRight;     ///< pointer of above-right CTU.
+  TComDataCU*   m_pCtuAbove;          ///< pointer of above CTU.
+  TComDataCU*   m_pCtuLeft;           ///< pointer of left CTU
+  TComDataCU*   m_apcCUColocated[NUM_REF_PIC_LIST_01];  ///< pointer of temporally colocated CU's for both directions
+  TComMvField   m_cMvFieldA;          ///< motion vector of position A
+  TComMvField   m_cMvFieldB;          ///< motion vector of position B
+  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_puhIntraDir[MAX_NUM_CHANNEL_TYPE]; // 0-> Luma, 1-> Chroma
+  UChar*        m_puhInterDir;        ///< array of inter directions
+  Char*         m_apiMVPIdx[NUM_REF_PIC_LIST_01];       ///< array of motion vector predictor candidates
+  Char*         m_apiMVPNum[NUM_REF_PIC_LIST_01];       ///< array of number of possible motion vectors predictors
+  Bool*         m_pbIPCMFlag;         ///< array of intra_pcm flags
+
+  // -------------------------------------------------------------------------------------------------------------------
+  // misc. variables
+  // -------------------------------------------------------------------------------------------------------------------
+
+  Bool          m_bDecSubCu;          ///< indicates decoder-mode
+  Double        m_dTotalCost;         ///< sum of partition RD costs
+  Distortion    m_uiTotalDistortion;  ///< sum of partition distortion
+  UInt          m_uiTotalBits;        ///< sum of partition bits
+  UInt          m_uiTotalBins;        ///< sum of partition bins
+  Char          m_codedQP;
+  UChar*        m_explicitRdpcmMode[MAX_NUM_COMPONENT]; ///< Stores the explicit RDPCM mode for all TUs belonging to this CU
+
+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 );
+
+  Void          deriveRightBottomIdx        ( UInt uiPartIdx, UInt& ruiPartIdxRB );
+  Bool          xGetColMVP( RefPicList eRefPicList, Int ctuRsAddr, Int uiPartUnitIdx, TComMv& rcMv, Int& riRefIdx );
+
+  /// compute required bits to encode MVD (used in AMVP)
+  UInt          xGetMvdBits           ( TComMv cMvd );
+  UInt          xGetComponentBits     ( Int iVal );
+
+  /// compute scaling factor from POC difference
+  Int           xGetDistScaleFactor   ( Int iCurrPOC, Int iCurrRefPOC, Int iColPOC, Int iColRefPOC );
+
+  Void xDeriveCenterIdx( UInt uiPartIdx, UInt& ruiPartIdxCenter );
+
+public:
+  TComDataCU();
+  virtual ~TComDataCU();
+
+  // -------------------------------------------------------------------------------------------------------------------
+  // create / destroy / initialize / copy
+  // -------------------------------------------------------------------------------------------------------------------
+
+  Void          create                ( ChromaFormat chromaFormatIDC, UInt uiNumPartition, UInt uiWidth, UInt uiHeight, Bool bDecSubCu, Int unitSize
+#if ADAPTIVE_QP_SELECTION
+    , Bool bGlobalRMARLBuffer = false
+#endif
+    );
+  Void          destroy               ();
+
+  Void          initCtu               ( TComPic* pcPic, UInt ctuRsAddr );
+  Void          initEstData           ( const UInt uiDepth, const Int qp, const Bool bTransquantBypass );
+  Void          initSubCU             ( TComDataCU* pcCU, UInt uiPartUnitIdx, UInt uiDepth, Int qp );
+  Void          setOutsideCUPart      ( UInt uiAbsPartIdx, UInt uiDepth );
+
+  Void          copySubCU             ( TComDataCU* pcCU, UInt uiPartUnitIdx, UInt uiDepth );
+  Void          copyInterPredInfoFrom ( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefPicList );
+  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;           }
+  const TComPic*  getPic              () const                  { return m_pcPic;           }
+  TComSlice*       getSlice           ()                        { return m_pcSlice;         }
+  const TComSlice* getSlice           () const                  { return m_pcSlice;         }
+  UInt&         getCtuRsAddr          ()                        { return m_ctuRsAddr;       }
+  UInt          getCtuRsAddr          () const                  { return m_ctuRsAddr;       }
+  UInt          getZorderIdxInCtu     () const                  { return m_absZIdxInCtu;    }
+  UInt          getCUPelX             () const                  { return m_uiCUPelX;        }
+  UInt          getCUPelY             () const                  { return m_uiCUPelY;        }
+
+  UChar*        getDepth              ()                        { return m_puhDepth;        }
+  UChar         getDepth              ( UInt uiIdx ) const      { return m_puhDepth[uiIdx]; }
+  Void          setDepth              ( UInt uiIdx, UChar  uh ) { m_puhDepth[uiIdx] = uh;   }
+
+  Void          setDepthSubParts      ( UInt uiDepth, UInt uiAbsPartIdx );
+
+  // -------------------------------------------------------------------------------------------------------------------
+  // 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] ); }
+  Void          setPredictionMode     ( UInt uiIdx, PredMode uh){ m_pePredMode[uiIdx] = uh;   }
+  Void          setPredModeSubParts   ( PredMode eMode, UInt uiAbsPartIdx, UInt uiDepth );
+
+  Char*         getCrossComponentPredictionAlpha( ComponentID compID )             { return m_crossComponentPredictionAlpha[compID];         }
+  Char          getCrossComponentPredictionAlpha( UInt uiIdx, ComponentID compID ) { return m_crossComponentPredictionAlpha[compID][uiIdx];  }
+
+  Bool*         getCUTransquantBypass ()                        { return m_CUTransquantBypass;        }
+  Bool          getCUTransquantBypass( UInt uiIdx )             { return m_CUTransquantBypass[uiIdx]; }
+
+  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 ) const      { 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, UInt absPartIdx, UInt depth, Bool &foundNonZeroCbf );
+  Void          setCodedQP            ( Char qp )               { m_codedQP = qp;             }
+  Char          getCodedQP            ()                        { return m_codedQP;           }
+
+  UChar*        getChromaQpAdj        ()                        { return m_ChromaQpAdj;       }
+  UChar         getChromaQpAdj        (Int idx)           const { return m_ChromaQpAdj[idx];  }
+  Void          setChromaQpAdj        (Int idx, UChar val)      { m_ChromaQpAdj[idx] = val;   }
+  Void          setChromaQpAdjSubParts( UChar val, Int absPartIdx, Int depth );
+  Void          setCodedChromaQpAdj   ( Char qp )               { m_codedChromaQpAdj = qp;    }
+  Char          getCodedChromaQpAdj   ()                        { return m_codedChromaQpAdj;  }
+
+  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      ( ComponentID compID )    { return m_puhTransformSkip[compID];}
+  UChar         getTransformSkip      ( UInt uiIdx, ComponentID compID)    { return m_puhTransformSkip[compID][uiIdx];}
+  Void          setTransformSkipSubParts  ( UInt useTransformSkip, ComponentID compID, UInt uiAbsPartIdx, UInt uiDepth);
+  Void          setTransformSkipSubParts  ( const UInt useTransformSkip[MAX_NUM_COMPONENT], UInt uiAbsPartIdx, UInt uiDepth );
+
+  UChar*        getExplicitRdpcmMode      ( ComponentID component ) { return m_explicitRdpcmMode[component]; }
+  UChar         getExplicitRdpcmMode      ( ComponentID component, UInt partIdx ) {return m_explicitRdpcmMode[component][partIdx]; }
+  Void          setExplicitRdpcmModePartRange ( UInt rdpcmMode, ComponentID compID, UInt uiAbsPartIdx, UInt uiCoveredPartIdxes );
+
+  Bool          isRDPCMEnabled         ( UInt uiAbsPartIdx )  { return getSlice()->getSPS()->getUseResidualDPCM(isIntra(uiAbsPartIdx) ? RDPCM_SIGNAL_IMPLICIT : RDPCM_SIGNAL_EXPLICIT); }
+
+  Void          setCrossComponentPredictionAlphaPartRange    ( Char alphaValue, ComponentID compID, UInt uiAbsPartIdx, UInt uiCoveredPartIdxes );
+  Void          setTransformSkipPartRange                    ( UInt useTransformSkip, ComponentID compID, UInt uiAbsPartIdx, UInt uiCoveredPartIdxes );
+
+  UInt          getQuadtreeTULog2MinSizeInCU( UInt uiIdx );
+
+  TComCUMvField* getCUMvField         ( RefPicList e )          { return  &m_acCUMvField[e];  }
+
+  TCoeff*       getCoeff              (ComponentID component)   { return m_pcTrCoeff[component]; }
+
+#if ADAPTIVE_QP_SELECTION
+  TCoeff*       getArlCoeff           ( ComponentID component ) { return m_pcArlCoeff[component]; }
+#endif
+  Pel*          getPCMSample          ( ComponentID component ) { return m_pcIPCMSample[component]; }
+
+  UChar         getCbf    ( UInt uiIdx, ComponentID eType )                  { return m_puhCbf[eType][uiIdx];  }
+  UChar*        getCbf    ( ComponentID eType )                              { return m_puhCbf[eType];         }
+  UChar         getCbf    ( UInt uiIdx, ComponentID eType, UInt uiTrDepth )  { return ( ( getCbf( uiIdx, eType ) >> uiTrDepth ) & 0x1 ); }
+  Void          setCbf    ( UInt uiIdx, ComponentID eType, UChar uh )        { m_puhCbf[eType][uiIdx] = uh;    }
+  Void          clearCbf  ( UInt uiIdx, ComponentID eType, UInt uiNumParts );
+  UChar         getQtRootCbf          ( UInt uiIdx );
+
+  Void          setCbfSubParts        ( const UInt uiCbf[MAX_NUM_COMPONENT],  UInt uiAbsPartIdx, UInt uiDepth           );
+  Void          setCbfSubParts        ( UInt uiCbf, ComponentID compID, UInt uiAbsPartIdx, UInt uiDepth                    );
+  Void          setCbfSubParts        ( UInt uiCbf, ComponentID compID, UInt uiAbsPartIdx, UInt uiPartIdx, UInt uiDepth    );
+
+  Void          setCbfPartRange       ( UInt uiCbf, ComponentID compID, UInt uiAbsPartIdx, UInt uiCoveredPartIdxes      );
+  Void          bitwiseOrCbfPartRange ( UInt uiCbf, ComponentID compID, UInt uiAbsPartIdx, UInt uiCoveredPartIdxes      );
+
+  // -------------------------------------------------------------------------------------------------------------------
+  // 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* pbBaseCtu, UInt uiCUAddr, UInt uiCUDepth, UInt uiPUIdx );
+
+#if AMP_MRG
+  Void          setMergeAMP( Bool b )      { m_bIsMergeAMP = b; }
+  Bool          getMergeAMP( )             { return m_bIsMergeAMP; }
+#endif
+
+  UChar*        getIntraDir         ( const ChannelType channelType )                   const { return m_puhIntraDir[channelType];         }
+  UChar         getIntraDir         ( const ChannelType channelType, const UInt uiIdx ) const { return m_puhIntraDir[channelType][uiIdx];  }
+
+  Void          setIntraDirSubParts ( const ChannelType channelType,
+                                      const UInt uiDir,
+                                      const UInt uiAbsPartIdx,
+                                      const 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);
+
+  // -------------------------------------------------------------------------------------------------------------------
+  // member functions for accessing partition information
+  // -------------------------------------------------------------------------------------------------------------------
+
+  Void          getPartIndexAndSize   ( UInt uiPartIdx, UInt& ruiPartAddr, Int& riWidth, Int& riHeight );
+  UChar         getNumPartitions      ( const UInt uiAbsPartIdx = 0 );
+  Bool          isFirstAbsZorderIdxInDepth (UInt uiAbsPartIdx, UInt uiDepth);
+
+  // -------------------------------------------------------------------------------------------------------------------
+  // 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*   getCtuLeft                  () { return m_pCtuLeft;       }
+  TComDataCU*   getCtuAbove                 () { return m_pCtuAbove;      }
+  TComDataCU*   getCtuAboveLeft             () { return m_pCtuAboveLeft;  }
+  TComDataCU*   getCtuAboveRight            () { return m_pCtuAboveRight; }
+  TComDataCU*   getCUColocated              ( RefPicList eRefPicList ) { return m_apcCUColocated[eRefPicList]; }
+  Bool          CUIsFromSameSlice           ( const TComDataCU *pCU /* Can be NULL */) const { return ( pCU!=NULL && pCU->getSlice()->getSliceCurStartCtuTsAddr() == getSlice()->getSliceCurStartCtuTsAddr() ); }
+  Bool          CUIsFromSameTile            ( const TComDataCU *pCU /* Can be NULL */) const;
+  Bool          CUIsFromSameSliceAndTile    ( const TComDataCU *pCU /* Can be NULL */) const;
+  Bool          CUIsFromSameSliceTileAndWavefrontRow( const TComDataCU *pCU /* Can be NULL */) const;
+  Bool          isLastSubCUOfCtu(const UInt absPartIdx);
+
+
+  TComDataCU*   getPULeft                   ( UInt&  uiLPartUnitIdx,
+                                              UInt uiCurrPartUnitIdx,
+                                              Bool bEnforceSliceRestriction=true,
+                                              Bool bEnforceTileRestriction=true );
+  TComDataCU*   getPUAbove                  ( UInt&  uiAPartUnitIdx,
+                                              UInt uiCurrPartUnitIdx,
+                                              Bool bEnforceSliceRestriction=true,
+                                              Bool planarAtCTUBoundary = 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 uiCurrAbsIdxInCtu );
+  TComDataCU*   getQpMinCuAbove             ( UInt&  uiAPartUnitIdx , UInt uiCurrAbsIdxInCtu );
+  Char          getRefQP                    ( UInt   uiCurrAbsIdxInCtu                       );
+
+  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 ); // NOTE: Unused function.
+
+  Bool          hasEqualMotion              ( UInt uiAbsPartIdx, TComDataCU* pcCandCU, UInt uiCandAbsPartIdx );
+  Void          getInterMergeCandidates       ( UInt uiAbsPartIdx, UInt uiPUIdx, TComMvField* pcMFieldNeighbours, UChar* puhInterDirNeighbours, Int& numValidMergeCand, Int mrgCandIdx = -1 );
+
+  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 )  const { return m_pePredMode[ uiPartIdx ] == MODE_INTRA;                                              }
+  Bool          isInter            ( UInt uiPartIdx )  const { return m_pePredMode[ uiPartIdx ] == MODE_INTER;                                              }
+  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           getIntraDirPredictor            ( UInt uiAbsPartIdx, Int uiIntraDirPred[NUM_MOST_PROBABLE_MODES], const ComponentID compID, Int* piMode = NULL );
+
+  // -------------------------------------------------------------------------------------------------------------------
+  // member functions for SBAC context
+  // -------------------------------------------------------------------------------------------------------------------
+
+  UInt          getCtxSplitFlag                 ( UInt   uiAbsPartIdx, UInt uiDepth                   );
+  UInt          getCtxQtCbf                     ( TComTU &rTu, const ChannelType chType );
+
+  UInt          getCtxSkipFlag                  ( UInt   uiAbsPartIdx                                 );
+  UInt          getCtxInterDir                  ( UInt   uiAbsPartIdx                                 );
+
+  UInt&         getTotalBins            ()                            { return m_uiTotalBins;                              }
+  // -------------------------------------------------------------------------------------------------------------------
+  // member functions for RD cost storage
+  // -------------------------------------------------------------------------------------------------------------------
+
+  Double&       getTotalCost()                  { return m_dTotalCost;        }
+  Distortion&   getTotalDistortion()            { return m_uiTotalDistortion; }
+  UInt&         getTotalBits()                  { return m_uiTotalBits;       }
+  UInt&         getTotalNumPart()               { return m_uiNumPartition;    }
+
+  UInt          getCoefScanIdx(const UInt uiAbsPartIdx, const UInt uiWidth, const UInt uiHeight, const ComponentID compID) const ;
+ 
+#if SVC_EXTENSION
+  Void          setLayerId (UInt layerId) { m_layerId = layerId; }
+  UInt          getLayerId ()               { return m_layerId; }
+  UInt          getLayerIdx ()              { return m_pcSlice->getVPS()->getLayerIdxInVps(m_layerId); }
+#if N0383_IL_CONSTRAINED_TILE_SETS_SEI
+  Bool          isInterLayerReference(UChar uhInterDir, TComMvField& cMvFieldL0, TComMvField& cMvFieldL1);
+#endif
+#if FAST_INTRA_SHVC
+  Int           reduceSetOfIntraModes              (  UInt   uiAbsPartIdx, Int* uiIntraDirPred, Int &fullSetOfModes );
+#endif
+#if REF_IDX_ME_ZEROMV
+  Bool          xCheckZeroMVILRMerge(UChar uhInterDir, TComMvField& cMvFieldL0, TComMvField& cMvFieldL1);
+  Bool          xCheckZeroMVILRMvdL1Zero(Int iRefList, Int iRefIdx, Int MvpIdx);
+#endif
+  TComDataCU*   getBaseColCU( UInt refLayerIdc, UInt uiCuAbsPartIdx, UInt &uiCUAddrBase, UInt &uiAbsPartIdxBase, Bool motionMapping = false );
+  TComDataCU*   getBaseColCU( UInt refLayerIdc, UInt pelX, UInt pelY, UInt &uiCUAddrBase, UInt &uiAbsPartIdxBase, Bool motionMapping = false );
+  Void          scaleBaseMV( UInt refLayerIdc, TComMvField& rcMvFieldEnhance, TComMvField& rcMvFieldBase );
+#endif
+};
+
+namespace RasterAddress
+{
+  /** Check whether 2 addresses point to the same column
+   * \param addrA          First address in raster scan order
+   * \param addrB          Second address in raters scan order
+   * \param numUnitsPerRow Number of units in a row
+   * \return Result of test
+   */
+  static inline Bool isEqualCol( Int addrA, Int addrB, Int numUnitsPerRow )
+  {
+    // addrA % numUnitsPerRow == addrB % numUnitsPerRow
+    return (( addrA ^ addrB ) &  ( numUnitsPerRow - 1 ) ) == 0;
+  }
+
+  /** Check whether 2 addresses point to the same row
+   * \param addrA          First address in raster scan order
+   * \param addrB          Second address in raters scan order
+   * \param numUnitsPerRow Number of units in a row
+   * \return Result of test
+   */
+  static inline Bool isEqualRow( Int addrA, Int addrB, Int numUnitsPerRow )
+  {
+    // addrA / numUnitsPerRow == addrB / numUnitsPerRow
+    return (( addrA ^ addrB ) &~ ( numUnitsPerRow - 1 ) ) == 0;
+  }
+
+  /** Check whether 2 addresses point to the same row or column
+   * \param addrA          First address in raster scan order
+   * \param addrB          Second address in raters scan order
+   * \param numUnitsPerRow Number of units in a row
+   * \return Result of test
+   */
+  static inline Bool isEqualRowOrCol( Int addrA, Int addrB, Int numUnitsPerRow )
+  {
+    return isEqualCol( addrA, addrB, numUnitsPerRow ) | isEqualRow( addrA, addrB, numUnitsPerRow );
+  }
+
+  /** Check whether one address points to the first column
+   * \param addr           Address in raster scan order
+   * \param numUnitsPerRow Number of units in a row
+   * \return Result of test
+   */
+  static inline Bool isZeroCol( Int addr, Int numUnitsPerRow )
+  {
+    // addr % numUnitsPerRow == 0
+    return ( addr & ( numUnitsPerRow - 1 ) ) == 0;
+  }
+
+  /** Check whether one address points to the first row
+   * \param addr           Address in raster scan order
+   * \param numUnitsPerRow Number of units in a row
+   * \return Result of test
+   */
+  static inline Bool isZeroRow( Int addr, Int numUnitsPerRow )
+  {
+    // addr / numUnitsPerRow == 0
+    return ( addr &~ ( numUnitsPerRow - 1 ) ) == 0;
+  }
+
+  /** Check whether one address points to a column whose index is smaller than a given value
+   * \param addr           Address in raster scan order
+   * \param val            Given column index value
+   * \param numUnitsPerRow Number of units in a row
+   * \return Result of test
+   */
+  static inline Bool lessThanCol( Int addr, Int val, Int numUnitsPerRow )
+  {
+    // addr % numUnitsPerRow < val
+    return ( addr & ( numUnitsPerRow - 1 ) ) < val;
+  }
+
+  /** Check whether one address points to a row whose index is smaller than a given value
+   * \param addr           Address in raster scan order
+   * \param val            Given row index value
+   * \param numUnitsPerRow Number of units in a row
+   * \return Result of test
+   */
+  static inline Bool lessThanRow( Int addr, Int val, Int numUnitsPerRow )
+  {
+    // addr / numUnitsPerRow < val
+    return addr < val * numUnitsPerRow;
+  }
+}
+
+//! \}
+
+#endif
Index: /tags/SHM-9.0/source/Lib/TLibCommon/TComInterpolationFilter.cpp
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibCommon/TComInterpolationFilter.cpp	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibCommon/TComInterpolationFilter.cpp	(revision 1088)
@@ -0,0 +1,383 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ * \file
+ * \brief Implementation of TComInterpolationFilter class
+ */
+
+// ====================================================================================================================
+// Includes
+// ====================================================================================================================
+
+#include "TComRom.h"
+#include "TComInterpolationFilter.h"
+#include <assert.h>
+
+#include "TComChromaFormat.h"
+
+
+//! \ingroup TLibCommon
+//! \{
+
+// ====================================================================================================================
+// Tables
+// ====================================================================================================================
+
+const TFilterCoeff TComInterpolationFilter::m_lumaFilter[LUMA_INTERPOLATION_FILTER_SUB_SAMPLE_POSITIONS][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 TFilterCoeff TComInterpolationFilter::m_chromaFilter[CHROMA_INTERPOLATION_FILTER_SUB_SAMPLE_POSITIONS][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 }
+};
+
+// ====================================================================================================================
+// 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, Pel *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 )
+  {
+    const Int shift = std::max<Int>(2, (IF_INTERNAL_PREC - bitDepth));
+
+    for (row = 0; row < height; row++)
+    {
+      for (col = 0; col < width; col++)
+      {
+        Pel val = leftShift_round(src[col], shift);
+        dst[col] = val - (Pel)IF_INTERNAL_OFFS;
+      }
+
+      src += srcStride;
+      dst += dstStride;
+    }
+  }
+  else
+  {
+    const Int shift = std::max<Int>(2, (IF_INTERNAL_PREC - bitDepth));
+
+    Pel maxVal = (1 << bitDepth) - 1;
+    Pel minVal = 0;
+    for (row = 0; row < height; row++)
+    {
+      for (col = 0; col < width; col++)
+      {
+        Pel val = src[ col ];
+        val = rightShift_round((val + IF_INTERNAL_OFFS), 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, Pel const *src, Int srcStride, Pel *dst, Int dstStride, Int width, Int height, TFilterCoeff const *coeff)
+{
+  Int row, col;
+
+  Pel 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;
+  Pel maxVal;
+  Int headRoom = std::max<Int>(2, (IF_INTERNAL_PREC - bitDepth));
+  Int shift    = IF_FILTER_PREC;
+  // with the current settings (IF_INTERNAL_PREC = 14 and IF_FILTER_PREC = 6), though headroom can be
+  // negative for bit depths greater than 14, shift will remain non-negative for bit depths of 8->20
+  assert(shift >= 0);
+
+  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];
+      }
+
+      Pel 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, Pel *dst, Int dstStride, Int width, Int height, Bool isLast, TFilterCoeff 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  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, Pel *dst, Int dstStride, Int width, Int height, Bool isFirst, Bool isLast, TFilterCoeff 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/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::filterHor(const ComponentID compID, Pel *src, Int srcStride, Pel *dst, Int dstStride, Int width, Int height, Int frac, Bool isLast, const ChromaFormat fmt )
+{
+  if ( frac == 0 )
+  {
+    filterCopy(g_bitDepth[toChannelType(compID)], src, srcStride, dst, dstStride, width, height, true, isLast );
+  }
+  else if (isLuma(compID))
+  {
+    assert(frac >= 0 && frac < LUMA_INTERPOLATION_FILTER_SUB_SAMPLE_POSITIONS);
+    filterHor<NTAPS_LUMA>(g_bitDepth[toChannelType(compID)], src, srcStride, dst, dstStride, width, height, isLast, m_lumaFilter[frac]);
+  }
+  else
+  {
+    const UInt csx = getComponentScaleX(compID, fmt);
+    assert(frac >=0 && csx<2 && (frac<<(1-csx)) < CHROMA_INTERPOLATION_FILTER_SUB_SAMPLE_POSITIONS);
+    filterHor<NTAPS_CHROMA>(g_bitDepth[toChannelType(compID)], src, srcStride, dst, dstStride, width, height, isLast, m_chromaFilter[frac<<(1-csx)]);
+  }
+}
+
+
+/**
+ * \brief Filter a block of Luma/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::filterVer(const ComponentID compID, Pel *src, Int srcStride, Pel *dst, Int dstStride, Int width, Int height, Int frac, Bool isFirst, Bool isLast, const ChromaFormat fmt )
+{
+  if ( frac == 0 )
+  {
+    filterCopy(g_bitDepth[toChannelType(compID)], src, srcStride, dst, dstStride, width, height, isFirst, isLast );
+  }
+  else if (isLuma(compID))
+  {
+    assert(frac >= 0 && frac < LUMA_INTERPOLATION_FILTER_SUB_SAMPLE_POSITIONS);
+    filterVer<NTAPS_LUMA>(g_bitDepth[toChannelType(compID)], src, srcStride, dst, dstStride, width, height, isFirst, isLast, m_lumaFilter[frac]);
+  }
+  else
+  {
+    const UInt csy = getComponentScaleY(compID, fmt);
+    assert(frac >=0 && csy<2 && (frac<<(1-csy)) < CHROMA_INTERPOLATION_FILTER_SUB_SAMPLE_POSITIONS);
+    filterVer<NTAPS_CHROMA>(g_bitDepth[toChannelType(compID)], src, srcStride, dst, dstStride, width, height, isFirst, isLast, m_chromaFilter[frac<<(1-csy)]);
+  }
+}
+
+//! \}
Index: /tags/SHM-9.0/source/Lib/TLibCommon/TComInterpolationFilter.h
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibCommon/TComInterpolationFilter.h	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibCommon/TComInterpolationFilter.h	(revision 1088)
@@ -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-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ * \file
+ * \brief Declaration of TComInterpolationFilter class
+ */
+
+#ifndef __TCOMINTERPOLATIONFILTER__
+#define __TCOMINTERPOLATIONFILTER__
+
+#include "TypeDef.h"
+
+//! \ingroup TLibCommon
+//! \{
+
+#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 TFilterCoeff m_lumaFilter[LUMA_INTERPOLATION_FILTER_SUB_SAMPLE_POSITIONS][NTAPS_LUMA];     ///< Luma filter taps
+  static const TFilterCoeff m_chromaFilter[CHROMA_INTERPOLATION_FILTER_SUB_SAMPLE_POSITIONS][NTAPS_CHROMA]; ///< Chroma filter taps
+
+  static Void filterCopy(Int bitDepth, const Pel *src, Int srcStride, Pel *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, Pel *dst, Int dstStride, Int width, Int height, TFilterCoeff const *coeff);
+
+  template<Int N>
+  static Void filterHor(Int bitDepth, Pel *src, Int srcStride, Pel *dst, Int dstStride, Int width, Int height,               Bool isLast, TFilterCoeff const *coeff);
+  template<Int N>
+  static Void filterVer(Int bitDepth, Pel *src, Int srcStride, Pel *dst, Int dstStride, Int width, Int height, Bool isFirst, Bool isLast, TFilterCoeff const *coeff);
+
+public:
+  TComInterpolationFilter() {}
+  ~TComInterpolationFilter() {}
+
+  Void filterHor(const ComponentID compID, Pel *src, Int srcStride, Pel *dst, Int dstStride, Int width, Int height, Int frac,               Bool isLast, const ChromaFormat fmt );
+  Void filterVer(const ComponentID compID, Pel *src, Int srcStride, Pel *dst, Int dstStride, Int width, Int height, Int frac, Bool isFirst, Bool isLast, const ChromaFormat fmt );
+};
+
+//! \}
+
+#endif
Index: /tags/SHM-9.0/source/Lib/TLibCommon/TComList.h
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibCommon/TComList.h	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibCommon/TComList.h	(revision 1088)
@@ -0,0 +1,115 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TComList.h
+    \brief    general list class (header)
+*/
+
+#ifndef __TCOMLIST__
+#define __TCOMLIST__
+
+#if _MSC_VER > 1000
+#pragma once
+#endif // _MSC_VER > 1000
+
+#include <list>
+#include <assert.h>
+#include "CommonDef.h"
+
+#include <cstdlib>
+using namespace std;
+
+//! \ingroup TLibCommon
+//! \{
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// list template
+template< class C >
+class TComList : public std::list< C > // NOTE: should not inherit from STL classes
+{
+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 std::list< C >::find( this->begin(), this->end(), rcT );
+  }
+};
+
+//! \}
+
+#endif
Index: /tags/SHM-9.0/source/Lib/TLibCommon/TComLoopFilter.cpp
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibCommon/TComLoopFilter.cpp	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibCommon/TComLoopFilter.cpp	(revision 1088)
@@ -0,0 +1,927 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TComLoopFilter.cpp
+    \brief    deblocking filter
+*/
+
+#include "TComLoopFilter.h"
+#include "TComSlice.h"
+#include "TComMv.h"
+#include "TComTU.h"
+
+//! \ingroup TLibCommon
+//! \{
+
+// ====================================================================================================================
+// Constants
+// ====================================================================================================================
+
+//#define   EDGE_VER    0
+//#define   EDGE_HOR    1
+
+#define DEFAULT_INTRA_TC_OFFSET 2 ///< Default intra TC offset
+
+// ====================================================================================================================
+// Tables
+// ====================================================================================================================
+
+const UChar TComLoopFilter::sm_tcTable[MAX_QP + 1 + DEFAULT_INTRA_TC_OFFSET] =
+{
+  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[MAX_QP + 1] =
+{
+  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( Int edgeDir = 0; edgeDir < NUM_EDGE_DIR; edgeDir++ )
+  {
+    m_aapucBS       [edgeDir] = NULL;
+    m_aapbEdgeFilter[edgeDir] = 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( Int edgeDir = 0; edgeDir < NUM_EDGE_DIR; edgeDir++ )
+  {
+    m_aapucBS       [edgeDir] = new UChar[m_uiNumPartitions];
+    m_aapbEdgeFilter[edgeDir] = new Bool [m_uiNumPartitions];
+  }
+}
+
+Void TComLoopFilter::destroy()
+{
+  for( Int edgeDir = 0; edgeDir < NUM_EDGE_DIR; edgeDir++ )
+  {
+    if (m_aapucBS[edgeDir] != NULL)
+    {
+      delete [] m_aapucBS[edgeDir];
+      m_aapucBS[edgeDir] = NULL;
+    }
+
+    if (m_aapbEdgeFilter[edgeDir])
+    {
+      delete [] m_aapbEdgeFilter[edgeDir];
+      m_aapbEdgeFilter[edgeDir] = NULL;
+    }
+  }
+}
+
+/**
+ - call deblocking function for every CU
+ .
+ \param  pcPic   picture class (TComPic) pointer
+ */
+Void TComLoopFilter::loopFilterPic( TComPic* pcPic )
+{
+  // Horizontal filtering
+  for ( UInt ctuRsAddr = 0; ctuRsAddr < pcPic->getNumberOfCtusInFrame(); ctuRsAddr++ )
+  {
+    TComDataCU* pCtu = pcPic->getCtu( ctuRsAddr );
+
+    ::memset( m_aapucBS       [EDGE_VER], 0, sizeof( UChar ) * m_uiNumPartitions );
+    ::memset( m_aapbEdgeFilter[EDGE_VER], 0, sizeof( Bool  ) * m_uiNumPartitions );
+
+    // CU-based deblocking
+    xDeblockCU( pCtu, 0, 0, EDGE_VER );
+  }
+
+  // Vertical filtering
+  for ( UInt ctuRsAddr = 0; ctuRsAddr < pcPic->getNumberOfCtusInFrame(); ctuRsAddr++ )
+  {
+    TComDataCU* pCtu = pcPic->getCtu( ctuRsAddr );
+
+    ::memset( m_aapucBS       [EDGE_HOR], 0, sizeof( UChar ) * m_uiNumPartitions );
+    ::memset( m_aapbEdgeFilter[EDGE_HOR], 0, sizeof( Bool  ) * m_uiNumPartitions );
+
+    // CU-based deblocking
+    xDeblockCU( pCtu, 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, DeblockEdgeDir edgeDir )
+{
+  if(pcCU->getPic()==0||pcCU->getPartitionSize(uiAbsZorderIdx)==NUMBER_OF_PART_SIZES)
+  {
+    return;
+  }
+  TComPic* pcPic     = pcCU->getPic();
+  UInt uiCurNumParts = pcPic->getNumPartitionsInCtu() >> (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 REPN_FORMAT_IN_VPS
+      if( ( uiLPelX < pcCU->getSlice()->getPicWidthInLumaSamples() ) && ( uiTPelY < pcCU->getSlice()->getPicHeightInLumaSamples() ) )
+#else
+      if( ( uiLPelX < pcCU->getSlice()->getSPS()->getPicWidthInLumaSamples() ) && ( uiTPelY < pcCU->getSlice()->getSPS()->getPicHeightInLumaSamples() ) )
+#endif
+      {
+        xDeblockCU( pcCU, uiAbsZorderIdx, uiDepth+1, edgeDir );
+      }
+    }
+    return;
+  }
+
+  xSetLoopfilterParam( pcCU, uiAbsZorderIdx );
+  TComTURecurse tuRecurse(pcCU, uiAbsZorderIdx);
+  xSetEdgefilterTU   ( tuRecurse );
+  xSetEdgefilterPU   ( pcCU, uiAbsZorderIdx );
+
+  for( UInt uiPartIdx = uiAbsZorderIdx; uiPartIdx < uiAbsZorderIdx + uiCurNumParts; uiPartIdx++ )
+  {
+    UInt uiBSCheck;
+    if( (g_uiMaxCUWidth >> g_uiMaxCUDepth) == 4 )
+    {
+      uiBSCheck = (edgeDir == EDGE_VER && uiPartIdx%2 == 0) || (edgeDir == EDGE_HOR && (uiPartIdx-((uiPartIdx>>2)<<2))/2 == 0);
+    }
+    else
+    {
+      uiBSCheck = 1;
+    }
+
+    if ( m_aapbEdgeFilter[edgeDir][uiPartIdx] && uiBSCheck )
+    {
+      xGetBoundaryStrengthSingle ( pcCU, edgeDir, uiPartIdx );
+    }
+  }
+
+  UInt uiPelsInPart = g_uiMaxCUWidth >> g_uiMaxCUDepth;
+  UInt PartIdxIncr = DEBLOCK_SMALLEST_BLOCK / uiPelsInPart ? DEBLOCK_SMALLEST_BLOCK / uiPelsInPart : 1 ;
+
+  UInt uiSizeInPU = pcPic->getNumPartInCtuWidth()>>(uiDepth);
+  const ChromaFormat chFmt=pcPic->getChromaFormat();
+  const UInt shiftFactor  = edgeDir == EDGE_VER ? pcPic->getComponentScaleX(COMPONENT_Cb) : pcPic->getComponentScaleY(COMPONENT_Cb);
+  const Bool bAlwaysDoChroma=chFmt==CHROMA_444;
+
+  for ( Int iEdge = 0; iEdge < uiSizeInPU ; iEdge+=PartIdxIncr)
+  {
+    xEdgeFilterLuma     ( pcCU, uiAbsZorderIdx, uiDepth, edgeDir, iEdge );
+    if ( chFmt!=CHROMA_400 && (bAlwaysDoChroma ||
+                               (uiPelsInPart>DEBLOCK_SMALLEST_BLOCK) ||
+                               (iEdge % ( (DEBLOCK_SMALLEST_BLOCK<<shiftFactor)/uiPelsInPart ) ) == 0
+                              )
+       )
+    {
+      xEdgeFilterChroma   ( pcCU, uiAbsZorderIdx, uiDepth, edgeDir, iEdge );
+    }
+  }
+}
+
+Void TComLoopFilter::xSetEdgefilterMultiple( TComDataCU*    pcCU,
+                                             UInt           uiAbsZorderIdx,
+                                             UInt           uiDepth,
+                                             DeblockEdgeDir edgeDir,
+                                             Int            iEdgeIdx,
+                                             Bool           bValue,
+                                             UInt           uiWidthInBaseUnits,
+                                             UInt           uiHeightInBaseUnits,
+                                             const TComRectangle *rect)
+{
+  if ( uiWidthInBaseUnits == 0 )
+  {
+    uiWidthInBaseUnits  = pcCU->getPic()->getNumPartInCtuWidth () >> uiDepth;
+  }
+  if ( uiHeightInBaseUnits == 0 )
+  {
+    uiHeightInBaseUnits = pcCU->getPic()->getNumPartInCtuHeight() >> uiDepth;
+  }
+  const UInt uiNumElem = edgeDir == EDGE_VER ? uiHeightInBaseUnits : uiWidthInBaseUnits;
+  assert( uiNumElem > 0 );
+  assert( uiWidthInBaseUnits > 0 );
+  assert( uiHeightInBaseUnits > 0 );
+  for( UInt ui = 0; ui < uiNumElem; ui++ )
+  {
+    const UInt uiBsIdx = xCalcBsIdx( pcCU, uiAbsZorderIdx, edgeDir, iEdgeIdx, ui, rect );
+    m_aapbEdgeFilter[edgeDir][uiBsIdx] = bValue;
+    if (iEdgeIdx == 0)
+    {
+      m_aapucBS[edgeDir][uiBsIdx] = bValue;
+    }
+  }
+}
+
+Void TComLoopFilter::xSetEdgefilterTU(  TComTU &rTu )
+{
+  TComDataCU* pcCU  = rTu.getCU();
+  UInt uiTransDepthTotal = rTu.GetTransformDepthTotal();
+
+  if( pcCU->getTransformIdx( rTu.GetAbsPartIdxTU() ) + pcCU->getDepth( rTu.GetAbsPartIdxTU()) > uiTransDepthTotal )
+  {
+    TComTURecurse tuChild(rTu, false);
+    do
+    {
+      xSetEdgefilterTU( tuChild );
+    } while (tuChild.nextSection(rTu));
+    return;
+  }
+
+  const TComRectangle &rect = rTu.getRect(COMPONENT_Y);
+
+  const UInt uiWidthInBaseUnits  = rect.width / (g_uiMaxCUWidth >> g_uiMaxCUDepth);
+  const UInt uiHeightInBaseUnits = rect.height / (g_uiMaxCUWidth >> g_uiMaxCUDepth);
+
+  xSetEdgefilterMultiple( pcCU, rTu.GetAbsPartIdxCU(), uiTransDepthTotal, EDGE_VER, 0, m_stLFCUParam.bInternalEdge, uiWidthInBaseUnits, uiHeightInBaseUnits, &rect );
+  xSetEdgefilterMultiple( pcCU, rTu.GetAbsPartIdxCU(), uiTransDepthTotal, EDGE_HOR, 0, m_stLFCUParam.bInternalEdge, uiWidthInBaseUnits, uiHeightInBaseUnits, &rect );
+}
+
+Void TComLoopFilter::xSetEdgefilterPU( TComDataCU* pcCU, UInt uiAbsZorderIdx )
+{
+  const UInt uiDepth = pcCU->getDepth( uiAbsZorderIdx );
+  const UInt uiWidthInBaseUnits  = pcCU->getPic()->getNumPartInCtuWidth () >> uiDepth;
+  const UInt uiHeightInBaseUnits = pcCU->getPic()->getNumPartInCtuHeight() >> 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 != NULL )
+    {
+      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 != NULL )
+    {
+      m_stLFCUParam.bTopEdge = true;
+    }
+    else
+    {
+      m_stLFCUParam.bTopEdge = false;
+    }
+  }
+}
+
+Void TComLoopFilter::xGetBoundaryStrengthSingle ( TComDataCU* pCtu, DeblockEdgeDir edgeDir, UInt uiAbsPartIdx4x4BlockWithinCtu )
+{
+  TComSlice * const pcSlice = pCtu->getSlice();
+
+  const Bool lfCrossSliceBoundaryFlag=pCtu->getSlice()->getLFCrossSliceBoundaryFlag();
+
+  const UInt uiPartQ = uiAbsPartIdx4x4BlockWithinCtu;
+  TComDataCU* const pcCUQ = pCtu;
+
+  UInt uiPartP;
+  TComDataCU* pcCUP;
+  UInt uiBs = 0;
+
+  //-- Calculate Block Index
+  if (edgeDir == EDGE_VER)
+  {
+    pcCUP = pcCUQ->getPULeft(uiPartP, uiPartQ, !lfCrossSliceBoundaryFlag, !m_bLFCrossTileBoundary);
+  }
+  else  // (edgeDir == EDGE_HOR)
+  {
+    pcCUP = pcCUQ->getPUAbove(uiPartP, uiPartQ, !pCtu->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[edgeDir][uiAbsPartIdx4x4BlockWithinCtu] && (pcCUQ->getCbf( nsPartQ, COMPONENT_Y, pcCUQ->getTransformIdx(nsPartQ)) != 0 || pcCUP->getCbf( nsPartP, COMPONENT_Y, pcCUP->getTransformIdx(nsPartP) ) != 0) )
+    {
+      uiBs = 1;
+    }
+    else
+    {
+      if (edgeDir == EDGE_HOR)
+      {
+        pcCUP = pcCUQ->getPUAbove(uiPartP, uiPartQ, !pCtu->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[edgeDir][uiAbsPartIdx4x4BlockWithinCtu] = uiBs;
+}
+
+
+Void TComLoopFilter::xEdgeFilterLuma( TComDataCU* pcCU, UInt uiAbsZorderIdx, UInt uiDepth, DeblockEdgeDir edgeDir, Int iEdge  )
+{
+  TComPicYuv* pcPicYuvRec = pcCU->getPic()->getPicYuvRec();
+  Pel* piSrc    = pcPicYuvRec->getAddr(COMPONENT_Y, pcCU->getCtuRsAddr(), uiAbsZorderIdx );
+  Pel* piTmpSrc = piSrc;
+
+  const Bool lfCrossSliceBoundaryFlag=pcCU->getSlice()->getLFCrossSliceBoundaryFlag();
+
+  Int  iStride = pcPicYuvRec->getStride(COMPONENT_Y);
+  Int iQP = 0;
+  Int iQP_P = 0;
+  Int iQP_Q = 0;
+  UInt uiNumParts = pcCU->getPic()->getNumPartInCtuWidth()>>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 (edgeDir == EDGE_VER)
+  {
+    iOffset = 1;
+    iSrcStep = iStride;
+    piTmpSrc += iEdge*uiPelsInPart;
+  }
+  else  // (edgeDir == EDGE_HOR)
+  {
+    iOffset = iStride;
+    iSrcStep = 1;
+    piTmpSrc += iEdge*uiPelsInPart*iStride;
+  }
+
+  for ( UInt iIdx = 0; iIdx < uiNumParts; iIdx++ )
+  {
+    uiBsAbsIdx = xCalcBsIdx( pcCU, uiAbsZorderIdx, edgeDir, iEdge, iIdx);
+    uiBs = m_aapucBS[edgeDir][uiBsAbsIdx];
+    if ( uiBs )
+    {
+      iQP_Q = pcCU->getQP( uiBsAbsIdx );
+      uiPartQIdx = uiBsAbsIdx;
+      // Derive neighboring PU index
+      if (edgeDir == EDGE_VER)
+      {
+        pcCUP = pcCUQ->getPULeft (uiPartPIdx, uiPartQIdx,!lfCrossSliceBoundaryFlag, !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_bitDepth[CHANNEL_TYPE_LUMA]-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, DeblockEdgeDir edgeDir, Int iEdge )
+{
+  TComPicYuv* pcPicYuvRec = pcCU->getPic()->getPicYuvRec();
+  Int         iStride     = pcPicYuvRec->getStride(COMPONENT_Cb);
+  Pel*        piSrcCb     = pcPicYuvRec->getAddr( COMPONENT_Cb, pcCU->getCtuRsAddr(), uiAbsZorderIdx );
+  Pel*        piSrcCr     = pcPicYuvRec->getAddr( COMPONENT_Cr, pcCU->getCtuRsAddr(), uiAbsZorderIdx );
+  Int iQP = 0;
+  Int iQP_P = 0;
+  Int iQP_Q = 0;
+
+  UInt  uiPelsInPartChromaH = g_uiMaxCUWidth >> (g_uiMaxCUDepth+pcPicYuvRec->getComponentScaleX(COMPONENT_Cb));
+  UInt  uiPelsInPartChromaV = g_uiMaxCUWidth >> (g_uiMaxCUDepth+pcPicYuvRec->getComponentScaleY(COMPONENT_Cb));
+
+  Int   iOffset, iSrcStep;
+  UInt  uiLoopLength;
+
+  const UInt uiCtuWidthInBaseUnits = pcCU->getPic()->getNumPartInCtuWidth();
+
+  Bool  bPCMFilter = (pcCU->getSlice()->getSPS()->getUsePCM() && pcCU->getSlice()->getSPS()->getPCMFilterDisableFlag())? true : false;
+  Bool  bPartPNoFilter = false;
+  Bool  bPartQNoFilter = false;
+  TComDataCU* pcCUQ = pcCU;
+  Int tcOffsetDiv2 = pcCU->getSlice()->getDeblockingFilterTcOffsetDiv2();
+
+  // Vertical Position
+  UInt uiEdgeNumInCtuVert = g_auiZscanToRaster[uiAbsZorderIdx]%uiCtuWidthInBaseUnits + iEdge;
+  UInt uiEdgeNumInCtuHor = g_auiZscanToRaster[uiAbsZorderIdx]/uiCtuWidthInBaseUnits + iEdge;
+
+  if ( (uiPelsInPartChromaH < DEBLOCK_SMALLEST_BLOCK) && (uiPelsInPartChromaV < DEBLOCK_SMALLEST_BLOCK) &&
+       (
+         ( (uiEdgeNumInCtuVert%(DEBLOCK_SMALLEST_BLOCK/uiPelsInPartChromaH)) && (edgeDir==EDGE_VER) ) ||
+         ( (uiEdgeNumInCtuHor %(DEBLOCK_SMALLEST_BLOCK/uiPelsInPartChromaV)) && (edgeDir==EDGE_HOR) )
+       )
+     )
+  {
+    return;
+  }
+
+
+  const Bool lfCrossSliceBoundaryFlag=pcCU->getSlice()->getLFCrossSliceBoundaryFlag();
+
+  UInt  uiNumParts = pcCU->getPic()->getNumPartInCtuWidth()>>uiDepth;
+
+  UInt  uiBsAbsIdx;
+  UChar ucBs;
+
+  Pel* piTmpSrcCb = piSrcCb;
+  Pel* piTmpSrcCr = piSrcCr;
+
+  if (edgeDir == EDGE_VER)
+  {
+    iOffset   = 1;
+    iSrcStep  = iStride;
+    piTmpSrcCb += iEdge*uiPelsInPartChromaH;
+    piTmpSrcCr += iEdge*uiPelsInPartChromaH;
+    uiLoopLength=uiPelsInPartChromaV;
+  }
+  else  // (edgeDir == EDGE_HOR)
+  {
+    iOffset   = iStride;
+    iSrcStep  = 1;
+    piTmpSrcCb += iEdge*iStride*uiPelsInPartChromaV;
+    piTmpSrcCr += iEdge*iStride*uiPelsInPartChromaV;
+    uiLoopLength=uiPelsInPartChromaH;
+  }
+
+  for ( UInt iIdx = 0; iIdx < uiNumParts; iIdx++ )
+  {
+    uiBsAbsIdx = xCalcBsIdx( pcCU, uiAbsZorderIdx, edgeDir, iEdge, iIdx);
+    ucBs = m_aapucBS[edgeDir][uiBsAbsIdx];
+
+    if ( ucBs > 1)
+    {
+      iQP_Q = pcCU->getQP( uiBsAbsIdx );
+      UInt  uiPartQIdx = uiBsAbsIdx;
+      // Derive neighboring PU index
+      TComDataCU* pcCUP;
+      UInt  uiPartPIdx;
+
+      if (edgeDir == EDGE_VER)
+      {
+        pcCUP = pcCUQ->getPULeft (uiPartPIdx, uiPartQIdx,!lfCrossSliceBoundaryFlag, !m_bLFCrossTileBoundary);
+      }
+      else  // (edgeDir == 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  = pcCU->getSlice()->getPPS()->getQpOffset(ComponentID(chromaIdx + 1));
+        Pel* piTmpSrcChroma = (chromaIdx == 0) ? piTmpSrcCb : piTmpSrcCr;
+
+        iQP = ((iQP_P + iQP_Q + 1) >> 1) + chromaQPOffset;
+        if (iQP >= chromaQPMappingTableSize)
+        {
+          if (pcPicYuvRec->getChromaFormat()==CHROMA_420) iQP -=6;
+          else if (iQP>51) iQP=51;
+        }
+        else if (iQP >= 0 )
+        {
+          iQP = getScaledChromaQP(iQP, pcPicYuvRec->getChromaFormat());
+        }
+
+        Int iBitdepthScale = 1 << (g_bitDepth[CHANNEL_TYPE_CHROMA]-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 < uiLoopLength; uiStep++ )
+        {
+          xPelFilterChroma( piTmpSrcChroma + iSrcStep*(uiStep+iIdx*uiLoopLength), 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] = Clip((m3+delta), CHANNEL_TYPE_LUMA);
+      piSrc[0] = Clip((m4-delta), CHANNEL_TYPE_LUMA);
+
+      Int tc2 = tc>>1;
+      if(bFilterSecondP)
+      {
+        Int delta1 = Clip3(-tc2, tc2, (( ((m1+m3+1)>>1)- m2+delta)>>1));
+        piSrc[-iOffset*2] = Clip((m2+delta1), CHANNEL_TYPE_LUMA);
+      }
+      if(bFilterSecondQ)
+      {
+        Int delta2 = Clip3(-tc2, tc2, (( ((m6+m4+1)>>1)- m5-delta)>>1));
+        piSrc[ iOffset] = Clip((m5+delta2), CHANNEL_TYPE_LUMA);
+      }
+    }
+  }
+
+  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] = Clip((m3+delta), CHANNEL_TYPE_CHROMA);
+  piSrc[0] = Clip((m4-delta), CHANNEL_TYPE_CHROMA);
+
+  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: /tags/SHM-9.0/source/Lib/TLibCommon/TComLoopFilter.h
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibCommon/TComLoopFilter.h	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibCommon/TComLoopFilter.h	(revision 1088)
@@ -0,0 +1,143 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TComLoopFilter.h
+    \brief    deblocking filter (header)
+*/
+
+#ifndef __TCOMLOOPFILTER__
+#define __TCOMLOOPFILTER__
+
+#include "CommonDef.h"
+#include "TComPic.h"
+
+//! \ingroup TLibCommon
+//! \{
+
+#define DEBLOCK_SMALLEST_BLOCK  8
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// deblocking filter class
+class TComLoopFilter
+{
+private:
+
+  UInt      m_uiNumPartitions;
+  UChar*    m_aapucBS[NUM_EDGE_DIR];         ///< Bs for [Ver/Hor][Y/U/V][Blk_Idx]
+  Bool*     m_aapbEdgeFilter[NUM_EDGE_DIR];
+  LFCUParam m_stLFCUParam;                   ///< status structure
+
+  Bool      m_bLFCrossTileBoundary;
+
+protected:
+  /// CU-level deblocking function
+  Void xDeblockCU                 ( TComDataCU* pcCU, UInt uiAbsZorderIdx, UInt uiDepth, DeblockEdgeDir edgeDir );
+
+  // set / get functions
+  Void xSetLoopfilterParam        ( TComDataCU* pcCU, UInt uiAbsZorderIdx );
+  // filtering functions
+  Void xSetEdgefilterTU           ( TComTU &rTu );
+  Void xSetEdgefilterPU           ( TComDataCU* pcCU, UInt uiAbsZorderIdx );
+  Void xGetBoundaryStrengthSingle ( TComDataCU* pCtu, DeblockEdgeDir edgeDir, UInt uiPartIdx );
+  UInt xCalcBsIdx                 ( TComDataCU* pcCU, UInt absZIdxInCtu, DeblockEdgeDir edgeDir, Int iEdgeIdx, Int iBaseUnitIdx, const struct TComRectangle *rect=NULL )
+  {
+    TComPic* const pcPic = pcCU->getPic();
+    const UInt ctuWidthInBaseUnits = pcPic->getNumPartInCtuWidth();
+    Int rasterOffsetTU=0;
+    if (rect != NULL)
+    {
+      const UInt minCuWidth =pcPic->getMinCUWidth();
+      const UInt minCuHeight=pcPic->getMinCUHeight();
+      rasterOffsetTU = rect->x0/minCuWidth + (rect->y0/minCuHeight)*ctuWidthInBaseUnits;
+    }
+    if( edgeDir == EDGE_VER )
+    {
+      return g_auiRasterToZscan[g_auiZscanToRaster[absZIdxInCtu] + iBaseUnitIdx * ctuWidthInBaseUnits + iEdgeIdx + rasterOffsetTU ];
+    }
+    else
+    {
+      return g_auiRasterToZscan[g_auiZscanToRaster[absZIdxInCtu] + iEdgeIdx * ctuWidthInBaseUnits + iBaseUnitIdx + rasterOffsetTU ];
+    }
+  }
+
+  Void xSetEdgefilterMultiple( TComDataCU* pcCU,
+                               UInt uiAbsZorderIdx,
+                               UInt uiDepth,
+                               DeblockEdgeDir edgeDir,
+                               Int iEdgeIdx,
+                               Bool bValue,
+                               UInt uiWidthInBaseUnits = 0,
+                               UInt uiHeightInBaseUnits = 0,
+                               const TComRectangle *rect = 0
+                               );
+
+  Void xEdgeFilterLuma            ( TComDataCU* pcCU, UInt uiAbsZorderIdx, UInt uiDepth, DeblockEdgeDir edgeDir, Int iEdge );
+  Void xEdgeFilterChroma          ( TComDataCU* pcCU, UInt uiAbsZorderIdx, UInt uiDepth, DeblockEdgeDir edgeDir, 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: /tags/SHM-9.0/source/Lib/TLibCommon/TComMotionInfo.cpp
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibCommon/TComMotionInfo.cpp	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibCommon/TComMotionInfo.cpp	(revision 1088)
@@ -0,0 +1,351 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TComMotionInfo.cpp
+    \brief    motion information handling classes
+*/
+
+#include <memory.h>
+#include "TComMotionInfo.h"
+#include "assert.h"
+#include <stdlib.h>
+
+//! \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);
+    Int iRefIdx = 0;
+
+    cMv = m_pcMv[ uiPartIdx ];
+    PredMode 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: /tags/SHM-9.0/source/Lib/TLibCommon/TComMotionInfo.h
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibCommon/TComMotionInfo.h	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibCommon/TComMotionInfo.h	(revision 1088)
@@ -0,0 +1,176 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TComMotionInfo.h
+    \brief    motion information handling classes (header)
+    \todo     TComMvField seems to be better to be inherited from TComMv
+*/
+
+#ifndef __TCOMMOTIONINFO__
+#define __TCOMMOTIONINFO__
+
+#include <memory.h>
+#include "CommonDef.h"
+#include "TComMv.h"
+
+//! \ingroup TLibCommon
+//! \{
+
+// ====================================================================================================================
+// Type definition
+// ====================================================================================================================
+
+/// 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;
+
+// ====================================================================================================================
+// 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(); }
+};
+
+/// 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);
+
+#if REF_IDX_MFM
+  Void setMvField( TComMvField const& mvField, Int iIdx )
+  {
+    m_pcMv[iIdx]      = mvField.getMv();
+    m_piRefIdx[iIdx]  = mvField.getRefIdx();
+    return;
+  }
+
+  Void setMvField( TComMv cMv, Int iRefIdx, Int iIdx )
+  {
+    m_pcMv[iIdx]      = cMv;
+    m_piRefIdx[iIdx]  = iRefIdx;
+    return;
+  }
+#endif
+};
+
+//! \}
+
+#endif // __TCOMMOTIONINFO__
Index: /tags/SHM-9.0/source/Lib/TLibCommon/TComMv.h
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibCommon/TComMv.h	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibCommon/TComMv.h	(revision 1088)
@@ -0,0 +1,164 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TComMv.h
+    \brief    motion vector class (header)
+*/
+
+#ifndef __TCOMMV__
+#define __TCOMMV__
+
+#include "CommonDef.h"
+#include <cstdlib>
+
+//! \ingroup TLibCommon
+//! \{
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// basic motion vector class
+class TComMv
+{
+private:
+  Short m_iHor;     ///< horizontal component of motion vector
+  Short m_iVer;     ///< vertical component of motion vector
+
+public:
+
+  // ------------------------------------------------------------------------------------------------------------------
+  // constructors
+  // ------------------------------------------------------------------------------------------------------------------
+
+  TComMv() :
+  m_iHor(0),
+  m_iVer(0)
+  {
+  }
+
+  TComMv( Short iHor, Short iVer ) :
+  m_iHor(iHor),
+  m_iVer(iVer)
+  {
+  }
+
+  // ------------------------------------------------------------------------------------------------------------------
+  // 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;  }
+
+  // ------------------------------------------------------------------------------------------------------------------
+  // 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 );   }
+
+  // ------------------------------------------------------------------------------------------------------------------
+  // 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 );
+  }
+#if SVC_EXTENSION
+  const TComMv scaleMv( Int iScaleX, Int iScaleY ) const
+  {
+    Int mvx = iScaleX == 4096 ? getHor() : Clip3( -32768, 32767, (iScaleX * getHor() + 127 + (iScaleX * getHor() < 0)) >> 8 );
+    Int mvy = iScaleY == 4096 ? getVer() : Clip3( -32768, 32767, (iScaleY * getVer() + 127 + (iScaleY * getVer() < 0)) >> 8 );
+    return TComMv( mvx, mvy );
+  }
+#endif
+};// END CLASS DEFINITION TComMV
+
+//! \}
+
+#endif // __TCOMMV__
Index: /tags/SHM-9.0/source/Lib/TLibCommon/TComPattern.cpp
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibCommon/TComPattern.cpp	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibCommon/TComPattern.cpp	(revision 1088)
@@ -0,0 +1,734 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TComPattern.cpp
+    \brief    neighbouring pixel access classes
+*/
+
+#include "TComPic.h"
+#include "TComPattern.h"
+#include "TComDataCU.h"
+#include "TComTU.h"
+#include "Debug.h"
+#include "TComPrediction.h"
+
+//! \ingroup TLibCommon
+//! \{
+
+// Forward declarations
+
+/// padding of unavailable reference samples for intra prediction
+#if O0043_BEST_EFFORT_DECODING
+Void fillReferenceSamples( const Int bitDepth, const Int bitDepthDelta, TComDataCU* pcCU, const Pel* piRoiOrigin, Pel* piAdiTemp, const Bool* bNeighborFlags,
+#else
+Void fillReferenceSamples( const Int bitDepth, TComDataCU* pcCU, const Pel* piRoiOrigin, Pel* piAdiTemp, const Bool* bNeighborFlags,
+#endif
+                           const Int iNumIntraNeighbor, const Int unitWidth, const Int unitHeight, const Int iAboveUnits, const Int iLeftUnits,
+                           const UInt uiCuWidth, const UInt uiCuHeight, const UInt uiWidth, const UInt uiHeight, const Int iPicStride,
+                           const ChannelType chType, const ChromaFormat chFmt );
+
+/// 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 );
+
+
+// ====================================================================================================================
+// 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  iOffsetRight  neighbour offset (right)
+ \param  iOffsetAbove  neighbour offset (above)
+ \param  iOffsetBottom neighbour offset (bottom)
+ */
+Void TComPatternParam::setPatternParamPel ( Pel* piTexture,
+                                           Int iRoiWidth,
+                                           Int iRoiHeight,
+                                           Int iStride
+                                           )
+{
+  m_piROIOrigin    = piTexture;
+  m_iROIWidth       = iRoiWidth;
+  m_iROIHeight      = iRoiHeight;
+  m_iPatternStride  = iStride;
+}
+
+// ====================================================================================================================
+// Public member functions (TComPattern)
+// ====================================================================================================================
+
+Void TComPattern::initPattern (Pel* piY,
+                               Int iRoiWidth,
+                               Int iRoiHeight,
+                               Int iStride)
+{
+  m_cPatternY. setPatternParamPel( piY,  iRoiWidth, iRoiHeight, iStride);
+}
+
+
+// TODO: move this function to TComPrediction.cpp.
+Void TComPrediction::initAdiPatternChType( TComTU &rTu, Bool& bAbove, Bool& bLeft, const ComponentID compID, const Bool bFilterRefSamples DEBUG_STRING_FN_DECLARE(sDebug))
+{
+  const ChannelType chType    = toChannelType(compID);
+
+  TComDataCU *pcCU=rTu.getCU();
+  const UInt uiZorderIdxInPart=rTu.GetAbsPartIdxTU();
+  const UInt uiTuWidth        = rTu.getRect(compID).width;
+  const UInt uiTuHeight       = rTu.getRect(compID).height;
+  const UInt uiTuWidth2       = uiTuWidth  << 1;
+  const UInt uiTuHeight2      = uiTuHeight << 1;
+
+  const Int  iBaseUnitSize    = g_uiMaxCUWidth >> g_uiMaxCUDepth;
+  const Int  iUnitWidth       = iBaseUnitSize  >> pcCU->getPic()->getPicYuvRec()->getComponentScaleX(compID);
+  const Int  iUnitHeight      = iBaseUnitSize  >> pcCU->getPic()->getPicYuvRec()->getComponentScaleY(compID);
+  const Int  iTUWidthInUnits  = uiTuWidth  / iUnitWidth;
+  const Int  iTUHeightInUnits = uiTuHeight / iUnitHeight;
+  const Int  iAboveUnits      = iTUWidthInUnits  << 1;
+  const Int  iLeftUnits       = iTUHeightInUnits << 1;
+
+  assert(iTUHeightInUnits > 0 && iTUWidthInUnits > 0);
+
+  const Int  iPartIdxStride   = pcCU->getPic()->getNumPartInCtuWidth();
+  const UInt uiPartIdxLT      = pcCU->getZorderIdxInCtu() + uiZorderIdxInPart;
+  const UInt uiPartIdxRT      = g_auiRasterToZscan[ g_auiZscanToRaster[ uiPartIdxLT ] +   iTUWidthInUnits  - 1                   ];
+  const UInt uiPartIdxLB      = g_auiRasterToZscan[ g_auiZscanToRaster[ uiPartIdxLT ] + ((iTUHeightInUnits - 1) * iPartIdxStride)];
+
+  Int   iPicStride = pcCU->getPic()->getStride(compID);
+  Bool  bNeighborFlags[4 * MAX_NUM_SPU_W + 1];
+  Int   iNumIntraNeighbor = 0;
+
+  bNeighborFlags[iLeftUnits] = isAboveLeftAvailable( pcCU, uiPartIdxLT );
+  iNumIntraNeighbor += bNeighborFlags[iLeftUnits] ? 1 : 0;
+  iNumIntraNeighbor  += isAboveAvailable     ( pcCU, uiPartIdxLT, uiPartIdxRT, (bNeighborFlags + iLeftUnits + 1)                    );
+  iNumIntraNeighbor  += isAboveRightAvailable( pcCU, uiPartIdxLT, uiPartIdxRT, (bNeighborFlags + iLeftUnits + 1 + iTUWidthInUnits ) );
+  iNumIntraNeighbor  += isLeftAvailable      ( pcCU, uiPartIdxLT, uiPartIdxLB, (bNeighborFlags + iLeftUnits - 1)                    );
+  iNumIntraNeighbor  += isBelowLeftAvailable ( pcCU, uiPartIdxLT, uiPartIdxLB, (bNeighborFlags + iLeftUnits - 1 - iTUHeightInUnits) );
+
+  bAbove = true;
+  bLeft  = true;
+
+  const ChromaFormat chFmt       = rTu.GetChromaFormat();
+  const UInt         uiROIWidth  = uiTuWidth2+1;
+  const UInt         uiROIHeight = uiTuHeight2+1;
+
+  assert(uiROIWidth*uiROIHeight <= m_iYuvExtSize);
+
+#ifdef DEBUG_STRING
+  std::stringstream ss(stringstream::out);
+#endif
+
+  {
+    Pel *piAdiTemp   = m_piYuvExt[compID][PRED_BUF_UNFILTERED];
+    Pel *piRoiOrigin = pcCU->getPic()->getPicYuvRec()->getAddr(compID, pcCU->getCtuRsAddr(), pcCU->getZorderIdxInCtu()+uiZorderIdxInPart);
+#if O0043_BEST_EFFORT_DECODING
+    fillReferenceSamples (g_bitDepthInStream[chType], g_bitDepthInStream[chType] - g_bitDepth[chType], pcCU, piRoiOrigin, piAdiTemp, bNeighborFlags, iNumIntraNeighbor,  iUnitWidth, iUnitHeight, iAboveUnits, iLeftUnits,
+#else
+    fillReferenceSamples (g_bitDepth[chType], pcCU, piRoiOrigin, piAdiTemp, bNeighborFlags, iNumIntraNeighbor,  iUnitWidth, iUnitHeight, iAboveUnits, iLeftUnits,
+#endif
+                          uiTuWidth, uiTuHeight, uiROIWidth, uiROIHeight, iPicStride, toChannelType(compID), chFmt);
+
+
+#ifdef DEBUG_STRING
+    if (DebugOptionList::DebugString_Pred.getInt()&DebugStringGetPredModeMask(MODE_INTRA))
+    {
+      ss << "###: generating Ref Samples for channel " << compID << " and " << rTu.getRect(compID).width << " x " << rTu.getRect(compID).height << "\n";
+      for (UInt y=0; y<uiROIHeight; y++)
+      {
+        ss << "###: - ";
+        for (UInt x=0; x<uiROIWidth; x++)
+        {
+          if (x==0 || y==0)
+            ss << piAdiTemp[y*uiROIWidth + x] << ", ";
+//          if (x%16==15) ss << "\nPart size: ~ ";
+        }
+        ss << "\n";
+      }
+    }
+#endif
+
+    if (bFilterRefSamples)
+    {
+      // generate filtered intra prediction samples
+
+            Int          stride    = uiROIWidth;
+      const Pel         *piSrcPtr  = piAdiTemp                             + (stride * uiTuHeight2); // bottom left
+            Pel         *piDestPtr = m_piYuvExt[compID][PRED_BUF_FILTERED] + (stride * uiTuHeight2); // bottom left
+
+      //------------------------------------------------
+
+      Bool useStrongIntraSmoothing = isLuma(chType) && pcCU->getSlice()->getSPS()->getUseStrongIntraSmoothing();
+
+      const Pel bottomLeft = piAdiTemp[stride * uiTuHeight2];
+      const Pel topLeft    = piAdiTemp[0];
+      const Pel topRight   = piAdiTemp[uiTuWidth2];
+
+      if (useStrongIntraSmoothing)
+      {
+#if O0043_BEST_EFFORT_DECODING
+        const Int  threshold     = 1 << (g_bitDepthInStream[chType] - 5);
+#else
+        const Int  threshold     = 1 << (g_bitDepth[chType] - 5);
+#endif
+        const Bool bilinearLeft  = abs((bottomLeft + topLeft ) - (2 * piAdiTemp[stride * uiTuHeight])) < threshold; //difference between the
+        const Bool bilinearAbove = abs((topLeft    + topRight) - (2 * piAdiTemp[         uiTuWidth ])) < threshold; //ends and the middle
+        if ((uiTuWidth < 32) || (!bilinearLeft) || (!bilinearAbove))
+          useStrongIntraSmoothing = false;
+      }
+
+      *piDestPtr = *piSrcPtr; // bottom left is not filtered
+      piDestPtr -= stride;
+      piSrcPtr  -= stride;
+
+      //------------------------------------------------
+
+      //left column (bottom to top)
+
+      if (useStrongIntraSmoothing)
+      {
+        const Int shift = g_aucConvertToBit[uiTuHeight] + 3; //log2(uiTuHeight2)
+
+        for(UInt i=1; i<uiTuHeight2; i++, piDestPtr-=stride)
+        {
+          *piDestPtr = (((uiTuHeight2 - i) * bottomLeft) + (i * topLeft) + uiTuHeight) >> shift;
+        }
+
+        piSrcPtr -= stride * (uiTuHeight2 - 1);
+      }
+      else
+      {
+        for(UInt i=1; i<uiTuHeight2; i++, piDestPtr-=stride, piSrcPtr-=stride)
+        {
+          *piDestPtr = ( piSrcPtr[stride] + 2*piSrcPtr[0] + piSrcPtr[-stride] + 2 ) >> 2;
+        }
+      }
+
+      //------------------------------------------------
+
+      //top-left
+
+      if (useStrongIntraSmoothing)
+      {
+        *piDestPtr = piSrcPtr[0];
+      }
+      else
+      {
+        *piDestPtr = ( piSrcPtr[stride] + 2*piSrcPtr[0] + piSrcPtr[1] + 2 ) >> 2;
+      }
+      piDestPtr += 1;
+      piSrcPtr  += 1;
+
+      //------------------------------------------------
+
+      //top row (left-to-right)
+
+      if (useStrongIntraSmoothing)
+      {
+        const Int shift = g_aucConvertToBit[uiTuWidth] + 3; //log2(uiTuWidth2)
+
+        for(UInt i=1; i<uiTuWidth2; i++, piDestPtr++)
+        {
+          *piDestPtr = (((uiTuWidth2 - i) * topLeft) + (i * topRight) + uiTuWidth) >> shift;
+        }
+
+        piSrcPtr += uiTuWidth2 - 1;
+      }
+      else
+      {
+        for(UInt i=1; i<uiTuWidth2; i++, piDestPtr++, piSrcPtr++)
+        {
+          *piDestPtr = ( piSrcPtr[1] + 2*piSrcPtr[0] + piSrcPtr[-1] + 2 ) >> 2;
+        }
+      }
+
+      //------------------------------------------------
+
+      *piDestPtr=*piSrcPtr; // far right is not filtered
+
+#ifdef DEBUG_STRING
+    if (DebugOptionList::DebugString_Pred.getInt()&DebugStringGetPredModeMask(MODE_INTRA))
+    {
+      ss << "###: filtered result for channel " << compID <<"\n";
+      for (UInt y=0; y<uiROIHeight; y++)
+      {
+        ss << "###: - ";
+        for (UInt x=0; x<uiROIWidth; x++)
+        {
+          if (x==0 || y==0)
+            ss << m_piYuvExt[compID][PRED_BUF_FILTERED][y*uiROIWidth + x] << ", ";
+//          if (x%16==15) ss << "\nPart size: ~ ";
+        }
+        ss << "\n";
+      }
+    }
+#endif
+
+
+    }
+  }
+  DEBUG_STRING_APPEND(sDebug, ss.str())
+}
+
+#if O0043_BEST_EFFORT_DECODING
+Void fillReferenceSamples( const Int bitDepth, const Int bitDepthDelta, TComDataCU* pcCU, const Pel* piRoiOrigin, Pel* piAdiTemp, const Bool* bNeighborFlags,
+#else
+Void fillReferenceSamples( const Int bitDepth, TComDataCU* pcCU, const Pel* piRoiOrigin, Pel* piAdiTemp, const Bool* bNeighborFlags,
+#endif
+                           const Int iNumIntraNeighbor, const Int unitWidth, const Int unitHeight, const Int iAboveUnits, const Int iLeftUnits,
+                           const UInt uiCuWidth, const UInt uiCuHeight, const UInt uiWidth, const UInt uiHeight, const Int iPicStride,
+                           const ChannelType chType, const ChromaFormat chFmt )
+{
+  const Pel* piRoiTemp;
+  Int  i, j;
+  Int  iDCValue = 1 << (bitDepth - 1);
+  const Int iTotalUnits = iAboveUnits + iLeftUnits + 1; //+1 for top-left
+
+  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 and top and top right with rec. samples
+    piRoiTemp = piRoiOrigin - iPicStride - 1;
+
+    for (i=0; i<uiWidth; i++)
+    {
+#if O0043_BEST_EFFORT_DECODING
+      piAdiTemp[i] = piRoiTemp[i] << bitDepthDelta;
+#else
+      piAdiTemp[i] = piRoiTemp[i];
+#endif
+    }
+
+    // Fill left and below left border with rec. samples
+    piRoiTemp = piRoiOrigin - 1;
+
+    for (i=1; i<uiHeight; i++)
+    {
+#if O0043_BEST_EFFORT_DECODING
+      piAdiTemp[i*uiWidth] = (*(piRoiTemp)) << bitDepthDelta;
+#else
+      piAdiTemp[i*uiWidth] = *(piRoiTemp);
+#endif
+      piRoiTemp += iPicStride;
+    }
+  }
+  else // reference samples are partially available
+  {
+    // all above units have "unitWidth" samples each, all left/below-left units have "unitHeight" samples each
+    const Int  iTotalSamples = (iLeftUnits * unitHeight) + ((iAboveUnits + 1) * unitWidth);
+    Pel  piAdiLine[5 * MAX_CU_SIZE];
+    Pel  *piAdiLineTemp;
+    const Bool *pbNeighborFlags;
+
+
+    // Initialize
+    for (i=0; i<iTotalSamples; i++)
+    {
+      piAdiLine[i] = iDCValue;
+    }
+
+    // Fill top-left sample
+    piRoiTemp = piRoiOrigin - iPicStride - 1;
+    piAdiLineTemp = piAdiLine + (iLeftUnits * unitHeight);
+    pbNeighborFlags = bNeighborFlags + iLeftUnits;
+    if (*pbNeighborFlags)
+    {
+#if O0043_BEST_EFFORT_DECODING
+      Pel topLeftVal=piRoiTemp[0] << bitDepthDelta;
+#else
+      Pel topLeftVal=piRoiTemp[0];
+#endif
+      for (i=0; i<unitWidth; i++)
+      {
+        piAdiLineTemp[i] = topLeftVal;
+      }
+    }
+
+    // Fill left & below-left samples (downwards)
+    piRoiTemp += iPicStride;
+    piAdiLineTemp--;
+    pbNeighborFlags--;
+
+    for (j=0; j<iLeftUnits; j++)
+    {
+      if (*pbNeighborFlags)
+      {
+        for (i=0; i<unitHeight; i++)
+        {
+#if O0043_BEST_EFFORT_DECODING
+          piAdiLineTemp[-i] = piRoiTemp[i*iPicStride] << bitDepthDelta;
+#else
+          piAdiLineTemp[-i] = piRoiTemp[i*iPicStride];
+#endif
+        }
+      }
+      piRoiTemp += unitHeight*iPicStride;
+      piAdiLineTemp -= unitHeight;
+      pbNeighborFlags--;
+    }
+
+    // Fill above & above-right samples (left-to-right) (each unit has "unitWidth" samples)
+    piRoiTemp = piRoiOrigin - iPicStride;
+    // offset line buffer by iNumUints2*unitHeight (for left/below-left) + unitWidth (for above-left)
+    piAdiLineTemp = piAdiLine + (iLeftUnits * unitHeight) + unitWidth;
+    pbNeighborFlags = bNeighborFlags + iLeftUnits + 1;
+    for (j=0; j<iAboveUnits; j++)
+    {
+      if (*pbNeighborFlags)
+      {
+        for (i=0; i<unitWidth; i++)
+        {
+#if O0043_BEST_EFFORT_DECODING
+          piAdiLineTemp[i] = piRoiTemp[i] << bitDepthDelta;
+#else
+          piAdiLineTemp[i] = piRoiTemp[i];
+#endif
+        }
+      }
+      piRoiTemp += unitWidth;
+      piAdiLineTemp += unitWidth;
+      pbNeighborFlags++;
+    }
+
+    // Pad reference samples when necessary
+    Int iCurrJnit = 0;
+    Pel  *piAdiLineCur   = piAdiLine;
+    const UInt piAdiLineTopRowOffset = iLeftUnits * (unitHeight - unitWidth);
+
+    if (!bNeighborFlags[0])
+    {
+      // very bottom unit of bottom-left; at least one unit will be valid.
+      {
+        Int   iNext = 1;
+        while (iNext < iTotalUnits && !bNeighborFlags[iNext])
+        {
+          iNext++;
+        }
+        Pel *piAdiLineNext = piAdiLine + ((iNext < iLeftUnits) ? (iNext * unitHeight) : (piAdiLineTopRowOffset + (iNext * unitWidth)));
+        const Pel refSample = *piAdiLineNext;
+        // Pad unavailable samples with new value
+        Int iNextOrTop = std::min<Int>(iNext, iLeftUnits);
+        // fill left column
+        while (iCurrJnit < iNextOrTop)
+        {
+          for (i=0; i<unitHeight; i++)
+          {
+            piAdiLineCur[i] = refSample;
+          }
+          piAdiLineCur += unitHeight;
+          iCurrJnit++;
+        }
+        // fill top row
+        while (iCurrJnit < iNext)
+        {
+          for (i=0; i<unitWidth; i++)
+          {
+            piAdiLineCur[i] = refSample;
+          }
+          piAdiLineCur += unitWidth;
+          iCurrJnit++;
+        }
+      }
+    }
+
+    // pad all other reference samples.
+    while (iCurrJnit < iTotalUnits)
+    {
+      if (!bNeighborFlags[iCurrJnit]) // samples not available
+      {
+        {
+          const Int numSamplesInCurrUnit = (iCurrJnit >= iLeftUnits) ? unitWidth : unitHeight;
+          const Pel refSample = *(piAdiLineCur-1);
+          for (i=0; i<numSamplesInCurrUnit; i++)
+          {
+            piAdiLineCur[i] = refSample;
+          }
+          piAdiLineCur += numSamplesInCurrUnit;
+          iCurrJnit++;
+        }
+      }
+      else
+      {
+        piAdiLineCur += (iCurrJnit >= iLeftUnits) ? unitWidth : unitHeight;
+        iCurrJnit++;
+      }
+    }
+
+    // Copy processed samples
+
+    piAdiLineTemp = piAdiLine + uiHeight + unitWidth - 2;
+    // top left, top and top right samples
+    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];
+    }
+  }
+}
+
+/** 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.
+ */
+
+Bool TComPrediction::filteringIntraReferenceSamples(const ComponentID compID, UInt uiDirMode, UInt uiTuChWidth, UInt uiTuChHeight, const ChromaFormat chFmt, const Bool intraReferenceSmoothingDisabled)
+{
+  Bool bFilter;
+
+  if (!filterIntraReferenceSamples(toChannelType(compID), chFmt, intraReferenceSmoothingDisabled))
+  {
+    bFilter=false;
+  }
+  else
+  {
+    assert(uiTuChWidth>=4 && uiTuChHeight>=4 && uiTuChWidth<128 && uiTuChHeight<128);
+
+    if (uiDirMode == DC_IDX)
+    {
+      bFilter=false; //no smoothing for DC or LM chroma
+    }
+    else
+    {
+      Int diff = min<Int>(abs((Int) uiDirMode - HOR_IDX), abs((Int)uiDirMode - VER_IDX));
+      UInt sizeIndex=g_aucConvertToBit[uiTuChWidth];
+      assert(sizeIndex < MAX_INTRA_FILTER_DEPTHS);
+      bFilter = diff > m_aucIntraFilter[toChannelType(compID)][sizeIndex];
+    }
+  }
+  return bFilter;
+}
+
+Bool isAboveLeftAvailable( TComDataCU* pcCU, UInt uiPartIdxLT )
+{
+  Bool bAboveLeftFlag;
+  UInt uiPartAboveLeft;
+  TComDataCU* pcCUAboveLeft = pcCU->getPUAboveLeft( uiPartAboveLeft, uiPartIdxLT );
+  if(pcCU->getSlice()->getPPS()->getConstrainedIntraPred())
+  {
+    bAboveLeftFlag = ( pcCUAboveLeft && pcCUAboveLeft->isIntra( uiPartAboveLeft ) );
+  }
+  else
+  {
+    bAboveLeftFlag = (pcCUAboveLeft ? true : false);
+  }
+  return bAboveLeftFlag;
+}
+
+Int 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->isIntra( uiPartAbove ) )
+      {
+        iNumIntra++;
+        *pbValidFlags = true;
+      }
+      else
+      {
+        *pbValidFlags = false;
+      }
+    }
+    else
+    {
+      if (pcCUAbove)
+      {
+        iNumIntra++;
+        *pbValidFlags = true;
+      }
+      else
+      {
+        *pbValidFlags = false;
+      }
+    }
+    pbValidFlags++;
+  }
+  return iNumIntra;
+}
+
+Int 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()->getNumPartInCtuWidth();
+  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->isIntra( uiPartLeft ) )
+      {
+        iNumIntra++;
+        *pbValidFlags = true;
+      }
+      else
+      {
+        *pbValidFlags = false;
+      }
+    }
+    else
+    {
+      if ( pcCULeft )
+      {
+        iNumIntra++;
+        *pbValidFlags = true;
+      }
+      else
+      {
+        *pbValidFlags = false;
+      }
+    }
+    pbValidFlags--; // opposite direction
+  }
+
+  return iNumIntra;
+}
+
+Int 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->isIntra( uiPartAboveRight ) )
+      {
+        iNumIntra++;
+        *pbValidFlags = true;
+      }
+      else
+      {
+        *pbValidFlags = false;
+      }
+    }
+    else
+    {
+      if ( pcCUAboveRight )
+      {
+        iNumIntra++;
+        *pbValidFlags = true;
+      }
+      else
+      {
+        *pbValidFlags = false;
+      }
+    }
+    pbValidFlags++;
+  }
+
+  return iNumIntra;
+}
+
+Int isBelowLeftAvailable( TComDataCU* pcCU, UInt uiPartIdxLT, UInt uiPartIdxLB, Bool *bValidFlags )
+{
+  const UInt uiNumUnitsInPU = (g_auiZscanToRaster[uiPartIdxLB] - g_auiZscanToRaster[uiPartIdxLT]) / pcCU->getPic()->getNumPartInCtuWidth() + 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->isIntra( uiPartBelowLeft ) )
+      {
+        iNumIntra++;
+        *pbValidFlags = true;
+      }
+      else
+      {
+        *pbValidFlags = false;
+      }
+    }
+    else
+    {
+      if ( pcCUBelowLeft )
+      {
+        iNumIntra++;
+        *pbValidFlags = true;
+      }
+      else
+      {
+        *pbValidFlags = false;
+      }
+    }
+    pbValidFlags--; // opposite direction
+  }
+
+  return iNumIntra;
+}
+//! \}
Index: /tags/SHM-9.0/source/Lib/TLibCommon/TComPattern.h
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibCommon/TComPattern.h	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibCommon/TComPattern.h	(revision 1088)
@@ -0,0 +1,114 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TComPattern.h
+    \brief    neighbouring pixel access classes (header)
+*/
+
+#ifndef __TCOMPATTERN__
+#define __TCOMPATTERN__
+
+// Include files
+#include <stdio.h>
+#include "CommonDef.h"
+#include <string>
+
+//! \ingroup TLibCommon
+//! \{
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+class TComDataCU;
+class TComTU;
+
+/// neighbouring pixel access class for one component
+class TComPatternParam
+{
+private:
+  Pel*  m_piROIOrigin;
+
+public:
+  Int   m_iROIWidth;
+  Int   m_iROIHeight;
+  Int   m_iPatternStride;
+
+  /// return starting position of ROI (ROI = &pattern[AboveOffset][LeftOffset])
+  __inline Pel*  getROIOrigin()
+  {
+    return  m_piROIOrigin;
+  }
+
+  /// set parameters from Pel buffer for accessing neighbouring pixels
+  Void setPatternParamPel (Pel*        piTexture,
+                           Int         iRoiWidth,
+                           Int         iRoiHeight,
+                           Int         iStride
+                           );
+};
+
+/// neighbouring pixel access class for all components
+class TComPattern
+{
+private:
+  TComPatternParam  m_cPatternY;
+//  TComPatternParam  m_cPatternCb;
+  //TComPatternParam  m_cPatternCr;
+
+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;  }
+
+  // -------------------------------------------------------------------------------------------------------------------
+  // initialization functions
+  // -------------------------------------------------------------------------------------------------------------------
+
+  /// set parameters from Pel buffers for accessing neighbouring pixels
+  Void initPattern            (Pel*        piY,
+                               Int         iRoiWidth,
+                               Int         iRoiHeight,
+                               Int         iStride );
+
+
+
+
+};
+
+//! \}
+
+#endif // __TCOMPATTERN__
Index: /tags/SHM-9.0/source/Lib/TLibCommon/TComPic.cpp
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibCommon/TComPic.cpp	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibCommon/TComPic.cpp	(revision 1088)
@@ -0,0 +1,414 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TComPic.cpp
+    \brief    picture class
+*/
+
+#include "TComPic.h"
+#include "SEI.h"
+
+//! \ingroup TLibCommon
+//! \{
+
+// ====================================================================================================================
+// Constructor / destructor / create / destroy
+// ====================================================================================================================
+
+TComPic::TComPic()
+: m_uiTLayer                              (0)
+, m_bUsedByCurr                           (false)
+, m_bIsLongTerm                           (false)
+, m_apcPicSym                             (NULL)
+, m_pcPicYuvPred                          (NULL)
+, m_pcPicYuvResi                          (NULL)
+, m_bReconstructed                        (false)
+, m_bNeededForOutput                      (false)
+, m_uiCurrSliceIdx                        (0)
+, m_bCheckLTMSB                           (false)
+#if SVC_EXTENSION
+, m_layerId( 0 )
+#endif
+{
+#if SVC_EXTENSION
+  memset( m_pcFullPelBaseRec, 0, sizeof( m_pcFullPelBaseRec ) );
+  memset( m_bSpatialEnhLayer, false, sizeof( m_bSpatialEnhLayer ) );
+  memset( m_equalPictureSizeAndOffsetFlag, false, sizeof( m_equalPictureSizeAndOffsetFlag ) );
+#endif
+  for(UInt i=0; i<NUM_PIC_YUV; i++)
+  {
+    m_apcPicYuv[i]      = NULL;
+  }
+}
+
+TComPic::~TComPic()
+{
+}
+#if SVC_EXTENSION
+Void TComPic::create( Int iWidth, Int iHeight, ChromaFormat chromaFormatIDC, UInt uiMaxWidth, UInt uiMaxHeight, UInt uiMaxDepth, Window &conformanceWindow, Window &defaultDisplayWindow,
+                      Int *numReorderPics, TComSPS* pcSps, Bool bIsVirtual)
+{
+  m_apcPicSym     = new TComPicSym;  m_apcPicSym   ->create( chromaFormatIDC, iWidth, iHeight, uiMaxWidth, uiMaxHeight, uiMaxDepth );
+  if (!bIsVirtual)
+  {
+#if R0156_CONF_WINDOW_IN_REP_FORMAT
+    m_apcPicYuv[PIC_YUV_ORG]  = new TComPicYuv;  m_apcPicYuv[PIC_YUV_ORG]->create( iWidth, iHeight, chromaFormatIDC, uiMaxWidth, uiMaxHeight, uiMaxDepth, &conformanceWindow );
+#else
+    m_apcPicYuv[PIC_YUV_ORG]  = new TComPicYuv;  m_apcPicYuv[PIC_YUV_ORG]->create( iWidth, iHeight, chromaFormatIDC, uiMaxWidth, uiMaxHeight, uiMaxDepth, pcSps );
+#endif
+#if R0156_CONF_WINDOW_IN_REP_FORMAT
+    m_apcPicYuv[PIC_YUV_TRUE_ORG]  = new TComPicYuv;  m_apcPicYuv[PIC_YUV_TRUE_ORG]->create( iWidth, iHeight, chromaFormatIDC, uiMaxWidth, uiMaxHeight, uiMaxDepth, &conformanceWindow );
+#else
+    m_apcPicYuv[PIC_YUV_TRUE_ORG]  = new TComPicYuv;  m_apcPicYuv[PIC_YUV_TRUE_ORG]->create( iWidth, iHeight, chromaFormatIDC, uiMaxWidth, uiMaxHeight, uiMaxDepth, pcSps );
+#endif
+  }
+#if R0156_CONF_WINDOW_IN_REP_FORMAT
+  m_apcPicYuv[PIC_YUV_REC]  = new TComPicYuv;  m_apcPicYuv[PIC_YUV_REC]->create( iWidth, iHeight, chromaFormatIDC, uiMaxWidth, uiMaxHeight, uiMaxDepth, &conformanceWindow );
+#else
+  m_apcPicYuv[PIC_YUV_REC]  = new TComPicYuv;  m_apcPicYuv[PIC_YUV_REC]->create( iWidth, iHeight, chromaFormatIDC, uiMaxWidth, uiMaxHeight, uiMaxDepth, pcSps );
+#endif
+
+  for( Int i = 0; i < MAX_LAYERS; i++ )
+  {
+    if( m_bSpatialEnhLayer[i] )
+    {
+#if R0156_CONF_WINDOW_IN_REP_FORMAT
+      m_pcFullPelBaseRec[i] = new TComPicYuv;  m_pcFullPelBaseRec[i]->create( iWidth, iHeight, chromaFormatIDC, uiMaxWidth, uiMaxHeight, uiMaxDepth, &conformanceWindow );
+#else
+      m_pcFullPelBaseRec[i] = new TComPicYuv;  m_pcFullPelBaseRec[i]->create( iWidth, iHeight, chromaFormatIDC, uiMaxWidth, uiMaxHeight, uiMaxDepth, pcSps );
+#endif
+    }
+  }
+
+  m_layerId = pcSps ? pcSps->getLayerId() : 0;
+
+  // 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;
+}
+#else
+Void TComPic::create( Int iWidth, Int iHeight, ChromaFormat chromaFormatIDC, UInt uiMaxWidth, UInt uiMaxHeight, UInt uiMaxDepth, Window &conformanceWindow, Window &defaultDisplayWindow,
+                      Int *numReorderPics, Bool bIsVirtual)
+{
+  m_apcPicSym     = new TComPicSym;  m_apcPicSym   ->create( chromaFormatIDC, iWidth, iHeight, uiMaxWidth, uiMaxHeight, uiMaxDepth );
+  if (!bIsVirtual)
+  {
+    m_apcPicYuv[PIC_YUV_ORG]  = new TComPicYuv;  m_apcPicYuv[PIC_YUV_ORG]->create( iWidth, iHeight, chromaFormatIDC, uiMaxWidth, uiMaxHeight, uiMaxDepth );
+    m_apcPicYuv[PIC_YUV_TRUE_ORG]  = new TComPicYuv;  m_apcPicYuv[PIC_YUV_TRUE_ORG]->create( iWidth, iHeight, chromaFormatIDC, uiMaxWidth, uiMaxHeight, uiMaxDepth );
+  }
+  m_apcPicYuv[PIC_YUV_REC]  = new TComPicYuv;  m_apcPicYuv[PIC_YUV_REC]->create( iWidth, iHeight, chromaFormatIDC, 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;
+}
+#endif
+
+Void TComPic::destroy()
+{
+  if (m_apcPicSym)
+  {
+    m_apcPicSym->destroy();
+    delete m_apcPicSym;
+    m_apcPicSym = NULL;
+  }
+
+  for(UInt i=0; i<NUM_PIC_YUV; i++)
+  {
+    if (m_apcPicYuv[i])
+    {
+      m_apcPicYuv[i]->destroy();
+      delete m_apcPicYuv[i];
+      m_apcPicYuv[i]  = NULL;
+    }
+  }
+
+  deleteSEIs(m_SEIs);
+#if SVC_EXTENSION
+  for( Int i = 0; i < MAX_LAYERS; i++ )
+  {
+    if( m_bSpatialEnhLayer[i] && m_pcFullPelBaseRec[i] )
+    {
+      m_pcFullPelBaseRec[i]->destroy();
+      delete m_pcFullPelBaseRec[i];
+      m_pcFullPelBaseRec[i]  = NULL;
+    }
+  }
+#endif 
+}
+
+Void TComPic::compressMotion()
+{
+  TComPicSym* pPicSym = getPicSym();
+  for ( UInt uiCUAddr = 0; uiCUAddr < pPicSym->getNumberOfCtusInFrame(); uiCUAddr++ )
+  {
+    TComDataCU* pCtu = pPicSym->getCtu(uiCUAddr);
+    pCtu->compressMV();
+  }
+}
+
+Bool  TComPic::getSAOMergeAvailability(Int currAddr, Int mergeAddr)
+{
+  Bool mergeCtbInSliceSeg = (mergeAddr >= getPicSym()->getCtuTsToRsAddrMap(getCtu(currAddr)->getSlice()->getSliceCurStartCtuTsAddr()));
+  Bool mergeCtbInTile     = (getPicSym()->getTileIdxMap(mergeAddr) == getPicSym()->getTileIdxMap(currAddr));
+  return (mergeCtbInSliceSeg && mergeCtbInTile);
+}
+
+UInt TComPic::getSubstreamForCtuAddr(const UInt ctuAddr, const Bool bAddressInRaster, TComSlice *pcSlice)
+{
+  UInt subStrm;
+
+  if (pcSlice->getPPS()->getNumSubstreams() > 1) // wavefronts, and possibly tiles being used.
+  {
+    if (pcSlice->getPPS()->getEntropyCodingSyncEnabledFlag())
+    {
+      const TComPicSym &picSym            = *(getPicSym());
+      const UInt ctuRsAddr                = bAddressInRaster?ctuAddr : picSym.getCtuTsToRsAddrMap(ctuAddr);
+      const UInt frameWidthInCtus         = picSym.getFrameWidthInCtus();
+      const UInt tileIndex                = picSym.getTileIdxMap(ctuRsAddr);
+      const UInt numTileColumns           = (picSym.getNumTileColumnsMinus1()+1);
+      const TComTile *pTile               = picSym.getTComTile(tileIndex);
+      const UInt firstCtuRsAddrOfTile     = pTile->getFirstCtuRsAddr();
+      const UInt tileYInCtus              = firstCtuRsAddrOfTile / frameWidthInCtus;
+      // independent tiles => substreams are "per tile"
+      const UInt ctuLine                  = ctuRsAddr / frameWidthInCtus;
+      const UInt startingSubstreamForTile =(tileYInCtus*numTileColumns) + (pTile->getTileHeightInCtus()*(tileIndex%numTileColumns));
+      subStrm = startingSubstreamForTile + (ctuLine - tileYInCtus);
+    }
+    else
+    {
+      const TComPicSym &picSym            = *(getPicSym());
+      const UInt ctuRsAddr                = bAddressInRaster?ctuAddr : picSym.getCtuTsToRsAddrMap(ctuAddr);
+      const UInt tileIndex                = picSym.getTileIdxMap(ctuRsAddr);
+      subStrm=tileIndex;
+    }
+  }
+  else
+  {
+    // dependent tiles => substreams are "per frame".
+    subStrm = 0;
+  }
+  return subStrm;
+}
+
+#if SVC_EXTENSION
+Void copyOnetoOnePicture(    // SVC_NONCOLL
+                  Pel *in,        
+                  Pel *out,      
+                  Int nCols,
+                  Int nRows, 
+                  Int fullRowWidth)
+{
+  Int rX;
+
+  for (rX = 0; rX < nRows; rX++)       
+  {
+    memcpy( out, in, sizeof(Pel) * nCols );
+    in = in + fullRowWidth;
+    out = out + fullRowWidth;
+  }
+}
+
+Void TComPic::copyUpsampledPictureYuv(TComPicYuv*   pcPicYuvIn, TComPicYuv*   pcPicYuvOut)
+{
+  Int upsampledRowWidthLuma = pcPicYuvOut->getStride(COMPONENT_Y); // 2 * pcPicYuvOut->getLumaMargin() + pcPicYuvOut->getWidth(); 
+  Int upsampledRowWidthCroma = pcPicYuvOut->getStride(COMPONENT_Cb); //2 * pcPicYuvOut->getChromaMargin() + (pcPicYuvOut->getWidth()>>1);
+
+  copyOnetoOnePicture(
+    pcPicYuvIn->getAddr(COMPONENT_Y),        
+    pcPicYuvOut->getAddr(COMPONENT_Y),      
+    pcPicYuvOut->getWidth(COMPONENT_Y), 
+    pcPicYuvOut->getHeight(COMPONENT_Y),
+    upsampledRowWidthLuma);
+  copyOnetoOnePicture(
+    pcPicYuvIn->getAddr(COMPONENT_Cr),        
+    pcPicYuvOut->getAddr(COMPONENT_Cr),      
+    pcPicYuvOut->getWidth(COMPONENT_Y)>>1, 
+    pcPicYuvOut->getHeight(COMPONENT_Y)>>1,
+    upsampledRowWidthCroma);
+  copyOnetoOnePicture(
+    pcPicYuvIn->getAddr(COMPONENT_Cb),        
+    pcPicYuvOut->getAddr(COMPONENT_Cb),      
+    pcPicYuvOut->getWidth(COMPONENT_Y)>>1, 
+    pcPicYuvOut->getHeight(COMPONENT_Y)>>1,
+    upsampledRowWidthCroma);
+}
+
+#if REF_IDX_MFM
+Void TComPic::copyUpsampledMvField(UInt refLayerIdc, TComPic* pcPicBase)
+{
+  UInt numPartitions = 1<<(g_uiMaxCUDepth<<1);
+  UInt widthMinPU    = g_uiMaxCUWidth/(1<<g_uiMaxCUDepth);
+  UInt heightMinPU   = g_uiMaxCUHeight/(1<<g_uiMaxCUDepth);
+  Int  unitNum       = max (1, (Int)((16/widthMinPU)*(16/heightMinPU)) ); 
+
+  for(UInt cuIdx = 0; cuIdx < getPicSym()->getNumberOfCtusInFrame(); cuIdx++)  //each LCU
+  {
+    TComDataCU* pcCUDes = getCtu(cuIdx);
+
+    for(UInt absPartIdx = 0; absPartIdx < numPartitions; absPartIdx+=unitNum )  //each 16x16 unit
+    {
+      //pixel position of each unit in up-sampled layer
+      UInt  pelX = pcCUDes->getCUPelX() + g_auiRasterToPelX[ g_auiZscanToRaster[absPartIdx] ];
+      UInt  pelY = pcCUDes->getCUPelY() + g_auiRasterToPelY[ g_auiZscanToRaster[absPartIdx] ];
+      UInt baseCUAddr, baseAbsPartIdx;
+
+      TComDataCU *pcColCU = 0;
+      pcColCU = pcCUDes->getBaseColCU(refLayerIdc, pelX, pelY, baseCUAddr, baseAbsPartIdx, true);
+
+      if( pcColCU && pcColCU->getPredictionMode(baseAbsPartIdx) == MODE_INTER )  //base layer unit not skip and invalid mode
+      {
+        for(UInt refPicList = 0; refPicList < 2; refPicList++)  //for each reference list
+        {
+          TComMvField sMvFieldBase, sMvField;
+          pcColCU->getMvField( pcColCU, baseAbsPartIdx, (RefPicList)refPicList, sMvFieldBase);
+          pcCUDes->scaleBaseMV( refLayerIdc, sMvField, sMvFieldBase );
+
+          pcCUDes->getCUMvField((RefPicList)refPicList)->setMvField(sMvField, absPartIdx);
+          pcCUDes->setPredictionMode(absPartIdx, MODE_INTER);
+        }
+      }
+      else
+      {
+        TComMvField zeroMvField;  //zero MV and invalid reference index
+        pcCUDes->getCUMvField(REF_PIC_LIST_0)->setMvField(zeroMvField, absPartIdx);
+        pcCUDes->getCUMvField(REF_PIC_LIST_1)->setMvField(zeroMvField, absPartIdx);
+        pcCUDes->setPredictionMode(absPartIdx, MODE_INTRA);
+      }
+
+      for(UInt i = 1; i < unitNum; i++ )  
+      {
+        pcCUDes->getCUMvField(REF_PIC_LIST_0)->setMvField(pcCUDes->getCUMvField(REF_PIC_LIST_0)->getMv(absPartIdx), pcCUDes->getCUMvField(REF_PIC_LIST_0)->getRefIdx(absPartIdx), absPartIdx + i);
+        pcCUDes->getCUMvField(REF_PIC_LIST_1)->setMvField(pcCUDes->getCUMvField(REF_PIC_LIST_1)->getMv(absPartIdx), pcCUDes->getCUMvField(REF_PIC_LIST_1)->getRefIdx(absPartIdx), absPartIdx + i);
+        pcCUDes->setPredictionMode(absPartIdx+i, pcCUDes->getPredictionMode(absPartIdx));
+      }
+    }
+    memset( pcCUDes->getPartitionSize(), SIZE_2Nx2N, sizeof(Char)*numPartitions );
+  }
+}
+
+Void TComPic::initUpsampledMvField()
+{
+  UInt uiNumPartitions   = 1<<(g_uiMaxCUDepth<<1);
+
+  for(UInt cuIdx = 0; cuIdx < getPicSym()->getNumberOfCtusInFrame(); cuIdx++)  //each LCU
+  {
+    TComDataCU* pcCUDes = getCtu(cuIdx);
+    TComMvField zeroMvField;
+    for(UInt list = 0; list < 2; list++)  //each reference list
+    {
+      for(UInt i = 0; i < uiNumPartitions; i++ )  
+      {
+        pcCUDes->getCUMvField(REF_PIC_LIST_0)->setMvField(zeroMvField, i);
+        pcCUDes->getCUMvField(REF_PIC_LIST_1)->setMvField(zeroMvField, i);
+        pcCUDes->setPredictionMode(i, MODE_INTRA);
+        pcCUDes->setPartitionSize(i, SIZE_2Nx2N);
+      }
+    }
+  }
+  return;
+}
+#endif
+
+#if MFM_ENCCONSTRAINT
+Bool TComPic::checkSameRefInfo()
+{
+  Bool bSameRefInfo = true;
+  TComSlice * pSlice0 = getSlice( 0 );
+  for( UInt uSliceID = getNumAllocatedSlice() - 1 ; bSameRefInfo && uSliceID > 0 ; uSliceID-- )
+  {
+    TComSlice * pSliceN = getSlice( uSliceID );
+    if( pSlice0->getSliceType() != pSliceN->getSliceType() )
+    {
+      bSameRefInfo = false;
+    }
+    else if( pSlice0->getSliceType() != I_SLICE )
+    {
+      Int nListNum = pSlice0->getSliceType() == B_SLICE ? 2 : 1;
+      for( Int nList = 0 ; nList < nListNum ; nList++ )
+      {
+        RefPicList eRefList = ( RefPicList )nList;
+        if( pSlice0->getNumRefIdx( eRefList ) == pSliceN->getNumRefIdx( eRefList ) )
+        {
+          for( Int refIdx = pSlice0->getNumRefIdx( eRefList ) - 1 ; refIdx >= 0 ; refIdx-- )
+          {
+            if( pSlice0->getRefPic( eRefList , refIdx ) != pSliceN->getRefPic( eRefList , refIdx ) )
+            {
+              bSameRefInfo = false;
+              break;
+            }
+          }
+        }
+        else
+        {
+          bSameRefInfo = false;
+          break;
+        }
+      }
+    }
+  }
+
+  return( bSameRefInfo );  
+}
+#endif
+#endif //SVC_EXTENSION
+
+//! \}
Index: /tags/SHM-9.0/source/Lib/TLibCommon/TComPic.h
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibCommon/TComPic.h	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibCommon/TComPic.h	(revision 1088)
@@ -0,0 +1,233 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \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"
+#if AVC_BASE
+#include <fstream>
+#endif
+
+//! \ingroup TLibCommon
+//! \{
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// picture class (symbol + YUV buffers)
+
+class TComPic
+{
+public:
+  typedef enum { PIC_YUV_ORG=0, PIC_YUV_REC=1, PIC_YUV_TRUE_ORG=2, NUM_PIC_YUV=3 } PIC_YUV_T;
+     // TRUE_ORG is the input file without any pre-encoder colour space conversion (but with possible bit depth increment)
+  TComPicYuv*   getPicYuvTrueOrg()        { return  m_apcPicYuv[PIC_YUV_TRUE_ORG]; }
+
+private:
+  UInt                  m_uiTLayer;               //  Temporal layer
+  Bool                  m_bUsedByCurr;            //  Used by current picture
+  Bool                  m_bIsLongTerm;            //  IS long term picture
+  TComPicSym*           m_apcPicSym;              //  Symbol
+  TComPicYuv*           m_apcPicYuv[NUM_PIC_YUV];
+
+  TComPicYuv*           m_pcPicYuvPred;           //  Prediction
+  TComPicYuv*           m_pcPicYuvResi;           //  Residual
+  Bool                  m_bReconstructed;
+  Bool                  m_bNeededForOutput;
+  UInt                  m_uiCurrSliceIdx;         // Index of current slice
+  Bool                  m_bCheckLTMSB;
+
+  Int                   m_numReorderPics[MAX_TLAYER];
+  Window                m_conformanceWindow;
+  Window                m_defaultDisplayWindow;
+
+  Bool                  m_isTop;
+  Bool                  m_isField;
+
+  std::vector<std::vector<TComDataCU*> > m_vSliceCUDataLink;
+
+  SEIMessages  m_SEIs; ///< Any SEI messages that have been received.  If !NULL we own the object.
+#if SVC_EXTENSION
+  UInt                  m_layerId;              //  Layer ID
+  Bool                  m_bSpatialEnhLayer[MAX_LAYERS];       // whether current layer is a spatial enhancement layer,
+  TComPicYuv*           m_pcFullPelBaseRec[MAX_LAYERS];    // upsampled base layer recontruction for difference domain inter prediction
+#if REF_IDX_MFM
+  Bool                  m_equalPictureSizeAndOffsetFlag[MAX_LAYERS]; 
+#endif
+#endif
+#if Q0048_CGS_3D_ASYMLUT
+  Int                   m_nFrameBit;
+#endif
+#if POC_RESET_IDC_DECODER
+  Bool                  m_currAuFlag;
+#endif
+public:
+  TComPic();
+  virtual ~TComPic();
+  
+#if SVC_EXTENSION
+  Void          create( Int iWidth, Int iHeight, ChromaFormat chromaFormatIDC, UInt uiMaxWidth, UInt uiMaxHeight, UInt uiMaxDepth, Window &conformanceWindow, Window &defaultDisplayWindow, 
+                        Int *numReorderPics, TComSPS* pcSps = NULL, Bool bIsVirtual = false );
+#else
+  Void          create( Int iWidth, Int iHeight, ChromaFormat chromaFormatIDC, UInt uiMaxWidth, UInt uiMaxHeight, UInt uiMaxDepth, Window &conformanceWindow, Window &defaultDisplayWindow,
+                        Int *numReorderPics,Bool bIsVirtual /*= false*/ );
+#endif //SVC_EXTENSION 
+
+  virtual Void  destroy();
+
+  UInt          getTLayer() const               { return m_uiTLayer;   }
+  Void          setTLayer( UInt uiTLayer ) { m_uiTLayer = uiTLayer; }
+
+  Bool          getUsedByCurr() const            { return m_bUsedByCurr; }
+  Void          setUsedByCurr( Bool bUsed ) { m_bUsedByCurr = bUsed; }
+  Bool          getIsLongTerm() const            { 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() const        { return  m_apcPicSym->getSlice(m_uiCurrSliceIdx)->getPOC();  }
+  TComDataCU*   getCtu( UInt ctuRsAddr )           { return  m_apcPicSym->getCtu( ctuRsAddr ); }
+  const TComDataCU* getCtu( UInt ctuRsAddr ) const { return  m_apcPicSym->getCtu( ctuRsAddr ); }
+
+  TComPicYuv*   getPicYuvOrg()        { return  m_apcPicYuv[PIC_YUV_ORG]; }
+  TComPicYuv*   getPicYuvRec()        { return  m_apcPicYuv[PIC_YUV_REC]; }
+
+  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          getNumberOfCtusInFrame() const     { return m_apcPicSym->getNumberOfCtusInFrame(); }
+  UInt          getNumPartInCtuWidth() const       { return m_apcPicSym->getNumPartInCtuWidth();   }
+  UInt          getNumPartInCtuHeight() const      { return m_apcPicSym->getNumPartInCtuHeight();  }
+  UInt          getNumPartitionsInCtu() const      { return m_apcPicSym->getNumPartitionsInCtu();  }
+  UInt          getFrameWidthInCtus() const        { return m_apcPicSym->getFrameWidthInCtus();    }
+  UInt          getFrameHeightInCtus() const       { return m_apcPicSym->getFrameHeightInCtus();   }
+  UInt          getMinCUWidth() const              { return m_apcPicSym->getMinCUWidth();          }
+  UInt          getMinCUHeight() const             { return m_apcPicSym->getMinCUHeight();         }
+
+  Int           getStride(const ComponentID id) const          { return m_apcPicYuv[PIC_YUV_REC]->getStride(id); }
+  Int           getComponentScaleX(const ComponentID id) const    { return m_apcPicYuv[PIC_YUV_REC]->getComponentScaleX(id); }
+  Int           getComponentScaleY(const ComponentID id) const    { return m_apcPicYuv[PIC_YUV_REC]->getComponentScaleY(id); }
+  ChromaFormat  getChromaFormat() const                           { return m_apcPicYuv[PIC_YUV_REC]->getChromaFormat(); }
+  Int           getNumberValidComponents() const                  { return m_apcPicYuv[PIC_YUV_REC]->getNumberValidComponents(); }
+
+  Void          setReconMark (Bool b) { m_bReconstructed = b;     }
+  Bool          getReconMark () const      { return m_bReconstructed;  }
+  Void          setOutputMark (Bool b) { m_bNeededForOutput = b;     }
+  Bool          getOutputMark () const      { 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() const           { return m_uiCurrSliceIdx;                }
+  Void          setCurrSliceIdx(UInt i)      { m_uiCurrSliceIdx = i;                   }
+  UInt          getNumAllocatedSlice() const      {return m_apcPicSym->getNumAllocatedSlice();}
+  Void          allocateNewSlice()           {m_apcPicSym->allocateNewSlice();         }
+  Void          clearSliceBuffer()           {m_apcPicSym->clearSliceBuffer();         }
+
+  Window&       getConformanceWindow()  { return m_conformanceWindow; }
+  Window&       getDefDisplayWindow()   { return m_defaultDisplayWindow; }
+
+  Bool          getSAOMergeAvailability(Int currAddr, Int mergeAddr);
+
+  UInt          getSubstreamForCtuAddr(const UInt ctuAddr, const Bool bAddressInRaster, TComSlice *pcSlice);
+
+  /* field coding parameters*/
+
+   Void              setTopField(Bool b)                  {m_isTop = b;}
+   Bool              isTopField()                         {return m_isTop;}
+   Void              setField(Bool b)                     {m_isField = b;}
+   Bool              isField()                            {return m_isField;}
+
+  /** 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; }
+
+#if SVC_EXTENSION
+  Void          setLayerId (UInt layerId)   { m_layerId = layerId; }
+  UInt          getLayerId ()               { return m_layerId; }
+  UInt          getLayerIdx()               { return getSlice(0)->getVPS()->getLayerIdxInVps(m_layerId); }
+  Bool          isSpatialEnhLayer(UInt refLayerIdc)             { return m_bSpatialEnhLayer[refLayerIdc]; }
+  Void          setSpatialEnhLayerFlag (UInt refLayerIdc, Bool b) { m_bSpatialEnhLayer[refLayerIdc] = b; }
+  Void          setFullPelBaseRec   (UInt refLayerIdc, TComPicYuv* p) { m_pcFullPelBaseRec[refLayerIdc] = p; }
+  TComPicYuv*   getFullPelBaseRec   (UInt refLayerIdc)  { return  m_pcFullPelBaseRec[refLayerIdc];  }
+#if REF_IDX_ME_ZEROMV || ENCODER_FAST_MODE || REF_IDX_MFM
+  Bool          isILR( UInt currLayerId )   { return ( m_bIsLongTerm && m_layerId < currLayerId ); }
+#endif
+#if REF_IDX_MFM
+  Bool          equalPictureSizeAndOffsetFlag(UInt refLayerIdc)             { return m_equalPictureSizeAndOffsetFlag[refLayerIdc]; }
+  Void          setEqualPictureSizeAndOffsetFlag(UInt refLayerIdc, Bool b)  { m_equalPictureSizeAndOffsetFlag[refLayerIdc] = b;    }
+  Void          copyUpsampledMvField  ( UInt refLayerIdc, TComPic* pcPicBase );
+  Void          initUpsampledMvField  ();
+#endif
+#if MFM_ENCCONSTRAINT
+  Bool          checkSameRefInfo();
+#endif
+  Void          copyUpsampledPictureYuv(TComPicYuv*   pcPicYuvIn, TComPicYuv*   pcPicYuvOut); 
+#if Q0048_CGS_3D_ASYMLUT
+  Void          setFrameBit( Int n )  { m_nFrameBit = n;    }
+  Int           getFrameBit()         { return m_nFrameBit; }
+#endif
+#if POC_RESET_IDC_DECODER
+  Bool          isCurrAu() { return m_currAuFlag; }
+  Void          setCurrAuFlag(Bool x) {m_currAuFlag = x; }
+#endif
+#endif //SVC_EXTENSION
+};// END CLASS DEFINITION TComPic
+
+//! \}
+
+#endif // __TCOMPIC__
Index: /tags/SHM-9.0/source/Lib/TLibCommon/TComPicSym.cpp
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibCommon/TComPicSym.cpp	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibCommon/TComPicSym.cpp	(revision 1088)
@@ -0,0 +1,501 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TComPicSym.cpp
+    \brief    picture symbol class
+*/
+
+#include "TComPicSym.h"
+#include "TComSampleAdaptiveOffset.h"
+#include "TComSlice.h"
+
+//! \ingroup TLibCommon
+//! \{
+
+// ====================================================================================================================
+// Constructor / destructor / create / destroy
+// ====================================================================================================================
+
+TComPicSym::TComPicSym()
+:m_frameWidthInCtus(0)
+,m_frameHeightInCtus(0)
+,m_uiMaxCUWidth(0)
+,m_uiMaxCUHeight(0)
+,m_uiMinCUWidth(0)
+,m_uiMinCUHeight(0)
+,m_uhTotalDepth(0)
+,m_numPartitionsInCtu(0)
+,m_numPartInCtuWidth(0)
+,m_numPartInCtuHeight(0)
+,m_numCtusInFrame(0)
+,m_apcTComSlice(NULL)
+,m_uiNumAllocatedSlice(0)
+,m_pictureCtuArray(NULL)
+,m_numTileColumnsMinus1(0)
+,m_numTileRowsMinus1(0)
+,m_ctuTsToRsAddrMap(NULL)
+,m_puiTileIdxMap(NULL)
+,m_ctuRsToTsAddrMap(NULL)
+,m_saoBlkParams(NULL)
+{}
+
+
+Void TComPicSym::create  ( ChromaFormat chromaFormatIDC, Int iPicWidth, Int iPicHeight, UInt uiMaxWidth, UInt uiMaxHeight, UInt uiMaxDepth )
+{
+  UInt i;
+
+  m_uhTotalDepth       = uiMaxDepth;
+  m_numPartitionsInCtu = 1<<(m_uhTotalDepth<<1);
+
+  m_uiMaxCUWidth       = uiMaxWidth;
+  m_uiMaxCUHeight      = uiMaxHeight;
+
+  m_uiMinCUWidth       = uiMaxWidth  >> m_uhTotalDepth;
+  m_uiMinCUHeight      = uiMaxHeight >> m_uhTotalDepth;
+
+  m_numPartInCtuWidth  = m_uiMaxCUWidth  / m_uiMinCUWidth;  // equivalent to 1<<m_uhTotalDepth
+  m_numPartInCtuHeight = m_uiMaxCUHeight / m_uiMinCUHeight; // equivalent to 1<<m_uhTotalDepth
+
+  m_frameWidthInCtus   = ( iPicWidth %m_uiMaxCUWidth  ) ? iPicWidth /m_uiMaxCUWidth  + 1 : iPicWidth /m_uiMaxCUWidth;
+  m_frameHeightInCtus  = ( iPicHeight%m_uiMaxCUHeight ) ? iPicHeight/m_uiMaxCUHeight + 1 : iPicHeight/m_uiMaxCUHeight;
+
+  m_numCtusInFrame     = m_frameWidthInCtus * m_frameHeightInCtus;
+  m_pictureCtuArray    = new TComDataCU*[m_numCtusInFrame];
+
+  if (m_uiNumAllocatedSlice>0)
+  {
+    for ( i=0; i<m_uiNumAllocatedSlice ; i++ )
+    {
+      delete m_apcTComSlice[i];
+    }
+    delete [] m_apcTComSlice;
+  }
+  m_apcTComSlice      = new TComSlice*[m_numCtusInFrame];
+  m_apcTComSlice[0]   = new TComSlice;
+  m_uiNumAllocatedSlice = 1;
+  for ( i=0; i<m_numCtusInFrame ; i++ )
+  {
+    m_pictureCtuArray[i] = new TComDataCU;
+    m_pictureCtuArray[i]->create( chromaFormatIDC, m_numPartitionsInCtu, m_uiMaxCUWidth, m_uiMaxCUHeight, false, m_uiMaxCUWidth >> m_uhTotalDepth
+#if ADAPTIVE_QP_SELECTION
+      , true
+#endif
+      );
+  }
+
+  m_ctuTsToRsAddrMap = new UInt[m_numCtusInFrame+1];
+  m_puiTileIdxMap    = new UInt[m_numCtusInFrame];
+  m_ctuRsToTsAddrMap = new UInt[m_numCtusInFrame+1];
+
+#if N0383_IL_CONSTRAINED_TILE_SETS_SEI
+  m_piTileSetIdxMap = new Int[m_numCtusInFrame];
+  m_pucTileSetType = new UChar[m_numCtusInFrame];
+  m_pbSkippedTileSetFlag = new Bool[m_numCtusInFrame];
+#endif  
+
+  for( i=0; i<m_numCtusInFrame; i++ )
+  {
+    m_ctuTsToRsAddrMap[i] = i;
+    m_ctuRsToTsAddrMap[i] = i;
+  }
+
+  m_saoBlkParams = new SAOBlkParam[m_numCtusInFrame];
+}
+
+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_numCtusInFrame; i++)
+  {
+    m_pictureCtuArray[i]->destroy();
+    delete m_pictureCtuArray[i];
+    m_pictureCtuArray[i] = NULL;
+  }
+  delete [] m_pictureCtuArray;
+  m_pictureCtuArray = NULL;
+
+  delete [] m_ctuTsToRsAddrMap;
+  m_ctuTsToRsAddrMap = NULL;
+
+  delete [] m_puiTileIdxMap;
+  m_puiTileIdxMap = NULL;
+#if N0383_IL_CONSTRAINED_TILE_SETS_SEI
+  delete [] m_piTileSetIdxMap;
+  m_piTileSetIdxMap = NULL;
+  delete [] m_pucTileSetType;
+  m_pucTileSetType = NULL;
+  delete [] m_pbSkippedTileSetFlag;
+  m_pbSkippedTileSetFlag = NULL;
+#endif
+
+  delete [] m_ctuRsToTsAddrMap;
+  m_ctuRsToTsAddrMap = NULL;
+
+  if(m_saoBlkParams)
+  {
+    delete[] m_saoBlkParams; m_saoBlkParams = NULL;
+  }
+}
+
+Void TComPicSym::allocateNewSlice()
+{
+  assert ((m_uiNumAllocatedSlice + 1) <= m_numCtusInFrame);
+  m_apcTComSlice[m_uiNumAllocatedSlice ++] = new TComSlice;
+  if (m_uiNumAllocatedSlice>=2)
+  {
+    m_apcTComSlice[m_uiNumAllocatedSlice-1]->copySliceInfo( m_apcTComSlice[m_uiNumAllocatedSlice-2] );
+#if SVC_EXTENSION
+    m_apcTComSlice[m_uiNumAllocatedSlice-1]->initSlice( m_apcTComSlice[m_uiNumAllocatedSlice-1]->getLayerId() );
+#else
+    m_apcTComSlice[m_uiNumAllocatedSlice-1]->initSlice();
+#endif
+  }
+}
+
+Void TComPicSym::clearSliceBuffer()
+{
+  UInt i;
+  for (i = 1; i < m_uiNumAllocatedSlice; i++)
+  {
+    delete m_apcTComSlice[i];
+  }
+  m_uiNumAllocatedSlice = 1;
+}
+
+Void TComPicSym::initCtuTsRsAddrMaps()
+{
+  //generate the Coding Order Map and Inverse Coding Order Map
+  for(Int ctuTsAddr=0, ctuRsAddr=0; ctuTsAddr<getNumberOfCtusInFrame(); ctuTsAddr++, ctuRsAddr = xCalculateNextCtuRSAddr(ctuRsAddr))
+  {
+    setCtuTsToRsAddrMap(ctuTsAddr, ctuRsAddr);
+    setCtuRsToTsAddrMap(ctuRsAddr, ctuTsAddr);
+  }
+  setCtuTsToRsAddrMap(getNumberOfCtusInFrame(), getNumberOfCtusInFrame());
+  setCtuRsToTsAddrMap(getNumberOfCtusInFrame(), getNumberOfCtusInFrame());
+}
+
+Void TComPicSym::initTiles(TComPPS *pps)
+{
+  //set NumColumnsMinus1 and NumRowsMinus1
+  setNumTileColumnsMinus1( pps->getNumTileColumnsMinus1() );
+  setNumTileRowsMinus1(    pps->getNumTileRowsMinus1()    );
+
+  const Int numCols = pps->getNumTileColumnsMinus1() + 1;
+  const Int numRows = pps->getNumTileRowsMinus1() + 1;
+  const Int numTiles = numRows * numCols;
+
+  // allocate memory for tile parameters
+  m_tileParameters.resize(numTiles);
+
+  if( pps->getTileUniformSpacingFlag() )
+  {
+    //set width and height for each (uniform) tile
+    for(Int row=0; row < numRows; row++)
+    {
+      for(Int col=0; col < numCols; col++)
+      {
+        const Int tileIdx = row * numCols + col;
+        m_tileParameters[tileIdx].setTileWidthInCtus(  (col+1)*getFrameWidthInCtus( )/numCols - (col*getFrameWidthInCtus( ))/numCols );
+        m_tileParameters[tileIdx].setTileHeightInCtus( (row+1)*getFrameHeightInCtus()/numRows - (row*getFrameHeightInCtus())/numRows );
+      }
+    }
+  }
+  else
+  {
+    //set the width for each tile
+    for(Int row=0; row < numRows; row++)
+    {
+      Int cumulativeTileWidth = 0;
+      for(Int col=0; col < getNumTileColumnsMinus1(); col++)
+      {
+        m_tileParameters[row * numCols + col].setTileWidthInCtus( pps->getTileColumnWidth(col) );
+        cumulativeTileWidth += pps->getTileColumnWidth(col);
+      }
+      m_tileParameters[row * numCols + getNumTileColumnsMinus1()].setTileWidthInCtus( getFrameWidthInCtus()-cumulativeTileWidth );
+    }
+
+    //set the height for each tile
+    for(Int col=0; col < numCols; col++)
+    {
+      Int cumulativeTileHeight = 0;
+      for(Int row=0; row < getNumTileRowsMinus1(); row++)
+      {
+        m_tileParameters[row * numCols + col].setTileHeightInCtus( pps->getTileRowHeight(row) );
+        cumulativeTileHeight += pps->getTileRowHeight(row);
+      }
+      m_tileParameters[getNumTileRowsMinus1() * numCols + col].setTileHeightInCtus( getFrameHeightInCtus()-cumulativeTileHeight );
+    }
+  }
+
+#if TILE_SIZE_CHECK
+  Int minWidth  = 1;
+  Int minHeight = 1;
+  const Int profileIdc = pps->getSPS()->getPTL()->getGeneralPTL()->getProfileIdc();
+  if (  profileIdc == Profile::MAIN || profileIdc == Profile::MAIN10) //TODO: add more profiles to the tile-size check...
+  {
+    if (pps->getTilesEnabledFlag())
+    {
+      minHeight = 64  / g_uiMaxCUHeight;
+      minWidth  = 256 / g_uiMaxCUWidth;
+    }
+  }
+  for(Int row=0; row < numRows; row++)
+  {
+    for(Int col=0; col < numCols; col++)
+    {
+      const Int tileIdx = row * numCols + col;
+      assert (m_tileParameters[tileIdx].getTileWidthInCtus() >= minWidth);
+      assert (m_tileParameters[tileIdx].getTileHeightInCtus() >= minHeight);
+    }
+  }
+#endif
+
+  //initialize each tile of the current picture
+  for( Int row=0; row < numRows; row++ )
+  {
+    for( Int col=0; col < numCols; col++ )
+    {
+      const Int tileIdx = row * numCols + col;
+
+      //initialize the RightEdgePosInCU for each tile
+      Int rightEdgePosInCTU = 0;
+      for( Int i=0; i <= col; i++ )
+      {
+        rightEdgePosInCTU += m_tileParameters[row * numCols + i].getTileWidthInCtus();
+      }
+      m_tileParameters[tileIdx].setRightEdgePosInCtus(rightEdgePosInCTU-1);
+
+      //initialize the BottomEdgePosInCU for each tile
+      Int bottomEdgePosInCTU = 0;
+      for( Int i=0; i <= row; i++ )
+      {
+        bottomEdgePosInCTU += m_tileParameters[i * numCols + col].getTileHeightInCtus();
+      }
+      m_tileParameters[tileIdx].setBottomEdgePosInCtus(bottomEdgePosInCTU-1);
+
+      //initialize the FirstCUAddr for each tile
+      m_tileParameters[tileIdx].setFirstCtuRsAddr( (m_tileParameters[tileIdx].getBottomEdgePosInCtus() - m_tileParameters[tileIdx].getTileHeightInCtus() + 1) * getFrameWidthInCtus() +
+                                                    m_tileParameters[tileIdx].getRightEdgePosInCtus()  - m_tileParameters[tileIdx].getTileWidthInCtus()  + 1);
+    }
+  }
+
+  Int  columnIdx = 0;
+  Int  rowIdx = 0;
+
+  //initialize the TileIdxMap
+  for( Int i=0; i<m_numCtusInFrame; i++)
+  {
+    for( Int col=0; col < numCols; col++)
+    {
+      if(i % getFrameWidthInCtus() <= m_tileParameters[col].getRightEdgePosInCtus())
+      {
+        columnIdx = col;
+        break;
+      }
+    }
+    for(Int row=0; row < numRows; row++)
+    {
+      if(i / getFrameWidthInCtus() <= m_tileParameters[row*numCols].getBottomEdgePosInCtus())
+      {
+        rowIdx = row;
+        break;
+      }
+    }
+    m_puiTileIdxMap[i] = rowIdx * numCols + columnIdx;
+  }
+}
+UInt TComPicSym::xCalculateNextCtuRSAddr( UInt currCtuRsAddr )
+{
+  UInt  nextCtuRsAddr;
+
+  //get the tile index for the current CTU
+  const UInt uiTileIdx = getTileIdxMap(currCtuRsAddr);
+
+  //get the raster scan address for the next CTU
+  if( currCtuRsAddr % m_frameWidthInCtus == getTComTile(uiTileIdx)->getRightEdgePosInCtus() && currCtuRsAddr / m_frameWidthInCtus == getTComTile(uiTileIdx)->getBottomEdgePosInCtus() )
+  //the current CTU is the last CTU of the tile
+  {
+    if(uiTileIdx+1 == getNumTiles())
+    {
+      nextCtuRsAddr = m_numCtusInFrame;
+    }
+    else
+    {
+      nextCtuRsAddr = getTComTile(uiTileIdx+1)->getFirstCtuRsAddr();
+    }
+  }
+  else //the current CTU is not the last CTU of the tile
+  {
+    if( currCtuRsAddr % m_frameWidthInCtus == getTComTile(uiTileIdx)->getRightEdgePosInCtus() )  //the current CTU is on the rightmost edge of the tile
+    {
+      nextCtuRsAddr = currCtuRsAddr + m_frameWidthInCtus - getTComTile(uiTileIdx)->getTileWidthInCtus() + 1;
+    }
+    else
+    {
+      nextCtuRsAddr = currCtuRsAddr + 1;
+    }
+  }
+
+  return nextCtuRsAddr;
+}
+
+Void TComPicSym::deriveLoopFilterBoundaryAvailibility(Int ctuRsAddr,
+                                                      Bool& isLeftAvail,
+                                                      Bool& isRightAvail,
+                                                      Bool& isAboveAvail,
+                                                      Bool& isBelowAvail,
+                                                      Bool& isAboveLeftAvail,
+                                                      Bool& isAboveRightAvail,
+                                                      Bool& isBelowLeftAvail,
+                                                      Bool& isBelowRightAvail
+                                                      )
+{
+
+  isLeftAvail      = (ctuRsAddr % m_frameWidthInCtus != 0);
+  isRightAvail     = (ctuRsAddr % m_frameWidthInCtus != m_frameWidthInCtus-1);
+  isAboveAvail     = (ctuRsAddr >= m_frameWidthInCtus );
+  isBelowAvail     = (ctuRsAddr <  m_numCtusInFrame - m_frameWidthInCtus);
+  isAboveLeftAvail = (isAboveAvail && isLeftAvail);
+  isAboveRightAvail= (isAboveAvail && isRightAvail);
+  isBelowLeftAvail = (isBelowAvail && isLeftAvail);
+  isBelowRightAvail= (isBelowAvail && isRightAvail);
+
+  Bool isLoopFiltAcrossTilePPS = getCtu(ctuRsAddr)->getSlice()->getPPS()->getLoopFilterAcrossTilesEnabledFlag();
+
+  {
+    TComDataCU* ctuCurr  = getCtu(ctuRsAddr);
+    TComDataCU* ctuLeft  = isLeftAvail ?getCtu(ctuRsAddr-1):NULL;
+    TComDataCU* ctuRight = isRightAvail?getCtu(ctuRsAddr+1):NULL;
+    TComDataCU* ctuAbove = isAboveAvail?getCtu(ctuRsAddr-m_frameWidthInCtus):NULL;
+    TComDataCU* ctuBelow = isBelowAvail?getCtu(ctuRsAddr+m_frameWidthInCtus):NULL;
+    TComDataCU* ctuAboveLeft  = isAboveLeftAvail ? getCtu(ctuRsAddr-m_frameWidthInCtus-1):NULL;
+    TComDataCU* ctuAboveRight = isAboveRightAvail? getCtu(ctuRsAddr-m_frameWidthInCtus+1):NULL;
+    TComDataCU* ctuBelowLeft  = isBelowLeftAvail ? getCtu(ctuRsAddr+m_frameWidthInCtus-1):NULL;
+    TComDataCU* ctuBelowRight = isBelowRightAvail? getCtu(ctuRsAddr+m_frameWidthInCtus+1):NULL;
+
+    {
+      //left
+      if(ctuLeft != NULL)
+      {
+        isLeftAvail = (ctuCurr->getSlice()->getSliceCurStartCtuTsAddr() != ctuLeft->getSlice()->getSliceCurStartCtuTsAddr())?ctuCurr->getSlice()->getLFCrossSliceBoundaryFlag():true;
+      }
+      //above
+      if(ctuAbove != NULL)
+      {
+        isAboveAvail = (ctuCurr->getSlice()->getSliceCurStartCtuTsAddr() != ctuAbove->getSlice()->getSliceCurStartCtuTsAddr())?ctuCurr->getSlice()->getLFCrossSliceBoundaryFlag():true;
+      }
+      //right
+      if(ctuRight != NULL)
+      {
+        isRightAvail = (ctuCurr->getSlice()->getSliceCurStartCtuTsAddr() != ctuRight->getSlice()->getSliceCurStartCtuTsAddr())?ctuRight->getSlice()->getLFCrossSliceBoundaryFlag():true;
+      }
+      //below
+      if(ctuBelow != NULL)
+      {
+        isBelowAvail = (ctuCurr->getSlice()->getSliceCurStartCtuTsAddr() != ctuBelow->getSlice()->getSliceCurStartCtuTsAddr())?ctuBelow->getSlice()->getLFCrossSliceBoundaryFlag():true;
+      }
+      //above-left
+      if(ctuAboveLeft != NULL)
+      {
+        isAboveLeftAvail = (ctuCurr->getSlice()->getSliceCurStartCtuTsAddr() != ctuAboveLeft->getSlice()->getSliceCurStartCtuTsAddr())?ctuCurr->getSlice()->getLFCrossSliceBoundaryFlag():true;
+      }
+      //below-right
+      if(ctuBelowRight != NULL)
+      {
+        isBelowRightAvail = (ctuCurr->getSlice()->getSliceCurStartCtuTsAddr() != ctuBelowRight->getSlice()->getSliceCurStartCtuTsAddr())?ctuBelowRight->getSlice()->getLFCrossSliceBoundaryFlag():true;
+      }
+
+      //above-right
+      if(ctuAboveRight != NULL)
+      {
+        Int curSliceStartTsAddr  = ctuCurr->getSlice()->getSliceCurStartCtuTsAddr();
+        Int aboveRightSliceStartTsAddr = ctuAboveRight->getSlice()->getSliceCurStartCtuTsAddr();
+
+        isAboveRightAvail = (curSliceStartTsAddr == aboveRightSliceStartTsAddr)?(true):
+          (
+          (curSliceStartTsAddr > aboveRightSliceStartTsAddr)?(ctuCurr->getSlice()->getLFCrossSliceBoundaryFlag())
+          :(ctuAboveRight->getSlice()->getLFCrossSliceBoundaryFlag())
+          );
+      }
+      //below-left
+      if(ctuBelowLeft != NULL)
+      {
+        Int curSliceStartTsAddr       = ctuCurr->getSlice()->getSliceCurStartCtuTsAddr();
+        Int belowLeftSliceStartTsAddr = ctuBelowLeft->getSlice()->getSliceCurStartCtuTsAddr();
+
+        isBelowLeftAvail = (curSliceStartTsAddr == belowLeftSliceStartTsAddr)?(true):
+          (
+          (curSliceStartTsAddr > belowLeftSliceStartTsAddr)?(ctuCurr->getSlice()->getLFCrossSliceBoundaryFlag())
+          :(ctuBelowLeft->getSlice()->getLFCrossSliceBoundaryFlag())
+          );
+      }
+    }
+
+    if(!isLoopFiltAcrossTilePPS)
+    {
+      isLeftAvail      = (!isLeftAvail      ) ?false:(getTileIdxMap( ctuLeft->getCtuRsAddr()         ) == getTileIdxMap( ctuRsAddr ));
+      isAboveAvail     = (!isAboveAvail     ) ?false:(getTileIdxMap( ctuAbove->getCtuRsAddr()        ) == getTileIdxMap( ctuRsAddr ));
+      isRightAvail     = (!isRightAvail     ) ?false:(getTileIdxMap( ctuRight->getCtuRsAddr()        ) == getTileIdxMap( ctuRsAddr ));
+      isBelowAvail     = (!isBelowAvail     ) ?false:(getTileIdxMap( ctuBelow->getCtuRsAddr()        ) == getTileIdxMap( ctuRsAddr ));
+      isAboveLeftAvail = (!isAboveLeftAvail ) ?false:(getTileIdxMap( ctuAboveLeft->getCtuRsAddr()    ) == getTileIdxMap( ctuRsAddr ));
+      isAboveRightAvail= (!isAboveRightAvail) ?false:(getTileIdxMap( ctuAboveRight->getCtuRsAddr()   ) == getTileIdxMap( ctuRsAddr ));
+      isBelowLeftAvail = (!isBelowLeftAvail ) ?false:(getTileIdxMap( ctuBelowLeft->getCtuRsAddr()    ) == getTileIdxMap( ctuRsAddr ));
+      isBelowRightAvail= (!isBelowRightAvail) ?false:(getTileIdxMap( ctuBelowRight->getCtuRsAddr()   ) == getTileIdxMap( ctuRsAddr ));
+    }
+  }
+
+}
+
+
+TComTile::TComTile()
+: m_tileWidthInCtus     (0)
+, m_tileHeightInCtus    (0)
+, m_rightEdgePosInCtus  (0)
+, m_bottomEdgePosInCtus (0)
+, m_firstCtuRsAddr      (0)
+{
+}
+
+TComTile::~TComTile()
+{
+}
+//! \}
Index: /tags/SHM-9.0/source/Lib/TLibCommon/TComPicSym.h
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibCommon/TComPicSym.h	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibCommon/TComPicSym.h	(revision 1088)
@@ -0,0 +1,189 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TComPicSym.h
+    \brief    picture symbol class (header)
+*/
+
+#ifndef __TCOMPICSYM__
+#define __TCOMPICSYM__
+
+
+// Include files
+#include "CommonDef.h"
+#include "TComSlice.h"
+#include "TComDataCU.h"
+class TComSampleAdaptiveOffset;
+class TComPPS;
+
+//! \ingroup TLibCommon
+//! \{
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+class TComTile
+{
+private:
+  UInt      m_tileWidthInCtus;
+  UInt      m_tileHeightInCtus;
+  UInt      m_rightEdgePosInCtus;
+  UInt      m_bottomEdgePosInCtus;
+  UInt      m_firstCtuRsAddr;
+
+public:
+  TComTile();
+  virtual ~TComTile();
+
+  Void      setTileWidthInCtus     ( UInt i )            { m_tileWidthInCtus = i; }
+  UInt      getTileWidthInCtus     () const              { return m_tileWidthInCtus; }
+  Void      setTileHeightInCtus    ( UInt i )            { m_tileHeightInCtus = i; }
+  UInt      getTileHeightInCtus    () const              { return m_tileHeightInCtus; }
+  Void      setRightEdgePosInCtus  ( UInt i )            { m_rightEdgePosInCtus = i; }
+  UInt      getRightEdgePosInCtus  () const              { return m_rightEdgePosInCtus; }
+  Void      setBottomEdgePosInCtus ( UInt i )            { m_bottomEdgePosInCtus = i; }
+  UInt      getBottomEdgePosInCtus () const              { return m_bottomEdgePosInCtus; }
+  Void      setFirstCtuRsAddr      ( UInt i )            { m_firstCtuRsAddr = i; }
+  UInt      getFirstCtuRsAddr      () const              { return m_firstCtuRsAddr; }
+};
+
+/// picture symbol class
+class TComPicSym
+{
+private:
+  UInt          m_frameWidthInCtus;
+  UInt          m_frameHeightInCtus;
+
+  UInt          m_uiMaxCUWidth;
+  UInt          m_uiMaxCUHeight;
+  UInt          m_uiMinCUWidth;
+  UInt          m_uiMinCUHeight;
+
+  UChar         m_uhTotalDepth;       ///< max. depth
+  UInt          m_numPartitionsInCtu;
+  UInt          m_numPartInCtuWidth;
+  UInt          m_numPartInCtuHeight;
+  UInt          m_numCtusInFrame;
+
+  TComSlice**   m_apcTComSlice;
+  UInt          m_uiNumAllocatedSlice;
+  TComDataCU**  m_pictureCtuArray;        ///< array of CU data.
+
+  Int           m_numTileColumnsMinus1;
+  Int           m_numTileRowsMinus1;
+  std::vector<TComTile> m_tileParameters;
+  UInt*         m_ctuTsToRsAddrMap;    ///< for a given TS (Tile-Scan; coding order) address, returns the RS (Raster-Scan) address. cf CtbAddrTsToRs in specification.
+  UInt*         m_puiTileIdxMap;       ///< the map of the tile index relative to CTU raster scan address
+  UInt*         m_ctuRsToTsAddrMap;    ///< for a given RS (Raster-Scan) address, returns the TS (Tile-Scan; coding order) address. cf CtbAddrRsToTs in specification.
+
+  SAOBlkParam *m_saoBlkParams;
+
+#if SVC_EXTENSION
+#if N0383_IL_CONSTRAINED_TILE_SETS_SEI
+  Int*          m_piTileSetIdxMap;     //the map of the tile set index relative to LCU raster scan address
+  UChar*        m_pucTileSetType;
+  Bool*         m_pbSkippedTileSetFlag;
+#endif
+#endif
+
+public:
+  Void               create  ( ChromaFormat chromaFormatIDC, Int iPicWidth, Int iPicHeight, UInt uiMaxWidth, UInt uiMaxHeight, UInt uiMaxDepth );
+  Void               destroy ();
+
+  TComPicSym  ();
+  TComSlice*         getSlice(UInt i)                                      { return m_apcTComSlice[i];             }
+  const TComSlice*   getSlice(UInt i) const                                { return m_apcTComSlice[i];             }
+  UInt               getFrameWidthInCtus() const                           { return m_frameWidthInCtus;            }
+  UInt               getFrameHeightInCtus() const                          { return m_frameHeightInCtus;           }
+  UInt               getMinCUWidth() const                                 { return m_uiMinCUWidth;                }
+  UInt               getMinCUHeight() const                                { return m_uiMinCUHeight;               }
+  UInt               getNumberOfCtusInFrame() const                        { return m_numCtusInFrame;              }
+  TComDataCU*        getCtu( UInt ctuRsAddr )                              { return m_pictureCtuArray[ctuRsAddr];  }
+  const TComDataCU*  getCtu( UInt ctuRsAddr ) const                        { return m_pictureCtuArray[ctuRsAddr];  }
+
+  Void               setSlice(TComSlice* p, UInt i)                        { m_apcTComSlice[i] = p;           }
+  UInt               getNumAllocatedSlice() const                          { return m_uiNumAllocatedSlice;         }
+  Void               allocateNewSlice();
+  Void               clearSliceBuffer();
+  UInt               getNumPartitionsInCtu() const                         { return m_numPartitionsInCtu;   }
+  UInt               getNumPartInCtuWidth() const                          { return m_numPartInCtuWidth;    }
+  UInt               getNumPartInCtuHeight() const                         { return m_numPartInCtuHeight;   }
+  Void               setNumTileColumnsMinus1( Int i )                      { m_numTileColumnsMinus1 = i;    }
+  Int                getNumTileColumnsMinus1() const                       { return m_numTileColumnsMinus1; }
+  Void               setNumTileRowsMinus1( Int i )                         { m_numTileRowsMinus1 = i;       }
+  Int                getNumTileRowsMinus1() const                          { return m_numTileRowsMinus1;    }
+  Int                getNumTiles() const                                   { return (m_numTileRowsMinus1+1)*(m_numTileColumnsMinus1+1); }
+  TComTile*          getTComTile  ( UInt tileIdx )                         { return &(m_tileParameters[tileIdx]); }
+  const TComTile*    getTComTile  ( UInt tileIdx ) const                   { return &(m_tileParameters[tileIdx]); }
+  Void               setCtuTsToRsAddrMap( Int ctuTsAddr, Int ctuRsAddr )   { *(m_ctuTsToRsAddrMap + ctuTsAddr) = ctuRsAddr; }
+  UInt               getCtuTsToRsAddrMap( Int ctuTsAddr ) const            { return *(m_ctuTsToRsAddrMap + (ctuTsAddr>=m_numCtusInFrame ? m_numCtusInFrame : ctuTsAddr)); }
+  UInt               getTileIdxMap( Int ctuRsAddr ) const                  { return *(m_puiTileIdxMap + ctuRsAddr); }
+  Void               setCtuRsToTsAddrMap( Int ctuRsAddr, Int ctuTsOrder )  { *(m_ctuRsToTsAddrMap + ctuRsAddr) = ctuTsOrder; }
+  UInt               getCtuRsToTsAddrMap( Int ctuRsAddr ) const            { return *(m_ctuRsToTsAddrMap + (ctuRsAddr>=m_numCtusInFrame ? m_numCtusInFrame : ctuRsAddr)); }
+  Void               initTiles(TComPPS *pps);
+
+  Void               initCtuTsRsAddrMaps();
+  SAOBlkParam*       getSAOBlkParam()                                      { return m_saoBlkParams;}
+  const SAOBlkParam* getSAOBlkParam() const                                { return m_saoBlkParams;}
+  Void               deriveLoopFilterBoundaryAvailibility(Int ctuRsAddr,
+                                                          Bool& isLeftAvail, Bool& isRightAvail, Bool& isAboveAvail, Bool& isBelowAvail,
+                                                          Bool& isAboveLeftAvail, Bool& isAboveRightAvail, Bool& isBelowLeftAvail, Bool& isBelowRightAvail);
+protected:
+  UInt               xCalculateNextCtuRSAddr( UInt uiCurrCtuRSAddr );
+
+#if SVC_EXTENSION
+public:
+#if LAYER_CTB
+  UInt        getMaxCUWidth()           { return m_uiMaxCUWidth;                }
+  UInt        getMaxCUHeight()          { return m_uiMaxCUHeight;               }
+#endif
+#if N0383_IL_CONSTRAINED_TILE_SETS_SEI
+  Void         setTileSetIdxMap( Int i, Int tileSetIdx, UChar setType, Bool skipFlag )
+  {
+    m_piTileSetIdxMap[i]       = tileSetIdx;
+    m_pucTileSetType[i]        = setType;
+    m_pbSkippedTileSetFlag[i]  = skipFlag;
+  }
+  Int          getTileSetIdxMap( Int i )                             { return *(m_piTileSetIdxMap + i); }
+  UChar        getTileSetType( Int i )                               { return *(m_pucTileSetType + i); }
+  Bool         getSkippedTileSetFlag( Int i )                        { return *(m_pbSkippedTileSetFlag + i); }
+#endif
+#endif //SVC_EXTENSION
+
+};// END CLASS DEFINITION TComPicSym
+
+//! \}
+
+#endif // __TCOMPICSYM__
+
Index: /tags/SHM-9.0/source/Lib/TLibCommon/TComPicYuv.cpp
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibCommon/TComPicYuv.cpp	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibCommon/TComPicYuv.cpp	(revision 1088)
@@ -0,0 +1,345 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TComPicYuv.cpp
+    \brief    picture YUV buffer class
+*/
+
+#include <cstdlib>
+#include <assert.h>
+#include <memory.h>
+
+#ifdef __APPLE__
+#include <malloc/malloc.h>
+#else
+#include <malloc.h>
+#endif
+
+#include "TComPicYuv.h"
+#include "TLibVideoIO/TVideoIOYuv.h"
+
+//! \ingroup TLibCommon
+//! \{
+
+TComPicYuv::TComPicYuv()
+{
+  for(UInt i=0; i<MAX_NUM_COMPONENT; i++)
+  {
+    m_apiPicBuf[i]    = NULL;   // Buffer (including margin)
+    m_piPicOrg[i]     = NULL;    // m_apiPicBufY + m_iMarginLuma*getStride() + m_iMarginLuma
+  }
+
+  for(UInt i=0; i<MAX_NUM_CHANNEL_TYPE; i++)
+  {
+    m_ctuOffsetInBuffer[i]=0;
+    m_subCuOffsetInBuffer[i]=0;
+  }
+
+  m_bIsBorderExtended = false;
+}
+
+
+
+
+TComPicYuv::~TComPicYuv()
+{
+}
+
+#if SVC_EXTENSION
+#if R0156_CONF_WINDOW_IN_REP_FORMAT
+Void TComPicYuv::create( const Int iPicWidth, const Int iPicHeight, const ChromaFormat chromaFormatIDC, const UInt uiMaxCUWidth, const UInt uiMaxCUHeight, const UInt uiMaxCUDepth, Window* conformanceWindow )
+#else
+Void TComPicYuv::create( const Int iPicWidth, const Int iPicHeight, const ChromaFormat chromaFormatIDC, const UInt uiMaxCUWidth, const UInt uiMaxCUHeight, const UInt uiMaxCUDepth, TComSPS* pcSps )
+#endif
+#else
+Void TComPicYuv::create( const Int  iPicWidth,    const  Int iPicHeight,    const ChromaFormat chromaFormatIDC,
+                         const UInt uiMaxCUWidth, const UInt uiMaxCUHeight, const UInt uiMaxCUDepth )
+#endif
+{
+  m_iPicWidth         = iPicWidth;
+  m_iPicHeight        = iPicHeight;
+  m_chromaFormatIDC   = chromaFormatIDC;
+  
+#if SVC_EXTENSION
+#if R0156_CONF_WINDOW_IN_REP_FORMAT
+  if(conformanceWindow != NULL)
+  {
+    m_conformanceWindow = *conformanceWindow;
+  }
+#else
+  if(pcSps != NULL)
+  {
+    m_conformanceWindow = pcSps->getConformanceWindow();
+  }
+#endif
+#endif
+  
+#if LAYER_CTB
+  m_iMarginX    = uiMaxCUWidth  + 16; // for 16-byte alignment
+  m_iMarginY    = uiMaxCUHeight + 16;  // margin for 8-tap filter and infinite padding
+#else
+  m_iMarginX          = g_uiMaxCUWidth  + 16; // for 16-byte alignment
+  m_iMarginY          = g_uiMaxCUHeight + 16;  // margin for 8-tap filter and infinite padding
+#endif
+  
+  m_bIsBorderExtended = false;
+
+  // assign the picture arrays and set up the ptr to the top left of the original picture
+  {
+    Int chan=0;
+    for(; chan<getNumberValidComponents(); chan++)
+    {
+      const ComponentID ch=ComponentID(chan);
+      m_apiPicBuf[chan] = (Pel*)xMalloc( Pel, getStride(ch)       * getTotalHeight(ch));
+      m_piPicOrg[chan]  = m_apiPicBuf[chan] + (m_iMarginY >> getComponentScaleY(ch))   * getStride(ch)       + (m_iMarginX >> getComponentScaleX(ch));
+    }
+    for(;chan<MAX_NUM_COMPONENT; chan++)
+    {
+      m_apiPicBuf[chan] = NULL;
+      m_piPicOrg[chan]  = NULL;
+    }
+  }
+
+
+  const Int numCuInWidth  = m_iPicWidth  / uiMaxCUWidth  + (m_iPicWidth  % uiMaxCUWidth  != 0);
+  const Int numCuInHeight = m_iPicHeight / uiMaxCUHeight + (m_iPicHeight % uiMaxCUHeight != 0);
+  for(Int chan=0; chan<2; chan++)
+  {
+    const ComponentID ch=ComponentID(chan);
+    const Int ctuHeight=uiMaxCUHeight>>getComponentScaleY(ch);
+    const Int ctuWidth=uiMaxCUWidth>>getComponentScaleX(ch);
+    const Int stride = getStride(ch);
+
+    m_ctuOffsetInBuffer[chan] = new Int[numCuInWidth * numCuInHeight];
+
+    for (Int cuRow = 0; cuRow < numCuInHeight; cuRow++)
+      for (Int cuCol = 0; cuCol < numCuInWidth; cuCol++)
+        m_ctuOffsetInBuffer[chan][cuRow * numCuInWidth + cuCol] = stride * cuRow * ctuHeight + cuCol * ctuWidth;
+
+    m_subCuOffsetInBuffer[chan] = new Int[(size_t)1 << (2 * uiMaxCUDepth)];
+
+    const Int numSubBlockPartitions=(1<<uiMaxCUDepth);
+    const Int minSubBlockHeight    =(ctuHeight >> uiMaxCUDepth);
+    const Int minSubBlockWidth     =(ctuWidth  >> uiMaxCUDepth);
+
+    for (Int buRow = 0; buRow < numSubBlockPartitions; buRow++)
+      for (Int buCol = 0; buCol < numSubBlockPartitions; buCol++)
+        m_subCuOffsetInBuffer[chan][(buRow << uiMaxCUDepth) + buCol] = stride  * buRow * minSubBlockHeight + buCol * minSubBlockWidth;
+  }
+  return;
+}
+
+
+
+Void TComPicYuv::destroy()
+{
+  for(Int chan=0; chan<MAX_NUM_COMPONENT; chan++)
+  {
+    m_piPicOrg[chan] = NULL;
+
+    if( m_apiPicBuf[chan] ){ xFree( m_apiPicBuf[chan] );    m_apiPicBuf[chan] = NULL; }
+  }
+
+  for(UInt chan=0; chan<MAX_NUM_CHANNEL_TYPE; chan++)
+  {
+    if (m_ctuOffsetInBuffer[chan]) delete[] m_ctuOffsetInBuffer[chan]; m_ctuOffsetInBuffer[chan] = NULL;
+    if (m_subCuOffsetInBuffer[chan]) delete[] m_subCuOffsetInBuffer[chan]; m_subCuOffsetInBuffer[chan] = NULL;
+  }
+}
+
+
+
+Void  TComPicYuv::copyToPic (TComPicYuv*  pcPicYuvDst) const
+{
+  assert( m_iPicWidth  == pcPicYuvDst->getWidth(COMPONENT_Y)  );
+  assert( m_iPicHeight == pcPicYuvDst->getHeight(COMPONENT_Y) );
+  assert( m_chromaFormatIDC == pcPicYuvDst->getChromaFormat() );
+
+  for(Int chan=0; chan<getNumberValidComponents(); chan++)
+  {
+    const ComponentID ch=ComponentID(chan);
+    ::memcpy ( pcPicYuvDst->getBuf(ch), m_apiPicBuf[ch], sizeof (Pel) * getStride(ch) * getTotalHeight(ch));
+  }
+  return;
+}
+
+
+Void TComPicYuv::extendPicBorder ()
+{
+  if ( m_bIsBorderExtended ) return;
+
+  for(Int chan=0; chan<getNumberValidComponents(); chan++)
+  {
+    const ComponentID ch=ComponentID(chan);
+    Pel *piTxt=getAddr(ch); // piTxt = point to (0,0) of image within bigger picture.
+    const Int iStride=getStride(ch);
+    const Int iWidth=getWidth(ch);
+    const Int iHeight=getHeight(ch);
+    const Int iMarginX=getMarginX(ch);
+    const Int iMarginY=getMarginY(ch);
+
+    Pel*  pi = piTxt;
+    // do left and right margins
+    for (Int y = 0; y < iHeight; y++)
+    {
+      for (Int x = 0; x < iMarginX; x++ )
+      {
+        pi[ -iMarginX + x ] = pi[0];
+        pi[    iWidth + x ] = pi[iWidth-1];
+      }
+      pi += iStride;
+    }
+
+    // pi is now the (0,height) (bottom left of image within bigger picture
+    pi -= (iStride + iMarginX);
+    // pi is now the (-marginX, height-1)
+    for (Int y = 0; y < iMarginY; y++ )
+    {
+      ::memcpy( pi + (y+1)*iStride, pi, sizeof(Pel)*(iWidth + (iMarginX<<1)) );
+    }
+
+    // pi is still (-marginX, height-1)
+    pi -= ((iHeight-1) * iStride);
+    // pi is now (-marginX, 0)
+    for (Int y = 0; y < iMarginY; y++ )
+    {
+      ::memcpy( pi - (y+1)*iStride, pi, sizeof(Pel)*(iWidth + (iMarginX<<1)) );
+    }
+  }
+
+  m_bIsBorderExtended = true;
+}
+
+
+
+// NOTE: This function is never called, but may be useful for developers.
+Void TComPicYuv::dump (const Char* pFileName, Bool bAdd) const
+{
+  FILE* pFile;
+  if (!bAdd)
+  {
+    pFile = fopen (pFileName, "wb");
+  }
+  else
+  {
+    pFile = fopen (pFileName, "ab");
+  }
+
+
+  for(Int chan = 0; chan < getNumberValidComponents(); chan++)
+  {
+    const ComponentID  ch     = ComponentID(chan);
+    const Int          shift  = g_bitDepth[toChannelType(ch)] - 8;
+    const Int          offset = (shift>0)?(1<<(shift-1)):0;
+    const Pel         *pi     = getAddr(ch);
+    const Int          stride = getStride(ch);
+    const Int          height = getHeight(ch);
+    const Int          width  = getWidth(ch);
+
+    for (Int y = 0; y < height; y++ )
+    {
+      for (Int x = 0; x < width; x++ )
+      {
+        UChar uc = (UChar)Clip3<Pel>(0, 255, (pi[x]+offset)>>shift);
+        fwrite( &uc, sizeof(UChar), 1, pFile );
+      }
+      pi += stride;
+    }
+  }
+
+  fclose(pFile);
+}
+
+Void TComPicYuv::dump( Char* pFileName, Bool bAdd, Int bitDepth )
+{
+  FILE* pFile;
+  if (!bAdd)
+  {
+    pFile = fopen (pFileName, "wb");
+  }
+  else
+  {
+    pFile = fopen (pFileName, "ab");
+  }
+
+  if( bitDepth == 8 )
+  {
+    dump( pFileName, bAdd );
+    return;
+  }
+
+  for(Int chan = 0; chan < getNumberValidComponents(); chan++)
+  {
+    const ComponentID  ch     = ComponentID(chan);
+    const Int          shift  = g_bitDepth[toChannelType(ch)] - 8;
+    const Int          offset = (shift>0)?(1<<(shift-1)):0;
+    const Pel         *pi     = getAddr(ch);
+    const Int          stride = getStride(ch);
+    const Int          height = getHeight(ch);
+    const Int          width  = getWidth(ch);
+
+    for (Int y = 0; y < height; y++ )
+    {
+      for (Int x = 0; x < width; x++ )
+      {
+        Pel pix  = Clip3<Pel>(0, (1 << bitDepth)-1, (pi[x]+offset)>>shift);
+
+        UChar uc = pix & 0xff;      
+        fwrite( &uc, sizeof(UChar), 1, pFile );
+        uc = (pix >> 8) & 0xff;      
+        fwrite( &uc, sizeof(UChar), 1, pFile );
+      }
+      pi += stride;
+    }
+  }
+  
+  fclose(pFile);
+}
+
+#if AUXILIARY_PICTURES
+Void TComPicYuv::convertToMonochrome()
+{
+  Pel grayVal = (1 << (g_bitDepth[CHANNEL_TYPE_CHROMA] - 1));
+
+  for( UInt comp = 1; comp < getNumberValidComponents(); comp++ )
+  {
+    const ComponentID ch=ComponentID(comp);
+    for( UInt i = 0; i < getStride(ch) * getTotalHeight(ch); i++ )
+    {
+      m_apiPicBuf[ch][i] = grayVal;
+    }
+  }
+}
+#endif
+
+//! \}
Index: /tags/SHM-9.0/source/Lib/TLibCommon/TComPicYuv.h
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibCommon/TComPicYuv.h	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibCommon/TComPicYuv.h	(revision 1088)
@@ -0,0 +1,197 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TComPicYuv.h
+    \brief    picture YUV buffer class (header)
+*/
+
+#ifndef __TCOMPICYUV__
+#define __TCOMPICYUV__
+
+#include <stdio.h>
+#include "CommonDef.h"
+#include "TComRom.h"
+#include "TComChromaFormat.h"
+#include "SEI.h"
+#if SVC_EXTENSION
+#include "TComSlice.h"
+#endif
+//! \ingroup TLibCommon
+//! \{
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// picture YUV buffer class
+class TComPicYuv
+{
+private:
+
+  // ------------------------------------------------------------------------------------------------
+  //  YUV buffer
+  // ------------------------------------------------------------------------------------------------
+
+  Pel*  m_apiPicBuf[MAX_NUM_COMPONENT];             ///< Buffer (including margin)
+
+  Pel*  m_piPicOrg[MAX_NUM_COMPONENT];              ///< m_apiPicBufY + m_iMarginLuma*getStride() + m_iMarginLuma
+
+  // ------------------------------------------------------------------------------------------------
+  //  Parameter for general YUV buffer usage
+  // ------------------------------------------------------------------------------------------------
+
+  Int   m_iPicWidth;                                ///< Width of picture in pixels
+  Int   m_iPicHeight;                               ///< Height of picture in pixels
+  ChromaFormat m_chromaFormatIDC;                   ///< Chroma Format
+
+  Int*  m_ctuOffsetInBuffer[MAX_NUM_CHANNEL_TYPE];  ///< Gives an offset in the buffer for a given CTU (and channel)
+  Int*  m_subCuOffsetInBuffer[MAX_NUM_CHANNEL_TYPE];///< Gives an offset in the buffer for a given sub-CU (and channel), relative to start of CTU
+
+  Int   m_iMarginX;                                 ///< margin of Luma channel (chroma's may be smaller, depending on ratio)
+  Int   m_iMarginY;                                 ///< margin of Luma channel (chroma's may be smaller, depending on ratio)
+
+  Bool  m_bIsBorderExtended;
+
+#if SVC_EXTENSION
+  Window  m_conformanceWindow;
+#if M0040_ADAPTIVE_RESOLUTION_CHANGE
+  Bool    m_isReconstructed;
+#endif
+#endif //SVC_EXTENSION
+ 
+public:
+               TComPicYuv         ();
+  virtual     ~TComPicYuv         ();
+
+  // ------------------------------------------------------------------------------------------------
+  //  Memory management
+  // ------------------------------------------------------------------------------------------------
+#if SVC_EXTENSION
+#if R0156_CONF_WINDOW_IN_REP_FORMAT
+  Void  create      ( Int iPicWidth, Int iPicHeight, ChromaFormat chromaFormatIDC, UInt uiMaxCUWidth, UInt uiMaxCUHeight, UInt uiMaxCUDepth, Window* conformanceWindow = NULL);
+#else
+  Void  create      ( Int iPicWidth, Int iPicHeight, ChromaFormat chromaFormatIDC, UInt uiMaxCUWidth, UInt uiMaxCUHeight, UInt uiMaxCUDepth, TComSPS* pcSps = NULL);
+#endif
+#else
+  Void          create            (const Int iPicWidth,
+                                   const Int iPicHeight,
+                                   const ChromaFormat chromaFormatIDC,
+                                   const UInt uiMaxCUWidth,
+                                   const UInt uiMaxCUHeight,
+                                   const UInt uiMaxCUDepth );
+#endif //SVC_EXTENSION
+  
+  Void          destroy           ();
+
+  // The following have been removed - Use CHROMA_400 in the above function call.
+  //Void  createLuma  ( Int iPicWidth, Int iPicHeight, UInt uiMaxCUWidth, UInt uiMaxCUHeight, UInt uhMaxCUDepth );
+  //Void  destroyLuma ();
+
+  // ------------------------------------------------------------------------------------------------
+  //  Get information of picture
+  // ------------------------------------------------------------------------------------------------
+
+  Int           getWidth          (const ComponentID id) const { return  m_iPicWidth >> getComponentScaleX(id);   }
+  Int           getHeight         (const ComponentID id) const { return  m_iPicHeight >> getComponentScaleY(id);  }
+  ChromaFormat  getChromaFormat   ()                     const { return m_chromaFormatIDC; }
+  UInt          getNumberValidComponents() const { return ::getNumberValidComponents(m_chromaFormatIDC); }
+
+  Int           getStride         (const ComponentID id) const { return ((m_iPicWidth     ) + (m_iMarginX  <<1)) >> getComponentScaleX(id); }
+  Int           getTotalHeight    (const ComponentID id) const { return ((m_iPicHeight    ) + (m_iMarginY  <<1)) >> getComponentScaleY(id); }
+
+  Int           getMarginX        (const ComponentID id) const { return m_iMarginX >> getComponentScaleX(id);  }
+  Int           getMarginY        (const ComponentID id) const { return m_iMarginY >> getComponentScaleY(id);  }
+
+  // ------------------------------------------------------------------------------------------------
+  //  Access function for picture buffer
+  // ------------------------------------------------------------------------------------------------
+
+  //  Access starting position of picture buffer with margin
+  Pel*          getBuf            (const ComponentID ch)       { return  m_apiPicBuf[ch];   }
+
+  //  Access starting position of original picture
+  Pel*          getAddr           (const ComponentID ch)       { return  m_piPicOrg[ch];   }
+  const Pel*    getAddr           (const ComponentID ch) const { return  m_piPicOrg[ch];   }
+
+  //  Access starting position of original picture for specific coding unit (CU) or partition unit (PU)
+  Pel*          getAddr           (const ComponentID ch, const Int ctuRSAddr )       { return m_piPicOrg[ch] + m_ctuOffsetInBuffer[ch==0?0:1][ ctuRSAddr ]; }
+  const Pel*    getAddr           (const ComponentID ch, const Int ctuRSAddr ) const { return m_piPicOrg[ch] + m_ctuOffsetInBuffer[ch==0?0:1][ ctuRSAddr ]; }
+  Pel*          getAddr           (const ComponentID ch, const Int ctuRSAddr, const Int uiAbsZorderIdx )
+                                     { return m_piPicOrg[ch] + m_ctuOffsetInBuffer[ch==0?0:1][ctuRSAddr] + m_subCuOffsetInBuffer[ch==0?0:1][g_auiZscanToRaster[uiAbsZorderIdx]]; }
+  const Pel*    getAddr           (const ComponentID ch, const Int ctuRSAddr, const Int uiAbsZorderIdx ) const
+                                     { return m_piPicOrg[ch] + m_ctuOffsetInBuffer[ch==0?0:1][ctuRSAddr] + m_subCuOffsetInBuffer[ch==0?0:1][g_auiZscanToRaster[uiAbsZorderIdx]]; }
+
+  UInt          getComponentScaleX(const ComponentID id) const { return ::getComponentScaleX(id, m_chromaFormatIDC); }
+  UInt          getComponentScaleY(const ComponentID id) const { return ::getComponentScaleY(id, m_chromaFormatIDC); }
+
+  // ------------------------------------------------------------------------------------------------
+  //  Miscellaneous
+  // ------------------------------------------------------------------------------------------------
+
+  //  Copy function to picture
+  Void          copyToPic         ( TComPicYuv*  pcPicYuvDst ) const ;
+
+  //  Extend function of picture buffer
+  Void          extendPicBorder   ();
+
+  //  Dump picture
+  Void          dump              (const Char* pFileName, Bool bAdd = false) const ;
+
+  // Set border extension flag
+  Void          setBorderExtension(Bool b) { m_bIsBorderExtended = b; }
+  
+#if SVC_EXTENSION
+  Void          setHeight   ( Int iPicHeight )     { m_iPicHeight = iPicHeight; }
+  Window&       getConformanceWindow()                           { return  m_conformanceWindow;             }
+  Void          setConformanceWindow(Window& conformanceWindow ) { m_conformanceWindow = conformanceWindow; }
+#if M0040_ADAPTIVE_RESOLUTION_CHANGE
+  Void          setReconstructed(Bool x) { m_isReconstructed = x;    }
+  Bool          isReconstructed()        { return m_isReconstructed; }
+#endif
+#if AUXILIARY_PICTURES  
+  Void          convertToMonochrome();
+#endif
+#endif //SVC_EXTENSION
+  Void          dump( Char* pFileName, Bool bAdd, Int bitDepth );
+
+};// END CLASS DEFINITION TComPicYuv
+
+
+// These functions now return the length of the digest strings.
+UInt calcChecksum(const TComPicYuv& pic, TComDigest &digest);
+UInt calcCRC     (const TComPicYuv& pic, TComDigest &digest);
+UInt calcMD5     (const TComPicYuv& pic, TComDigest &digest);
+std::string digestToString(const TComDigest &digest, Int numChar);
+//! \}
+
+#endif // __TCOMPICYUV__
Index: /tags/SHM-9.0/source/Lib/TLibCommon/TComPicYuvMD5.cpp
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibCommon/TComPicYuvMD5.cpp	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibCommon/TComPicYuvMD5.cpp	(revision 1088)
@@ -0,0 +1,222 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "TComPicYuv.h"
+#include "libmd5/MD5.h"
+
+//! \ingroup TLibCommon
+//! \{
+
+/**
+ * Update md5 using n samples from plane, each sample is adjusted to
+ * OUTBIT_BITDEPTH_DIV8.
+ */
+template<UInt OUTPUT_BITDEPTH_DIV8>
+static Void md5_block(MD5& md5, const Pel* plane, UInt n)
+{
+  /* create a 64 byte buffer for packing Pel's into */
+  UChar buf[64/OUTPUT_BITDEPTH_DIV8][OUTPUT_BITDEPTH_DIV8];
+  for (UInt i = 0; i < n; i++)
+  {
+    Pel pel = plane[i];
+    /* perform bitdepth and endian conversion */
+    for (UInt d = 0; d < OUTPUT_BITDEPTH_DIV8; d++)
+    {
+      buf[i][d] = pel >> (d*8);
+    }
+  }
+  md5.update((UChar*)buf, n * OUTPUT_BITDEPTH_DIV8);
+}
+
+/**
+ * Update md5 with all samples in plane in raster order, each sample
+ * is adjusted to OUTBIT_BITDEPTH_DIV8.
+ */
+template<UInt OUTPUT_BITDEPTH_DIV8>
+static Void md5_plane(MD5& md5, const Pel* plane, UInt width, UInt height, UInt stride)
+{
+  /* N is the number of samples to process per md5 update.
+   * All N samples must fit in buf */
+  UInt N = 32;
+  UInt width_modN = width % N;
+  UInt width_less_modN = width - width_modN;
+
+  for (UInt y = 0; y < height; y++)
+  {
+    /* convert pels into unsigned 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);
+  }
+}
+
+
+UInt compCRC(Int bitdepth, const Pel* plane, UInt width, UInt height, UInt stride, TComDigest &digest)
+{
+  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.hash.push_back((crcVal>>8)  & 0xff);
+  digest.hash.push_back( crcVal      & 0xff);
+  return 2;
+}
+
+UInt calcCRC(const TComPicYuv& pic, TComDigest &digest)
+{
+  UInt digestLen=0;
+  digest.hash.clear();
+  for(Int chan=0; chan<pic.getNumberValidComponents(); chan++)
+  {
+    const ComponentID compID=ComponentID(chan);
+    digestLen=compCRC(g_bitDepth[toChannelType(compID)], pic.getAddr(compID), pic.getWidth(compID), pic.getHeight(compID), pic.getStride(compID), digest);
+  }
+  return digestLen;
+}
+
+UInt compChecksum(Int bitdepth, const Pel* plane, UInt width, UInt height, UInt stride, TComDigest &digest)
+{
+  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.hash.push_back((checksum>>24) & 0xff);
+  digest.hash.push_back((checksum>>16) & 0xff);
+  digest.hash.push_back((checksum>>8)  & 0xff);
+  digest.hash.push_back( checksum      & 0xff);
+  return 4;
+}
+
+UInt calcChecksum(const TComPicYuv& pic, TComDigest &digest)
+{
+  UInt digestLen=0;
+  digest.hash.clear();
+  for(Int chan=0; chan<pic.getNumberValidComponents(); chan++)
+  {
+    const ComponentID compID=ComponentID(chan);
+    digestLen=compChecksum(g_bitDepth[toChannelType(compID)], pic.getAddr(compID), pic.getWidth(compID), pic.getHeight(compID), pic.getStride(compID), digest);
+  }
+  return digestLen;
+}
+/**
+ * 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.
+ */
+UInt calcMD5(const TComPicYuv& pic, TComDigest &digest)
+{
+  /* 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 md5[MAX_NUM_COMPONENT];
+
+  digest.hash.clear();
+  for(Int chan=0; chan<pic.getNumberValidComponents(); chan++)
+  {
+    const ComponentID compID=ComponentID(chan);
+    md5_plane_func = g_bitDepth[toChannelType(compID)] <= 8 ? (MD5PlaneFunc)md5_plane<1> : (MD5PlaneFunc)md5_plane<2>;
+    UChar tmp_digest[MD5_DIGEST_STRING_LENGTH];
+    md5_plane_func(md5[compID], pic.getAddr(compID), pic.getWidth(compID), pic.getHeight(compID), pic.getStride(compID));
+    md5[compID].finalize(tmp_digest);
+    for(UInt i=0; i<MD5_DIGEST_STRING_LENGTH; i++)
+    {
+      digest.hash.push_back(tmp_digest[i]);
+    }
+  }
+  return 16;
+}
+
+std::string digestToString(const TComDigest &digest, Int numChar)
+{
+  static const Char* hex = "0123456789abcdef";
+  std::string result;
+
+  for(Int pos=0; pos<Int(digest.hash.size()); pos++)
+  {
+    if ((pos % numChar) == 0 && pos!=0 ) result += ',';
+    result += hex[digest.hash[pos] >> 4];
+    result += hex[digest.hash[pos] & 0xf];
+  }
+
+  return result;
+}
+
+//! \}
Index: /tags/SHM-9.0/source/Lib/TLibCommon/TComPrediction.cpp
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibCommon/TComPrediction.cpp	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibCommon/TComPrediction.cpp	(revision 1088)
@@ -0,0 +1,902 @@
+/* The copyright in this software is beinOMg made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TComPrediction.cpp
+    \brief    prediction class
+*/
+
+#include <memory.h>
+#include "TComPrediction.h"
+#include "TComTU.h"
+
+//! \ingroup TLibCommon
+//! \{
+
+// ====================================================================================================================
+// Tables
+// ====================================================================================================================
+
+const UChar TComPrediction::m_aucIntraFilter[MAX_NUM_CHANNEL_TYPE][MAX_INTRA_FILTER_DEPTHS] =
+{
+  { // Luma
+    10, //4x4
+    7, //8x8
+    1, //16x16
+    0, //32x32
+    10, //64x64
+  },
+  { // Chroma
+    10, //4xn
+    7, //8xn
+    1, //16xn
+    0, //32xn
+    10, //64xn
+  }
+
+};
+
+// ====================================================================================================================
+// Constructor / destructor / initialize
+// ====================================================================================================================
+
+TComPrediction::TComPrediction()
+: m_pLumaRecBuffer(0)
+, m_iLumaRecStride(0)
+{
+  for(UInt ch=0; ch<MAX_NUM_COMPONENT; ch++)
+  {
+    for(UInt buf=0; buf<2; buf++)
+    {
+      m_piYuvExt[ch][buf] = NULL;
+    }
+  }
+}
+
+TComPrediction::~TComPrediction()
+{
+  destroy();
+}
+
+Void TComPrediction::destroy()
+{
+  for(UInt ch=0; ch<MAX_NUM_COMPONENT; ch++)
+  {
+    for(UInt buf=0; buf<NUM_PRED_BUF; buf++)
+    {
+      delete [] m_piYuvExt[ch][buf];
+      m_piYuvExt[ch][buf] = NULL;
+    }
+  }
+
+  for(UInt i=0; i<NUM_REF_PIC_LIST_01; i++)
+  {
+    m_acYuvPred[i].destroy();
+  }
+
+  m_cYuvPredTemp.destroy();
+
+  if( m_pLumaRecBuffer )
+  {
+    delete [] m_pLumaRecBuffer;
+    m_pLumaRecBuffer = 0;
+  }
+  m_iLumaRecStride = 0;
+
+  for (UInt i = 0; i < LUMA_INTERPOLATION_FILTER_SUB_SAMPLE_POSITIONS; i++)
+  {
+    for (UInt j = 0; j < LUMA_INTERPOLATION_FILTER_SUB_SAMPLE_POSITIONS; j++)
+    {
+      m_filteredBlock[i][j].destroy();
+    }
+    m_filteredBlockTmp[i].destroy();
+  }
+}
+
+Void TComPrediction::initTempBuff(ChromaFormat chromaFormatIDC)
+{
+  // if it has been initialised before, but the chroma format has changed, release the memory and start again.
+  if( m_piYuvExt[COMPONENT_Y][PRED_BUF_UNFILTERED] != NULL && m_cYuvPredTemp.getChromaFormat()!=chromaFormatIDC)
+  {
+    destroy();
+  }
+
+  if( m_piYuvExt[COMPONENT_Y][PRED_BUF_UNFILTERED] == NULL ) // check if first is null (in which case, nothing initialised yet)
+  {
+    Int extWidth  = MAX_CU_SIZE + 16;
+    Int extHeight = MAX_CU_SIZE + 1;
+
+    for (UInt i = 0; i < LUMA_INTERPOLATION_FILTER_SUB_SAMPLE_POSITIONS; i++)
+    {
+      m_filteredBlockTmp[i].create(extWidth, extHeight + 7, chromaFormatIDC);
+      for (UInt j = 0; j < LUMA_INTERPOLATION_FILTER_SUB_SAMPLE_POSITIONS; j++)
+      {
+        m_filteredBlock[i][j].create(extWidth, extHeight, chromaFormatIDC);
+      }
+    }
+
+    m_iYuvExtSize = (MAX_CU_SIZE*2+1) * (MAX_CU_SIZE*2+1);
+    for(UInt ch=0; ch<MAX_NUM_COMPONENT; ch++)
+    {
+      for(UInt buf=0; buf<NUM_PRED_BUF; buf++)
+      {
+        m_piYuvExt[ch][buf] = new Pel[ m_iYuvExtSize ];
+      }
+    }
+
+    // new structure
+    for(UInt i=0; i<NUM_REF_PIC_LIST_01; i++)
+    {
+      m_acYuvPred[i] .create( MAX_CU_SIZE, MAX_CU_SIZE, chromaFormatIDC );
+    }
+
+    m_cYuvPredTemp.create( MAX_CU_SIZE, MAX_CU_SIZE, chromaFormatIDC );
+  }
+
+
+  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 ];
+    }
+  }
+}
+
+// ====================================================================================================================
+// Public member functions
+// ====================================================================================================================
+
+// Function for calculating DC value of the reference samples used in Intra prediction
+//NOTE: Bit-Limit - 25-bit source
+Pel TComPrediction::predIntraGetPredValDC( const Pel* pSrc, Int iSrcStride, UInt iWidth, UInt iHeight, ChannelType channelType, ChromaFormat format, 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.
+ */
+//NOTE: Bit-Limit - 25-bit source
+Void TComPrediction::xPredIntraAng(       Int bitDepth,
+                                    const Pel* pSrc,     Int srcStride,
+                                          Pel* pTrueDst, Int dstStrideTrue,
+                                          UInt uiWidth, UInt uiHeight, ChannelType channelType, ChromaFormat format,
+                                          UInt dirMode, Bool blkAboveAvailable, Bool blkLeftAvailable
+                                  , const Bool bEnableEdgeFilters
+                                  )
+{
+  Int width=Int(uiWidth);
+  Int height=Int(uiHeight);
+
+  // Map the mode index to main prediction direction and angle
+  assert( dirMode != PLANAR_IDX ); //no planar
+  const Bool modeDC        = dirMode==DC_IDX;
+
+  // Do the DC prediction
+  if (modeDC)
+  {
+    const Pel dcval = predIntraGetPredValDC(pSrc, srcStride, width, height, channelType, format, blkAboveAvailable, blkLeftAvailable);
+
+    for (Int y=height;y>0;y--, pTrueDst+=dstStrideTrue)
+    {
+      for (Int x=0; x<width;) // width is always a multiple of 4.
+      {
+        pTrueDst[x++] = dcval;
+      }
+    }
+  }
+  else // Do angular predictions
+  {
+    const Bool       bIsModeVer         = (dirMode >= 18);
+    const Int        intraPredAngleMode = (bIsModeVer) ? (Int)dirMode - VER_IDX :  -((Int)dirMode - HOR_IDX);
+    const Int        absAngMode         = abs(intraPredAngleMode);
+    const Int        signAng            = intraPredAngleMode < 0 ? -1 : 1;
+    const Bool       edgeFilter         = bEnableEdgeFilters && isLuma(channelType) && (width <= MAXIMUM_INTRA_FILTERED_WIDTH) && (height <= MAXIMUM_INTRA_FILTERED_HEIGHT);
+
+    // Set bitshifts and scale the angle parameter to block size
+    static const Int angTable[9]    = {0,    2,    5,   9,  13,  17,  21,  26,  32};
+    static const Int invAngTable[9] = {0, 4096, 1638, 910, 630, 482, 390, 315, 256}; // (256 * 32) / Angle
+    Int invAngle                    = invAngTable[absAngMode];
+    Int absAng                      = angTable[absAngMode];
+    Int intraPredAngle              = signAng * absAng;
+
+    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)
+    {
+      const Int refMainOffsetPreScale = (bIsModeVer ? height : width ) - 1;
+      const Int refMainOffset         = height - 1;
+      for (Int x=0;x<width+1;x++)
+      {
+        refAbove[x+refMainOffset] = pSrc[x-srcStride-1];
+      }
+      for (Int y=0;y<height+1;y++)
+      {
+        refLeft[y+refMainOffset] = pSrc[(y-1)*srcStride-1];
+      }
+      refMain = (bIsModeVer ? refAbove : refLeft)  + refMainOffset;
+      refSide = (bIsModeVer ? refLeft  : refAbove) + refMainOffset;
+
+      // Extend the Main reference to the left.
+      Int invAngleSum    = 128;       // rounding for (shift by 8)
+      for (Int k=-1; k>(refMainOffsetPreScale+1)*intraPredAngle>>5; k--)
+      {
+        invAngleSum += invAngle;
+        refMain[k] = refSide[invAngleSum>>8];
+      }
+    }
+    else
+    {
+      for (Int x=0;x<2*width+1;x++)
+      {
+        refAbove[x] = pSrc[x-srcStride-1];
+      }
+      for (Int y=0;y<2*height+1;y++)
+      {
+        refLeft[y] = pSrc[(y-1)*srcStride-1];
+      }
+      refMain = bIsModeVer ? refAbove : refLeft ;
+      refSide = bIsModeVer ? refLeft  : refAbove;
+    }
+
+    // swap width/height if we are doing a horizontal mode:
+    Pel tempArray[MAX_CU_SIZE*MAX_CU_SIZE];
+    const Int dstStride = bIsModeVer ? dstStrideTrue : MAX_CU_SIZE;
+    Pel *pDst = bIsModeVer ? pTrueDst : tempArray;
+    if (!bIsModeVer)
+    {
+      std::swap(width, height);
+    }
+
+    if (intraPredAngle == 0)  // pure vertical or pure horizontal
+    {
+      for (Int y=0;y<height;y++)
+      {
+        for (Int x=0;x<width;x++)
+        {
+          pDst[y*dstStride+x] = refMain[x+1];
+        }
+      }
+
+      if (edgeFilter)
+      {
+        for (Int y=0;y<height;y++)
+        {
+          pDst[y*dstStride] = Clip3 (0, ((1 << bitDepth) - 1), pDst[y*dstStride] + (( refSide[y+1] - refSide[0] ) >> 1) );
+        }
+      }
+    }
+    else
+    {
+      Pel *pDsty=pDst;
+
+      for (Int y=0, deltaPos=intraPredAngle; y<height; y++, deltaPos+=intraPredAngle, pDsty+=dstStride)
+      {
+        const Int deltaInt   = deltaPos >> 5;
+        const Int deltaFract = deltaPos & (32 - 1);
+
+        if (deltaFract)
+        {
+          // Do linear filtering
+          const Pel *pRM=refMain+deltaInt+1;
+          Int lastRefMainPel=*pRM++;
+          for (Int x=0;x<width;pRM++,x++)
+          {
+            Int thisRefMainPel=*pRM;
+            pDsty[x+0] = (Pel) ( ((32-deltaFract)*lastRefMainPel + deltaFract*thisRefMainPel +16) >> 5 );
+            lastRefMainPel=thisRefMainPel;
+          }
+        }
+        else
+        {
+          // Just copy the integer samples
+          for (Int x=0;x<width; x++)
+          {
+            pDsty[x] = refMain[x+deltaInt+1];
+          }
+        }
+      }
+    }
+
+    // Flip the block if this is the horizontal mode
+    if (!bIsModeVer)
+    {
+      for (Int y=0; y<height; y++)
+      {
+        for (Int x=0; x<width; x++)
+        {
+          pTrueDst[x*dstStrideTrue] = pDst[x];
+        }
+        pTrueDst++;
+        pDst+=dstStride;
+      }
+    }
+  }
+}
+
+Void TComPrediction::predIntraAng( const ComponentID compID, UInt uiDirMode, Pel* piOrg /* Will be null for decoding */, UInt uiOrgStride, Pel* piPred, UInt uiStride, TComTU &rTu, Bool bAbove, Bool bLeft, const Bool bUseFilteredPredSamples, const Bool bUseLosslessDPCM )
+{
+  const ChromaFormat   format      = rTu.GetChromaFormat();
+  const ChannelType    channelType = toChannelType(compID);
+  const TComRectangle &rect        = rTu.getRect(isLuma(compID) ? COMPONENT_Y : COMPONENT_Cb);
+  const Int            iWidth      = rect.width;
+  const Int            iHeight     = rect.height;
+
+  assert( g_aucConvertToBit[ iWidth ] >= 0 ); //   4x  4
+  assert( g_aucConvertToBit[ iWidth ] <= 5 ); // 128x128
+  //assert( iWidth == iHeight  );
+
+        Pel *pDst = piPred;
+
+  // get starting pixel in block
+  const Int sw = (2 * iWidth + 1);
+
+  if ( bUseLosslessDPCM )
+  {
+    const Pel *ptrSrc = getPredictorPtr( compID, false );
+    // Sample Adaptive intra-Prediction (SAP)
+    if (uiDirMode==HOR_IDX)
+    {
+      // left column filled with reference samples
+      // remaining columns filled with piOrg data (if available).
+      for(Int y=0; y<iHeight; y++)
+      {
+        piPred[y*uiStride+0] = ptrSrc[(y+1)*sw];
+      }
+      if (piOrg!=0)
+      {
+        piPred+=1; // miss off first column
+        for(Int y=0; y<iHeight; y++, piPred+=uiStride, piOrg+=uiOrgStride)
+        {
+          memcpy(piPred, piOrg, (iWidth-1)*sizeof(Pel));
+        }
+      }
+    }
+    else // VER_IDX
+    {
+      // top row filled with reference samples
+      // remaining rows filled with piOrd data (if available)
+      for(Int x=0; x<iWidth; x++)
+      {
+        piPred[x] = ptrSrc[x+1];
+      }
+      if (piOrg!=0)
+      {
+        piPred+=uiStride; // miss off the first row
+        for(Int y=1; y<iHeight; y++, piPred+=uiStride, piOrg+=uiOrgStride)
+        {
+          memcpy(piPred, piOrg, iWidth*sizeof(Pel));
+        }
+      }
+    }
+  }
+  else
+  {
+    const Pel *ptrSrc = getPredictorPtr( compID, bUseFilteredPredSamples );
+
+    if ( uiDirMode == PLANAR_IDX )
+    {
+      xPredIntraPlanar( ptrSrc+sw+1, sw, pDst, uiStride, iWidth, iHeight, channelType, format );
+    }
+    else
+    {
+      // Create the prediction
+            TComDataCU *const pcCU              = rTu.getCU();
+      const UInt              uiAbsPartIdx      = rTu.GetAbsPartIdxTU();
+      const Bool              enableEdgeFilters = !(pcCU->isRDPCMEnabled(uiAbsPartIdx) && pcCU->getCUTransquantBypass(uiAbsPartIdx));
+
+#if O0043_BEST_EFFORT_DECODING
+      xPredIntraAng( g_bitDepthInStream[channelType], ptrSrc+sw+1, sw, pDst, uiStride, iWidth, iHeight, channelType, format, uiDirMode, bAbove, bLeft, enableEdgeFilters );
+#else
+      xPredIntraAng( g_bitDepth[channelType], ptrSrc+sw+1, sw, pDst, uiStride, iWidth, iHeight, channelType, format, uiDirMode, bAbove, bLeft, enableEdgeFilters );
+#endif
+
+      if(( uiDirMode == DC_IDX ) && bAbove && bLeft )
+      {
+        xDCPredFiltering( ptrSrc+sw+1, sw, pDst, uiStride, iWidth, iHeight, channelType );
+      }
+    }
+  }
+
+}
+
+/** 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 ( 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 );
+      }
+    }
+    return;
+  }
+
+  for ( iPartIdx = 0; iPartIdx < pcCU->getNumPartitions(); iPartIdx++ )
+  {
+    pcCU->getPartIndexAndSize( iPartIdx, uiPartAddr, iWidth, iHeight );
+
+    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 );
+      }
+    }
+  }
+  return;
+}
+
+Void TComPrediction::xPredInterUni ( TComDataCU* pcCU, UInt uiPartAddr, Int iWidth, Int iHeight, RefPicList eRefPicList, TComYuv* pcYuvPred, Bool bi )
+{
+  Int         iRefIdx     = pcCU->getCUMvField( eRefPicList )->getRefIdx( uiPartAddr );           assert (iRefIdx >= 0);
+  TComMv      cMv         = pcCU->getCUMvField( eRefPicList )->getMv( uiPartAddr );
+  pcCU->clipMv(cMv);
+
+#if SVC_EXTENSION
+  if( pcCU->getLayerId() > 0 )
+  {
+    TComPic* refPic = pcCU->getSlice()->getRefPic(eRefPicList, iRefIdx);
+
+    if( refPic->isILR(pcCU->getLayerId()) )
+    {
+      // It is a requirement of bitstream conformance that when the reference picture represented by the variable refIdxLX is an inter-layer reference picture, 
+      // VpsInterLayerSamplePredictionEnabled[ LayerIdxInVps[ currLayerId ] ][ LayerIdxInVps[ rLId ] ] shall be equal to 1, where rLId is set equal to nuh_layer_id of the inter-layer picture
+      assert( pcCU->getSlice()->getVPS()->isSamplePredictionType( pcCU->getLayerIdx(), refPic->getLayerIdx() ) );
+
+#if REF_IDX_ME_ZEROMV
+      // It is a requirement of bitstream conformance that the variables mvLX[ 0 ] and mvLX[ 1 ] shall be equal to 0 if the value of refIdxLX corresponds to an inter-layer reference picture. 
+      assert( cMv.getHor() == 0 && cMv.getVer() == 0 );
+#endif
+    }
+
+  }
+#endif
+
+  for (UInt ch=COMPONENT_Y; ch<pcYuvPred->getNumberValidComponents(); ch++)
+    xPredInterBlk  (ComponentID(ch),  pcCU, pcCU->getSlice()->getRefPic( eRefPicList, iRefIdx )->getPicYuvRec(), uiPartAddr, &cMv, iWidth, iHeight, pcYuvPred, bi );
+}
+
+Void TComPrediction::xPredInterBi ( TComDataCU* pcCU, UInt uiPartAddr, Int iWidth, Int iHeight, TComYuv* pcYuvPred )
+{
+  TComYuv* pcMbYuv;
+  Int      iRefIdx[NUM_REF_PIC_LIST_01] = {-1, -1};
+
+  for ( UInt refList = 0; refList < NUM_REF_PIC_LIST_01; refList++ )
+  {
+    RefPicList eRefPicList = (refList ? REF_PIC_LIST_1 : REF_PIC_LIST_0);
+    iRefIdx[refList] = pcCU->getCUMvField( eRefPicList )->getRefIdx( uiPartAddr );
+
+    if ( iRefIdx[refList] < 0 )
+    {
+      continue;
+    }
+
+    assert( iRefIdx[refList] < pcCU->getSlice()->getNumRefIdx(eRefPicList) );
+
+    pcMbYuv = &m_acYuvPred[refList];
+    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[REF_PIC_LIST_0], &m_acYuvPred[REF_PIC_LIST_1], iRefIdx[REF_PIC_LIST_0], iRefIdx[REF_PIC_LIST_1], uiPartAddr, iWidth, iHeight, pcYuvPred );
+  }
+  else if ( pcCU->getSlice()->getPPS()->getUseWP() && pcCU->getSlice()->getSliceType() == P_SLICE )
+  {
+    xWeightedPredictionUni( pcCU, &m_acYuvPred[REF_PIC_LIST_0], uiPartAddr, iWidth, iHeight, REF_PIC_LIST_0, pcYuvPred );
+  }
+  else
+  {
+    xWeightedAverage( &m_acYuvPred[REF_PIC_LIST_0], &m_acYuvPred[REF_PIC_LIST_1], iRefIdx[REF_PIC_LIST_0], iRefIdx[REF_PIC_LIST_1], uiPartAddr, iWidth, iHeight, pcYuvPred );
+  }
+}
+
+/**
+ * \brief Generate motion-compensated 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::xPredInterBlk(const ComponentID compID, TComDataCU *cu, TComPicYuv *refPic, UInt partAddr, TComMv *mv, Int width, Int height, TComYuv *dstPic, Bool bi )
+{
+  Int     refStride  = refPic->getStride(compID);
+  Int     dstStride  = dstPic->getStride(compID);
+  Int shiftHor=(2+refPic->getComponentScaleX(compID));
+  Int shiftVer=(2+refPic->getComponentScaleY(compID));
+
+  Int     refOffset  = (mv->getHor() >> shiftHor) + (mv->getVer() >> shiftVer) * refStride;
+
+  Pel*    ref     = refPic->getAddr(compID, cu->getCtuRsAddr(), cu->getZorderIdxInCtu() + partAddr ) + refOffset;
+
+  Pel*    dst = dstPic->getAddr( compID, partAddr );
+
+  Int     xFrac  = mv->getHor() & ((1<<shiftHor)-1);
+  Int     yFrac  = mv->getVer() & ((1<<shiftVer)-1);
+  UInt    cxWidth  = width  >> refPic->getComponentScaleX(compID);
+  UInt    cxHeight = height >> refPic->getComponentScaleY(compID);
+
+  const ChromaFormat chFmt = cu->getPic()->getChromaFormat();
+
+  if ( yFrac == 0 )
+  {
+    m_if.filterHor(compID, ref, refStride, dst,  dstStride, cxWidth, cxHeight, xFrac, !bi, chFmt);
+  }
+  else if ( xFrac == 0 )
+  {
+    m_if.filterVer(compID, ref, refStride, dst, dstStride, cxWidth, cxHeight, yFrac, true, !bi, chFmt);
+  }
+  else
+  {
+    Int   tmpStride = m_filteredBlockTmp[0].getStride(compID);
+    Pel*  tmp       = m_filteredBlockTmp[0].getAddr(compID);
+
+    const Int vFilterSize = isLuma(compID) ? NTAPS_LUMA : NTAPS_CHROMA;
+
+    m_if.filterHor(compID, ref - ((vFilterSize>>1) -1)*refStride, refStride, tmp, tmpStride, cxWidth, cxHeight+vFilterSize-1, xFrac, false,      chFmt);
+    m_if.filterVer(compID, tmp + ((vFilterSize>>1) -1)*tmpStride, tmpStride, dst, dstStride, cxWidth, cxHeight,               yFrac, false, !bi, chFmt);
+  }
+}
+
+Void TComPrediction::xWeightedAverage( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, Int iRefIdx0, Int iRefIdx1, UInt uiPartIdx, Int iWidth, Int iHeight, TComYuv* pcYuvDst )
+{
+  if( iRefIdx0 >= 0 && iRefIdx1 >= 0 )
+  {
+    pcYuvDst->addAvg( pcYuvSrc0, pcYuvSrc1, uiPartIdx, iWidth, iHeight );
+  }
+  else if ( iRefIdx0 >= 0 && iRefIdx1 <  0 )
+  {
+    pcYuvSrc0->copyPartToPartYuv( pcYuvDst, uiPartIdx, iWidth, iHeight );
+  }
+  else if ( iRefIdx0 <  0 && iRefIdx1 >= 0 )
+  {
+    pcYuvSrc1->copyPartToPartYuv( pcYuvDst, 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).
+ */
+//NOTE: Bit-Limit - 24-bit source
+Void TComPrediction::xPredIntraPlanar( const Pel* pSrc, Int srcStride, Pel* rpDst, Int dstStride, UInt width, UInt height, ChannelType channelType, ChromaFormat format )
+{
+  assert(width <= height);
+
+  Int leftColumn[MAX_CU_SIZE+1], topRow[MAX_CU_SIZE+1], bottomRow[MAX_CU_SIZE], rightColumn[MAX_CU_SIZE];
+  UInt shift1Dhor = g_aucConvertToBit[ width ] + 2;
+  UInt shift1Dver = g_aucConvertToBit[ height ] + 2;
+
+  // Get left and above reference column and row
+  for(Int k=0;k<width+1;k++)
+  {
+    topRow[k] = pSrc[k-srcStride];
+  }
+
+  for (Int k=0; k < height+1; k++)
+  {
+    leftColumn[k] = pSrc[k*srcStride-1];
+  }
+
+  // Prepare intermediate variables used in interpolation
+  Int bottomLeft = leftColumn[height];
+  Int topRight   = topRow[width];
+
+  for(Int k=0;k<width;k++)
+  {
+    bottomRow[k]  = bottomLeft - topRow[k];
+    topRow[k]     <<= shift1Dver;
+  }
+
+  for(Int k=0;k<height;k++)
+  {
+    rightColumn[k]  = topRight - leftColumn[k];
+    leftColumn[k]   <<= shift1Dhor;
+  }
+
+  const UInt topRowShift = 0;
+
+  // Generate prediction signal
+  for (Int y=0;y<height;y++)
+  {
+    Int horPred = leftColumn[y] + width;
+    for (Int x=0;x<width;x++)
+    {
+      horPred += rightColumn[y];
+      topRow[x] += bottomRow[x];
+
+      Int vertPred = ((topRow[x] + topRowShift)>>topRowShift);
+      rpDst[y*dstStride+x] = ( horPred + vertPred ) >> (shift1Dhor+1);
+    }
+  }
+}
+
+/** 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( const Pel* pSrc, Int iSrcStride, Pel* pDst, Int iDstStride, Int iWidth, Int iHeight, ChannelType channelType )
+{
+  Int x, y, iDstStride2, iSrcStride2;
+
+  if (isLuma(channelType) && (iWidth <= MAXIMUM_INTRA_FILTERED_WIDTH) && (iHeight <= MAXIMUM_INTRA_FILTERED_HEIGHT))
+  {
+    //top-left
+    pDst[0] = (Pel)((pSrc[-iSrcStride] + pSrc[-1] + 2 * pDst[0] + 2) >> 2);
+
+    //top row (vertical filter)
+    for ( x = 1; x < iWidth; x++ )
+    {
+      pDst[x] = (Pel)((pSrc[x - iSrcStride] +  3 * pDst[x] + 2) >> 2);
+    }
+
+    //left column (horizontal filter)
+    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;
+}
+
+/* Static member function */
+Bool TComPrediction::UseDPCMForFirstPassIntraEstimation(TComTU &rTu, const UInt uiDirMode)
+{
+  return (rTu.getCU()->isRDPCMEnabled(rTu.GetAbsPartIdxTU()) ) &&
+          rTu.getCU()->getCUTransquantBypass(rTu.GetAbsPartIdxTU()) &&
+          (uiDirMode==HOR_IDX || uiDirMode==VER_IDX);
+}
+
+#if SVC_EXTENSION
+#if O0215_PHASE_ALIGNMENT_REMOVAL
+Void TComPrediction::upsampleBasePic( TComSlice* currSlice, UInt refLayerIdc, TComPicYuv* pcUsPic, TComPicYuv* pcBasePic, TComPicYuv* pcTempPic )
+{
+  m_cUsf.upsampleBasePic( currSlice, refLayerIdc, pcUsPic, pcBasePic, pcTempPic );
+}
+#else
+#if O0215_PHASE_ALIGNMENT
+#if O0194_JOINT_US_BITSHIFT
+Void TComPrediction::upsampleBasePic( TComSlice* currSlice, UInt refLayerIdc, TComPicYuv* pcUsPic, TComPicYuv* pcBasePic, TComPicYuv* pcTempPic, Bool phaseAlignFlag )
+{
+  m_cUsf.upsampleBasePic( currSlice, refLayerIdc, pcUsPic, pcBasePic, pcTempPic, phaseAlignFlag );
+}
+#else
+Void TComPrediction::upsampleBasePic( UInt refLayerIdc, TComPicYuv* pcUsPic, TComPicYuv* pcBasePic, TComPicYuv* pcTempPic, const Window window, Bool phaseAlignFlag )
+{
+  m_cUsf.upsampleBasePic( refLayerIdc, pcUsPic, pcBasePic, pcTempPic, window, phaseAlignFlag );
+}
+#endif
+#else
+#if O0194_JOINT_US_BITSHIFT
+#if REF_REGION_OFFSET
+Void TComPrediction::upsampleBasePic( UInt refLayerIdc, TComPicYuv* pcUsPic, TComPicYuv* pcBasePic, TComPicYuv* pcTempPic, const Window window, const Window altRefWindow )
+{
+  m_cUsf.upsampleBasePic( refLayerIdc, pcUsPic, pcBasePic, pcTempPic, window, altRefWindow );
+}
+#else
+Void TComPrediction::upsampleBasePic( TComSlice* currSlice, UInt refLayerIdc, TComPicYuv* pcUsPic, TComPicYuv* pcBasePic, TComPicYuv* pcTempPic, const Window window)
+{
+  m_cUsf.upsampleBasePic( refLayerIdc, pcUsPic, pcBasePic, pcTempPic, window);
+}
+#endif
+#else
+Void TComPrediction::upsampleBasePic( UInt refLayerIdc, TComPicYuv* pcUsPic, TComPicYuv* pcBasePic, TComPicYuv* pcTempPic, const Window window)
+{
+  m_cUsf.upsampleBasePic( refLayerIdc, pcUsPic, pcBasePic, pcTempPic, window);
+}
+#endif
+#endif
+#endif
+#endif //SVC_EXTENSION
+//! \}
Index: /tags/SHM-9.0/source/Lib/TLibCommon/TComPrediction.h
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibCommon/TComPrediction.h	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibCommon/TComPrediction.h	(revision 1088)
@@ -0,0 +1,174 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TComPrediction.h
+    \brief    prediction class (header)
+*/
+
+#ifndef __TCOMPREDICTION__
+#define __TCOMPREDICTION__
+
+
+// Include files
+#include "TComPic.h"
+#include "TComMotionInfo.h"
+#include "TComPattern.h"
+#include "TComTrQuant.h"
+#include "TComInterpolationFilter.h"
+#include "TComWeightPrediction.h"
+
+class TComTU; // forward declaration
+
+#if SVC_EXTENSION
+#include "TComUpsampleFilter.h"
+#endif
+//! \ingroup TLibCommon
+//! \{
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// prediction class
+typedef enum PRED_BUF_E
+{
+  PRED_BUF_UNFILTERED=0,
+  PRED_BUF_FILTERED=1,
+  NUM_PRED_BUF=2
+} PRED_BUF;
+
+static const UInt MAX_INTRA_FILTER_DEPTHS=5;
+
+class TComPrediction : public TComWeightPrediction
+{
+private:
+  static const UChar m_aucIntraFilter[MAX_NUM_CHANNEL_TYPE][MAX_INTRA_FILTER_DEPTHS];
+
+protected:
+  Pel*      m_piYuvExt[MAX_NUM_COMPONENT][NUM_PRED_BUF];
+  Int       m_iYuvExtSize;
+
+  TComYuv   m_acYuvPred[NUM_REF_PIC_LIST_01];
+  TComYuv   m_cYuvPredTemp;
+  TComYuv m_filteredBlock[LUMA_INTERPOLATION_FILTER_SUB_SAMPLE_POSITIONS][LUMA_INTERPOLATION_FILTER_SUB_SAMPLE_POSITIONS];
+  TComYuv m_filteredBlockTmp[LUMA_INTERPOLATION_FILTER_SUB_SAMPLE_POSITIONS];
+
+  TComInterpolationFilter m_if;
+
+  Pel*   m_pLumaRecBuffer;       ///< array for downsampled reconstructed luma sample
+  Int    m_iLumaRecStride;       ///< stride of #m_pLumaRecBuffer array
+
+  Void xPredIntraAng            ( Int bitDepth, const Pel* pSrc, Int srcStride, Pel* pDst, Int dstStride, UInt width, UInt height, ChannelType channelType, ChromaFormat format, UInt dirMode, Bool blkAboveAvailable, Bool blkLeftAvailable, const Bool bEnableEdgeFilters );
+  Void xPredIntraPlanar         ( const Pel* pSrc, Int srcStride, Pel* rpDst, Int dstStride, UInt width, UInt height, ChannelType channelType, ChromaFormat format );
+
+  // motion compensation functions
+  Void xPredInterUni            ( TComDataCU* pcCU,                          UInt uiPartAddr,               Int iWidth, Int iHeight, RefPicList eRefPicList, TComYuv* pcYuvPred, Bool bi=false          );
+  Void xPredInterBi             ( TComDataCU* pcCU,                          UInt uiPartAddr,               Int iWidth, Int iHeight,                         TComYuv* pcYuvPred          );
+  Void xPredInterBlk(const ComponentID compID, TComDataCU *cu, TComPicYuv *refPic, UInt partAddr, TComMv *mv, Int width, Int height, TComYuv *dstPic, Bool bi );
+  Void xWeightedAverage         ( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, Int iRefIdx0, Int iRefIdx1, UInt uiPartAddr, Int iWidth, Int iHeight, TComYuv* pcYuvDst );
+
+  Void xGetLLSPrediction ( const Pel* pSrc0, Int iSrcStride, Pel* pDst0, Int iDstStride, UInt uiWidth, UInt uiHeight, UInt uiExt0, const ChromaFormat chFmt  DEBUG_STRING_FN_DECLARE(sDebug) );
+
+  Void xDCPredFiltering( const Pel* pSrc, Int iSrcStride, Pel* pDst, Int iDstStride, Int iWidth, Int iHeight, ChannelType channelType );
+  Bool xCheckIdenticalMotion    ( TComDataCU* pcCU, UInt PartAddr);
+  Void destroy();
+
+#if SVC_EXTENSION
+  TComUpsampleFilter      m_cUsf;
+#endif
+
+public:
+  TComPrediction();
+  virtual ~TComPrediction();
+
+  Void    initTempBuff(ChromaFormat chromaFormatIDC);
+
+  ChromaFormat getChromaFormat() const { return m_cYuvPredTemp.getChromaFormat(); }
+
+  // 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 predIntraAng               ( const ComponentID compID, UInt uiDirMode, Pel *piOrg /* Will be null for decoding */, UInt uiOrgStride, Pel* piPred, UInt uiStride, TComTU &rTu, Bool bAbove, Bool bLeft, const Bool bUseFilteredPredSamples, const Bool bUseLosslessDPCM = false );
+
+  Pel  predIntraGetPredValDC      ( const Pel* pSrc, Int iSrcStride, UInt iWidth, UInt iHeight, ChannelType channelType, ChromaFormat format, Bool bAbove, Bool bLeft );
+
+  Pel*  getPredictorPtr           ( const ComponentID compID, const Bool bUseFilteredPredictions )
+  {
+    return m_piYuvExt[compID][bUseFilteredPredictions?PRED_BUF_FILTERED:PRED_BUF_UNFILTERED];
+  }
+
+  // This function is actually still in TComPattern.cpp
+  /// set parameters from CU data for accessing ADI data
+  Void initAdiPatternChType ( TComTU &rTu,
+                              Bool&       bAbove,
+                              Bool&       bLeft,
+                              const ComponentID compID, const Bool bFilterRefSamples
+                              DEBUG_STRING_FN_DECLARE(sDebug)
+                              );
+
+  static Bool filteringIntraReferenceSamples(const ComponentID compID, UInt uiDirMode, UInt uiTuChWidth, UInt uiTuChHeight, const ChromaFormat chFmt, const Bool intraReferenceSmoothingDisabled);
+
+  static Bool UseDPCMForFirstPassIntraEstimation(TComTU &rTu, const UInt uiDirMode);
+
+#if SVC_EXTENSION
+#if O0215_PHASE_ALIGNMENT_REMOVAL
+Void upsampleBasePic( TComSlice* currSlice, UInt refLayerIdc, TComPicYuv* pcUsPic, TComPicYuv* pcBasePic, TComPicYuv* pcTempPic );
+#else
+#if O0215_PHASE_ALIGNMENT
+#if O0194_JOINT_US_BITSHIFT
+  Void upsampleBasePic( TComSlice* currSlice, UInt refLayerIdc, TComPicYuv* pcUsPic, TComPicYuv* pcBasePic, TComPicYuv* pcTempPic, Bool phaseAlignFlag );
+#else
+  Void upsampleBasePic( UInt refLayerIdc, TComPicYuv* pcUsPic, TComPicYuv* pcBasePic, TComPicYuv* pcTempPic, const Window window, Bool phaseAlignFlag );
+#endif
+#else
+#if O0194_JOINT_US_BITSHIFT
+#if REF_REGION_OFFSET
+  Void upsampleBasePic( TComSlice* currSlice, UInt refLayerIdc, TComPicYuv* pcUsPic, TComPicYuv* pcBasePic, TComPicYuv* pcTempPic, const Window window, const Window altRefWindow );
+#else
+  Void upsampleBasePic( TComSlice* currSlice, UInt refLayerIdc, TComPicYuv* pcUsPic, TComPicYuv* pcBasePic, TComPicYuv* pcTempPic, const Window window );
+#endif
+#else
+  Void upsampleBasePic( UInt refLayerIdc, TComPicYuv* pcUsPic, TComPicYuv* pcBasePic, TComPicYuv* pcTempPic, const Window window );
+#endif
+#endif
+#endif
+#endif //SVC_EXTENSION
+};
+
+//! \}
+
+#endif // __TCOMPREDICTION__
Index: /tags/SHM-9.0/source/Lib/TLibCommon/TComRdCost.cpp
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibCommon/TComRdCost.cpp	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibCommon/TComRdCost.cpp	(revision 1088)
@@ -0,0 +1,1610 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TComRdCost.cpp
+    \brief    RD cost computation class
+*/
+
+#include <math.h>
+#include <assert.h>
+#include "TComRom.h"
+#include "TComRdCost.h"
+
+//! \ingroup TLibCommon
+//! \{
+
+TComRdCost::TComRdCost()
+{
+  init();
+}
+
+TComRdCost::~TComRdCost()
+{
+}
+
+// Calculate RD functions
+Double TComRdCost::calcRdCost( UInt uiBits, Distortion uiDistortion, Bool bFlag, DFunc eDFunc )
+{
+  Double dRdCost = 0.0;
+  Double dLambda = 0.0;
+
+  switch ( eDFunc )
+  {
+    case DF_SSE:
+      assert(0);
+      break;
+    case DF_SAD:
+#if RExt__HIGH_BIT_DEPTH_SUPPORT
+      dLambda = m_dLambdaMotionSAD[0]; // 0 is valid, because for lossless blocks, the cost equation is modified to compensate.
+#else
+      dLambda = (Double)m_uiLambdaMotionSAD[0]; // 0 is valid, because for lossless blocks, the cost equation is modified to compensate.
+#endif
+      break;
+    case DF_DEFAULT:
+      dLambda =         m_dLambda;
+      break;
+    case DF_SSE_FRAME:
+      dLambda =         m_dFrameLambda;
+      break;
+    default:
+      assert (0);
+      break;
+  }
+
+  if (bFlag) //NOTE: this "bFlag" is never true
+  {
+    // Intra8x8, Intra4x4 Block only...
+    if (m_costMode != COST_STANDARD_LOSSY)
+    {
+      dRdCost = (Double(uiDistortion) / dLambda) + Double(uiBits); // all lossless costs would have uiDistortion=0, and therefore this cost function can be used.
+    }
+    else
+    {
+      dRdCost = (((Double)uiDistortion) + ((Double)uiBits * dLambda));
+    }
+  }
+  else
+  {
+    if (eDFunc == DF_SAD)
+    {
+      if (m_costMode != COST_STANDARD_LOSSY)
+      {
+        dRdCost = ((Double(uiDistortion) * 65536) / dLambda) + Double(uiBits); // all lossless costs would have uiDistortion=0, and therefore this cost function can be used.
+      }
+      else
+      {
+        dRdCost = floor(Double(uiDistortion) + (floor((Double(uiBits) * dLambda) + 0.5) / 65536.0));
+      }
+    }
+    else
+    {
+      if (m_costMode != COST_STANDARD_LOSSY)
+      {
+        dRdCost = (Double(uiDistortion) / dLambda) + Double(uiBits); // all lossless costs would have uiDistortion=0, and therefore this cost function can be used.
+      }
+      else
+      {
+        dRdCost = floor(Double(uiDistortion) + (Double(uiBits) * dLambda) + 0.5);
+      }
+    }
+  }
+
+  return dRdCost;
+}
+
+Double TComRdCost::calcRdCost64( UInt64 uiBits, UInt64 uiDistortion, Bool bFlag, DFunc eDFunc )
+{
+  Double dRdCost = 0.0;
+  Double dLambda = 0.0;
+
+  switch ( eDFunc )
+  {
+    case DF_SSE:
+      assert(0);
+      break;
+    case DF_SAD:
+#if RExt__HIGH_BIT_DEPTH_SUPPORT
+      dLambda = m_dLambdaMotionSAD[0]; // 0 is valid, because for lossless blocks, the cost equation is modified to compensate.
+#else
+      dLambda = (Double)m_uiLambdaMotionSAD[0]; // 0 is valid, because for lossless blocks, the cost equation is modified to compensate.
+#endif
+      break;
+    case DF_DEFAULT:
+      dLambda =         m_dLambda;
+      break;
+    case DF_SSE_FRAME:
+      dLambda =         m_dFrameLambda;
+      break;
+    default:
+      assert (0);
+      break;
+  }
+
+  if (bFlag) //NOTE: this "bFlag" is never true
+  {
+    // Intra8x8, Intra4x4 Block only...
+    if (m_costMode != COST_STANDARD_LOSSY)
+    {
+      dRdCost = (Double(uiDistortion) / dLambda) + Double(uiBits); // all lossless costs would have uiDistortion=0, and therefore this cost function can be used.
+    }
+    else
+    {
+      dRdCost = (((Double)(Int64)uiDistortion) + ((Double)(Int64)uiBits * dLambda));
+    }
+  }
+  else
+  {
+    if (eDFunc == DF_SAD)
+    {
+      if (m_costMode != COST_STANDARD_LOSSY)
+      {
+        dRdCost = ((Double(uiDistortion) * 65536) / dLambda) + Double(uiBits); // all lossless costs would have uiDistortion=0, and therefore this cost function can be used.
+      }
+      else
+      {
+        dRdCost = floor(Double(uiDistortion) + (floor((Double(uiBits) * dLambda) + 0.5) / 65536.0));
+      }
+    }
+    else
+    {
+      if (m_costMode != COST_STANDARD_LOSSY)
+      {
+        dRdCost = (Double(uiDistortion) / dLambda) + Double(uiBits); // all lossless costs would have uiDistortion=0, and therefore this cost function can be used.
+      }
+      else
+      {
+        dRdCost = floor(Double(uiDistortion) + (Double(uiBits) * dLambda) + 0.5);
+      }
+    }
+  }
+
+  return dRdCost;
+}
+
+Void TComRdCost::setLambda( Double dLambda )
+{
+  m_dLambda           = dLambda;
+  m_sqrtLambda        = sqrt(m_dLambda);
+#if RExt__HIGH_BIT_DEPTH_SUPPORT
+  m_dLambdaMotionSAD[0] = 65536.0 * m_sqrtLambda;
+  m_dLambdaMotionSSE[0] = 65536.0 * m_dLambda;
+#if FULL_NBIT
+  dLambda = 0.57 * pow(2.0, ((LOSSLESS_AND_MIXED_LOSSLESS_RD_COST_TEST_QP_PRIME - 12) / 3.0));
+#else
+  dLambda = 0.57 * pow(2.0, ((LOSSLESS_AND_MIXED_LOSSLESS_RD_COST_TEST_QP_PRIME - 12 - 6 * (g_bitDepth[CHANNEL_TYPE_LUMA] - 8)) / 3.0));
+#endif
+  m_dLambdaMotionSAD[1] = 65536.0 * sqrt(dLambda);
+  m_dLambdaMotionSSE[1] = 65536.0 * dLambda;
+#else
+  m_uiLambdaMotionSAD[0] = (UInt)floor(65536.0 * m_sqrtLambda);
+  m_uiLambdaMotionSSE[0] = (UInt)floor(65536.0 * m_dLambda   );
+#if FULL_NBIT
+  dLambda = 0.57 * pow(2.0, ((LOSSLESS_AND_MIXED_LOSSLESS_RD_COST_TEST_QP_PRIME - 12) / 3.0));
+#else
+  dLambda = 0.57 * pow(2.0, ((LOSSLESS_AND_MIXED_LOSSLESS_RD_COST_TEST_QP_PRIME - 12 - 6 * (g_bitDepth[CHANNEL_TYPE_LUMA] - 8)) / 3.0));
+#endif
+  m_uiLambdaMotionSAD[1] = (UInt)floor(65536.0 * sqrt(dLambda));
+  m_uiLambdaMotionSSE[1] = (UInt)floor(65536.0 * dLambda   );
+#endif
+}
+
+
+// Initalize Function Pointer by [eDFunc]
+Void TComRdCost::init()
+{
+  m_afpDistortFunc[DF_DEFAULT] = NULL;                  // for DF_DEFAULT
+
+  m_afpDistortFunc[DF_SSE    ] = TComRdCost::xGetSSE;
+  m_afpDistortFunc[DF_SSE4   ] = TComRdCost::xGetSSE4;
+  m_afpDistortFunc[DF_SSE8   ] = TComRdCost::xGetSSE8;
+  m_afpDistortFunc[DF_SSE16  ] = TComRdCost::xGetSSE16;
+  m_afpDistortFunc[DF_SSE32  ] = TComRdCost::xGetSSE32;
+  m_afpDistortFunc[DF_SSE64  ] = TComRdCost::xGetSSE64;
+  m_afpDistortFunc[DF_SSE16N ] = TComRdCost::xGetSSE16N;
+
+  m_afpDistortFunc[DF_SAD    ] = TComRdCost::xGetSAD;
+  m_afpDistortFunc[DF_SAD4   ] = TComRdCost::xGetSAD4;
+  m_afpDistortFunc[DF_SAD8   ] = TComRdCost::xGetSAD8;
+  m_afpDistortFunc[DF_SAD16  ] = TComRdCost::xGetSAD16;
+  m_afpDistortFunc[DF_SAD32  ] = TComRdCost::xGetSAD32;
+  m_afpDistortFunc[DF_SAD64  ] = TComRdCost::xGetSAD64;
+  m_afpDistortFunc[DF_SAD16N ] = TComRdCost::xGetSAD16N;
+
+  m_afpDistortFunc[DF_SADS   ] = TComRdCost::xGetSAD;
+  m_afpDistortFunc[DF_SADS4  ] = TComRdCost::xGetSAD4;
+  m_afpDistortFunc[DF_SADS8  ] = TComRdCost::xGetSAD8;
+  m_afpDistortFunc[DF_SADS16 ] = TComRdCost::xGetSAD16;
+  m_afpDistortFunc[DF_SADS32 ] = TComRdCost::xGetSAD32;
+  m_afpDistortFunc[DF_SADS64 ] = TComRdCost::xGetSAD64;
+  m_afpDistortFunc[DF_SADS16N] = TComRdCost::xGetSAD16N;
+
+#if AMP_SAD
+  m_afpDistortFunc[DF_SAD12  ] = TComRdCost::xGetSAD12;
+  m_afpDistortFunc[DF_SAD24  ] = TComRdCost::xGetSAD24;
+  m_afpDistortFunc[DF_SAD48  ] = TComRdCost::xGetSAD48;
+
+  m_afpDistortFunc[DF_SADS12 ] = TComRdCost::xGetSAD12;
+  m_afpDistortFunc[DF_SADS24 ] = TComRdCost::xGetSAD24;
+  m_afpDistortFunc[DF_SADS48 ] = TComRdCost::xGetSAD48;
+#endif
+  m_afpDistortFunc[DF_HADS   ] = TComRdCost::xGetHADs;
+  m_afpDistortFunc[DF_HADS4  ] = TComRdCost::xGetHADs;
+  m_afpDistortFunc[DF_HADS8  ] = TComRdCost::xGetHADs;
+  m_afpDistortFunc[DF_HADS16 ] = TComRdCost::xGetHADs;
+  m_afpDistortFunc[DF_HADS32 ] = TComRdCost::xGetHADs;
+  m_afpDistortFunc[DF_HADS64 ] = TComRdCost::xGetHADs;
+  m_afpDistortFunc[DF_HADS16N] = TComRdCost::xGetHADs;
+
+  m_costMode                   = COST_STANDARD_LOSSY;
+
+#if RExt__HIGH_BIT_DEPTH_SUPPORT
+  m_dCost                      = 0;
+#else
+  m_uiCost                     = 0;
+#endif
+  m_iCostScale                 = 0;
+}
+
+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[DF_SAD12];
+  }
+  else if (rcDistParam.iCols == 24)
+  {
+    rcDistParam.DistFunc = m_afpDistortFunc[DF_SAD24];
+  }
+  else if (rcDistParam.iCols == 48)
+  {
+    rcDistParam.DistFunc = m_afpDistortFunc[DF_SAD48];
+  }
+#endif
+
+  // initialize
+  rcDistParam.iSubShift  = 0;
+}
+
+// Setting the Distortion Parameter for Inter (subpel ME with step)
+Void TComRdCost::setDistParam( TComPattern* pcPatternKey, Pel* piRefY, Int iRefStride, Int iStep, DistParam& rcDistParam, Bool bHADME )
+{
+#if O0194_WEIGHTED_PREDICTION_CGS
+  // Bug fix: The correct bit depth has not been used for weighted cost calculation
+  rcDistParam.bitDepth = g_bitDepth[CHANNEL_TYPE_LUMA];
+#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();
+
+  // 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[DF_SADS12];
+    }
+    else if (rcDistParam.iCols == 24)
+    {
+      rcDistParam.DistFunc = m_afpDistortFunc[DF_SADS24];
+    }
+    else if (rcDistParam.iCols == 48)
+    {
+      rcDistParam.DistFunc = m_afpDistortFunc[DF_SADS48];
+    }
+#endif
+  }
+  else
+  {
+    rcDistParam.DistFunc = m_afpDistortFunc[DF_HADS + g_aucConvertToBit[ rcDistParam.iCols ] + 1 ];
+  }
+
+  // initialize
+  rcDistParam.iSubShift  = 0;
+}
+
+Void TComRdCost::setDistParam( DistParam& rcDP, Int bitDepth, Pel* p1, Int iStride1, Pel* p2, Int iStride2, Int iWidth, Int iHeight, Bool bHadamard )
+{
+  rcDP.pOrg       = p1;
+  rcDP.pCur       = p2;
+  rcDP.iStrideOrg = iStride1;
+  rcDP.iStrideCur = iStride2;
+  rcDP.iCols      = iWidth;
+  rcDP.iRows      = iHeight;
+  rcDP.iStep      = 1;
+  rcDP.iSubShift  = 0;
+  rcDP.bitDepth   = bitDepth;
+  rcDP.DistFunc   = m_afpDistortFunc[ ( bHadamard ? DF_HADS : DF_SADS ) + g_aucConvertToBit[ iWidth ] + 1 ];
+}
+
+Distortion TComRdCost::calcHAD( Int bitDepth, Pel* pi0, Int iStride0, Pel* pi1, Int iStride1, Int iWidth, Int iHeight )
+{
+  Distortion uiSum = 0;
+  Int x, y;
+
+  if ( ( (iWidth % 8) == 0 ) && ( (iHeight % 8) == 0 ) )
+  {
+    for ( y=0; y<iHeight; y+= 8 )
+    {
+      for ( x=0; x<iWidth; x+= 8 )
+      {
+        uiSum += xCalcHADs8x8( &pi0[x], &pi1[x], iStride0, iStride1, 1 );
+      }
+      pi0 += iStride0*8;
+      pi1 += iStride1*8;
+    }
+  }
+  else
+  {
+    assert ( ( (iWidth % 4) == 0 ) && ( (iHeight % 4) == 0 ) );
+
+    for ( y=0; y<iHeight; y+= 4 )
+    {
+      for ( x=0; x<iWidth; x+= 4 )
+      {
+        uiSum += xCalcHADs4x4( &pi0[x], &pi1[x], iStride0, iStride1, 1 );
+      }
+      pi0 += iStride0*4;
+      pi1 += iStride1*4;
+    }
+  }
+
+  return ( uiSum >> DISTORTION_PRECISION_ADJUSTMENT(bitDepth-8) );
+}
+
+Distortion TComRdCost::getDistPart( Int bitDepth, Pel* piCur, Int iCurStride,  Pel* piOrg, Int iOrgStride, UInt uiBlkWidth, UInt uiBlkHeight, const ComponentID compID, DFunc eDFunc )
+{
+  DistParam cDtParam;
+  setDistParam( uiBlkWidth, uiBlkHeight, eDFunc, cDtParam );
+  cDtParam.pOrg       = piOrg;
+  cDtParam.pCur       = piCur;
+  cDtParam.iStrideOrg = iOrgStride;
+  cDtParam.iStrideCur = iCurStride;
+  cDtParam.iStep      = 1;
+
+  cDtParam.bApplyWeight = false;
+  cDtParam.compIdx      = MAX_NUM_COMPONENT; // just for assert: to be sure it was set before use
+  cDtParam.bitDepth     = bitDepth;
+
+  if (isChroma(compID))
+  {
+    return ((Distortion) (m_distortionWeight[compID] * cDtParam.DistFunc( &cDtParam )));
+  }
+  else
+  {
+    return cDtParam.DistFunc( &cDtParam );
+  }
+}
+
+// ====================================================================================================================
+// Distortion functions
+// ====================================================================================================================
+
+// --------------------------------------------------------------------------------------------------------------------
+// SAD
+// --------------------------------------------------------------------------------------------------------------------
+
+Distortion TComRdCost::xGetSAD( DistParam* pcDtParam )
+{
+  if ( pcDtParam->bApplyWeight )
+  {
+    return TComRdCostWeightPrediction::xGetSADw( pcDtParam );
+  }
+  const Pel* piOrg   = pcDtParam->pOrg;
+  const Pel* piCur   = pcDtParam->pCur;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iCols   = pcDtParam->iCols;
+  Int  iStrideCur = pcDtParam->iStrideCur;
+  Int  iStrideOrg = pcDtParam->iStrideOrg;
+
+  Distortion 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) );
+}
+
+Distortion TComRdCost::xGetSAD4( DistParam* pcDtParam )
+{
+  if ( pcDtParam->bApplyWeight )
+  {
+    return TComRdCostWeightPrediction::xGetSADw( pcDtParam );
+  }
+  const Pel* piOrg   = pcDtParam->pOrg;
+  const 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;
+
+  Distortion 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) );
+}
+
+Distortion TComRdCost::xGetSAD8( DistParam* pcDtParam )
+{
+  if ( pcDtParam->bApplyWeight )
+  {
+    return TComRdCostWeightPrediction::xGetSADw( pcDtParam );
+  }
+  const Pel* piOrg      = pcDtParam->pOrg;
+  const 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;
+
+  Distortion 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) );
+}
+
+Distortion TComRdCost::xGetSAD16( DistParam* pcDtParam )
+{
+  if ( pcDtParam->bApplyWeight )
+  {
+    return TComRdCostWeightPrediction::xGetSADw( pcDtParam );
+  }
+  const Pel* piOrg   = pcDtParam->pOrg;
+  const 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;
+
+  Distortion 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
+Distortion TComRdCost::xGetSAD12( DistParam* pcDtParam )
+{
+  if ( pcDtParam->bApplyWeight )
+  {
+    return TComRdCostWeightPrediction::xGetSADw( pcDtParam );
+  }
+  const Pel* piOrg   = pcDtParam->pOrg;
+  const 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;
+
+  Distortion 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
+
+Distortion TComRdCost::xGetSAD16N( DistParam* pcDtParam )
+{
+  const Pel* piOrg   = pcDtParam->pOrg;
+  const 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;
+
+  Distortion 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) );
+}
+
+Distortion TComRdCost::xGetSAD32( DistParam* pcDtParam )
+{
+  if ( pcDtParam->bApplyWeight )
+  {
+    return TComRdCostWeightPrediction::xGetSADw( pcDtParam );
+  }
+  const Pel* piOrg   = pcDtParam->pOrg;
+  const 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;
+
+  Distortion 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
+Distortion TComRdCost::xGetSAD24( DistParam* pcDtParam )
+{
+  if ( pcDtParam->bApplyWeight )
+  {
+    return TComRdCostWeightPrediction::xGetSADw( pcDtParam );
+  }
+  const Pel* piOrg   = pcDtParam->pOrg;
+  const 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;
+
+  Distortion 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
+
+Distortion TComRdCost::xGetSAD64( DistParam* pcDtParam )
+{
+  if ( pcDtParam->bApplyWeight )
+  {
+    return TComRdCostWeightPrediction::xGetSADw( pcDtParam );
+  }
+  const Pel* piOrg   = pcDtParam->pOrg;
+  const 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;
+
+  Distortion 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
+Distortion TComRdCost::xGetSAD48( DistParam* pcDtParam )
+{
+  if ( pcDtParam->bApplyWeight )
+  {
+    return TComRdCostWeightPrediction::xGetSADw( pcDtParam );
+  }
+  const Pel* piOrg   = pcDtParam->pOrg;
+  const 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;
+
+  Distortion 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
+
+// --------------------------------------------------------------------------------------------------------------------
+// SSE
+// --------------------------------------------------------------------------------------------------------------------
+
+Distortion TComRdCost::xGetSSE( DistParam* pcDtParam )
+{
+  if ( pcDtParam->bApplyWeight )
+  {
+    return TComRdCostWeightPrediction::xGetSSEw( pcDtParam );
+  }
+  const Pel* piOrg   = pcDtParam->pOrg;
+  const Pel* piCur   = pcDtParam->pCur;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iCols   = pcDtParam->iCols;
+  Int  iStrideOrg = pcDtParam->iStrideOrg;
+  Int  iStrideCur = pcDtParam->iStrideCur;
+
+  Distortion uiSum   = 0;
+  UInt       uiShift = DISTORTION_PRECISION_ADJUSTMENT((pcDtParam->bitDepth-8) << 1);
+
+  Intermediate_Int iTemp;
+
+  for( ; iRows != 0; iRows-- )
+  {
+    for (Int n = 0; n < iCols; n++ )
+    {
+      iTemp = piOrg[n  ] - piCur[n  ];
+      uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    }
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+
+  return ( uiSum );
+}
+
+Distortion TComRdCost::xGetSSE4( DistParam* pcDtParam )
+{
+  if ( pcDtParam->bApplyWeight )
+  {
+    assert( pcDtParam->iCols == 4 );
+    return TComRdCostWeightPrediction::xGetSSEw( pcDtParam );
+  }
+  const Pel* piOrg   = pcDtParam->pOrg;
+  const Pel* piCur   = pcDtParam->pCur;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iStrideOrg = pcDtParam->iStrideOrg;
+  Int  iStrideCur = pcDtParam->iStrideCur;
+
+  Distortion uiSum   = 0;
+  UInt       uiShift = DISTORTION_PRECISION_ADJUSTMENT((pcDtParam->bitDepth-8) << 1);
+
+  Intermediate_Int  iTemp;
+
+  for( ; iRows != 0; iRows-- )
+  {
+
+    iTemp = piOrg[0] - piCur[0]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[1] - piCur[1]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[2] - piCur[2]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[3] - piCur[3]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+
+  return ( uiSum );
+}
+
+Distortion TComRdCost::xGetSSE8( DistParam* pcDtParam )
+{
+  if ( pcDtParam->bApplyWeight )
+  {
+    assert( pcDtParam->iCols == 8 );
+    return TComRdCostWeightPrediction::xGetSSEw( pcDtParam );
+  }
+  const Pel* piOrg   = pcDtParam->pOrg;
+  const Pel* piCur   = pcDtParam->pCur;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iStrideOrg = pcDtParam->iStrideOrg;
+  Int  iStrideCur = pcDtParam->iStrideCur;
+
+  Distortion uiSum   = 0;
+  UInt       uiShift = DISTORTION_PRECISION_ADJUSTMENT((pcDtParam->bitDepth-8) << 1);
+
+  Intermediate_Int  iTemp;
+
+  for( ; iRows != 0; iRows-- )
+  {
+    iTemp = piOrg[0] - piCur[0]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[1] - piCur[1]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[2] - piCur[2]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[3] - piCur[3]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[4] - piCur[4]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[5] - piCur[5]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[6] - piCur[6]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[7] - piCur[7]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+
+  return ( uiSum );
+}
+
+Distortion TComRdCost::xGetSSE16( DistParam* pcDtParam )
+{
+  if ( pcDtParam->bApplyWeight )
+  {
+    assert( pcDtParam->iCols == 16 );
+    return TComRdCostWeightPrediction::xGetSSEw( pcDtParam );
+  }
+  const Pel* piOrg   = pcDtParam->pOrg;
+  const Pel* piCur   = pcDtParam->pCur;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iStrideOrg = pcDtParam->iStrideOrg;
+  Int  iStrideCur = pcDtParam->iStrideCur;
+
+  Distortion uiSum   = 0;
+  UInt       uiShift = DISTORTION_PRECISION_ADJUSTMENT((pcDtParam->bitDepth-8) << 1);
+
+  Intermediate_Int  iTemp;
+
+  for( ; iRows != 0; iRows-- )
+  {
+
+    iTemp = piOrg[ 0] - piCur[ 0]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[ 1] - piCur[ 1]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[ 2] - piCur[ 2]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[ 3] - piCur[ 3]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[ 4] - piCur[ 4]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[ 5] - piCur[ 5]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[ 6] - piCur[ 6]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[ 7] - piCur[ 7]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[ 8] - piCur[ 8]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[ 9] - piCur[ 9]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[10] - piCur[10]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[11] - piCur[11]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[12] - piCur[12]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[13] - piCur[13]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[14] - piCur[14]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[15] - piCur[15]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+
+  return ( uiSum );
+}
+
+Distortion TComRdCost::xGetSSE16N( DistParam* pcDtParam )
+{
+  if ( pcDtParam->bApplyWeight )
+  {
+    return TComRdCostWeightPrediction::xGetSSEw( pcDtParam );
+  }
+  const Pel* piOrg   = pcDtParam->pOrg;
+  const Pel* piCur   = pcDtParam->pCur;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iCols   = pcDtParam->iCols;
+  Int  iStrideOrg = pcDtParam->iStrideOrg;
+  Int  iStrideCur = pcDtParam->iStrideCur;
+
+  Distortion uiSum   = 0;
+  UInt       uiShift = DISTORTION_PRECISION_ADJUSTMENT((pcDtParam->bitDepth-8) << 1);
+
+  Intermediate_Int  iTemp;
+
+  for( ; iRows != 0; iRows-- )
+  {
+    for (Int n = 0; n < iCols; n+=16 )
+    {
+
+      iTemp = piOrg[n+ 0] - piCur[n+ 0]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+      iTemp = piOrg[n+ 1] - piCur[n+ 1]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+      iTemp = piOrg[n+ 2] - piCur[n+ 2]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+      iTemp = piOrg[n+ 3] - piCur[n+ 3]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+      iTemp = piOrg[n+ 4] - piCur[n+ 4]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+      iTemp = piOrg[n+ 5] - piCur[n+ 5]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+      iTemp = piOrg[n+ 6] - piCur[n+ 6]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+      iTemp = piOrg[n+ 7] - piCur[n+ 7]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+      iTemp = piOrg[n+ 8] - piCur[n+ 8]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+      iTemp = piOrg[n+ 9] - piCur[n+ 9]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+      iTemp = piOrg[n+10] - piCur[n+10]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+      iTemp = piOrg[n+11] - piCur[n+11]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+      iTemp = piOrg[n+12] - piCur[n+12]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+      iTemp = piOrg[n+13] - piCur[n+13]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+      iTemp = piOrg[n+14] - piCur[n+14]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+      iTemp = piOrg[n+15] - piCur[n+15]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+
+    }
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+
+  return ( uiSum );
+}
+
+Distortion TComRdCost::xGetSSE32( DistParam* pcDtParam )
+{
+  if ( pcDtParam->bApplyWeight )
+  {
+    assert( pcDtParam->iCols == 32 );
+    return TComRdCostWeightPrediction::xGetSSEw( pcDtParam );
+  }
+  const Pel* piOrg   = pcDtParam->pOrg;
+  const Pel* piCur   = pcDtParam->pCur;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iStrideOrg = pcDtParam->iStrideOrg;
+  Int  iStrideCur = pcDtParam->iStrideCur;
+
+  Distortion uiSum   = 0;
+  UInt       uiShift = DISTORTION_PRECISION_ADJUSTMENT((pcDtParam->bitDepth-8) << 1);
+
+  Intermediate_Int  iTemp;
+
+  for( ; iRows != 0; iRows-- )
+  {
+
+    iTemp = piOrg[ 0] - piCur[ 0]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[ 1] - piCur[ 1]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[ 2] - piCur[ 2]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[ 3] - piCur[ 3]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[ 4] - piCur[ 4]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[ 5] - piCur[ 5]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[ 6] - piCur[ 6]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[ 7] - piCur[ 7]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[ 8] - piCur[ 8]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[ 9] - piCur[ 9]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[10] - piCur[10]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[11] - piCur[11]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[12] - piCur[12]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[13] - piCur[13]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[14] - piCur[14]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[15] - piCur[15]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[16] - piCur[16]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[17] - piCur[17]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[18] - piCur[18]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[19] - piCur[19]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[20] - piCur[20]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[21] - piCur[21]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[22] - piCur[22]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[23] - piCur[23]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[24] - piCur[24]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[25] - piCur[25]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[26] - piCur[26]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[27] - piCur[27]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[28] - piCur[28]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[29] - piCur[29]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[30] - piCur[30]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[31] - piCur[31]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+
+  return ( uiSum );
+}
+
+Distortion TComRdCost::xGetSSE64( DistParam* pcDtParam )
+{
+  if ( pcDtParam->bApplyWeight )
+  {
+    assert( pcDtParam->iCols == 64 );
+    return TComRdCostWeightPrediction::xGetSSEw( pcDtParam );
+  }
+  const Pel* piOrg   = pcDtParam->pOrg;
+  const Pel* piCur   = pcDtParam->pCur;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iStrideOrg = pcDtParam->iStrideOrg;
+  Int  iStrideCur = pcDtParam->iStrideCur;
+
+  Distortion uiSum   = 0;
+  UInt       uiShift = DISTORTION_PRECISION_ADJUSTMENT((pcDtParam->bitDepth-8) << 1);
+
+  Intermediate_Int  iTemp;
+
+  for( ; iRows != 0; iRows-- )
+  {
+    iTemp = piOrg[ 0] - piCur[ 0]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[ 1] - piCur[ 1]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[ 2] - piCur[ 2]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[ 3] - piCur[ 3]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[ 4] - piCur[ 4]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[ 5] - piCur[ 5]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[ 6] - piCur[ 6]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[ 7] - piCur[ 7]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[ 8] - piCur[ 8]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[ 9] - piCur[ 9]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[10] - piCur[10]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[11] - piCur[11]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[12] - piCur[12]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[13] - piCur[13]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[14] - piCur[14]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[15] - piCur[15]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[16] - piCur[16]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[17] - piCur[17]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[18] - piCur[18]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[19] - piCur[19]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[20] - piCur[20]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[21] - piCur[21]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[22] - piCur[22]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[23] - piCur[23]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[24] - piCur[24]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[25] - piCur[25]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[26] - piCur[26]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[27] - piCur[27]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[28] - piCur[28]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[29] - piCur[29]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[30] - piCur[30]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[31] - piCur[31]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[32] - piCur[32]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[33] - piCur[33]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[34] - piCur[34]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[35] - piCur[35]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[36] - piCur[36]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[37] - piCur[37]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[38] - piCur[38]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[39] - piCur[39]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[40] - piCur[40]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[41] - piCur[41]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[42] - piCur[42]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[43] - piCur[43]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[44] - piCur[44]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[45] - piCur[45]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[46] - piCur[46]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[47] - piCur[47]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[48] - piCur[48]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[49] - piCur[49]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[50] - piCur[50]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[51] - piCur[51]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[52] - piCur[52]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[53] - piCur[53]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[54] - piCur[54]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[55] - piCur[55]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[56] - piCur[56]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[57] - piCur[57]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[58] - piCur[58]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[59] - piCur[59]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[60] - piCur[60]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[61] - piCur[61]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[62] - piCur[62]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+    iTemp = piOrg[63] - piCur[63]; uiSum += Distortion(( iTemp * iTemp ) >> uiShift);
+
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+
+  return ( uiSum );
+}
+
+// --------------------------------------------------------------------------------------------------------------------
+// HADAMARD with step (used in fractional search)
+// --------------------------------------------------------------------------------------------------------------------
+
+Distortion TComRdCost::xCalcHADs2x2( Pel *piOrg, Pel *piCur, Int iStrideOrg, Int iStrideCur, Int iStep )
+{
+  Distortion satd = 0;
+  TCoeff 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;
+}
+
+Distortion TComRdCost::xCalcHADs4x4( Pel *piOrg, Pel *piCur, Int iStrideOrg, Int iStrideCur, Int iStep )
+{
+  Int k;
+  Distortion satd = 0;
+  TCoeff 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;
+}
+
+Distortion TComRdCost::xCalcHADs8x8( Pel *piOrg, Pel *piCur, Int iStrideOrg, Int iStrideCur, Int iStep )
+{
+  Int k, i, j, jj;
+  Distortion sad = 0;
+  TCoeff 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;
+}
+
+
+Distortion TComRdCost::xGetHADs( DistParam* pcDtParam )
+{
+  if ( pcDtParam->bApplyWeight )
+  {
+    return TComRdCostWeightPrediction::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;
+
+  Distortion uiSum = 0;
+
+  if( ( iRows % 8 == 0) && (iCols % 8 == 0) )
+  {
+    Int  iOffsetOrg = iStrideOrg<<3;
+    Int  iOffsetCur = iStrideCur<<3;
+    for ( y=0; y<iRows; y+= 8 )
+    {
+      for ( x=0; x<iCols; x+= 8 )
+      {
+        uiSum += xCalcHADs8x8( &piOrg[x], &piCur[x*iStep], iStrideOrg, iStrideCur, iStep );
+      }
+      piOrg += iOffsetOrg;
+      piCur += iOffsetCur;
+    }
+  }
+  else if( ( iRows % 4 == 0) && (iCols % 4 == 0) )
+  {
+    Int  iOffsetOrg = iStrideOrg<<2;
+    Int  iOffsetCur = iStrideCur<<2;
+
+    for ( y=0; y<iRows; y+= 4 )
+    {
+      for ( x=0; x<iCols; x+= 4 )
+      {
+        uiSum += xCalcHADs4x4( &piOrg[x], &piCur[x*iStep], iStrideOrg, iStrideCur, iStep );
+      }
+      piOrg += iOffsetOrg;
+      piCur += iOffsetCur;
+    }
+  }
+  else if( ( iRows % 2 == 0) && (iCols % 2 == 0) )
+  {
+    Int  iOffsetOrg = iStrideOrg<<1;
+    Int  iOffsetCur = iStrideCur<<1;
+    for ( y=0; y<iRows; y+=2 )
+    {
+      for ( x=0; x<iCols; x+=2 )
+      {
+        uiSum += xCalcHADs2x2( &piOrg[x], &piCur[x*iStep], iStrideOrg, iStrideCur, iStep );
+      }
+      piOrg += iOffsetOrg;
+      piCur += iOffsetCur;
+    }
+  }
+  else
+  {
+    assert(false);
+  }
+
+  return ( uiSum >> DISTORTION_PRECISION_ADJUSTMENT(pcDtParam->bitDepth-8) );
+}
+
+//! \}
Index: /tags/SHM-9.0/source/Lib/TLibCommon/TComRdCost.h
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibCommon/TComRdCost.h	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibCommon/TComRdCost.h	(revision 1088)
@@ -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-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TComRdCost.h
+    \brief    RD cost computation classes (header)
+*/
+
+#ifndef __TCOMRDCOST__
+#define __TCOMRDCOST__
+
+
+#include "CommonDef.h"
+#include "TComPattern.h"
+#include "TComMv.h"
+
+#include "TComSlice.h"
+#include "TComRdCostWeightPrediction.h"
+
+//! \ingroup TLibCommon
+//! \{
+
+class DistParam;
+class TComPattern;
+
+// ====================================================================================================================
+// Type definition
+// ====================================================================================================================
+
+// for function pointer
+typedef Distortion (*FpDistFunc) (DistParam*); // TODO: can this pointer be replaced with a reference? - there are no NULL checks on pointer.
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// distortion parameter class
+class DistParam
+{
+public:
+  Pel*  pOrg;
+  Pel*  pCur;
+  Int   iStrideOrg;
+  Int   iStrideCur;
+  Int   iRows;
+  Int   iCols;
+  Int   iStep;
+  FpDistFunc DistFunc;
+  Int   bitDepth;
+
+  Bool            bApplyWeight;     // whether weighted prediction is used or not
+  WPScalingParam  *wpCur;           // weighted prediction scaling parameters for current ref
+  ComponentID     compIdx;
+
+  // (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;
+  }
+};
+
+/// RD cost computation class
+class TComRdCost
+{
+private:
+  // for distortion
+
+  FpDistFunc              m_afpDistortFunc[DF_TOTAL_FUNCTIONS]; // [eDFunc]
+  CostMode                m_costMode;
+  Double                  m_distortionWeight[MAX_NUM_COMPONENT]; // only chroma values are used.
+  Double                  m_dLambda;
+  Double                  m_sqrtLambda;
+#if RExt__HIGH_BIT_DEPTH_SUPPORT
+  Double                  m_dLambdaMotionSAD[2 /* 0=standard, 1=for transquant bypass when mixed-lossless cost evaluation enabled*/];
+  Double                  m_dLambdaMotionSSE[2 /* 0=standard, 1=for transquant bypass when mixed-lossless cost evaluation enabled*/];
+#else
+  UInt                    m_uiLambdaMotionSAD[2 /* 0=standard, 1=for transquant bypass when mixed-lossless cost evaluation enabled*/];
+  UInt                    m_uiLambdaMotionSSE[2 /* 0=standard, 1=for transquant bypass when mixed-lossless cost evaluation enabled*/];
+#endif
+  Double                  m_dFrameLambda;
+
+  // for motion cost
+  TComMv                  m_mvPredictor;
+#if RExt__HIGH_BIT_DEPTH_SUPPORT
+  Double                  m_dCost;
+#else
+  UInt                    m_uiCost;
+#endif
+  Int                     m_iCostScale;
+
+public:
+  TComRdCost();
+  virtual ~TComRdCost();
+
+  Double  calcRdCost  ( UInt   uiBits, Distortion uiDistortion, Bool bFlag = false, DFunc eDFunc = DF_DEFAULT );
+  Double  calcRdCost64( UInt64 uiBits, UInt64 uiDistortion, Bool bFlag = false, DFunc eDFunc = DF_DEFAULT );
+
+  Void    setDistortionWeight  ( const ComponentID compID, const Double distortionWeight ) { m_distortionWeight[compID] = distortionWeight; }
+  Void    setLambda      ( Double dLambda );
+  Void    setFrameLambda ( Double dLambda ) { m_dFrameLambda = dLambda; }
+
+  Double  getSqrtLambda ()   { return m_sqrtLambda; }
+
+  Double  getLambda() { return m_dLambda; }
+  Double  getChromaWeight () { return ((m_distortionWeight[COMPONENT_Cb] + m_distortionWeight[COMPONENT_Cr]) / 2.0); }
+
+  Void    setCostMode(CostMode   m )    { m_costMode = m; }
+
+  // Distortion Functions
+  Void    init();
+
+  Void    setDistParam( UInt uiBlkWidth, UInt uiBlkHeight, DFunc eDFunc, DistParam& rcDistParam );
+  Void    setDistParam( TComPattern* pcPatternKey, Pel* piRefY, Int iRefStride,            DistParam& rcDistParam );
+  Void    setDistParam( TComPattern* pcPatternKey, Pel* piRefY, Int iRefStride, Int iStep, DistParam& rcDistParam, Bool bHADME=false );
+  Void    setDistParam( DistParam& rcDP, Int bitDepth, Pel* p1, Int iStride1, Pel* p2, Int iStride2, Int iWidth, Int iHeight, Bool bHadamard = false );
+
+  Distortion calcHAD(Int bitDepth, Pel* pi0, Int iStride0, Pel* pi1, Int iStride1, Int iWidth, Int iHeight );
+
+  // for motion cost
+  UInt    xGetComponentBits( Int iVal );
+#if RExt__HIGH_BIT_DEPTH_SUPPORT
+  Void    getMotionCost( Bool bSad, Int iAdd, Bool bIsTransquantBypass ) { m_dCost = (bSad ? m_dLambdaMotionSAD[(bIsTransquantBypass && m_costMode==COST_MIXED_LOSSLESS_LOSSY_CODING) ?1:0] + iAdd : m_dLambdaMotionSSE[(bIsTransquantBypass && m_costMode==COST_MIXED_LOSSLESS_LOSSY_CODING)?1:0] + iAdd); }
+#else
+  Void    getMotionCost( Bool bSad, Int iAdd, Bool bIsTransquantBypass ) { m_uiCost = (bSad ? m_uiLambdaMotionSAD[(bIsTransquantBypass && m_costMode==COST_MIXED_LOSSLESS_LOSSY_CODING) ?1:0] + iAdd : m_uiLambdaMotionSSE[(bIsTransquantBypass && m_costMode==COST_MIXED_LOSSLESS_LOSSY_CODING)?1:0] + iAdd); }
+#endif
+  Void    setPredictor( TComMv& rcMv )
+  {
+    m_mvPredictor = rcMv;
+  }
+  Void    setCostScale( Int iCostScale )    { m_iCostScale = iCostScale; }
+  __inline Distortion getCost( Int x, Int y )
+  {
+#if RExt__HIGH_BIT_DEPTH_SUPPORT
+    return Distortion((m_dCost * getBits(x, y)) / 65536.0);
+#else
+    return m_uiCost * getBits(x, y) >> 16;
+#endif
+  }
+#if RExt__HIGH_BIT_DEPTH_SUPPORT
+  Distortion getCost( UInt b )                 { return Distortion(( m_dCost * b ) / 65536.0); }
+#else
+  Distortion getCost( UInt b )                 { return ( m_uiCost * b ) >> 16; }
+#endif
+  UInt    getBits( Int x, Int y )
+  {
+    return xGetComponentBits((x << m_iCostScale) - m_mvPredictor.getHor())
+    +      xGetComponentBits((y << m_iCostScale) - m_mvPredictor.getVer());
+  }
+
+private:
+
+  static Distortion xGetSSE           ( DistParam* pcDtParam );
+  static Distortion xGetSSE4          ( DistParam* pcDtParam );
+  static Distortion xGetSSE8          ( DistParam* pcDtParam );
+  static Distortion xGetSSE16         ( DistParam* pcDtParam );
+  static Distortion xGetSSE32         ( DistParam* pcDtParam );
+  static Distortion xGetSSE64         ( DistParam* pcDtParam );
+  static Distortion xGetSSE16N        ( DistParam* pcDtParam );
+
+  static Distortion xGetSAD           ( DistParam* pcDtParam );
+  static Distortion xGetSAD4          ( DistParam* pcDtParam );
+  static Distortion xGetSAD8          ( DistParam* pcDtParam );
+  static Distortion xGetSAD16         ( DistParam* pcDtParam );
+  static Distortion xGetSAD32         ( DistParam* pcDtParam );
+  static Distortion xGetSAD64         ( DistParam* pcDtParam );
+  static Distortion xGetSAD16N        ( DistParam* pcDtParam );
+
+#if AMP_SAD
+  static Distortion xGetSAD12         ( DistParam* pcDtParam );
+  static Distortion xGetSAD24         ( DistParam* pcDtParam );
+  static Distortion xGetSAD48         ( DistParam* pcDtParam );
+
+#endif
+
+  static Distortion xGetHADs          ( DistParam* pcDtParam );
+  static Distortion xCalcHADs2x2      ( Pel *piOrg, Pel *piCurr, Int iStrideOrg, Int iStrideCur, Int iStep );
+  static Distortion xCalcHADs4x4      ( Pel *piOrg, Pel *piCurr, Int iStrideOrg, Int iStrideCur, Int iStep );
+  static Distortion xCalcHADs8x8      ( Pel *piOrg, Pel *piCurr, Int iStrideOrg, Int iStrideCur, Int iStep );
+
+
+public:
+
+  Distortion   getDistPart(Int bitDepth, Pel* piCur, Int iCurStride,  Pel* piOrg, Int iOrgStride, UInt uiBlkWidth, UInt uiBlkHeight, const ComponentID compID, DFunc eDFunc = DF_SSE );
+
+};// END CLASS DEFINITION TComRdCost
+
+//! \}
+
+#endif // __TCOMRDCOST__
Index: /tags/SHM-9.0/source/Lib/TLibCommon/TComRdCostWeightPrediction.cpp
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibCommon/TComRdCostWeightPrediction.cpp	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibCommon/TComRdCostWeightPrediction.cpp	(revision 1088)
@@ -0,0 +1,489 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TComRdCostWeightPrediction.cpp
+    \brief    RD cost computation class with Weighted-Prediction
+*/
+
+#include <math.h>
+#include <assert.h>
+#include "TComRdCost.h"
+#include "TComRdCostWeightPrediction.h"
+
+static Distortion xCalcHADs2x2w( const WPScalingParam &wpCur, const Pel *piOrg, const Pel *piCurr, Int iStrideOrg, Int iStrideCur, Int iStep );
+static Distortion xCalcHADs4x4w( const WPScalingParam &wpCur, const Pel *piOrg, const Pel *piCurr, Int iStrideOrg, Int iStrideCur, Int iStep );
+static Distortion xCalcHADs8x8w( const WPScalingParam &wpCur, const Pel *piOrg, const Pel *piCurr, Int iStrideOrg, Int iStrideCur, Int iStep );
+
+
+// --------------------------------------------------------------------------------------------------------------------
+// SAD
+// --------------------------------------------------------------------------------------------------------------------
+/** get weighted SAD cost
+ * \param pcDtParam
+ * \returns Distortion
+ */
+Distortion TComRdCostWeightPrediction::xGetSADw( DistParam* pcDtParam )
+{
+  const Pel            *piOrg      = pcDtParam->pOrg;
+  const Pel            *piCur      = pcDtParam->pCur;
+  const Int             iCols      = pcDtParam->iCols;
+  const Int             iStrideCur = pcDtParam->iStrideCur;
+  const Int             iStrideOrg = pcDtParam->iStrideOrg;
+  const ComponentID     compID     = pcDtParam->compIdx;
+
+  assert(compID<MAX_NUM_COMPONENT);
+
+  const WPScalingParam &wpCur      = pcDtParam->wpCur[compID];
+
+  const Int             w0         = wpCur.w;
+  const Int             offset     = wpCur.offset;
+  const Int             shift      = wpCur.shift;
+  const Int             round      = wpCur.round;
+
+  Distortion uiSum = 0;
+
+  for(Int iRows = pcDtParam->iRows; iRows != 0; iRows-- )
+  {
+    for (Int n = 0; n < iCols; n++ )
+    {
+      const Pel pred = ( (w0*piCur[n] + round) >> shift ) + offset ;
+
+      uiSum += abs( piOrg[n] - pred );
+    }
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+
+  pcDtParam->compIdx = MAX_NUM_COMPONENT;  // reset for DEBUG (assert test)
+
+  return uiSum >> DISTORTION_PRECISION_ADJUSTMENT(pcDtParam->bitDepth-8);
+}
+
+
+// --------------------------------------------------------------------------------------------------------------------
+// SSE
+// --------------------------------------------------------------------------------------------------------------------
+/** get weighted SSD cost
+ * \param pcDtParam
+ * \returns Distortion
+ */
+Distortion TComRdCostWeightPrediction::xGetSSEw( DistParam* pcDtParam )
+{
+  const Pel            *piOrg           = pcDtParam->pOrg;
+  const Pel            *piCur           = pcDtParam->pCur;
+  const Int             iCols           = pcDtParam->iCols;
+  const Int             iStrideOrg      = pcDtParam->iStrideOrg;
+  const Int             iStrideCur      = pcDtParam->iStrideCur;
+  const ComponentID     compIdx         = pcDtParam->compIdx;
+
+  assert( pcDtParam->iSubShift == 0 ); // NOTE: what is this protecting?
+
+  assert(compIdx<MAX_NUM_COMPONENT);
+  const WPScalingParam &wpCur           = pcDtParam->wpCur[compIdx];
+  const Int             w0              = wpCur.w;
+  const Int             offset          = wpCur.offset;
+  const Int             shift           = wpCur.shift;
+  const Int             round           = wpCur.round;
+  const UInt            distortionShift = DISTORTION_PRECISION_ADJUSTMENT((pcDtParam->bitDepth-8) << 1);
+
+  Distortion sum = 0;
+
+  for(Int iRows = pcDtParam->iRows ; iRows != 0; iRows-- )
+  {
+    for (Int n = 0; n < iCols; n++ )
+    {
+      const Pel pred     = ( (w0*piCur[n] + round) >> shift ) + offset ;
+      const Pel residual = piOrg[n] - pred;
+      sum += ( Distortion(residual) * Distortion(residual) ) >> distortionShift;
+    }
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+
+  pcDtParam->compIdx = MAX_NUM_COMPONENT; // reset for DEBUG (assert test)
+
+  return sum;
+}
+
+
+// --------------------------------------------------------------------------------------------------------------------
+// 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 Distortion
+ */
+Distortion xCalcHADs2x2w( const WPScalingParam &wpCur, const Pel *piOrg, const Pel *piCur, Int iStrideOrg, Int iStrideCur, Int iStep )
+{
+  const Int round  = wpCur.round;
+  const Int shift  = wpCur.shift;
+  const Int offset = wpCur.offset;
+  const Int w0     = wpCur.w;
+
+  Distortion satd  = 0;
+  TCoeff     diff[4];
+  TCoeff     m[4];
+
+  Pel   pred;
+
+  pred    = ( (w0*piCur[0*iStep             ] + round) >> shift ) + offset ;
+  diff[0] = piOrg[0             ] - pred;
+  pred    = ( (w0*piCur[1*iStep             ] + round) >> shift ) + offset ;
+  diff[1] = piOrg[1             ] - pred;
+  pred    = ( (w0*piCur[0*iStep + iStrideCur] + round) >> shift ) + offset ;
+  diff[2] = piOrg[iStrideOrg    ] - pred;
+  pred    = ( (w0*piCur[1*iStep + iStrideCur] + round) >> shift ) + 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 Distortion
+ */
+Distortion xCalcHADs4x4w( const WPScalingParam &wpCur, const Pel *piOrg, const Pel *piCur, Int iStrideOrg, Int iStrideCur, Int iStep )
+{
+  const Int round  = wpCur.round;
+  const Int shift  = wpCur.shift;
+  const Int offset = wpCur.offset;
+  const Int w0     = wpCur.w;
+
+  Distortion satd = 0;
+  TCoeff     diff[16];
+  TCoeff     m[16];
+  TCoeff     d[16];
+
+
+  for(Int k = 0; k < 16; k+=4 )
+  {
+    Pel pred;
+    pred      = ( (w0*piCur[0*iStep] + round) >> shift ) + offset ;
+    diff[k+0] = piOrg[0] - pred;
+    pred      = ( (w0*piCur[1*iStep] + round) >> shift ) + offset ;
+    diff[k+1] = piOrg[1] - pred;
+    pred      = ( (w0*piCur[2*iStep] + round) >> shift ) + offset ;
+    diff[k+2] = piOrg[2] - pred;
+    pred      = ( (w0*piCur[3*iStep] + round) >> shift ) + 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 (Int 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 Distortion
+ */
+Distortion xCalcHADs8x8w( const WPScalingParam &wpCur, const Pel *piOrg, const Pel *piCur, Int iStrideOrg, Int iStrideCur, Int iStep )
+{
+  Distortion sad=0;
+  TCoeff 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;
+  const Int round  = wpCur.round;
+  const Int shift  = wpCur.shift;
+  const Int offset = wpCur.offset;
+  const Int w0     = wpCur.w;
+
+  Pel   pred;
+
+  for(Int k = 0; k < 64; k+=8 )
+  {
+    pred      = ( (w0*piCur[     0] + round) >> shift ) + offset ;
+    diff[k+0] = piOrg[0] - pred;
+    pred      = ( (w0*piCur[iStep ] + round) >> shift ) + offset ;
+    diff[k+1] = piOrg[1] - pred;
+    pred      = ( (w0*piCur[iStep2] + round) >> shift ) + offset ;
+    diff[k+2] = piOrg[2] - pred;
+    pred      = ( (w0*piCur[iStep3] + round) >> shift ) + offset ;
+    diff[k+3] = piOrg[3] - pred;
+    pred      = ( (w0*piCur[iStep4] + round) >> shift ) + offset ;
+    diff[k+4] = piOrg[4] - pred;
+    pred      = ( (w0*piCur[iStep5] + round) >> shift ) + offset ;
+    diff[k+5] = piOrg[5] - pred;
+    pred      = ( (w0*piCur[iStep6] + round) >> shift ) + offset ;
+    diff[k+6] = piOrg[6] - pred;
+    pred      = ( (w0*piCur[iStep7] + round) >> shift ) + offset ;
+    diff[k+7] = piOrg[7] - pred;
+
+    piCur += iStrideCur;
+    piOrg += iStrideOrg;
+  }
+
+  //horizontal
+  for (Int j=0; j < 8; j++)
+  {
+    const Int 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 (Int 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 (Int j=0; j < 8; j++)
+  {
+    for (Int i=0; i < 8; i++)
+    {
+      sad += (abs(m2[j][i]));
+    }
+  }
+
+  sad=((sad+2)>>2);
+
+  return sad;
+}
+
+
+/** get weighted Hadamard cost
+ * \param *pcDtParam
+ * \returns Distortion
+ */
+Distortion TComRdCostWeightPrediction::xGetHADsw( DistParam* pcDtParam )
+{
+  const Pel        *piOrg      = pcDtParam->pOrg;
+  const Pel        *piCur      = pcDtParam->pCur;
+  const Int         iRows      = pcDtParam->iRows;
+  const Int         iCols      = pcDtParam->iCols;
+  const Int         iStrideCur = pcDtParam->iStrideCur;
+  const Int         iStrideOrg = pcDtParam->iStrideOrg;
+  const Int         iStep      = pcDtParam->iStep;
+  const ComponentID compIdx    = pcDtParam->compIdx;
+  assert(compIdx<MAX_NUM_COMPONENT);
+  const WPScalingParam  wpCur    = pcDtParam->wpCur[compIdx];
+
+  Distortion uiSum = 0;
+
+  if( ( iRows % 8 == 0) && (iCols % 8 == 0) )
+  {
+    const Int iOffsetOrg = iStrideOrg<<3;
+    const Int iOffsetCur = iStrideCur<<3;
+    for (Int y=0; y<iRows; y+= 8 )
+    {
+      for (Int x=0; x<iCols; x+= 8 )
+      {
+        uiSum += xCalcHADs8x8w( wpCur, &piOrg[x], &piCur[x*iStep], iStrideOrg, iStrideCur, iStep );
+      }
+      piOrg += iOffsetOrg;
+      piCur += iOffsetCur;
+    }
+  }
+  else if( ( iRows % 4 == 0) && (iCols % 4 == 0) )
+  {
+    const Int iOffsetOrg = iStrideOrg<<2;
+    const Int iOffsetCur = iStrideCur<<2;
+
+    for (Int y=0; y<iRows; y+= 4 )
+    {
+      for (Int x=0; x<iCols; x+= 4 )
+      {
+        uiSum += xCalcHADs4x4w( wpCur, &piOrg[x], &piCur[x*iStep], iStrideOrg, iStrideCur, iStep );
+      }
+      piOrg += iOffsetOrg;
+      piCur += iOffsetCur;
+    }
+  }
+  else
+  {
+    for (Int y=0; y<iRows; y+=2 )
+    {
+      for (Int x=0; x<iCols; x+=2 )
+      {
+        uiSum += xCalcHADs2x2w( wpCur, &piOrg[x], &piCur[x*iStep], iStrideOrg, iStrideCur, iStep );
+      }
+      piOrg += iStrideOrg;
+      piCur += iStrideCur;
+    }
+  }
+
+  return uiSum >> DISTORTION_PRECISION_ADJUSTMENT(pcDtParam->bitDepth-8);
+}
Index: /tags/SHM-9.0/source/Lib/TLibCommon/TComRdCostWeightPrediction.h
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibCommon/TComRdCostWeightPrediction.h	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibCommon/TComRdCostWeightPrediction.h	(revision 1088)
@@ -0,0 +1,64 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TComRdCostWeightPrediction.h
+    \brief    RD cost computation namespace (header)
+*/
+
+#ifndef __TCOMRDCOSTWEIGHTPREDICTION__
+#define __TCOMRDCOSTWEIGHTPREDICTION__
+
+
+#include "CommonDef.h"
+#include "TComPattern.h"
+#include "TComMv.h"
+#include "TComRdCost.h"
+#include "TComSlice.h"
+
+class DistParam;
+class TComPattern;
+
+// ====================================================================================================================
+// Namespace definition
+// ====================================================================================================================
+
+/// RD cost computation namespace, with Weighted Prediction
+namespace TComRdCostWeightPrediction
+{
+  Distortion xGetSSEw ( DistParam* pcDtParam );
+  Distortion xGetSADw ( DistParam* pcDtParam );
+  Distortion xGetHADsw( DistParam* pcDtParam );
+}// END NAMESPACE DEFINITION TComRdCostWeightPrediction
+
+#endif // __TCOMRDCOSTWEIGHTPREDICTION__
+
Index: /tags/SHM-9.0/source/Lib/TLibCommon/TComRectangle.h
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibCommon/TComRectangle.h	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibCommon/TComRectangle.h	(revision 1088)
@@ -0,0 +1,50 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+
+#ifndef __TCOMRECTANGLE__
+#define __TCOMRECTANGLE__
+
+
+struct TComRectangle
+{
+  UInt width;
+  UInt height;
+  UInt x0;
+  UInt y0;
+};
+
+
+
+
+#endif
Index: /tags/SHM-9.0/source/Lib/TLibCommon/TComRom.cpp
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibCommon/TComRom.cpp	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibCommon/TComRom.cpp	(revision 1088)
@@ -0,0 +1,746 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TComRom.cpp
+    \brief    global variables & functions
+*/
+
+#include "TComRom.h"
+#include <memory.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <iomanip>
+#include <assert.h>
+#include "TComDataCU.h"
+#include "Debug.h"
+// ====================================================================================================================
+// Initialize / destroy functions
+// ====================================================================================================================
+
+//! \ingroup TLibCommon
+//! \{
+
+class ScanGenerator
+{
+private:
+  UInt m_line, m_column;
+  const UInt m_blockWidth, m_blockHeight;
+  const UInt m_stride;
+  const COEFF_SCAN_TYPE m_scanType;
+
+public:
+  ScanGenerator(UInt blockWidth, UInt blockHeight, UInt stride, COEFF_SCAN_TYPE scanType)
+    : m_line(0), m_column(0), m_blockWidth(blockWidth), m_blockHeight(blockHeight), m_stride(stride), m_scanType(scanType)
+  { }
+
+  UInt GetCurrentX() const { return m_column; }
+  UInt GetCurrentY() const { return m_line; }
+
+  UInt GetNextIndex(UInt blockOffsetX, UInt blockOffsetY)
+  {
+    Int rtn=((m_line + blockOffsetY) * m_stride) + m_column + blockOffsetX;
+
+    //advance line and column to the next position
+    switch (m_scanType)
+    {
+      //------------------------------------------------
+
+      case SCAN_DIAG:
+        {
+          if ((m_column == (m_blockWidth - 1)) || (m_line == 0)) //if we reach the end of a rank, go diagonally down to the next one
+          {
+            m_line   += m_column + 1;
+            m_column  = 0;
+
+            if (m_line >= m_blockHeight) //if that takes us outside the block, adjust so that we are back on the bottom row
+            {
+              m_column += m_line - (m_blockHeight - 1);
+              m_line    = m_blockHeight - 1;
+            }
+          }
+          else
+          {
+            m_column++;
+            m_line--;
+          }
+        }
+        break;
+
+      //------------------------------------------------
+
+      case SCAN_HOR:
+        {
+          if (m_column == (m_blockWidth - 1))
+          {
+            m_line++;
+            m_column = 0;
+          }
+          else m_column++;
+        }
+        break;
+
+      //------------------------------------------------
+
+      case SCAN_VER:
+        {
+          if (m_line == (m_blockHeight - 1))
+          {
+            m_column++;
+            m_line = 0;
+          }
+          else m_line++;
+        }
+        break;
+
+      //------------------------------------------------
+
+      default:
+        {
+          std::cerr << "ERROR: Unknown scan type \"" << m_scanType << "\"in ScanGenerator::GetNextIndex" << std::endl;
+          exit(1);
+        }
+        break;
+    }
+
+    return rtn;
+  }
+};
+
+// 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++;
+  }
+
+  // initialise scan orders
+  for(UInt log2BlockHeight = 0; log2BlockHeight < MAX_CU_DEPTH; log2BlockHeight++)
+  {
+    for(UInt log2BlockWidth = 0; log2BlockWidth < MAX_CU_DEPTH; log2BlockWidth++)
+    {
+      const UInt blockWidth  = 1 << log2BlockWidth;
+      const UInt blockHeight = 1 << log2BlockHeight;
+      const UInt totalValues = blockWidth * blockHeight;
+
+      //--------------------------------------------------------------------------------------------------
+
+      //non-grouped scan orders
+
+      for (UInt scanTypeIndex = 0; scanTypeIndex < SCAN_NUMBER_OF_TYPES; scanTypeIndex++)
+      {
+        const COEFF_SCAN_TYPE scanType = COEFF_SCAN_TYPE(scanTypeIndex);
+
+        g_scanOrder[SCAN_UNGROUPED][scanType][log2BlockWidth][log2BlockHeight] = new UInt[totalValues];
+
+        ScanGenerator fullBlockScan(blockWidth, blockHeight, blockWidth, scanType);
+
+        for (UInt scanPosition = 0; scanPosition < totalValues; scanPosition++)
+        {
+          g_scanOrder[SCAN_UNGROUPED][scanType][log2BlockWidth][log2BlockHeight][scanPosition] = fullBlockScan.GetNextIndex(0, 0);
+        }
+      }
+
+      //--------------------------------------------------------------------------------------------------
+
+      //grouped scan orders
+
+      const UInt  groupWidth           = 1           << MLS_CG_LOG2_WIDTH;
+      const UInt  groupHeight          = 1           << MLS_CG_LOG2_HEIGHT;
+      const UInt  widthInGroups        = blockWidth  >> MLS_CG_LOG2_WIDTH;
+      const UInt  heightInGroups       = blockHeight >> MLS_CG_LOG2_HEIGHT;
+
+      const UInt  groupSize            = groupWidth    * groupHeight;
+      const UInt  totalGroups          = widthInGroups * heightInGroups;
+
+      for (UInt scanTypeIndex = 0; scanTypeIndex < SCAN_NUMBER_OF_TYPES; scanTypeIndex++)
+      {
+        const COEFF_SCAN_TYPE scanType = COEFF_SCAN_TYPE(scanTypeIndex);
+
+        g_scanOrder[SCAN_GROUPED_4x4][scanType][log2BlockWidth][log2BlockHeight] = new UInt[totalValues];
+
+        ScanGenerator fullBlockScan(widthInGroups, heightInGroups, groupWidth, scanType);
+
+        for (UInt groupIndex = 0; groupIndex < totalGroups; groupIndex++)
+        {
+          const UInt groupPositionY  = fullBlockScan.GetCurrentY();
+          const UInt groupPositionX  = fullBlockScan.GetCurrentX();
+          const UInt groupOffsetX    = groupPositionX * groupWidth;
+          const UInt groupOffsetY    = groupPositionY * groupHeight;
+          const UInt groupOffsetScan = groupIndex     * groupSize;
+
+          ScanGenerator groupScan(groupWidth, groupHeight, blockWidth, scanType);
+
+          for (UInt scanPosition = 0; scanPosition < groupSize; scanPosition++)
+          {
+            g_scanOrder[SCAN_GROUPED_4x4][scanType][log2BlockWidth][log2BlockHeight][groupOffsetScan + scanPosition] = groupScan.GetNextIndex(groupOffsetX, groupOffsetY);
+          }
+
+          fullBlockScan.GetNextIndex(0,0);
+        }
+      }
+
+      //--------------------------------------------------------------------------------------------------
+    }
+  }
+}
+
+Void destroyROM()
+{
+  for(UInt groupTypeIndex = 0; groupTypeIndex < SCAN_NUMBER_OF_GROUP_TYPES; groupTypeIndex++)
+  {
+    for (UInt scanOrderIndex = 0; scanOrderIndex < SCAN_NUMBER_OF_TYPES; scanOrderIndex++)
+    {
+      for (UInt log2BlockWidth = 0; log2BlockWidth < MAX_CU_DEPTH; log2BlockWidth++)
+      {
+        for (UInt log2BlockHeight = 0; log2BlockHeight < MAX_CU_DEPTH; log2BlockHeight++)
+        {
+          delete [] g_scanOrder[groupTypeIndex][scanOrderIndex][log2BlockWidth][log2BlockHeight];
+        }
+      }
+    }
+  }
+}
+
+// ====================================================================================================================
+// 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[NUMBER_OF_PART_SIZES] = { 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_maxTrDynamicRange[MAX_NUM_CHANNEL_TYPE];
+
+Int g_quantScales[SCALING_LIST_REM_NUM] =
+{
+  26214,23302,20560,18396,16384,14564
+};
+
+Int g_invQuantScales[SCALING_LIST_REM_NUM] =
+{
+  40,45,51,57,64,72
+};
+
+//--------------------------------------------------------------------------------------------------
+
+//structures
+
+#define DEFINE_DST4x4_MATRIX(a,b,c,d) \
+{ \
+  {  a,  b,  c,  d }, \
+  {  c,  c,  0, -c }, \
+  {  d, -a, -c,  b }, \
+  {  b, -d,  c, -a }, \
+}
+
+#define DEFINE_DCT4x4_MATRIX(a,b,c) \
+{ \
+  { a,  a,  a,  a}, \
+  { b,  c, -c, -b}, \
+  { a, -a, -a,  a}, \
+  { c, -b,  b, -c}  \
+}
+
+#define DEFINE_DCT8x8_MATRIX(a,b,c,d,e,f,g) \
+{ \
+  { a,  a,  a,  a,  a,  a,  a,  a}, \
+  { d,  e,  f,  g, -g, -f, -e, -d}, \
+  { b,  c, -c, -b, -b, -c,  c,  b}, \
+  { e, -g, -d, -f,  f,  d,  g, -e}, \
+  { a, -a, -a,  a,  a, -a, -a,  a}, \
+  { f, -d,  g,  e, -e, -g,  d, -f}, \
+  { c, -b,  b, -c, -c,  b, -b,  c}, \
+  { g, -f,  e, -d,  d, -e,  f, -g}  \
+}
+
+#define DEFINE_DCT16x16_MATRIX(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o) \
+{ \
+  { a,  a,  a,  a,  a,  a,  a,  a,  a,  a,  a,  a,  a,  a,  a,  a}, \
+  { h,  i,  j,  k,  l,  m,  n,  o, -o, -n, -m, -l, -k, -j, -i, -h}, \
+  { d,  e,  f,  g, -g, -f, -e, -d, -d, -e, -f, -g,  g,  f,  e,  d}, \
+  { i,  l,  o, -m, -j, -h, -k, -n,  n,  k,  h,  j,  m, -o, -l, -i}, \
+  { b,  c, -c, -b, -b, -c,  c,  b,  b,  c, -c, -b, -b, -c,  c,  b}, \
+  { j,  o, -k, -i, -n,  l,  h,  m, -m, -h, -l,  n,  i,  k, -o, -j}, \
+  { e, -g, -d, -f,  f,  d,  g, -e, -e,  g,  d,  f, -f, -d, -g,  e}, \
+  { k, -m, -i,  o,  h,  n, -j, -l,  l,  j, -n, -h, -o,  i,  m, -k}, \
+  { a, -a, -a,  a,  a, -a, -a,  a,  a, -a, -a,  a,  a, -a, -a,  a}, \
+  { l, -j, -n,  h, -o, -i,  m,  k, -k, -m,  i,  o, -h,  n,  j, -l}, \
+  { f, -d,  g,  e, -e, -g,  d, -f, -f,  d, -g, -e,  e,  g, -d,  f}, \
+  { m, -h,  l,  n, -i,  k,  o, -j,  j, -o, -k,  i, -n, -l,  h, -m}, \
+  { c, -b,  b, -c, -c,  b, -b,  c,  c, -b,  b, -c, -c,  b, -b,  c}, \
+  { n, -k,  h, -j,  m,  o, -l,  i, -i,  l, -o, -m,  j, -h,  k, -n}, \
+  { g, -f,  e, -d,  d, -e,  f, -g, -g,  f, -e,  d, -d,  e, -f,  g}, \
+  { o, -n,  m, -l,  k, -j,  i, -h,  h, -i,  j, -k,  l, -m,  n, -o}  \
+}
+
+#define DEFINE_DCT32x32_MATRIX(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E) \
+{ \
+  { a,  a,  a,  a,  a,  a,  a,  a,  a,  a,  a,  a,  a,  a,  a,  a,  a,  a,  a,  a,  a,  a,  a,  a,  a,  a,  a,  a,  a,  a,  a,  a}, \
+  { p,  q,  r,  s,  t,  u,  v,  w,  x,  y,  z,  A,  B,  C,  D,  E, -E, -D, -C, -B, -A, -z, -y, -x, -w, -v, -u, -t, -s, -r, -q, -p}, \
+  { h,  i,  j,  k,  l,  m,  n,  o, -o, -n, -m, -l, -k, -j, -i, -h, -h, -i, -j, -k, -l, -m, -n, -o,  o,  n,  m,  l,  k,  j,  i,  h}, \
+  { q,  t,  w,  z,  C, -E, -B, -y, -v, -s, -p, -r, -u, -x, -A, -D,  D,  A,  x,  u,  r,  p,  s,  v,  y,  B,  E, -C, -z, -w, -t, -q}, \
+  { d,  e,  f,  g, -g, -f, -e, -d, -d, -e, -f, -g,  g,  f,  e,  d,  d,  e,  f,  g, -g, -f, -e, -d, -d, -e, -f, -g,  g,  f,  e,  d}, \
+  { r,  w,  B, -D, -y, -t, -p, -u, -z, -E,  A,  v,  q,  s,  x,  C, -C, -x, -s, -q, -v, -A,  E,  z,  u,  p,  t,  y,  D, -B, -w, -r}, \
+  { i,  l,  o, -m, -j, -h, -k, -n,  n,  k,  h,  j,  m, -o, -l, -i, -i, -l, -o,  m,  j,  h,  k,  n, -n, -k, -h, -j, -m,  o,  l,  i}, \
+  { s,  z, -D, -w, -p, -v, -C,  A,  t,  r,  y, -E, -x, -q, -u, -B,  B,  u,  q,  x,  E, -y, -r, -t, -A,  C,  v,  p,  w,  D, -z, -s}, \
+  { b,  c, -c, -b, -b, -c,  c,  b,  b,  c, -c, -b, -b, -c,  c,  b,  b,  c, -c, -b, -b, -c,  c,  b,  b,  c, -c, -b, -b, -c,  c,  b}, \
+  { t,  C, -y, -p, -x,  D,  u,  s,  B, -z, -q, -w,  E,  v,  r,  A, -A, -r, -v, -E,  w,  q,  z, -B, -s, -u, -D,  x,  p,  y, -C, -t}, \
+  { j,  o, -k, -i, -n,  l,  h,  m, -m, -h, -l,  n,  i,  k, -o, -j, -j, -o,  k,  i,  n, -l, -h, -m,  m,  h,  l, -n, -i, -k,  o,  j}, \
+  { u, -E, -t, -v,  D,  s,  w, -C, -r, -x,  B,  q,  y, -A, -p, -z,  z,  p,  A, -y, -q, -B,  x,  r,  C, -w, -s, -D,  v,  t,  E, -u}, \
+  { e, -g, -d, -f,  f,  d,  g, -e, -e,  g,  d,  f, -f, -d, -g,  e,  e, -g, -d, -f,  f,  d,  g, -e, -e,  g,  d,  f, -f, -d, -g,  e}, \
+  { v, -B, -p, -C,  u,  w, -A, -q, -D,  t,  x, -z, -r, -E,  s,  y, -y, -s,  E,  r,  z, -x, -t,  D,  q,  A, -w, -u,  C,  p,  B, -v}, \
+  { k, -m, -i,  o,  h,  n, -j, -l,  l,  j, -n, -h, -o,  i,  m, -k, -k,  m,  i, -o, -h, -n,  j,  l, -l, -j,  n,  h,  o, -i, -m,  k}, \
+  { w, -y, -u,  A,  s, -C, -q,  E,  p,  D, -r, -B,  t,  z, -v, -x,  x,  v, -z, -t,  B,  r, -D, -p, -E,  q,  C, -s, -A,  u,  y, -w}, \
+  { a, -a, -a,  a,  a, -a, -a,  a,  a, -a, -a,  a,  a, -a, -a,  a,  a, -a, -a,  a,  a, -a, -a,  a,  a, -a, -a,  a,  a, -a, -a,  a}, \
+  { x, -v, -z,  t,  B, -r, -D,  p, -E, -q,  C,  s, -A, -u,  y,  w, -w, -y,  u,  A, -s, -C,  q,  E, -p,  D,  r, -B, -t,  z,  v, -x}, \
+  { l, -j, -n,  h, -o, -i,  m,  k, -k, -m,  i,  o, -h,  n,  j, -l, -l,  j,  n, -h,  o,  i, -m, -k,  k,  m, -i, -o,  h, -n, -j,  l}, \
+  { y, -s, -E,  r, -z, -x,  t,  D, -q,  A,  w, -u, -C,  p, -B, -v,  v,  B, -p,  C,  u, -w, -A,  q, -D, -t,  x,  z, -r,  E,  s, -y}, \
+  { f, -d,  g,  e, -e, -g,  d, -f, -f,  d, -g, -e,  e,  g, -d,  f,  f, -d,  g,  e, -e, -g,  d, -f, -f,  d, -g, -e,  e,  g, -d,  f}, \
+  { z, -p,  A,  y, -q,  B,  x, -r,  C,  w, -s,  D,  v, -t,  E,  u, -u, -E,  t, -v, -D,  s, -w, -C,  r, -x, -B,  q, -y, -A,  p, -z}, \
+  { m, -h,  l,  n, -i,  k,  o, -j,  j, -o, -k,  i, -n, -l,  h, -m, -m,  h, -l, -n,  i, -k, -o,  j, -j,  o,  k, -i,  n,  l, -h,  m}, \
+  { A, -r,  v, -E, -w,  q, -z, -B,  s, -u,  D,  x, -p,  y,  C, -t,  t, -C, -y,  p, -x, -D,  u, -s,  B,  z, -q,  w,  E, -v,  r, -A}, \
+  { c, -b,  b, -c, -c,  b, -b,  c,  c, -b,  b, -c, -c,  b, -b,  c,  c, -b,  b, -c, -c,  b, -b,  c,  c, -b,  b, -c, -c,  b, -b,  c}, \
+  { B, -u,  q, -x,  E,  y, -r,  t, -A, -C,  v, -p,  w, -D, -z,  s, -s,  z,  D, -w,  p, -v,  C,  A, -t,  r, -y, -E,  x, -q,  u, -B}, \
+  { n, -k,  h, -j,  m,  o, -l,  i, -i,  l, -o, -m,  j, -h,  k, -n, -n,  k, -h,  j, -m, -o,  l, -i,  i, -l,  o,  m, -j,  h, -k,  n}, \
+  { C, -x,  s, -q,  v, -A, -E,  z, -u,  p, -t,  y, -D, -B,  w, -r,  r, -w,  B,  D, -y,  t, -p,  u, -z,  E,  A, -v,  q, -s,  x, -C}, \
+  { g, -f,  e, -d,  d, -e,  f, -g, -g,  f, -e,  d, -d,  e, -f,  g,  g, -f,  e, -d,  d, -e,  f, -g, -g,  f, -e,  d, -d,  e, -f,  g}, \
+  { D, -A,  x, -u,  r, -p,  s, -v,  y, -B,  E,  C, -z,  w, -t,  q, -q,  t, -w,  z, -C, -E,  B, -y,  v, -s,  p, -r,  u, -x,  A, -D}, \
+  { o, -n,  m, -l,  k, -j,  i, -h,  h, -i,  j, -k,  l, -m,  n, -o, -o,  n, -m,  l, -k,  j, -i,  h, -h,  i, -j,  k, -l,  m, -n,  o}, \
+  { E, -D,  C, -B,  A, -z,  y, -x,  w, -v,  u, -t,  s, -r,  q, -p,  p, -q,  r, -s,  t, -u,  v, -w,  x, -y,  z, -A,  B, -C,  D, -E}  \
+}
+
+//--------------------------------------------------------------------------------------------------
+
+//coefficients
+
+#if RExt__HIGH_PRECISION_FORWARD_TRANSFORM
+const TMatrixCoeff g_aiT4 [TRANSFORM_NUMBER_OF_DIRECTIONS][4][4]   =
+{
+  DEFINE_DCT4x4_MATRIX  (16384, 21266,  9224),
+  DEFINE_DCT4x4_MATRIX  (   64,    83,    36)
+};
+
+const TMatrixCoeff g_aiT8 [TRANSFORM_NUMBER_OF_DIRECTIONS][8][8]   =
+{
+  DEFINE_DCT8x8_MATRIX  (16384, 21266,  9224, 22813, 19244, 12769,  4563),
+  DEFINE_DCT8x8_MATRIX  (   64,    83,    36,    89,    75,    50,    18)
+};
+
+const TMatrixCoeff g_aiT16[TRANSFORM_NUMBER_OF_DIRECTIONS][16][16] =
+{
+  DEFINE_DCT16x16_MATRIX(16384, 21266,  9224, 22813, 19244, 12769,  4563, 23120, 22063, 20450, 17972, 14642, 11109,  6446,  2316),
+  DEFINE_DCT16x16_MATRIX(   64,    83,    36,    89,    75,    50,    18,    90,    87,    80,    70,    57,    43,    25,     9)
+};
+
+const TMatrixCoeff g_aiT32[TRANSFORM_NUMBER_OF_DIRECTIONS][32][32] =
+{
+  DEFINE_DCT32x32_MATRIX(16384, 21266,  9224, 22813, 19244, 12769,  4563, 23120, 22063, 20450, 17972, 14642, 11109,  6446,  2316, 23106, 22852, 22445, 21848, 20995, 19810, 18601, 17143, 15718, 13853, 11749,  9846,  7908,  5573,  3281,   946),
+  DEFINE_DCT32x32_MATRIX(   64,    83,    36,    89,    75,    50,    18,    90,    87,    80,    70,    57,    43,    25,     9,    90,    90,    88,    85,    82,    78,    73,    67,    61,    54,    46,    38,    31,    22,    13,     4)
+};
+
+const TMatrixCoeff g_as_DST_MAT_4[TRANSFORM_NUMBER_OF_DIRECTIONS][4][4] =
+{
+  DEFINE_DST4x4_MATRIX( 7424, 14081, 18893, 21505),
+  DEFINE_DST4x4_MATRIX(   29,    55,    74,    84)
+};
+
+#else
+
+const TMatrixCoeff g_aiT4 [TRANSFORM_NUMBER_OF_DIRECTIONS][4][4]   =
+{
+  DEFINE_DCT4x4_MATRIX  (   64,    83,    36),
+  DEFINE_DCT4x4_MATRIX  (   64,    83,    36)
+};
+
+const TMatrixCoeff g_aiT8 [TRANSFORM_NUMBER_OF_DIRECTIONS][8][8]   =
+{
+  DEFINE_DCT8x8_MATRIX  (   64,    83,    36,    89,    75,    50,    18),
+  DEFINE_DCT8x8_MATRIX  (   64,    83,    36,    89,    75,    50,    18)
+};
+
+const TMatrixCoeff g_aiT16[TRANSFORM_NUMBER_OF_DIRECTIONS][16][16] =
+{
+  DEFINE_DCT16x16_MATRIX(   64,    83,    36,    89,    75,    50,    18,    90,    87,    80,    70,    57,    43,    25,     9),
+  DEFINE_DCT16x16_MATRIX(   64,    83,    36,    89,    75,    50,    18,    90,    87,    80,    70,    57,    43,    25,     9)
+};
+
+const TMatrixCoeff g_aiT32[TRANSFORM_NUMBER_OF_DIRECTIONS][32][32] =
+{
+  DEFINE_DCT32x32_MATRIX(   64,    83,    36,    89,    75,    50,    18,    90,    87,    80,    70,    57,    43,    25,     9,    90,    90,    88,    85,    82,    78,    73,    67,    61,    54,    46,    38,    31,    22,    13,     4),
+  DEFINE_DCT32x32_MATRIX(   64,    83,    36,    89,    75,    50,    18,    90,    87,    80,    70,    57,    43,    25,     9,    90,    90,    88,    85,    82,    78,    73,    67,    61,    54,    46,    38,    31,    22,    13,     4)
+};
+
+const TMatrixCoeff g_as_DST_MAT_4[TRANSFORM_NUMBER_OF_DIRECTIONS][4][4] =
+{
+  DEFINE_DST4x4_MATRIX(   29,    55,    74,    84),
+  DEFINE_DST4x4_MATRIX(   29,    55,    74,    84)
+};
+#endif
+
+
+//--------------------------------------------------------------------------------------------------
+
+#undef DEFINE_DST4x4_MATRIX
+#undef DEFINE_DCT4x4_MATRIX
+#undef DEFINE_DCT8x8_MATRIX
+#undef DEFINE_DCT16x16_MATRIX
+#undef DEFINE_DCT32x32_MATRIX
+
+//--------------------------------------------------------------------------------------------------
+
+
+const UChar g_aucChromaScale[NUM_CHROMA_FORMAT][chromaQPMappingTableSize]=
+{
+  //0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57
+  { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
+  { 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 },
+  { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,51,51,51,51,51,51 },
+  { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,51,51,51,51,51,51 }
+};
+
+// ====================================================================================================================
+// ADI
+// ====================================================================================================================
+
+#if FAST_UDI_USE_MPM
+const UChar g_aucIntraModeNumFast[MAX_CU_DEPTH] =
+{
+  3,  //   2x2
+  8,  //   4x4
+  8,  //   8x8
+  3,  //  16x16
+  3,  //  32x32
+  3   //  64x64
+};
+#else // FAST_UDI_USE_MPM
+const UChar g_aucIntraModeNumFast[MAX_CU_DEPTH] =
+{
+  3,  //   2x2
+  9,  //   4x4
+  9,  //   8x8
+  4,  //  16x16   33
+  4,  //  32x32   33
+  5   //  64x64   33
+};
+#endif // FAST_UDI_USE_MPM
+
+const UChar g_chroma422IntraAngleMappingTable[NUM_INTRA_MODE] =
+  //0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, DM
+  { 0, 1, 2, 2, 2, 2, 3, 5, 7, 8, 10, 12, 13, 15, 17, 18, 19, 20, 21, 22, 23, 23, 24, 24, 25, 25, 26, 27, 27, 28, 28, 29, 29, 30, 31, DM_CHROMA_IDX};
+
+// ====================================================================================================================
+// Bit-depth
+// ====================================================================================================================
+
+Int g_bitDepth   [MAX_NUM_CHANNEL_TYPE] = {8, 8};
+#if O0043_BEST_EFFORT_DECODING
+Int g_bitDepthInStream   [MAX_NUM_CHANNEL_TYPE] = {8, 8}; // In the encoder, this is the same as g_bitDepth. In the decoder, this can vary from g_bitDepth if the decoder is forced to use 'best-effort decoding' at a particular bit-depth.
+#endif
+Int g_PCMBitDepth[MAX_NUM_CHANNEL_TYPE] = {8, 8};    // PCM bit-depth
+
+// ====================================================================================================================
+// Misc.
+// ====================================================================================================================
+
+Char  g_aucConvertToBit  [ MAX_CU_SIZE+1 ];
+
+#if ENC_DEC_TRACE
+FILE*  g_hTrace = NULL; // Set to NULL to open up a file. Set to stdout to use the current output
+const Bool g_bEncDecTraceEnable  = true;
+const Bool g_bEncDecTraceDisable = false;
+Bool   g_HLSTraceEnable = true;
+Bool   g_bJustDoIt = false;
+UInt64 g_nSymbolCounter = 0;
+#endif
+// ====================================================================================================================
+// Scanning order & context model mapping
+// ====================================================================================================================
+
+// scanning order table
+UInt* g_scanOrder[SCAN_NUMBER_OF_GROUP_TYPES][SCAN_NUMBER_OF_TYPES][ MAX_CU_DEPTH ][ MAX_CU_DEPTH ];
+
+const UInt ctxIndMap4x4[4*4] =
+{
+  0, 1, 4, 5,
+  2, 3, 4, 5,
+  6, 6, 8, 8,
+  7, 7, 8, 8
+};
+
+const UInt g_uiMinInGroup[ LAST_SIGNIFICANT_GROUPS ] = {0,1,2,3,4,6,8,12,16,24};
+const UInt g_uiGroupIdx[ MAX_TU_SIZE ]   = {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};
+
+const Char *MatrixType[SCALING_LIST_SIZE_NUM][SCALING_LIST_NUM] =
+{
+  {
+    "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",
+   "INTRA32X32_CHROMAU_FROM16x16_CHROMAU",
+   "INTRA32X32_CHROMAV_FROM16x16_CHROMAV",
+   "INTER32X32_LUMA",
+   "INTER32X32_CHROMAU_FROM16x16_CHROMAU",
+   "INTER32X32_CHROMAV_FROM16x16_CHROMAV"
+  },
+};
+
+const Char *MatrixType_DC[SCALING_LIST_SIZE_NUM][SCALING_LIST_NUM] =
+{
+  {
+  },
+  {
+  },
+  {
+    "INTRA16X16_LUMA_DC",
+    "INTRA16X16_CHROMAU_DC",
+    "INTRA16X16_CHROMAV_DC",
+    "INTER16X16_LUMA_DC",
+    "INTER16X16_CHROMAU_DC",
+    "INTER16X16_CHROMAV_DC"
+  },
+  {
+    "INTRA32X32_LUMA_DC",
+    "INTRA32X32_CHROMAU_DC_FROM16x16_CHROMAU",
+    "INTRA32X32_CHROMAV_DC_FROM16x16_CHROMAV",
+    "INTER32X32_LUMA_DC",
+    "INTER32X32_CHROMAU_DC_FROM16x16_CHROMAU",
+    "INTER32X32_CHROMAV_DC_FROM16x16_CHROMAV"
+  },
+};
+
+Int g_quantTSDefault4x4[4*4] =
+{
+  16,16,16,16,
+  16,16,16,16,
+  16,16,16,16,
+  16,16,16,16
+};
+
+Int g_quantIntraDefault8x8[8*8] =
+{
+  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[8*8] =
+{
+  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   [SCALING_LIST_SIZE_NUM] = {16,64,256,1024};
+UInt g_scalingListSizeX  [SCALING_LIST_SIZE_NUM] = { 4, 8, 16,  32};
+
+#if SVC_EXTENSION
+#if FAST_INTRA_SHVC
+UInt g_reducedSetIntraModes[NUM_INTRA_MODE-1] = { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }; 
+UInt g_predefSetIntraModes[NUM_INTRA_MODE-1] = {26,10,18,34,2,22,14,30,6,24,12,28,8,20,16,32,4,17,19,15,21,13,23,11,25,9,27,7,29,5,31,3,33,0,2};
+#endif
+#if O0194_DIFFERENT_BITDEPTH_EL_BL
+Int  g_bitDepthLayer[MAX_NUM_CHANNEL_TYPE][MAX_LAYERS];
+#endif
+#if O0194_WEIGHTED_PREDICTION_CGS
+void * g_refWeightACDCParam; // type=wpACDCParam
+#endif
+Int g_mvScalingFactor  [MAX_LAYERS][2] = {{0,0}, {0,0}};
+Int g_posScalingFactor [MAX_LAYERS][2] = {{0,0}, {0,0}};
+
+std::string NaluToStr( NalUnitType nalu )
+{
+  switch( nalu )
+  {
+  case NAL_UNIT_CODED_SLICE_TRAIL_N:
+    return "TRAIL_N";
+  case NAL_UNIT_CODED_SLICE_TRAIL_R:
+    return "TRAIL_R";
+  
+  case NAL_UNIT_CODED_SLICE_TSA_N:
+    return "  TSA_N";
+  case NAL_UNIT_CODED_SLICE_TSA_R:
+    return "  TSA_R";
+  
+  case NAL_UNIT_CODED_SLICE_STSA_N:
+    return " STSA_N";
+  case NAL_UNIT_CODED_SLICE_STSA_R:
+    return " STSA_R";
+
+  case NAL_UNIT_CODED_SLICE_RADL_N:
+    return " RADL_N";
+  case NAL_UNIT_CODED_SLICE_RADL_R:
+    return " RADL_R";
+  
+  case NAL_UNIT_CODED_SLICE_RASL_N:
+    return " RASL_N";
+  case NAL_UNIT_CODED_SLICE_RASL_R:
+    return " RASL_R";
+
+  case NAL_UNIT_CODED_SLICE_BLA_W_LP:
+  case NAL_UNIT_CODED_SLICE_BLA_W_RADL:
+  case NAL_UNIT_CODED_SLICE_BLA_N_LP:
+    return "    BLA";
+
+  case NAL_UNIT_CODED_SLICE_IDR_W_RADL:
+  case NAL_UNIT_CODED_SLICE_IDR_N_LP:
+    return "    IDR";
+  
+  case NAL_UNIT_CODED_SLICE_CRA:
+    return "    CRA";
+
+  default:
+    return "       ";
+  };
+}
+#if LAYER_CTB
+UInt g_auiLayerMaxCUWidth[MAX_LAYERS];
+UInt g_auiLayerMaxCUHeight[MAX_LAYERS];
+UInt g_auiLayerMaxCUDepth[MAX_LAYERS];
+UInt g_auiLayerAddCUDepth[MAX_LAYERS];
+UInt g_auiLayerZscanToRaster[MAX_LAYERS][ MAX_NUM_SPU_W*MAX_NUM_SPU_W ];
+UInt g_auiLayerRasterToZscan[MAX_LAYERS][ MAX_NUM_SPU_W*MAX_NUM_SPU_W ];
+UInt g_auiLayerRasterToPelX[MAX_LAYERS][ MAX_NUM_SPU_W*MAX_NUM_SPU_W ];
+UInt g_auiLayerRasterToPelY[MAX_LAYERS][ MAX_NUM_SPU_W*MAX_NUM_SPU_W ];
+#endif
+#endif //SVC_EXTENSION
+
+//! \}
Index: /tags/SHM-9.0/source/Lib/TLibCommon/TComRom.h
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibCommon/TComRom.h	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibCommon/TComRom.h	(revision 1088)
@@ -0,0 +1,258 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TComRom.h
+    \brief    global variables & functions (header)
+*/
+
+#ifndef __TCOMROM__
+#define __TCOMROM__
+
+#include "CommonDef.h"
+
+#include<stdio.h>
+#include<iostream>
+
+//! \ingroup TLibCommon
+//! \{
+
+// ====================================================================================================================
+// Macros
+// ====================================================================================================================
+
+#define     MAX_CU_DEPTH             6                          // log2(CTUSize)
+#define     MAX_CU_SIZE             (1<<(MAX_CU_DEPTH))         // maximum allowable size of CU, surely 64? (not 1<<7 = 128)
+#define     MIN_PU_SIZE              4
+#define     MIN_TU_SIZE              4
+#define     MAX_TU_SIZE             32
+#define     MAX_NUM_SPU_W           (MAX_CU_SIZE/MIN_PU_SIZE)   // maximum number of SPU in horizontal line
+
+#define     SCALING_LIST_REM_NUM     6
+
+// ====================================================================================================================
+// Initialize / destroy functions
+// ====================================================================================================================
+
+Void         initROM();
+Void         destroyROM();
+
+// ====================================================================================================================
+// 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 ];
+extern       UInt*  g_scanOrder[SCAN_NUMBER_OF_GROUP_TYPES][SCAN_NUMBER_OF_TYPES][ MAX_CU_DEPTH ][ MAX_CU_DEPTH ];
+
+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 (CTU width/height, max. CU depth)
+extern       UInt g_uiMaxCUWidth;
+extern       UInt g_uiMaxCUHeight;
+extern       UInt g_uiMaxCUDepth;
+extern       UInt g_uiAddCUDepth;
+
+extern       UInt g_auiPUOffset[NUMBER_OF_PART_SIZES];
+
+#define QUANT_SHIFT                14 // Q(4) = 2^14
+#define IQUANT_SHIFT                6
+#define SCALE_BITS                 15 // Inherited from TMuC, pressumably for fractional bit estimates in RDOQ
+
+extern Int g_maxTrDynamicRange[MAX_NUM_CHANNEL_TYPE];
+
+#define SQRT2                      11585
+#define SQRT2_SHIFT                13
+#define INVSQRT2                   11585
+#define INVSQRT2_SHIFT             14
+#define ADDITIONAL_MULTIPLIER_BITS 14
+
+#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[SCALING_LIST_REM_NUM];             // Q(QP%6)
+extern Int g_invQuantScales[SCALING_LIST_REM_NUM];          // IQ(QP%6)
+
+#if RExt__HIGH_PRECISION_FORWARD_TRANSFORM
+static const Int g_transformMatrixShift[TRANSFORM_NUMBER_OF_DIRECTIONS] = { 14, 6 };
+#else
+static const Int g_transformMatrixShift[TRANSFORM_NUMBER_OF_DIRECTIONS] = {  6, 6 };
+#endif
+
+extern const TMatrixCoeff g_aiT4 [TRANSFORM_NUMBER_OF_DIRECTIONS][4][4];
+extern const TMatrixCoeff g_aiT8 [TRANSFORM_NUMBER_OF_DIRECTIONS][8][8];
+extern const TMatrixCoeff g_aiT16[TRANSFORM_NUMBER_OF_DIRECTIONS][16][16];
+extern const TMatrixCoeff g_aiT32[TRANSFORM_NUMBER_OF_DIRECTIONS][32][32];
+
+// ====================================================================================================================
+// Luma QP to Chroma QP mapping
+// ====================================================================================================================
+
+static const Int chromaQPMappingTableSize = 58;
+
+extern const UChar  g_aucChromaScale[NUM_CHROMA_FORMAT][chromaQPMappingTableSize];
+
+// ====================================================================================================================
+// Entropy Coding
+// ====================================================================================================================
+
+#define CONTEXT_STATE_BITS             6
+#define LAST_SIGNIFICANT_GROUPS       10
+
+// ====================================================================================================================
+// Scanning order & context mapping table
+// ====================================================================================================================
+
+extern const UInt   ctxIndMap4x4[4*4];
+
+extern const UInt   g_uiGroupIdx[ MAX_TU_SIZE ];
+extern const UInt   g_uiMinInGroup[ LAST_SIGNIFICANT_GROUPS ];
+
+// ====================================================================================================================
+// ADI table
+// ====================================================================================================================
+
+extern const UChar  g_aucIntraModeNumFast[MAX_CU_DEPTH];
+
+extern const UChar  g_chroma422IntraAngleMappingTable[NUM_INTRA_MODE];
+
+// ====================================================================================================================
+// Bit-depth
+// ====================================================================================================================
+
+extern        Int g_bitDepth   [MAX_NUM_CHANNEL_TYPE];
+extern        Int g_PCMBitDepth[MAX_NUM_CHANNEL_TYPE];
+#if O0043_BEST_EFFORT_DECODING
+extern        Int g_bitDepthInStream   [MAX_NUM_CHANNEL_TYPE]; // In the encoder, this is the same as g_bitDepth. In the decoder, this can vary from g_bitDepth if the decoder is forced to use 'best-effort decoding' at a particular bit-depth.
+#endif
+
+// ====================================================================================================================
+// Mode-Dependent DST Matrices
+// ====================================================================================================================
+
+extern const TMatrixCoeff g_as_DST_MAT_4 [TRANSFORM_NUMBER_OF_DIRECTIONS][4][4];
+
+// ====================================================================================================================
+// 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"    );
+
+#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
+
+#endif
+
+
+#define SCALING_LIST_NUM (MAX_NUM_COMPONENT * NUMBER_OF_PREDICTION_MODES) ///< list number for quantization matrix
+
+#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_BITS 8                                               ///< bit depth of scaling list entries
+#define LOG2_SCALING_LIST_NEUTRAL_VALUE 4                                 ///< log2 of the value that, when used in a scaling list, has no effect on quantisation
+#define SCALING_LIST_DC 16                                                ///< default DC value
+
+extern const Char *MatrixType[SCALING_LIST_SIZE_NUM][SCALING_LIST_NUM];
+extern const Char *MatrixType_DC[SCALING_LIST_SIZE_NUM][SCALING_LIST_NUM];
+
+extern Int g_quantTSDefault4x4[4*4];
+extern Int g_quantIntraDefault8x8[8*8];
+extern Int g_quantInterDefault8x8[8*8];
+
+extern UInt g_scalingListSize [SCALING_LIST_SIZE_NUM];
+extern UInt g_scalingListSizeX[SCALING_LIST_SIZE_NUM];
+extern UInt g_scalingListNum  [SCALING_LIST_SIZE_NUM];
+
+#if SVC_EXTENSION
+#if FAST_INTRA_SHVC
+extern UInt g_reducedSetIntraModes[NUM_INTRA_MODE-1];
+extern UInt g_predefSetIntraModes[NUM_INTRA_MODE-1];
+#endif
+extern Int g_mvScalingFactor  [MAX_LAYERS][2];
+extern Int g_posScalingFactor [MAX_LAYERS][2];
+std::string NaluToStr( NalUnitType nalu );
+#if LAYER_CTB
+extern       UInt g_auiLayerMaxCUWidth[MAX_LAYERS];
+extern       UInt g_auiLayerMaxCUHeight[MAX_LAYERS];
+extern       UInt g_auiLayerMaxCUDepth[MAX_LAYERS];
+extern       UInt g_auiLayerAddCUDepth[MAX_LAYERS];
+extern       UInt g_auiLayerZscanToRaster[MAX_LAYERS][ MAX_NUM_SPU_W*MAX_NUM_SPU_W ];
+extern       UInt g_auiLayerRasterToZscan[MAX_LAYERS][ MAX_NUM_SPU_W*MAX_NUM_SPU_W ];
+extern       UInt g_auiLayerRasterToPelX[MAX_LAYERS][ MAX_NUM_SPU_W*MAX_NUM_SPU_W ];
+extern       UInt g_auiLayerRasterToPelY[MAX_LAYERS][ MAX_NUM_SPU_W*MAX_NUM_SPU_W ];
+#endif
+#endif //SVC_EXTENSION
+
+//! \}
+
+#endif  //__TCOMROM__
+
Index: /tags/SHM-9.0/source/Lib/TLibCommon/TComSampleAdaptiveOffset.cpp
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibCommon/TComSampleAdaptiveOffset.cpp	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibCommon/TComSampleAdaptiveOffset.cpp	(revision 1088)
@@ -0,0 +1,733 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TComSampleAdaptiveOffset.cpp
+    \brief    sample adaptive offset class
+*/
+
+#include "TComSampleAdaptiveOffset.h"
+#include <string.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <math.h>
+
+//! \ingroup TLibCommon
+//! \{
+#if !SVC_EXTENSION
+UInt g_saoMaxOffsetQVal[MAX_NUM_COMPONENT];
+#endif
+
+SAOOffset::SAOOffset()
+{
+  reset();
+}
+
+SAOOffset::~SAOOffset()
+{
+
+}
+
+Void SAOOffset::reset()
+{
+  modeIdc = SAO_MODE_OFF;
+  typeIdc = -1;
+  typeAuxInfo = -1;
+  ::memset(offset, 0, sizeof(Int)* MAX_NUM_SAO_CLASSES);
+}
+
+const SAOOffset& SAOOffset::operator= (const SAOOffset& src)
+{
+  modeIdc = src.modeIdc;
+  typeIdc = src.typeIdc;
+  typeAuxInfo = src.typeAuxInfo;
+  ::memcpy(offset, src.offset, sizeof(Int)* MAX_NUM_SAO_CLASSES);
+
+  return *this;
+}
+
+
+SAOBlkParam::SAOBlkParam()
+{
+  reset();
+}
+
+SAOBlkParam::~SAOBlkParam()
+{
+
+}
+
+Void SAOBlkParam::reset()
+{
+  for(Int compIdx = 0; compIdx < MAX_NUM_COMPONENT; compIdx++)
+  {
+    offsetParam[compIdx].reset();
+  }
+}
+
+const SAOBlkParam& SAOBlkParam::operator= (const SAOBlkParam& src)
+{
+  for(Int compIdx = 0; compIdx < MAX_NUM_COMPONENT; compIdx++)
+  {
+    offsetParam[compIdx] = src.offsetParam[compIdx];
+  }
+  return *this;
+
+}
+
+TComSampleAdaptiveOffset::TComSampleAdaptiveOffset()
+{
+  m_tempPicYuv = NULL;
+  m_lineBufWidth = 0;
+  m_signLineBuf1 = NULL;
+  m_signLineBuf2 = NULL;
+}
+
+
+TComSampleAdaptiveOffset::~TComSampleAdaptiveOffset()
+{
+  destroy();
+
+  if (m_signLineBuf1) delete[] m_signLineBuf1; m_signLineBuf1 = NULL;
+  if (m_signLineBuf2) delete[] m_signLineBuf2; m_signLineBuf2 = NULL;
+}
+
+Void TComSampleAdaptiveOffset::create( Int picWidth, Int picHeight, ChromaFormat format, UInt maxCUWidth, UInt maxCUHeight, UInt maxCUDepth, UInt lumaBitShift, UInt chromaBitShift )
+{
+  destroy();
+
+  m_picWidth        = picWidth;
+  m_picHeight       = picHeight;
+  m_chromaFormatIDC = format;
+  m_maxCUWidth      = maxCUWidth;
+  m_maxCUHeight     = maxCUHeight;
+
+  m_numCTUInWidth   = (m_picWidth/m_maxCUWidth) + ((m_picWidth % m_maxCUWidth)?1:0);
+  m_numCTUInHeight  = (m_picHeight/m_maxCUHeight) + ((m_picHeight % m_maxCUHeight)?1:0);
+  m_numCTUsPic      = m_numCTUInHeight*m_numCTUInWidth;
+
+  //temporary picture buffer
+  if ( !m_tempPicYuv )
+  {
+    m_tempPicYuv = new TComPicYuv;
+    m_tempPicYuv->create( m_picWidth, m_picHeight, m_chromaFormatIDC, m_maxCUWidth, m_maxCUHeight, maxCUDepth );
+  }
+
+  //bit-depth related
+  for(Int compIdx = 0; compIdx < MAX_NUM_COMPONENT; compIdx++)
+  {
+    Int bitDepthSample = g_bitDepth[toChannelType(ComponentID(compIdx))];
+    m_offsetStepLog2  [compIdx] = isLuma(ComponentID(compIdx))? lumaBitShift : chromaBitShift;
+#if SVC_EXTENSION
+    m_saoMaxOffsetQVal[compIdx] = (1<<(min(bitDepthSample,MAX_SAO_TRUNCATED_BITDEPTH)-5))-1; //Table 9-32, inclusive
+#else
+    g_saoMaxOffsetQVal[compIdx] = (1<<(min(bitDepthSample,MAX_SAO_TRUNCATED_BITDEPTH)-5))-1; //Table 9-32, inclusive
+#endif
+  }
+}
+
+Void TComSampleAdaptiveOffset::destroy()
+{
+  if ( m_tempPicYuv )
+  {
+    m_tempPicYuv->destroy();
+    delete m_tempPicYuv;
+    m_tempPicYuv = NULL;
+  }
+}
+
+Void TComSampleAdaptiveOffset::invertQuantOffsets(ComponentID compIdx, Int typeIdc, Int typeAuxInfo, Int* dstOffsets, Int* srcOffsets)
+{
+  Int codedOffset[MAX_NUM_SAO_CLASSES];
+
+  ::memcpy(codedOffset, srcOffsets, sizeof(Int)*MAX_NUM_SAO_CLASSES);
+  ::memset(dstOffsets, 0, sizeof(Int)*MAX_NUM_SAO_CLASSES);
+
+  if(typeIdc == SAO_TYPE_START_BO)
+  {
+    for(Int i=0; i< 4; i++)
+    {
+      dstOffsets[(typeAuxInfo+ i)%NUM_SAO_BO_CLASSES] = codedOffset[(typeAuxInfo+ i)%NUM_SAO_BO_CLASSES]*(1<<m_offsetStepLog2[compIdx]);
+    }
+  }
+  else //EO
+  {
+    for(Int i=0; i< NUM_SAO_EO_CLASSES; i++)
+    {
+      dstOffsets[i] = codedOffset[i] *(1<<m_offsetStepLog2[compIdx]);
+    }
+    assert(dstOffsets[SAO_CLASS_EO_PLAIN] == 0); //keep EO plain offset as zero
+  }
+
+}
+
+Int TComSampleAdaptiveOffset::getMergeList(TComPic* pic, Int ctuRsAddr, SAOBlkParam* blkParams, SAOBlkParam* mergeList[NUM_SAO_MERGE_TYPES])
+{
+  Int ctuX = ctuRsAddr % m_numCTUInWidth;
+  Int ctuY = ctuRsAddr / m_numCTUInWidth;
+  Int mergedCTUPos;
+  Int numValidMergeCandidates = 0;
+
+  for(Int mergeType=0; mergeType< NUM_SAO_MERGE_TYPES; mergeType++)
+  {
+    SAOBlkParam* mergeCandidate = NULL;
+
+    switch(mergeType)
+    {
+    case SAO_MERGE_ABOVE:
+      {
+        if(ctuY > 0)
+        {
+          mergedCTUPos = ctuRsAddr- m_numCTUInWidth;
+          if( pic->getSAOMergeAvailability(ctuRsAddr, mergedCTUPos) )
+          {
+            mergeCandidate = &(blkParams[mergedCTUPos]);
+          }
+        }
+      }
+      break;
+    case SAO_MERGE_LEFT:
+      {
+        if(ctuX > 0)
+        {
+          mergedCTUPos = ctuRsAddr- 1;
+          if( pic->getSAOMergeAvailability(ctuRsAddr, mergedCTUPos) )
+          {
+            mergeCandidate = &(blkParams[mergedCTUPos]);
+          }
+        }
+      }
+      break;
+    default:
+      {
+        printf("not a supported merge type");
+        assert(0);
+        exit(-1);
+      }
+    }
+
+    mergeList[mergeType]=mergeCandidate;
+    if (mergeCandidate != NULL)
+    {
+      numValidMergeCandidates++;
+    }
+  }
+
+  return numValidMergeCandidates;
+}
+
+
+Void TComSampleAdaptiveOffset::reconstructBlkSAOParam(SAOBlkParam& recParam, SAOBlkParam* mergeList[NUM_SAO_MERGE_TYPES])
+{
+  const Int numberOfComponents = getNumberValidComponents(m_chromaFormatIDC);
+  for(Int compIdx = 0; compIdx < numberOfComponents; compIdx++)
+  {
+    const ComponentID component = ComponentID(compIdx);
+    SAOOffset& offsetParam = recParam[component];
+
+    if(offsetParam.modeIdc == SAO_MODE_OFF)
+    {
+      continue;
+    }
+
+    switch(offsetParam.modeIdc)
+    {
+    case SAO_MODE_NEW:
+      {
+        invertQuantOffsets(component, offsetParam.typeIdc, offsetParam.typeAuxInfo, offsetParam.offset, offsetParam.offset);
+      }
+      break;
+    case SAO_MODE_MERGE:
+      {
+        SAOBlkParam* mergeTarget = mergeList[offsetParam.typeIdc];
+        assert(mergeTarget != NULL);
+
+        offsetParam = (*mergeTarget)[component];
+      }
+      break;
+    default:
+      {
+        printf("Not a supported mode");
+        assert(0);
+        exit(-1);
+      }
+    }
+  }
+}
+
+Void TComSampleAdaptiveOffset::reconstructBlkSAOParams(TComPic* pic, SAOBlkParam* saoBlkParams)
+{
+  for(Int compIdx = 0; compIdx < MAX_NUM_COMPONENT; compIdx++)
+  {
+    m_picSAOEnabled[compIdx] = false;
+  }
+
+  const Int numberOfComponents = getNumberValidComponents(m_chromaFormatIDC);
+
+  for(Int ctuRsAddr=0; ctuRsAddr< m_numCTUsPic; ctuRsAddr++)
+  {
+    SAOBlkParam* mergeList[NUM_SAO_MERGE_TYPES] = { NULL };
+    getMergeList(pic, ctuRsAddr, saoBlkParams, mergeList);
+
+    reconstructBlkSAOParam(saoBlkParams[ctuRsAddr], mergeList);
+
+    for(Int compIdx = 0; compIdx < numberOfComponents; compIdx++)
+    {
+      if(saoBlkParams[ctuRsAddr][compIdx].modeIdc != SAO_MODE_OFF)
+      {
+        m_picSAOEnabled[compIdx] = true;
+      }
+    }
+  }
+}
+
+
+Void TComSampleAdaptiveOffset::offsetBlock(ComponentID compIdx, Int typeIdx, Int* offset
+                                          , Pel* srcBlk, Pel* resBlk, Int srcStride, Int resStride,  Int width, Int height
+                                          , Bool isLeftAvail,  Bool isRightAvail, Bool isAboveAvail, Bool isBelowAvail, Bool isAboveLeftAvail, Bool isAboveRightAvail, Bool isBelowLeftAvail, Bool isBelowRightAvail)
+{
+  if(m_lineBufWidth != m_maxCUWidth)
+  {
+    m_lineBufWidth = m_maxCUWidth;
+
+    if (m_signLineBuf1) delete[] m_signLineBuf1; m_signLineBuf1 = NULL;
+    m_signLineBuf1 = new Char[m_lineBufWidth+1];
+
+    if (m_signLineBuf2) delete[] m_signLineBuf2; m_signLineBuf2 = NULL;
+    m_signLineBuf2 = new Char[m_lineBufWidth+1];
+  }
+
+  const Int maxSampleValueIncl = (1<< g_bitDepth[toChannelType(compIdx)] )-1;
+
+  Int x,y, startX, startY, endX, endY, edgeType;
+  Int firstLineStartX, firstLineEndX, lastLineStartX, lastLineEndX;
+  Char signLeft, signRight, signDown;
+
+  Pel* srcLine = srcBlk;
+  Pel* resLine = resBlk;
+
+  switch(typeIdx)
+  {
+  case SAO_TYPE_EO_0:
+    {
+      offset += 2;
+      startX = isLeftAvail ? 0 : 1;
+      endX   = isRightAvail ? width : (width -1);
+      for (y=0; y< height; y++)
+      {
+        signLeft = (Char)sgn(srcLine[startX] - srcLine[startX-1]);
+        for (x=startX; x< endX; x++)
+        {
+          signRight = (Char)sgn(srcLine[x] - srcLine[x+1]); 
+          edgeType =  signRight + signLeft;
+          signLeft  = -signRight;
+
+          resLine[x] = Clip3<Int>(0, maxSampleValueIncl, srcLine[x] + offset[edgeType]);
+        }
+        srcLine  += srcStride;
+        resLine += resStride;
+      }
+
+    }
+    break;
+  case SAO_TYPE_EO_90:
+    {
+      offset += 2;
+      Char *signUpLine = m_signLineBuf1;
+
+      startY = isAboveAvail ? 0 : 1;
+      endY   = isBelowAvail ? height : height-1;
+      if (!isAboveAvail)
+      {
+        srcLine += srcStride;
+        resLine += resStride;
+      }
+
+      Pel* srcLineAbove= srcLine- srcStride;
+      for (x=0; x< width; x++)
+      {
+        signUpLine[x] = (Char)sgn(srcLine[x] - srcLineAbove[x]);
+      }
+
+      Pel* srcLineBelow;
+      for (y=startY; y<endY; y++)
+      {
+        srcLineBelow= srcLine+ srcStride;
+
+        for (x=0; x< width; x++)
+        {
+          signDown  = (Char)sgn(srcLine[x] - srcLineBelow[x]);
+          edgeType = signDown + signUpLine[x];
+          signUpLine[x]= -signDown;
+
+          resLine[x] = Clip3<Int>(0, maxSampleValueIncl, srcLine[x] + offset[edgeType]);
+        }
+        srcLine += srcStride;
+        resLine += resStride;
+      }
+
+    }
+    break;
+  case SAO_TYPE_EO_135:
+    {
+      offset += 2;
+      Char *signUpLine, *signDownLine, *signTmpLine;
+
+      signUpLine  = m_signLineBuf1;
+      signDownLine= m_signLineBuf2;
+
+      startX = isLeftAvail ? 0 : 1 ;
+      endX   = isRightAvail ? width : (width-1);
+
+      //prepare 2nd line's upper sign
+      Pel* srcLineBelow= srcLine+ srcStride;
+      for (x=startX; x< endX+1; x++)
+      {
+        signUpLine[x] = (Char)sgn(srcLineBelow[x] - srcLine[x- 1]);
+      }
+
+      //1st line
+      Pel* srcLineAbove= srcLine- srcStride;
+      firstLineStartX = isAboveLeftAvail ? 0 : 1;
+      firstLineEndX   = isAboveAvail? endX: 1;
+      for(x= firstLineStartX; x< firstLineEndX; x++)
+      {
+        edgeType  =  sgn(srcLine[x] - srcLineAbove[x- 1]) - signUpLine[x+1];
+
+        resLine[x] = Clip3<Int>(0, maxSampleValueIncl, srcLine[x] + offset[edgeType]);
+      }
+      srcLine  += srcStride;
+      resLine  += resStride;
+
+
+      //middle lines
+      for (y= 1; y< height-1; y++)
+      {
+        srcLineBelow= srcLine+ srcStride;
+
+        for (x=startX; x<endX; x++)
+        {
+          signDown =  (Char)sgn(srcLine[x] - srcLineBelow[x+ 1]);
+          edgeType =  signDown + signUpLine[x];
+          resLine[x] = Clip3<Int>(0, maxSampleValueIncl, srcLine[x] + offset[edgeType]);
+
+          signDownLine[x+1] = -signDown;
+        }
+        signDownLine[startX] = (Char)sgn(srcLineBelow[startX] - srcLine[startX-1]);
+
+        signTmpLine  = signUpLine;
+        signUpLine   = signDownLine;
+        signDownLine = signTmpLine;
+
+        srcLine += srcStride;
+        resLine += resStride;
+      }
+
+      //last line
+      srcLineBelow= srcLine+ srcStride;
+      lastLineStartX = isBelowAvail ? startX : (width -1);
+      lastLineEndX   = isBelowRightAvail ? width : (width -1);
+      for(x= lastLineStartX; x< lastLineEndX; x++)
+      {
+        edgeType =  sgn(srcLine[x] - srcLineBelow[x+ 1]) + signUpLine[x];
+        resLine[x] = Clip3<Int>(0, maxSampleValueIncl, srcLine[x] + offset[edgeType]);
+
+      }
+    }
+    break;
+  case SAO_TYPE_EO_45:
+    {
+      offset += 2;
+      Char *signUpLine = m_signLineBuf1+1;
+
+      startX = isLeftAvail ? 0 : 1;
+      endX   = isRightAvail ? width : (width -1);
+
+      //prepare 2nd line upper sign
+      Pel* srcLineBelow= srcLine+ srcStride;
+      for (x=startX-1; x< endX; x++)
+      {
+        signUpLine[x] = (Char)sgn(srcLineBelow[x] - srcLine[x+1]);
+      }
+
+
+      //first line
+      Pel* srcLineAbove= srcLine- srcStride;
+      firstLineStartX = isAboveAvail ? startX : (width -1 );
+      firstLineEndX   = isAboveRightAvail ? width : (width-1);
+      for(x= firstLineStartX; x< firstLineEndX; x++)
+      {
+        edgeType = sgn(srcLine[x] - srcLineAbove[x+1]) -signUpLine[x-1];
+        resLine[x] = Clip3<Int>(0, maxSampleValueIncl, srcLine[x] + offset[edgeType]);
+      }
+      srcLine += srcStride;
+      resLine += resStride;
+
+      //middle lines
+      for (y= 1; y< height-1; y++)
+      {
+        srcLineBelow= srcLine+ srcStride;
+
+        for(x= startX; x< endX; x++)
+        {
+          signDown =  (Char)sgn(srcLine[x] - srcLineBelow[x-1]);
+          edgeType =  signDown + signUpLine[x];
+          resLine[x] = Clip3<Int>(0, maxSampleValueIncl, srcLine[x] + offset[edgeType]);
+          signUpLine[x-1] = -signDown;
+        }
+        signUpLine[endX-1] = (Char)sgn(srcLineBelow[endX-1] - srcLine[endX]);
+        srcLine  += srcStride;
+        resLine += resStride;
+      }
+
+      //last line
+      srcLineBelow= srcLine+ srcStride;
+      lastLineStartX = isBelowLeftAvail ? 0 : 1;
+      lastLineEndX   = isBelowAvail ? endX : 1;
+      for(x= lastLineStartX; x< lastLineEndX; x++)
+      {
+        edgeType = sgn(srcLine[x] - srcLineBelow[x-1]) + signUpLine[x];
+        resLine[x] = Clip3<Int>(0, maxSampleValueIncl, srcLine[x] + offset[edgeType]);
+
+      }
+    }
+    break;
+  case SAO_TYPE_BO:
+    {
+      const Int shiftBits = g_bitDepth[toChannelType(compIdx)] - NUM_SAO_BO_CLASSES_LOG2;
+      for (y=0; y< height; y++)
+      {
+        for (x=0; x< width; x++)
+        {
+          resLine[x] = Clip3<Int>(0, maxSampleValueIncl, srcLine[x] + offset[srcLine[x] >> shiftBits] );
+        }
+        srcLine += srcStride;
+        resLine += resStride;
+      }
+    }
+    break;
+  default:
+    {
+      printf("Not a supported SAO types\n");
+      assert(0);
+      exit(-1);
+    }
+  }
+}
+
+Void TComSampleAdaptiveOffset::offsetCTU(Int ctuRsAddr, TComPicYuv* srcYuv, TComPicYuv* resYuv, SAOBlkParam& saoblkParam, TComPic* pPic)
+{
+  Bool isLeftAvail,isRightAvail,isAboveAvail,isBelowAvail,isAboveLeftAvail,isAboveRightAvail,isBelowLeftAvail,isBelowRightAvail;
+
+  const Int numberOfComponents = getNumberValidComponents(m_chromaFormatIDC);
+  Bool bAllOff=true;
+  for(Int compIdx = 0; compIdx < numberOfComponents; compIdx++)
+  {
+    if (saoblkParam[compIdx].modeIdc != SAO_MODE_OFF) bAllOff=false;
+  }
+  if (bAllOff) return;
+
+  //block boundary availability
+  pPic->getPicSym()->deriveLoopFilterBoundaryAvailibility(ctuRsAddr, isLeftAvail,isRightAvail,isAboveAvail,isBelowAvail,isAboveLeftAvail,isAboveRightAvail,isBelowLeftAvail,isBelowRightAvail);
+
+  Int yPos   = (ctuRsAddr / m_numCTUInWidth)*m_maxCUHeight;
+  Int xPos   = (ctuRsAddr % m_numCTUInWidth)*m_maxCUWidth;
+  Int height = (yPos + m_maxCUHeight > m_picHeight)?(m_picHeight- yPos):m_maxCUHeight;
+  Int width  = (xPos + m_maxCUWidth  > m_picWidth )?(m_picWidth - xPos):m_maxCUWidth;
+
+  for(Int compIdx = 0; compIdx < numberOfComponents; compIdx++)
+  {
+    const ComponentID component = ComponentID(compIdx);
+    SAOOffset& ctbOffset = saoblkParam[compIdx];
+
+    if(ctbOffset.modeIdc != SAO_MODE_OFF)
+    {
+      const UInt componentScaleX = getComponentScaleX(component, pPic->getChromaFormat());
+      const UInt componentScaleY = getComponentScaleY(component, pPic->getChromaFormat());
+
+      Int  blkWidth   = (width  >> componentScaleX);
+      Int  blkHeight  = (height >> componentScaleY);
+      Int  blkXPos    = (xPos   >> componentScaleX);
+      Int  blkYPos    = (yPos   >> componentScaleY);
+
+      Int  srcStride  = srcYuv->getStride(component);
+      Pel* srcBlk     = srcYuv->getAddr(component) + blkYPos*srcStride + blkXPos;
+
+      Int  resStride  = resYuv->getStride(component);
+      Pel* resBlk     = resYuv->getAddr(component) + blkYPos*resStride + blkXPos;
+
+      offsetBlock( component, ctbOffset.typeIdc, ctbOffset.offset
+                  , srcBlk, resBlk, srcStride, resStride, blkWidth, blkHeight
+                  , isLeftAvail, isRightAvail
+                  , isAboveAvail, isBelowAvail
+                  , isAboveLeftAvail, isAboveRightAvail
+                  , isBelowLeftAvail, isBelowRightAvail
+                  );
+    }
+  } //compIdx
+
+}
+
+
+Void TComSampleAdaptiveOffset::SAOProcess(TComPic* pDecPic)
+{
+  const Int numberOfComponents = getNumberValidComponents(m_chromaFormatIDC);
+  Bool bAllDisabled=true;
+  for(Int compIdx = 0; compIdx < numberOfComponents; compIdx++)
+  {
+    if (m_picSAOEnabled[compIdx]) bAllDisabled=false;
+  }
+  if (bAllDisabled) return;
+
+  TComPicYuv* resYuv = pDecPic->getPicYuvRec();
+  TComPicYuv* srcYuv = m_tempPicYuv;
+  resYuv->copyToPic(srcYuv);
+  for(Int ctuRsAddr= 0; ctuRsAddr < m_numCTUsPic; ctuRsAddr++)
+  {
+    offsetCTU(ctuRsAddr, srcYuv, resYuv, (pDecPic->getPicSym()->getSAOBlkParam())[ctuRsAddr], pDecPic);
+  } //ctu
+}
+
+
+/** 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 ctuRsAddr = 0; ctuRsAddr < pcPic->getNumberOfCtusInFrame() ; ctuRsAddr++ )
+    {
+      TComDataCU* pcCU = pcPic->getCtu(ctuRsAddr);
+
+      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->getNumPartitionsInCtu() >> (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 REPN_FORMAT_IN_VPS
+      if( ( uiLPelX < pcCU->getSlice()->getPicWidthInLumaSamples() ) && ( uiTPelY < pcCU->getSlice()->getPicHeightInLumaSamples() ) )
+#else
+      if( ( uiLPelX < pcCU->getSlice()->getSPS()->getPicWidthInLumaSamples() ) && ( uiTPelY < pcCU->getSlice()->getSPS()->getPicHeightInLumaSamples() ) )
+#endif
+        xPCMCURestoration( pcCU, uiAbsZorderIdx, uiDepth+1 );
+    }
+    return;
+  }
+
+  // restore PCM samples
+  if ((pcCU->getIPCMFlag(uiAbsZorderIdx)&& pcPic->getSlice(0)->getSPS()->getPCMFilterDisableFlag()) || pcCU->isLosslessCoded( uiAbsZorderIdx))
+  {
+    const UInt numComponents=pcPic->getNumberValidComponents();
+    for(UInt comp=0; comp<numComponents; comp++)
+    {
+      xPCMSampleRestoration (pcCU, uiAbsZorderIdx, uiDepth, ComponentID(comp));
+    }
+  }
+}
+
+/** 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, const ComponentID compID)
+{
+        TComPicYuv* pcPicYuvRec = pcCU->getPic()->getPicYuvRec();
+        UInt uiPcmLeftShiftBit;
+  const UInt uiMinCoeffSize = pcCU->getPic()->getMinCUWidth()*pcCU->getPic()->getMinCUHeight();
+  const UInt csx=pcPicYuvRec->getComponentScaleX(compID);
+  const UInt csy=pcPicYuvRec->getComponentScaleY(compID);
+  const UInt uiOffset   = (uiMinCoeffSize*uiAbsZorderIdx)>>(csx+csy);
+
+        Pel *piSrc = pcPicYuvRec->getAddr(compID, pcCU->getCtuRsAddr(), uiAbsZorderIdx);
+  const Pel *piPcm = pcCU->getPCMSample(compID) + uiOffset;
+  const UInt uiStride  = pcPicYuvRec->getStride(compID);
+  const UInt uiWidth  = ((g_uiMaxCUWidth >> uiDepth) >> csx);
+  const UInt uiHeight = ((g_uiMaxCUWidth >> uiDepth) >> csy);
+
+  if ( pcCU->isLosslessCoded(uiAbsZorderIdx) && !pcCU->getIPCMFlag(uiAbsZorderIdx) )
+  {
+    uiPcmLeftShiftBit = 0;
+  }
+  else
+  {
+    uiPcmLeftShiftBit = g_bitDepth[toChannelType(compID)] - pcCU->getSlice()->getSPS()->getPCMBitDepth(toChannelType(compID));
+  }
+
+  for(UInt uiY = 0; uiY < uiHeight; uiY++ )
+  {
+    for(UInt uiX = 0; uiX < uiWidth; uiX++ )
+    {
+      piSrc[uiX] = (piPcm[uiX] << uiPcmLeftShiftBit);
+    }
+    piPcm += uiWidth;
+    piSrc += uiStride;
+  }
+}
+
+//! \}
Index: /tags/SHM-9.0/source/Lib/TLibCommon/TComSampleAdaptiveOffset.h
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibCommon/TComSampleAdaptiveOffset.h	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibCommon/TComSampleAdaptiveOffset.h	(revision 1088)
@@ -0,0 +1,115 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TComSampleAdaptiveOffset.h
+    \brief    sample adaptive offset class (header)
+*/
+
+#ifndef __TCOMSAMPLEADAPTIVEOFFSET__
+#define __TCOMSAMPLEADAPTIVEOFFSET__
+
+#include "CommonDef.h"
+#include "TComPic.h"
+
+//! \ingroup TLibCommon
+//! \{
+
+
+// ====================================================================================================================
+// Constants
+// ====================================================================================================================
+
+#define MAX_SAO_TRUNCATED_BITDEPTH     10
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+#if !SVC_EXTENSION
+extern UInt g_saoMaxOffsetQVal[MAX_NUM_COMPONENT]; 
+#endif
+
+template <typename T> Int sgn(T val)
+{
+  return (T(0) < val) - (val < T(0));
+}
+
+class TComSampleAdaptiveOffset
+{
+public:
+  TComSampleAdaptiveOffset();
+  virtual ~TComSampleAdaptiveOffset();
+  Void SAOProcess(TComPic* pDecPic);
+  Void create( Int picWidth, Int picHeight, ChromaFormat format, UInt maxCUWidth, UInt maxCUHeight, UInt maxCUDepth, UInt lumaBitShift, UInt chromaBitShift );
+  Void destroy();
+  Void reconstructBlkSAOParams(TComPic* pic, SAOBlkParam* saoBlkParams);
+  Void PCMLFDisableProcess (TComPic* pcPic);
+#if SVC_EXTENSION
+  UInt* getSaoMaxOffsetQVal() { return m_saoMaxOffsetQVal; } 
+#endif
+protected:
+  Void offsetBlock(ComponentID compIdx, Int typeIdx, Int* offset, Pel* srcBlk, Pel* resBlk, Int srcStride, Int resStride,  Int width, Int height
+                  , Bool isLeftAvail, Bool isRightAvail, Bool isAboveAvail, Bool isBelowAvail, Bool isAboveLeftAvail, Bool isAboveRightAvail, Bool isBelowLeftAvail, Bool isBelowRightAvail);
+  Void invertQuantOffsets(ComponentID compIdx, Int typeIdc, Int typeAuxInfo, Int* dstOffsets, Int* srcOffsets);
+  Void reconstructBlkSAOParam(SAOBlkParam& recParam, SAOBlkParam* mergeList[NUM_SAO_MERGE_TYPES]);
+  Int  getMergeList(TComPic* pic, Int ctuRsAddr, SAOBlkParam* blkParams, SAOBlkParam* mergeList[NUM_SAO_MERGE_TYPES]);
+  Void offsetCTU(Int ctuRsAddr, TComPicYuv* srcYuv, TComPicYuv* resYuv, SAOBlkParam& saoblkParam, TComPic* pPic);
+  Void xPCMRestoration(TComPic* pcPic);
+  Void xPCMCURestoration ( TComDataCU* pcCU, UInt uiAbsZorderIdx, UInt uiDepth );
+  Void xPCMSampleRestoration (TComDataCU* pcCU, UInt uiAbsZorderIdx, UInt uiDepth, ComponentID component);
+protected:
+  UInt m_offsetStepLog2[MAX_NUM_COMPONENT]; //offset step
+  TComPicYuv*   m_tempPicYuv; //temporary buffer
+  Int m_picWidth;
+  Int m_picHeight;
+  Int m_maxCUWidth;
+  Int m_maxCUHeight;
+  Int m_numCTUInWidth;
+  Int m_numCTUInHeight;
+  Int m_numCTUsPic;
+
+
+  Int m_lineBufWidth;
+  Char* m_signLineBuf1;
+  Char* m_signLineBuf2;
+  ChromaFormat m_chromaFormatIDC;
+private:
+  Bool m_picSAOEnabled[MAX_NUM_COMPONENT];
+
+#if SVC_EXTENSION
+  UInt m_saoMaxOffsetQVal[MAX_NUM_COMPONENT]; 
+#endif
+};
+
+//! \}
+#endif
+
Index: /tags/SHM-9.0/source/Lib/TLibCommon/TComSlice.cpp
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibCommon/TComSlice.cpp	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibCommon/TComSlice.cpp	(revision 1088)
@@ -0,0 +1,4563 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TComSlice.cpp
+    \brief    slice header and SPS class
+*/
+
+#include "CommonDef.h"
+#include "TComSlice.h"
+#include "TComPic.h"
+#include "TLibEncoder/TEncSbac.h"
+#include "TLibDecoder/TDecSbac.h"
+
+
+//! \ingroup TLibCommon
+//! \{
+
+#if SVC_EXTENSION
+#include <numeric>
+ParameterSetMap<TComVPS> ParameterSetManager::m_vpsMap(MAX_NUM_VPS);
+ParameterSetMap<TComSPS> ParameterSetManager::m_spsMap(MAX_NUM_SPS);
+ParameterSetMap<TComPPS> ParameterSetManager::m_ppsMap(MAX_NUM_PPS);
+Int ParameterSetManager::m_activeVPSId = -1;
+#endif
+
+TComSlice::TComSlice()
+: m_iPPSId                        ( -1 )
+, m_PicOutputFlag                 ( true )
+, m_iPOC                          ( 0 )
+, m_iLastIDR                      ( 0 )
+, m_iAssociatedIRAP               ( 0 )
+, m_iAssociatedIRAPType           ( NAL_UNIT_INVALID )
+, m_pcRPS                         ( 0 )
+, m_LocalRPS                      ( )
+, m_iBDidx                        ( 0 )
+, m_RefPicListModification        ( )
+, 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_ChromaQpAdjEnabled            ( false )
+, m_deblockingFilterDisable       ( false )
+, m_deblockingFilterOverrideFlag  ( false )
+, m_deblockingFilterBetaOffsetDiv2( 0 )
+, m_deblockingFilterTcOffsetDiv2  ( 0 )
+, m_bCheckLDC                     ( false )
+, m_iSliceQpDelta                 ( 0 )
+, m_iDepth                        ( 0 )
+, m_bRefenced                     ( false )
+, m_pcVPS                         ( NULL )
+, m_pcSPS                         ( NULL )
+, m_pcPPS                         ( NULL )
+, m_pcPic                         ( NULL )
+#if ADAPTIVE_QP_SELECTION
+, m_pcTrQuant                     ( NULL )
+#endif
+, m_colFromL0Flag                 ( 1 )
+, m_noOutputPriorPicsFlag         ( false )
+, m_noRaslOutputFlag              ( false )
+, m_handleCraAsBlaFlag            ( false )
+, m_colRefIdx                     ( 0 )
+, m_maxNumMergeCand               ( 0 )
+, m_uiTLayer                      ( 0 )
+, m_bTLayerSwitchingFlag          ( false )
+, m_sliceMode                     ( NO_SLICES )
+, m_sliceArgument                 ( 0 )
+, m_sliceCurStartCtuTsAddr        ( 0 )
+, m_sliceCurEndCtuTsAddr          ( 0 )
+, m_sliceIdx                      ( 0 )
+, m_sliceSegmentMode              ( NO_SLICES )
+, m_sliceSegmentArgument          ( 0 )
+, m_sliceSegmentCurStartCtuTsAddr ( 0 )
+, m_sliceSegmentCurEndCtuTsAddr   ( 0 )
+, m_nextSlice                     ( false )
+, m_nextSliceSegment              ( false )
+, m_sliceBits                     ( 0 )
+, m_sliceSegmentBits              ( 0 )
+, m_bFinalized                    ( false )
+, m_substreamSizes                ( )
+, m_scalingList                   ( NULL )
+, m_cabacInitFlag                 ( false )
+, m_bLMvdL1Zero                   ( false )
+, m_temporalLayerNonReferenceFlag ( false )
+, m_LFCrossSliceBoundaryFlag      ( false )
+, m_enableTMVPFlag                ( true )
+#if SVC_EXTENSION
+#if R0226_SLICE_TMVP
+, m_availableForTMVPRefFlag       ( true )
+#endif
+, m_layerId                     ( 0 )
+#if REF_IDX_MFM
+, m_bMFMEnabledFlag               ( false )
+#endif
+#if POC_RESET_FLAG
+, m_bPocResetFlag                 ( false )
+#endif
+, m_bDiscardableFlag              ( false )
+#if O0149_CROSS_LAYER_BLA_FLAG
+, m_bCrossLayerBLAFlag            ( false )
+#endif
+#if POC_RESET_IDC_SIGNALLING
+, m_pocResetIdc                   ( 0 )
+, m_pocResetPeriodId              ( 0 )
+, m_fullPocResetFlag              ( false )
+, m_pocLsbVal                     ( 0 )
+, m_pocMsbVal                     ( 0 )
+, m_pocMsbValRequiredFlag         ( false )
+, m_pocMsbValPresentFlag          ( false )
+#if P0297_VPS_POC_LSB_ALIGNED_FLAG
+, m_pocMsbValNeeded               ( false )
+#endif
+#endif
+#if POC_RESET_IDC_DECODER || POC_RESET_IDC_ENCODER
+, m_picOrderCntLsb (0)
+#endif
+#endif //SVC_EXTENSION
+{
+  for(UInt i=0; i<NUM_REF_PIC_LIST_01; i++)
+  {
+    m_aiNumRefIdx[i] = 0;
+  }
+
+#if SVC_EXTENSION
+  memset( m_pcBaseColPic, 0, sizeof( m_pcBaseColPic ) );
+  m_activeNumILRRefIdx        = 0; 
+  m_interLayerPredEnabledFlag = 0;
+  ::memset( m_interLayerPredLayerIdc, 0, sizeof(m_interLayerPredLayerIdc) );
+#if P0312_VERT_PHASE_ADJ
+  ::memset( m_vertPhasePositionFlag, 0, sizeof(m_vertPhasePositionFlag) );
+#endif
+#endif //SVC_EXTENSION
+
+  for (UInt component = 0; component < MAX_NUM_COMPONENT; component++)
+  {
+    m_lambdas            [component] = 0.0;
+    m_iSliceChromaQpDelta[component] = 0;
+  }
+
+  initEqualRef();
+
+  for ( Int idx = 0; idx < MAX_NUM_REF; idx++ )
+  {
+    m_list1IdxToList0Idx[idx] = -1;
+  }
+
+  for(Int iNumCount = 0; iNumCount < MAX_NUM_REF; iNumCount++)
+  {
+    for(UInt i=0; i<NUM_REF_PIC_LIST_01; i++)
+    {
+      m_apcRefPicList [i][iNumCount] = NULL;
+      m_aiRefPOCList  [i][iNumCount] = 0;
+    }
+  }
+
+  resetWpScaling();
+  initWpAcDcParam();
+
+  for(Int ch=0; ch < MAX_NUM_CHANNEL_TYPE; ch++)
+  {
+    m_saoEnabledFlag[ch] = false;
+  }
+}
+
+TComSlice::~TComSlice()
+{
+}
+
+
+#if SVC_EXTENSION
+Void TComSlice::initSlice( UInt layerId )
+#else
+Void TComSlice::initSlice()
+#endif
+{
+#if SVC_EXTENSION
+  m_layerId = layerId;
+  m_activeNumILRRefIdx        = 0;
+  m_interLayerPredEnabledFlag = 0;
+#endif
+
+  for(UInt i=0; i<NUM_REF_PIC_LIST_01; i++)
+  {
+    m_aiNumRefIdx[i]      = 0;
+  }
+  m_colFromL0Flag = 1;
+
+  m_colRefIdx = 0;
+  initEqualRef();
+
+  m_bCheckLDC = false;
+
+  for (UInt component = 0; component < MAX_NUM_COMPONENT; component++) m_iSliceChromaQpDelta[component] = 0;
+
+  m_maxNumMergeCand = MRG_MAX_NUM_CANDS;
+
+  m_bFinalized=false;
+
+  m_substreamSizes.clear();
+  m_cabacInitFlag        = false;
+  m_enableTMVPFlag = true;
+#if POC_RESET_IDC_SIGNALLING
+  m_pocResetIdc                   = 0;
+  m_pocResetPeriodId              = 0;
+  m_fullPocResetFlag              = false;
+  m_pocLsbVal                     = 0;
+  m_pocMsbVal                     = 0;
+  m_pocMsbValRequiredFlag         = false;
+  m_pocMsbValPresentFlag          = false;
+#endif
+#if POC_RESET_IDC_DECODER || POC_RESET_IDC_ENCODER
+  m_picOrderCntLsb = 0;
+#endif
+#if P0297_VPS_POC_LSB_ALIGNED_FLAG
+  m_pocMsbValNeeded  = false;
+  m_pocResetDeltaPoc = 0;
+#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;
+}
+
+
+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 POC_RESET_IDC_ENCODER
+    if( (pcPic->getPOC() == poc) && (pcPic->getSlice(0)->isReferenced()) )
+#else
+    if(pcPic->getPOC() == poc)
+#endif
+    {
+      break;
+    }
+    iterPic++;
+#if SVC_EXTENSION
+    // return NULL, if picture with requested POC is not in the list, otherwise iterator goes outside of the list
+    if( iterPic == rcListPic.end() )
+    {
+      return NULL;
+    }
+#endif
+    pcPic = *(iterPic);
+  }
+#if POC_RESET_FLAG || POC_RESET_IDC_DECODER
+  assert( pcPic->getSlice(0)->isReferenced() );
+#endif
+  return  pcPic;
+}
+
+
+TComPic* TComSlice::xGetLongTermRefPic(TComList<TComPic*>& rcListPic, Int poc, Bool pocHasMsb)
+{
+  TComList<TComPic*>::iterator  iterPic = rcListPic.begin();
+  TComPic*                      pcPic = *(iterPic);
+  TComPic*                      pcStPic = pcPic;
+
+  Int pocCycle = 1 << getSPS()->getBitsForPOC();
+  if (!pocHasMsb)
+  {
+    poc = poc & (pocCycle - 1);
+  }
+
+  while ( iterPic != rcListPic.end() )
+  {
+    pcPic = *(iterPic);
+    if (pcPic && pcPic->getPOC()!=this->getPOC() && pcPic->getSlice( 0 )->isReferenced())
+    {
+      Int picPoc = pcPic->getPOC();
+      if (!pocHasMsb)
+      {
+        picPoc = picPoc & (pocCycle - 1);
+      }
+      
+#if POC_RESET_RPS
+      if( ((!pocHasMsb) && ((poc & (pocCycle-1)) == picPoc)) || ( pocHasMsb && (poc == picPoc)) )
+#else
+      if (poc == picPoc)
+#endif      
+      {
+        if(pcPic->getIsLongTerm())
+        {
+          return pcPic;
+        }
+        else
+        {
+          pcStPic = pcPic;
+        }
+        break;
+      }
+    }
+
+    iterPic++;
+  }
+
+  return  pcStPic;
+}
+
+Void TComSlice::setRefPOCList       ()
+{
+  for (Int iDir = 0; iDir < NUM_REF_PIC_LIST_01; iDir++)
+  {
+    for (Int iNumRefIdx = 0; iNumRefIdx < m_aiNumRefIdx[iDir]; iNumRefIdx++)
+    {
+      m_aiRefPOCList[iDir][iNumRefIdx] = m_apcRefPicList[iDir][iNumRefIdx]->getPOC();
+    }
+  }
+
+}
+
+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 SVC_EXTENSION
+Void TComSlice::setRefPicList( TComList<TComPic*>& rcListPic, Bool checkNumPocTotalCurr, TComPic** ilpPic)
+#else
+Void TComSlice::setRefPicList( TComList<TComPic*>& rcListPic, Bool checkNumPocTotalCurr )
+#endif
+{
+  if (!checkNumPocTotalCurr)
+  {
+    if (m_eSliceType == I_SLICE)
+    {
+      ::memset( m_apcRefPicList, 0, sizeof (m_apcRefPicList));
+      ::memset( m_aiNumRefIdx,   0, sizeof ( m_aiNumRefIdx ));
+
+      return;
+    }
+
+    m_aiNumRefIdx[REF_PIC_LIST_0] = getNumRefIdx(REF_PIC_LIST_0);
+    m_aiNumRefIdx[REF_PIC_LIST_1] = getNumRefIdx(REF_PIC_LIST_1);
+  }
+
+  TComPic*  pcRefPic= NULL;
+  static const UInt MAX_NUM_NEGATIVE_PICTURES=16;
+  TComPic*  RefPicSetStCurr0[MAX_NUM_NEGATIVE_PICTURES];
+  TComPic*  RefPicSetStCurr1[MAX_NUM_NEGATIVE_PICTURES];
+  TComPic*  RefPicSetLtCurr[MAX_NUM_NEGATIVE_PICTURES];
+  UInt NumPocStCurr0 = 0;
+  UInt NumPocStCurr1 = 0;
+  UInt NumPocLtCurr = 0;
+  Int i;
+
+#if SVC_EXTENSION
+  if( m_layerId == 0 || ( m_layerId > 0 && ( m_activeNumILRRefIdx == 0 || !((getNalUnitType() >= NAL_UNIT_CODED_SLICE_BLA_W_LP) && (getNalUnitType() <= NAL_UNIT_CODED_SLICE_CRA)) ) ) )
+  {
+#endif
+  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));
+  }
+#if SVC_EXTENSION
+  }
+#endif
+
+  // ref_pic_list_init
+  TComPic*  rpsCurrList0[MAX_NUM_REF+1];
+  TComPic*  rpsCurrList1[MAX_NUM_REF+1];
+#if SVC_EXTENSION
+  Int numInterLayerRPSPics = 0;
+#if M0040_ADAPTIVE_RESOLUTION_CHANGE
+  if( m_layerId > 0 && m_activeNumILRRefIdx > 0 )
+#else
+  if( m_layerId > 0 )
+#endif
+  {
+    for( i=0; i < m_pcVPS->getNumDirectRefLayers( m_layerId ); i++ )
+    {
+      Int maxTidIlRefPicsPlus1 = getVPS()->getMaxTidIlRefPicsPlus1(ilpPic[i]->getSlice(0)->getLayerIdx(), getLayerIdx());
+
+      if( ((Int)(ilpPic[i]->getSlice(0)->getTLayer())<= maxTidIlRefPicsPlus1-1) || (maxTidIlRefPicsPlus1==0 && ilpPic[i]->getSlice(0)->getRapPicFlag() ) )
+      {
+        numInterLayerRPSPics++;
+#if DISCARDABLE_PIC_RPS
+        assert( ilpPic[i]->getSlice(0)->getDiscardableFlag() == 0 );    // Inter-layer RPS shall not contain picture with discardable_flag = 1.
+#endif
+      }
+    }
+    if (numInterLayerRPSPics < m_activeNumILRRefIdx)
+    {
+      m_activeNumILRRefIdx = numInterLayerRPSPics;
+    }
+#if MAX_ONE_RESAMPLING_DIRECT_LAYERS
+    if( m_pcVPS->getScalabilityMask( SCALABILITY_ID ) )
+    {
+      Int numResampler = 0;
+#if MOTION_RESAMPLING_CONSTRAINT
+      Int numMotionResamplers = 0;
+      Int refResamplingLayer[MAX_LAYERS];
+      memset( refResamplingLayer, 0, sizeof( refResamplingLayer ) );
+#endif
+#if !RESAMPLING_CONSTRAINT_BUG_FIX
+      const Window &scalEL = getSPS()->getScaledRefLayerWindow(m_interLayerPredLayerIdc[i]);
+      Int scalingOffset = ((scalEL.getWindowLeftOffset()   == 0 ) && 
+                           (scalEL.getWindowRightOffset()  == 0 ) && 
+                           (scalEL.getWindowTopOffset()    == 0 ) && 
+                           (scalEL.getWindowBottomOffset() == 0 ) 
+                          );
+#endif
+
+      for( i=0; i < m_activeNumILRRefIdx; i++ )
+      {
+        UInt refLayerIdc = m_interLayerPredLayerIdc[i];
+        UInt refLayerId = m_pcVPS->getRefLayerId( m_layerId, refLayerIdc );
+#if RESAMPLING_CONSTRAINT_BUG_FIX
+#if MOVE_SCALED_OFFSET_TO_PPS
+#if O0098_SCALED_REF_LAYER_ID
+        const Window &scalEL = getPPS()->getScaledRefLayerWindowForLayer(refLayerId);
+#else
+        const Window &scalEL = getPPS()->getScaledRefLayerWindow(m_interLayerPredLayerIdc[i]);
+#endif
+#else
+#if O0098_SCALED_REF_LAYER_ID
+        const Window &scalEL = getSPS()->getScaledRefLayerWindowForLayer(refLayerId);
+#else
+        const Window &scalEL = getSPS()->getScaledRefLayerWindow(m_interLayerPredLayerIdc[i]);
+#endif
+#endif
+        Int scalingOffset = ((scalEL.getWindowLeftOffset()   == 0 ) && 
+                             (scalEL.getWindowRightOffset()  == 0 ) && 
+                             (scalEL.getWindowTopOffset()    == 0 ) && 
+                             (scalEL.getWindowBottomOffset() == 0 ) 
+                            );
+#endif
+#if O0194_DIFFERENT_BITDEPTH_EL_BL
+        Bool sameBitDepths = ( g_bitDepthLayer[CHANNEL_TYPE_LUMA][m_layerId] == g_bitDepthLayer[CHANNEL_TYPE_LUMA][refLayerId] ) && ( g_bitDepthLayer[CHANNEL_TYPE_CHROMA][m_layerId] == g_bitDepthLayer[CHANNEL_TYPE_CHROMA][refLayerId] );
+
+        if( !( g_posScalingFactor[refLayerIdc][0] == 65536 && g_posScalingFactor[refLayerIdc][1] == 65536 ) || !scalingOffset || !sameBitDepths 
+#if Q0048_CGS_3D_ASYMLUT
+          || getPPS()->getCGSFlag()
+#endif
+          ) // ratio 1x
+#else
+        if(!( g_posScalingFactor[refLayerIdc][0] == 65536 && g_posScalingFactor[refLayerIdc][1] == 65536 ) || (!scalingOffset)) // ratio 1x
+#endif
+        {
+#if MOTION_RESAMPLING_CONSTRAINT
+          UInt predType = m_pcVPS->getDirectDependencyType( m_layerId, refLayerId ) + 1;
+
+          if( predType & 0x1 )
+          {
+            numResampler++;
+            refResamplingLayer[i] = refLayerIdc + 1;
+          }
+
+          if( predType & 0x2 )
+          {
+            numMotionResamplers++;
+            refResamplingLayer[i] -= refLayerIdc + 1;
+          }
+#else
+          numResampler++;
+#endif
+        }
+      }
+      
+      // When both picture sample values and picture motion field resampling processes are invoked for decoding of a particular picture, they shall be applied to the same reference layer picture.
+      if( m_activeNumILRRefIdx > 1 && numResampler > 0 )
+      {
+        for( i=0; i < m_activeNumILRRefIdx; i++ )
+        {
+          assert( refResamplingLayer[i] >= 0 && "Motion and sample inter-layer prediction shall be from the same layer" );
+        }
+      }
+
+      // Bitstream constraint for SHVC: The picture resampling process as specified in subclause G.8.1.4.1 shall not be invoked more than once for decoding of each particular picture.
+      assert(numResampler <= 1);
+#if MOTION_RESAMPLING_CONSTRAINT
+      assert( numMotionResamplers <= 1  && "Up to 1 motion resampling is allowed" );
+#endif
+    }
+#endif
+  }
+  Int numPocTotalCurr = NumPocStCurr0 + NumPocStCurr1 + NumPocLtCurr + m_activeNumILRRefIdx;
+#else //SVC_EXTENSION
+  Int numPocTotalCurr = NumPocStCurr0 + NumPocStCurr1 + NumPocLtCurr;
+#endif //SVC_EXTENSION
+
+  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 SVC_EXTENSION    // inter-layer prediction is allowed for BLA, CRA pictures of nuh_layer_id>0
+    // - If the current picture is a BLA or CRA picture with nuh_layer_id equal to 0, 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() && getLayerId()==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);
+  }
+
+  Int cIdx = 0;
+  for ( i=0; i<NumPocStCurr0; i++, cIdx++)
+  {
+    rpsCurrList0[cIdx] = RefPicSetStCurr0[i];
+  }
+
+#if SVC_EXTENSION
+#if RPL_INIT_N0316_N0082
+    if( m_layerId > 0 )
+    {      
+      for( i = 0; i < m_activeNumILRRefIdx && cIdx < numPocTotalCurr; cIdx ++, i ++)      
+      {
+        Int refLayerIdc = m_interLayerPredLayerIdc[i];
+        Int maxTidIlRefPicsPlus1 = getVPS()->getMaxTidIlRefPicsPlus1(ilpPic[refLayerIdc]->getSlice(0)->getLayerIdx(), getLayerIdx());
+        if( ((Int)(ilpPic[refLayerIdc]->getSlice(0)->getTLayer())<=maxTidIlRefPicsPlus1-1) || (maxTidIlRefPicsPlus1==0 && ilpPic[refLayerIdc]->getSlice(0)->getRapPicFlag()) )
+        {
+          rpsCurrList0[cIdx] = ilpPic[refLayerIdc];
+        }
+      }
+    }
+#endif
+#endif //SVC_EXTENSION
+    for ( i=0; i<NumPocStCurr1; i++, cIdx++)
+    {
+      rpsCurrList0[cIdx] = RefPicSetStCurr1[i];
+    }
+    for ( i=0; i<NumPocLtCurr;  i++, cIdx++)
+    {
+      rpsCurrList0[cIdx] = RefPicSetLtCurr[i];
+    } 
+#if !RPL_INIT_N0316_N0082
+#if SVC_EXTENSION
+    if( m_layerId > 0 )
+    {
+      for( i = 0; i < m_activeNumILRRefIdx && cIdx < numPocTotalCurr; cIdx ++, i ++)      
+      {
+        Int refLayerIdc = m_interLayerPredLayerIdc[i];
+        Int maxTidIlRefPicsPlus1 = getVPS()->getMaxTidIlRefPicsPlus1(ilpPic[refLayerIdc]->getSlice(0)->getLayerIdx(), getLayerIdx());
+        if( ((Int)(ilpPic[refLayerIdc]->getSlice(0)->getTLayer())<=maxTidIlRefPicsPlus1-1) || (maxTidIlRefPicsPlus1==0 && ilpPic[refLayerIdc]->getSlice(0)->getRapPicFlag()) )
+        {
+          rpsCurrList0[cIdx] = ilpPic[refLayerIdc];
+        }
+      }
+    }
+#endif
+#endif
+  assert(cIdx == numPocTotalCurr);
+
+  if (m_eSliceType==B_SLICE)
+  {
+    cIdx = 0;
+    for ( i=0; i<NumPocStCurr1; i++, cIdx++)
+    {
+      rpsCurrList1[cIdx] = RefPicSetStCurr1[i];
+    }
+    for ( i=0; i<NumPocStCurr0; i++, cIdx++)
+    {
+      rpsCurrList1[cIdx] = RefPicSetStCurr0[i];
+    }
+    for ( i=0; i<NumPocLtCurr;  i++, cIdx++)
+    {
+      rpsCurrList1[cIdx] = RefPicSetLtCurr[i];
+    }    
+
+#if SVC_EXTENSION
+    if( m_layerId > 0 )
+    {
+      for( i = 0; i < m_activeNumILRRefIdx && cIdx < numPocTotalCurr; cIdx ++, i ++)
+      {
+        Int refLayerIdc = m_interLayerPredLayerIdc[i];
+        Int maxTidIlRefPicsPlus1 = getVPS()->getMaxTidIlRefPicsPlus1( ilpPic[refLayerIdc]->getSlice(0)->getLayerIdx(), getLayerIdx() );
+        if( ((Int)(ilpPic[refLayerIdc]->getSlice(0)->getTLayer())<=maxTidIlRefPicsPlus1-1) || (maxTidIlRefPicsPlus1==0 && ilpPic[refLayerIdc]->getSlice(0)->getRapPicFlag()) )
+        {
+          rpsCurrList1[cIdx] = ilpPic[refLayerIdc];
+        }
+      }
+    }
+#endif //SVC_EXTENSION
+
+    assert(cIdx == numPocTotalCurr);
+  }
+
+  ::memset(m_bIsUsedAsLongTerm, 0, sizeof(m_bIsUsedAsLongTerm));
+
+  for (Int rIdx = 0; rIdx < m_aiNumRefIdx[REF_PIC_LIST_0]; rIdx ++)
+  {
+    cIdx = m_RefPicListModification.getRefPicListModificationFlagL0() ? m_RefPicListModification.getRefPicSetIdxL0(rIdx) : rIdx % numPocTotalCurr;
+    assert(cIdx >= 0 && cIdx < numPocTotalCurr);
+    m_apcRefPicList[REF_PIC_LIST_0][rIdx] = rpsCurrList0[ cIdx ];
+#if RPL_INIT_N0316_N0082
+    m_bIsUsedAsLongTerm[0][rIdx] = ( cIdx >= NumPocStCurr0 && cIdx < NumPocStCurr0 + m_activeNumILRRefIdx ) || ( cIdx >= NumPocStCurr0 + NumPocStCurr1 + m_activeNumILRRefIdx );
+#else
+    m_bIsUsedAsLongTerm[REF_PIC_LIST_0][rIdx] = ( cIdx >= NumPocStCurr0 + NumPocStCurr1 );
+#endif
+  }
+  if ( m_eSliceType != B_SLICE )
+  {
+    m_aiNumRefIdx[REF_PIC_LIST_1] = 0;
+    ::memset( m_apcRefPicList[REF_PIC_LIST_1], 0, sizeof(m_apcRefPicList[REF_PIC_LIST_1]));
+  }
+  else
+  {
+    for (Int rIdx = 0; rIdx < m_aiNumRefIdx[REF_PIC_LIST_1]; rIdx ++)
+    {
+      cIdx = m_RefPicListModification.getRefPicListModificationFlagL1() ? m_RefPicListModification.getRefPicSetIdxL1(rIdx) : rIdx % numPocTotalCurr;
+      assert(cIdx >= 0 && cIdx < numPocTotalCurr);
+      m_apcRefPicList[REF_PIC_LIST_1][rIdx] = rpsCurrList1[ cIdx ];
+      m_bIsUsedAsLongTerm[REF_PIC_LIST_1][rIdx] = ( cIdx >= NumPocStCurr0 + NumPocStCurr1 );
+    }
+  }
+}
+
+Int TComSlice::getNumRpsCurrTempList()
+{
+  Int numRpsCurrTempList = 0;
+
+#if SVC_EXTENSION
+  if( m_eSliceType == I_SLICE || ( m_layerId && 
+    (m_eNalUnitType >= NAL_UNIT_CODED_SLICE_BLA_W_LP) &&
+    (m_eNalUnitType <= NAL_UNIT_CODED_SLICE_CRA) ) )
+#else
+  if (m_eSliceType == I_SLICE)
+#endif 
+  {
+#if SVC_EXTENSION
+    return m_activeNumILRRefIdx;
+#else
+    return 0;
+#endif
+  }
+  for(UInt i=0; i < m_pcRPS->getNumberOfNegativePictures()+ m_pcRPS->getNumberOfPositivePictures() + m_pcRPS->getNumberOfLongtermPictures(); i++)
+  {
+    if(m_pcRPS->getUsed(i))
+    {
+      numRpsCurrTempList++;
+    }
+  }
+#if SVC_EXTENSION
+  if( m_layerId > 0 )
+  {
+    numRpsCurrTempList += m_activeNumILRRefIdx;
+  }
+#endif
+
+  return numRpsCurrTempList;
+}
+
+Void TComSlice::initEqualRef()
+{
+  for (Int iDir = 0; iDir < NUM_REF_PIC_LIST_01; 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);
+      }
+    }
+  }
+}
+
+Void TComSlice::checkColRefIdx(UInt curSliceIdx, TComPic* pic)
+{
+  Int i;
+  TComSlice* curSlice = pic->getSlice(curSliceIdx);
+  Int currColRefPOC =  curSlice->getRefPOC( RefPicList(1 - curSlice->getColFromL0Flag()), curSlice->getColRefIdx());
+  TComSlice* preSlice;
+  Int preColRefPOC;
+  for(i=curSliceIdx-1; i>=0; i--)
+  {
+    preSlice = pic->getSlice(i);
+    if(preSlice->getSliceType() != I_SLICE)
+    {
+      preColRefPOC  = preSlice->getRefPOC( RefPicList(1 - preSlice->getColFromL0Flag()), preSlice->getColRefIdx());
+      if(currColRefPOC != preColRefPOC)
+      {
+        printf("Collocated_ref_idx shall always be the same for all slices of a coded picture!\n");
+        exit(EXIT_FAILURE);
+      }
+      else
+      {
+        break;
+      }
+    }
+  }
+}
+
+Void TComSlice::checkCRA(TComReferencePictureSet *pReferencePictureSet, Int& pocCRA, NalUnitType& associatedIRAPType, TComList<TComPic *>& rcListPic)
+{
+  for(Int i = 0; i < pReferencePictureSet->getNumberOfNegativePictures()+pReferencePictureSet->getNumberOfPositivePictures(); i++)
+  {
+    if(pocCRA < MAX_UINT && getPOC() > pocCRA)
+    {
+      assert(getPOC()+pReferencePictureSet->getDeltaPOC(i) >= pocCRA);
+    }
+  }
+  for(Int i = pReferencePictureSet->getNumberOfNegativePictures()+pReferencePictureSet->getNumberOfPositivePictures(); i < pReferencePictureSet->getNumberOfPictures(); i++)
+  {
+    if(pocCRA < MAX_UINT && getPOC() > pocCRA)
+    {
+      if (!pReferencePictureSet->getCheckLTMSBPresent(i))
+      {
+        assert(xGetLongTermRefPic(rcListPic, pReferencePictureSet->getPOC(i), false)->getPOC() >= pocCRA);
+      }
+      else
+      {
+        assert(pReferencePictureSet->getPOC(i) >= pocCRA);
+      }
+    }
+  }
+  if ( getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_W_RADL || getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_N_LP ) // IDR picture found
+  {
+    pocCRA = getPOC();
+    associatedIRAPType = getNalUnitType();
+  }
+  else if ( getNalUnitType() == NAL_UNIT_CODED_SLICE_CRA ) // CRA picture found
+  {
+    pocCRA = getPOC();
+    associatedIRAPType = getNalUnitType();
+  }
+  else if ( getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_LP
+         || getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_RADL
+         || getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_N_LP ) // BLA picture found
+  {
+    pocCRA = getPOC();
+    associatedIRAPType = getNalUnitType();
+  }
+}
+
+/** Function for marking the reference pictures when an IDR/CRA/CRANT/BLA/BLANT is encountered.
+ * \param pocCRA POC of the CRA/CRANT/BLA/BLANT picture
+ * \param bRefreshPending flag indicating if a deferred decoding refresh is pending
+ * \param rcListPic reference to the reference picture list
+ * This function marks the reference pictures as "unused for reference" in the following conditions.
+ * If the nal_unit_type is IDR/BLA/BLANT, all pictures in the reference picture list
+ * are marked as "unused for reference"
+ *    If the nal_unit_type is BLA/BLANT, set the pocCRA to the temporal reference of the current picture.
+ * Otherwise
+ *    If the bRefreshPending flag is true (a deferred decoding refresh is pending) and the current
+ *    temporal reference is greater than the temporal reference of the latest CRA/CRANT/BLA/BLANT picture (pocCRA),
+ *    mark all reference pictures except the latest CRA/CRANT/BLA/BLANT picture as "unused for reference" and set
+ *    the bRefreshPending flag to false.
+ *    If the nal_unit_type is CRA/CRANT, set the bRefreshPending flag to true and pocCRA to the temporal
+ *    reference of the current picture.
+ * Note that the current picture is already placed in the reference list and its marking is not changed.
+ * If the current picture has a nal_ref_idc that is not 0, it will remain marked as "used for reference".
+ */
+#if NO_CLRAS_OUTPUT_FLAG
+#if R0235_SMALLEST_LAYER_ID
+Void TComSlice::decodingRefreshMarking( TComList<TComPic*>& rcListPic, Bool noClrasOutputFlag, UInt smallestLayerId )
+#else
+Void TComSlice::decodingRefreshMarking( TComList<TComPic*>& rcListPic, Bool noClrasOutputFlag )
+#endif
+{
+  if( !isIRAP() )
+  {
+    return;
+  }
+
+  Int pocCurr = getPOC();
+  TComPic* rpcPic = NULL;
+
+  // When the current picture is an IRAP picture with nuh_layer_id equal to 0 and NoClrasOutputFlag is equal to 1, 
+  // all reference pictures with any value of nuh_layer_id currently in the DPB (if any) are marked as "unused for reference".
+#if R0235_SMALLEST_LAYER_ID
+  if (m_layerId == smallestLayerId && noClrasOutputFlag)
+#else
+  if( m_layerId == 0 && noClrasOutputFlag )
+#endif
+  {
+    // mark all pictures for all layers as not used for reference
+    TComList<TComPic*>::iterator iterPic = rcListPic.begin();
+    while( iterPic != rcListPic.end() )
+    {
+      rpcPic = *(iterPic);
+      if( rpcPic->getPOC() != pocCurr )
+      {
+        rpcPic->getSlice(0)->setReferenced(false);
+      }
+      iterPic++;
+    }
+  }
+
+  // When the current picture is an IRAP picture with NoRaslOutputFlag equal to 1, 
+  // all reference pictures with nuh_layer_id equal to currPicLayerId currently in the DPB (if any) are marked as "unused for reference".
+  if( m_noRaslOutputFlag )
+  {
+    // mark all pictures of a current layer as not used for reference
+    TComList<TComPic*>::iterator iterPic = rcListPic.begin();
+    while( iterPic != rcListPic.end() )
+    {
+      rpcPic = *(iterPic);
+      if( rpcPic->getPOC() != pocCurr && rpcPic->getLayerId() == m_layerId )
+      {
+        rpcPic->getSlice(0)->setReferenced(false);
+      }
+      iterPic++;
+    }
+  }
+}
+
+Void TComSlice::decodingRefreshMarking(Int& pocCRA, Bool& bRefreshPending, TComList<TComPic*>& rcListPic, Bool noClrasOutputFlag)
+#else
+Void TComSlice::decodingRefreshMarking(Int& pocCRA, Bool& bRefreshPending, TComList<TComPic*>& rcListPic)
+#endif
+{
+  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 NO_CLRAS_OUTPUT_FLAG
+#if POC_RESET_IDC_ENCODER
+      if (noClrasOutputFlag)
+      {
+        rpcPic->getSlice(0)->setReferenced(false);  // all layers // TODO. This does not mark all layers
+      }
+      else
+      {
+        if (rpcPic->getLayerId() == m_layerId) rpcPic->getSlice(0)->setReferenced(false);  // only current layer
+      }
+#else
+      if (noClrasOutputFlag)
+      {
+        if (rpcPic->getPOC() != pocCurr) rpcPic->getSlice(0)->setReferenced(false);  // all layers
+      }
+      else
+      {
+        if (rpcPic->getPOC() != pocCurr && rpcPic->getLayerId() == m_layerId) rpcPic->getSlice(0)->setReferenced(false);  // only current layer
+      }
+#endif
+#else
+      if (rpcPic->getPOC() != pocCurr) rpcPic->getSlice(0)->setReferenced(false);
+#endif
+      iterPic++;
+    }
+#if POC_RESET_IDC_ENCODER
+    this->getPic()->getSlice(0)->setReferenced(true);   // Mark the current picture back as refererced.
+#endif
+    if ( getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_LP
+      || getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_RADL
+      || getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_N_LP )
+    {
+      pocCRA = pocCurr;
+    }
+#if EFFICIENT_FIELD_IRAP
+    bRefreshPending = true;
+#endif
+  }
+  else // CRA or No DR
+  {
+#if EFFICIENT_FIELD_IRAP
+    if(getAssociatedIRAPType() == NAL_UNIT_CODED_SLICE_IDR_N_LP || getAssociatedIRAPType() == NAL_UNIT_CODED_SLICE_IDR_W_RADL)
+    {
+      if (bRefreshPending==true && pocCurr > m_iLastIDR) // IDR reference marking pending 
+      {
+        TComList<TComPic*>::iterator        iterPic       = rcListPic.begin();
+        while (iterPic != rcListPic.end())
+        {
+          rpcPic = *(iterPic);
+          if (rpcPic->getPOC() != pocCurr && rpcPic->getPOC() != m_iLastIDR)
+          {
+            rpcPic->getSlice(0)->setReferenced(false);
+          }
+          iterPic++;
+        }
+        bRefreshPending = false; 
+      }
+    }
+    else
+    {
+#endif
+      if (bRefreshPending==true && pocCurr > pocCRA) // CRA reference marking pending
+      {
+        TComList<TComPic*>::iterator iterPic = rcListPic.begin();
+        while (iterPic != rcListPic.end())
+        {
+          rpcPic = *(iterPic);
+          if (rpcPic->getPOC() != pocCurr && rpcPic->getPOC() != pocCRA)
+          {
+            rpcPic->getSlice(0)->setReferenced(false);
+          }
+          iterPic++;
+        }
+        bRefreshPending = false;
+      }
+#if EFFICIENT_FIELD_IRAP
+    }
+#endif
+    if ( getNalUnitType() == NAL_UNIT_CODED_SLICE_CRA ) // CRA picture found
+    {
+      bRefreshPending = true;
+      pocCRA = pocCurr;
+    }
+  }
+}
+
+Void TComSlice::copySliceInfo(TComSlice *pSrc)
+{
+  assert( pSrc != NULL );
+
+  Int i, j, k;
+
+  m_iPOC                 = pSrc->m_iPOC;
+  m_eNalUnitType         = pSrc->m_eNalUnitType;
+  m_eSliceType           = pSrc->m_eSliceType;
+  m_iSliceQp             = pSrc->m_iSliceQp;
+#if ADAPTIVE_QP_SELECTION
+  m_iSliceQpBase         = pSrc->m_iSliceQpBase;
+#endif
+  m_ChromaQpAdjEnabled = pSrc->m_ChromaQpAdjEnabled;
+  m_deblockingFilterDisable   = pSrc->m_deblockingFilterDisable;
+  m_deblockingFilterOverrideFlag = pSrc->m_deblockingFilterOverrideFlag;
+  m_deblockingFilterBetaOffsetDiv2 = pSrc->m_deblockingFilterBetaOffsetDiv2;
+  m_deblockingFilterTcOffsetDiv2 = pSrc->m_deblockingFilterTcOffsetDiv2;
+
+  for (i = 0; i < NUM_REF_PIC_LIST_01; 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;
+  for (UInt component = 0; component < MAX_NUM_COMPONENT; component++) m_iSliceChromaQpDelta[component] = pSrc->m_iSliceChromaQpDelta[component];
+  for (i = 0; i < NUM_REF_PIC_LIST_01; 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];
+      m_bIsUsedAsLongTerm[i][j] = pSrc->m_bIsUsedAsLongTerm[i][j];
+    }
+    m_bIsUsedAsLongTerm[i][MAX_NUM_REF] = pSrc->m_bIsUsedAsLongTerm[i][MAX_NUM_REF];
+  }
+  m_iDepth               = pSrc->m_iDepth;
+
+  // referenced slice
+  m_bRefenced            = pSrc->m_bRefenced;
+
+  // access channel
+#if SVC_EXTENSION
+  m_pcVPS                = pSrc->m_pcVPS;
+  m_layerId              = pSrc->m_layerId;
+  m_activeNumILRRefIdx         = pSrc->m_activeNumILRRefIdx;
+  m_interLayerPredEnabledFlag  = pSrc->m_interLayerPredEnabledFlag;
+  memcpy( m_interLayerPredLayerIdc, pSrc->m_interLayerPredLayerIdc, sizeof( m_interLayerPredLayerIdc ) );
+#if P0312_VERT_PHASE_ADJ
+  memcpy( m_vertPhasePositionFlag, pSrc->m_vertPhasePositionFlag, sizeof( m_vertPhasePositionFlag ) );
+#endif
+#endif
+  m_pcSPS                = pSrc->m_pcSPS;
+  m_pcPPS                = pSrc->m_pcPPS;
+  m_pcRPS                = pSrc->m_pcRPS;
+  m_iLastIDR             = pSrc->m_iLastIDR;
+
+  m_pcPic                = pSrc->m_pcPic;
+
+  m_colFromL0Flag        = pSrc->m_colFromL0Flag;
+  m_colRefIdx            = pSrc->m_colRefIdx;
+
+  setLambdas(pSrc->getLambdas());
+
+  for (i = 0; i < NUM_REF_PIC_LIST_01; 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_sliceCurStartCtuTsAddr        = pSrc->m_sliceCurStartCtuTsAddr;
+  m_sliceCurEndCtuTsAddr          = pSrc->m_sliceCurEndCtuTsAddr;
+  m_sliceIdx                      = pSrc->m_sliceIdx;
+  m_sliceSegmentMode              = pSrc->m_sliceSegmentMode;
+  m_sliceSegmentArgument          = pSrc->m_sliceSegmentArgument;
+  m_sliceSegmentCurStartCtuTsAddr = pSrc->m_sliceSegmentCurStartCtuTsAddr;
+  m_sliceSegmentCurEndCtuTsAddr   = pSrc->m_sliceSegmentCurEndCtuTsAddr;
+  m_nextSlice                     = pSrc->m_nextSlice;
+  m_nextSliceSegment              = pSrc->m_nextSliceSegment;
+
+  for ( UInt e=0 ; e<NUM_REF_PIC_LIST_01 ; e++ )
+  {
+    for ( UInt n=0 ; n<MAX_NUM_REF ; n++ )
+    {
+      memcpy(m_weightPredTable[e][n], pSrc->m_weightPredTable[e][n], sizeof(WPScalingParam)*MAX_NUM_COMPONENT );
+    }
+  }
+
+  for( UInt ch = 0 ; ch < MAX_NUM_CHANNEL_TYPE; ch++)
+  {
+    m_saoEnabledFlag[ch] = pSrc->m_saoEnabledFlag[ch];
+  }
+
+  m_cabacInitFlag                = pSrc->m_cabacInitFlag;
+
+  m_bLMvdL1Zero = pSrc->m_bLMvdL1Zero;
+  m_LFCrossSliceBoundaryFlag = pSrc->m_LFCrossSliceBoundaryFlag;
+  m_enableTMVPFlag                = pSrc->m_enableTMVPFlag;
+  m_maxNumMergeCand               = pSrc->m_maxNumMergeCand;
+}
+
+
+Int TComSlice::m_prevTid0POC = 0;
+
+/** Function for setting the slice's temporal layer ID and corresponding temporal_layer_switching_point_flag.
+ * \param uiTLayer Temporal layer ID of the current slice
+ * The decoder calls this function to set temporal_layer_switching_point_flag for each temporal layer based on
+ * the SPS's temporal_id_nesting_flag and the parsed PPS.  Then, current slice's temporal layer ID and
+ * temporal_layer_switching_point_flag is set accordingly.
+ */
+Void TComSlice::setTLayerInfo( UInt uiTLayer )
+{
+  m_uiTLayer = uiTLayer;
+}
+
+/** Function for checking if this is a switching-point
+*/
+Bool TComSlice::isTemporalLayerSwitchingPoint(TComList<TComPic*>& rcListPic)
+{
+  TComPic* rpcPic;
+  // loop through all pictures in the reference picture buffer
+  TComList<TComPic*>::iterator iterPic = rcListPic.begin();
+  while ( iterPic != rcListPic.end())
+  {
+    rpcPic = *(iterPic++);
+    if(rpcPic->getSlice(0)->isReferenced() && rpcPic->getPOC() != getPOC())
+    {
+      if(rpcPic->getTLayer() >= getTLayer())
+      {
+        return false;
+      }
+    }
+  }
+  return true;
+}
+
+/** Function for checking if this is a STSA candidate
+ */
+Bool TComSlice::isStepwiseTemporalLayerSwitchingPointCandidate(TComList<TComPic*>& rcListPic)
+{
+  TComPic* rpcPic;
+
+  TComList<TComPic*>::iterator iterPic = rcListPic.begin();
+  while ( iterPic != rcListPic.end())
+  {
+    rpcPic = *(iterPic++);
+    if(rpcPic->getSlice(0)->isReferenced() &&  (rpcPic->getUsedByCurr()==true) && rpcPic->getPOC() != getPOC())
+    {
+      if(rpcPic->getTLayer() >= getTLayer())
+      {
+        return false;
+      }
+    }
+  }
+  return true;
+}
+
+#if POC_RESET_IDC_ENCODER
+Void TComSlice::checkLeadingPictureRestrictions(TComList<TComPic*>& rcListPic, Bool usePocBeforeReset)
+#else
+Void TComSlice::checkLeadingPictureRestrictions(TComList<TComPic*>& rcListPic)
+#endif
+{
+  TComPic* rpcPic;
+
+  Int nalUnitType = this->getNalUnitType();
+
+  // When a picture is a leading picture, it shall be a RADL or RASL picture.
+  if(this->getAssociatedIRAPPOC() > this->getPOC())
+  {
+    // Do not check IRAP pictures since they may get a POC lower than their associated IRAP
+    if(nalUnitType < NAL_UNIT_CODED_SLICE_BLA_W_LP ||
+       nalUnitType > NAL_UNIT_RESERVED_IRAP_VCL23)
+    {
+      assert(nalUnitType == NAL_UNIT_CODED_SLICE_RASL_N ||
+             nalUnitType == NAL_UNIT_CODED_SLICE_RASL_R ||
+             nalUnitType == NAL_UNIT_CODED_SLICE_RADL_N ||
+             nalUnitType == NAL_UNIT_CODED_SLICE_RADL_R);
+    }
+  }
+
+  // When a picture is a trailing picture, it shall not be a RADL or RASL picture.
+  if(this->getAssociatedIRAPPOC() < this->getPOC())
+  {
+    assert(nalUnitType != NAL_UNIT_CODED_SLICE_RASL_N &&
+           nalUnitType != NAL_UNIT_CODED_SLICE_RASL_R &&
+           nalUnitType != NAL_UNIT_CODED_SLICE_RADL_N &&
+           nalUnitType != NAL_UNIT_CODED_SLICE_RADL_R);
+  }
+
+  // No RASL pictures shall be present in the bitstream that are associated
+  // with a BLA picture having nal_unit_type equal to BLA_W_RADL or BLA_N_LP.
+  if(nalUnitType == NAL_UNIT_CODED_SLICE_RASL_N ||
+     nalUnitType == NAL_UNIT_CODED_SLICE_RASL_R)
+  {
+    assert(this->getAssociatedIRAPType() != NAL_UNIT_CODED_SLICE_BLA_W_RADL &&
+           this->getAssociatedIRAPType() != NAL_UNIT_CODED_SLICE_BLA_N_LP);
+  }
+
+  // No RASL pictures shall be present in the bitstream that are associated with
+  // an IDR picture.
+  if(nalUnitType == NAL_UNIT_CODED_SLICE_RASL_N ||
+     nalUnitType == NAL_UNIT_CODED_SLICE_RASL_R)
+  {
+    assert(this->getAssociatedIRAPType() != NAL_UNIT_CODED_SLICE_IDR_N_LP   &&
+           this->getAssociatedIRAPType() != NAL_UNIT_CODED_SLICE_IDR_W_RADL);
+  }
+
+  // No RADL pictures shall be present in the bitstream that are associated with
+  // a BLA picture having nal_unit_type equal to BLA_N_LP or that are associated
+  // with an IDR picture having nal_unit_type equal to IDR_N_LP.
+  if(nalUnitType == NAL_UNIT_CODED_SLICE_RADL_N ||
+     nalUnitType == NAL_UNIT_CODED_SLICE_RADL_R)
+  {
+    assert(this->getAssociatedIRAPType() != NAL_UNIT_CODED_SLICE_BLA_N_LP   &&
+           this->getAssociatedIRAPType() != NAL_UNIT_CODED_SLICE_IDR_N_LP);
+  }
+
+  // loop through all pictures in the reference picture buffer
+  TComList<TComPic*>::iterator iterPic = rcListPic.begin();
+  while ( iterPic != rcListPic.end())
+  {
+    rpcPic = *(iterPic++);
+#if BUGFIX_INTRAPERIOD
+    if(!rpcPic->getReconMark())
+    {
+      continue;
+    }
+#endif
+    if (rpcPic->getPOC() == this->getPOC())
+    {
+      continue;
+    }
+
+    // Any picture that has PicOutputFlag equal to 1 that precedes an IRAP picture
+    // in decoding order shall precede the IRAP picture in output order.
+    // (Note that any picture following in output order would be present in the DPB)
+    if(rpcPic->getSlice(0)->getPicOutputFlag() == 1 && !this->getNoOutputPriorPicsFlag())
+    {
+      if(nalUnitType == NAL_UNIT_CODED_SLICE_BLA_N_LP    ||
+         nalUnitType == NAL_UNIT_CODED_SLICE_BLA_W_LP    ||
+         nalUnitType == NAL_UNIT_CODED_SLICE_BLA_W_RADL  ||
+         nalUnitType == NAL_UNIT_CODED_SLICE_CRA         ||
+         nalUnitType == NAL_UNIT_CODED_SLICE_IDR_N_LP    ||
+         nalUnitType == NAL_UNIT_CODED_SLICE_IDR_W_RADL)
+      {
+#if POC_RESET_IDC_ENCODER
+        if( usePocBeforeReset )
+        {
+          assert(rpcPic->getSlice(0)->getPocValueBeforeReset() < this->getPocValueBeforeReset());
+        }
+        else
+        {
+          assert(rpcPic->getPOC() < this->getPOC());
+        }
+#else
+        assert(rpcPic->getPOC() < this->getPOC());
+#endif
+      }
+    }
+
+    // Any picture that has PicOutputFlag equal to 1 that precedes an IRAP picture
+    // in decoding order shall precede any RADL picture associated with the IRAP
+    // picture in output order.
+    if(rpcPic->getSlice(0)->getPicOutputFlag() == 1)
+    {
+      if((nalUnitType == NAL_UNIT_CODED_SLICE_RADL_N ||
+          nalUnitType == NAL_UNIT_CODED_SLICE_RADL_R))
+      {
+        // rpcPic precedes the IRAP in decoding order
+        if(this->getAssociatedIRAPPOC() > rpcPic->getSlice(0)->getAssociatedIRAPPOC())
+        {
+          // rpcPic must not be the IRAP picture
+          if(this->getAssociatedIRAPPOC() != rpcPic->getPOC())
+          {
+#if POC_RESET_IDC_ENCODER
+            if( usePocBeforeReset )
+            {
+              assert(rpcPic->getSlice(0)->getPocValueBeforeReset() < this->getPocValueBeforeReset());
+            }
+            else
+            {
+              assert(rpcPic->getPOC() < this->getPOC());
+            }
+#else
+            assert(rpcPic->getPOC() < this->getPOC());
+#endif
+          }
+        }
+      }
+    }
+
+    // When a picture is a leading picture, it shall precede, in decoding order,
+    // all trailing pictures that are associated with the same IRAP picture.
+      if(nalUnitType == NAL_UNIT_CODED_SLICE_RASL_N ||
+         nalUnitType == NAL_UNIT_CODED_SLICE_RASL_R ||
+         nalUnitType == NAL_UNIT_CODED_SLICE_RADL_N ||
+         nalUnitType == NAL_UNIT_CODED_SLICE_RADL_R)
+      {
+        if(rpcPic->getSlice(0)->getAssociatedIRAPPOC() == this->getAssociatedIRAPPOC())
+        {
+          // rpcPic is a picture that preceded the leading in decoding order since it exist in the DPB
+          // rpcPic would violate the constraint if it was a trailing picture
+#if POC_RESET_IDC_ENCODER
+          if( usePocBeforeReset )
+          {
+            assert(rpcPic->getPOC() <= this->getAssociatedIrapPocBeforeReset());
+          }
+          else
+          {
+            assert(rpcPic->getPOC() <= this->getAssociatedIRAPPOC());
+          }
+#else
+          assert(rpcPic->getPOC() <= this->getAssociatedIRAPPOC());
+#endif
+        }
+      }
+
+    // Any RASL picture associated with a CRA or BLA picture shall precede any
+    // RADL picture associated with the CRA or BLA picture in output order
+    if(nalUnitType == NAL_UNIT_CODED_SLICE_RASL_N ||
+       nalUnitType == NAL_UNIT_CODED_SLICE_RASL_R)
+    {
+      if((this->getAssociatedIRAPType() == NAL_UNIT_CODED_SLICE_BLA_N_LP   ||
+          this->getAssociatedIRAPType() == NAL_UNIT_CODED_SLICE_BLA_W_LP   ||
+          this->getAssociatedIRAPType() == NAL_UNIT_CODED_SLICE_BLA_W_RADL ||
+          this->getAssociatedIRAPType() == NAL_UNIT_CODED_SLICE_CRA)       &&
+          this->getAssociatedIRAPPOC() == rpcPic->getSlice(0)->getAssociatedIRAPPOC())
+      {
+        if(rpcPic->getSlice(0)->getNalUnitType() == NAL_UNIT_CODED_SLICE_RADL_N ||
+           rpcPic->getSlice(0)->getNalUnitType() == NAL_UNIT_CODED_SLICE_RADL_R)
+        {
+          assert(rpcPic->getPOC() > this->getPOC());
+        }
+      }
+    }
+
+    // Any RASL picture associated with a CRA picture shall follow, in output
+    // order, any IRAP picture that precedes the CRA picture in decoding order.
+    if(nalUnitType == NAL_UNIT_CODED_SLICE_RASL_N ||
+       nalUnitType == NAL_UNIT_CODED_SLICE_RASL_R)
+    {
+      if(this->getAssociatedIRAPType() == NAL_UNIT_CODED_SLICE_CRA)
+      {
+        if(rpcPic->getSlice(0)->getPOC() < this->getAssociatedIRAPPOC() &&
+           (rpcPic->getSlice(0)->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_N_LP   ||
+            rpcPic->getSlice(0)->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_LP   ||
+            rpcPic->getSlice(0)->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_RADL ||
+            rpcPic->getSlice(0)->getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_N_LP   ||
+            rpcPic->getSlice(0)->getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_W_RADL ||
+            rpcPic->getSlice(0)->getNalUnitType() == NAL_UNIT_CODED_SLICE_CRA))
+        {
+          assert(this->getPOC() > rpcPic->getSlice(0)->getPOC());
+        }
+      }
+    }
+  }
+}
+
+
+
+/** Function for applying picture marking based on the Reference Picture Set in pReferencePictureSet.
+*/
+Void TComSlice::applyReferencePictureSet( TComList<TComPic*>& rcListPic, TComReferencePictureSet *pReferencePictureSet)
+{
+  TComPic* rpcPic;
+  Int i, isReference;
+
+#if !ALIGNED_BUMPING
+  checkLeadingPictureRestrictions(rcListPic);
+#endif
+
+  // loop through all pictures in the reference picture buffer
+  TComList<TComPic*>::iterator iterPic = rcListPic.begin();
+  while ( iterPic != rcListPic.end())
+  {
+    rpcPic = *(iterPic++);
+
+    if(!rpcPic->getSlice( 0 )->isReferenced())
+    {
+      continue;
+    }
+
+    isReference = 0;
+    // loop through all pictures in the Reference Picture Set
+    // to see if the picture should be kept as reference picture
+    for(i=0;i<pReferencePictureSet->getNumberOfPositivePictures()+pReferencePictureSet->getNumberOfNegativePictures();i++)
+    {
+      if(!rpcPic->getIsLongTerm() && rpcPic->getPicSym()->getSlice(0)->getPOC() == this->getPOC() + pReferencePictureSet->getDeltaPOC(i))
+      {
+        isReference = 1;
+        rpcPic->setUsedByCurr(pReferencePictureSet->getUsed(i));
+        rpcPic->setIsLongTerm(0);
+      }
+    }
+    for(;i<pReferencePictureSet->getNumberOfPictures();i++)
+    {
+      if(pReferencePictureSet->getCheckLTMSBPresent(i)==true)
+      {
+        if(rpcPic->getIsLongTerm() && (rpcPic->getPicSym()->getSlice(0)->getPOC()) == pReferencePictureSet->getPOC(i))
+        {
+          isReference = 1;
+          rpcPic->setUsedByCurr(pReferencePictureSet->getUsed(i));
+        }
+      }
+      else 
+      {
+        Int pocCycle = 1<<rpcPic->getPicSym()->getSlice(0)->getSPS()->getBitsForPOC();
+        Int curPoc = rpcPic->getPicSym()->getSlice(0)->getPOC() & (pocCycle-1);
+        Int refPoc = pReferencePictureSet->getPOC(i) & (pocCycle-1);
+        if(rpcPic->getIsLongTerm() && curPoc == refPoc)
+        {
+          isReference = 1;
+          rpcPic->setUsedByCurr(pReferencePictureSet->getUsed(i));
+        }
+      }
+
+    }
+#if DISCARDABLE_PIC_RPS
+    if( isReference ) // Current picture is in the temporal RPS
+    {
+      assert( rpcPic->getSlice(0)->getDiscardableFlag() == 0 ); // Temporal RPS shall not contain picture with discardable_flag equal to 1
+    }
+#endif
+    // mark the picture as "unused for reference" if it is not in
+    // the Reference Picture Set
+    if(rpcPic->getPicSym()->getSlice(0)->getPOC() != this->getPOC() && isReference == 0)
+    {
+      rpcPic->getSlice( 0 )->setReferenced( false );
+      rpcPic->setUsedByCurr(0);
+      rpcPic->setIsLongTerm(0);
+    }
+    //check that pictures of higher temporal layers are not used
+    assert(rpcPic->getSlice( 0 )->isReferenced()==0||rpcPic->getUsedByCurr()==0||rpcPic->getTLayer()<=this->getTLayer());
+    //check that pictures of higher or equal temporal layer are not in the RPS if the current picture is a TSA picture
+    if(this->getNalUnitType() == NAL_UNIT_CODED_SLICE_TSA_R || this->getNalUnitType() == NAL_UNIT_CODED_SLICE_TSA_N)
+    {
+      assert(rpcPic->getSlice( 0 )->isReferenced()==0||rpcPic->getTLayer()<this->getTLayer());
+    }
+    //check that pictures marked as temporal layer non-reference pictures are not used for reference
+    if(rpcPic->getPicSym()->getSlice(0)->getPOC() != this->getPOC() && rpcPic->getTLayer()==this->getTLayer())
+    {
+      assert(rpcPic->getSlice( 0 )->isReferenced()==0||rpcPic->getUsedByCurr()==0||rpcPic->getSlice( 0 )->getTemporalLayerNonReferenceFlag()==false);
+    }
+  }
+}
+
+/** Function for applying picture marking based on the Reference Picture Set in pReferencePictureSet.
+*/
+#if ALLOW_RECOVERY_POINT_AS_RAP
+Int TComSlice::checkThatAllRefPicsAreAvailable( TComList<TComPic*>& rcListPic, TComReferencePictureSet *pReferencePictureSet, Bool printErrors, Int pocRandomAccess, Bool bUseRecoveryPoint)
+#else
+Int TComSlice::checkThatAllRefPicsAreAvailable( TComList<TComPic*>& rcListPic, TComReferencePictureSet *pReferencePictureSet, Bool printErrors, Int pocRandomAccess)
+#endif
+{
+#if ALLOW_RECOVERY_POINT_AS_RAP
+  Int atLeastOneUnabledByRecoveryPoint = 0;
+  Int atLeastOneFlushedByPreviousIDR = 0;
+#endif
+  TComPic* rpcPic;
+  Int i, isAvailable;
+  Int atLeastOneLost = 0;
+  Int atLeastOneRemoved = 0;
+  Int iPocLost = 0;
+
+  // loop through all long-term pictures in the Reference Picture Set
+  // to see if the picture should be kept as reference picture
+  for(i=pReferencePictureSet->getNumberOfNegativePictures()+pReferencePictureSet->getNumberOfPositivePictures();i<pReferencePictureSet->getNumberOfPictures();i++)
+  {
+    isAvailable = 0;
+    // loop through all pictures in the reference picture buffer
+    TComList<TComPic*>::iterator iterPic = rcListPic.begin();
+    while ( iterPic != rcListPic.end())
+    {
+      rpcPic = *(iterPic++);
+      if(pReferencePictureSet->getCheckLTMSBPresent(i)==true)
+      {
+        if(rpcPic->getIsLongTerm() && (rpcPic->getPicSym()->getSlice(0)->getPOC()) == pReferencePictureSet->getPOC(i) && rpcPic->getSlice(0)->isReferenced())
+        {
+#if ALLOW_RECOVERY_POINT_AS_RAP
+          if(bUseRecoveryPoint && this->getPOC() > pocRandomAccess && this->getPOC() + pReferencePictureSet->getDeltaPOC(i) < pocRandomAccess)
+          {
+            isAvailable = 0;
+          }
+          else
+          {
+            isAvailable = 1;
+          }
+#else
+          isAvailable = 1;
+#endif
+        }
+      }
+      else
+      {
+        Int pocCycle = 1<<rpcPic->getPicSym()->getSlice(0)->getSPS()->getBitsForPOC();
+        Int curPoc = rpcPic->getPicSym()->getSlice(0)->getPOC() & (pocCycle-1);
+        Int refPoc = pReferencePictureSet->getPOC(i) & (pocCycle-1);
+        if(rpcPic->getIsLongTerm() && curPoc == refPoc && rpcPic->getSlice(0)->isReferenced())
+        {
+#if ALLOW_RECOVERY_POINT_AS_RAP
+          if(bUseRecoveryPoint && this->getPOC() > pocRandomAccess && this->getPOC() + pReferencePictureSet->getDeltaPOC(i) < pocRandomAccess)
+          {
+            isAvailable = 0;
+          }
+          else
+          {
+            isAvailable = 1;
+          }
+#else
+          isAvailable = 1;
+#endif
+        }
+      }
+    }
+    // if there was no such long-term check the short terms
+    if(!isAvailable)
+    {
+      iterPic = rcListPic.begin();
+      while ( iterPic != rcListPic.end())
+      {
+        rpcPic = *(iterPic++);
+
+        Int pocCycle = 1 << rpcPic->getPicSym()->getSlice(0)->getSPS()->getBitsForPOC();
+        Int curPoc = rpcPic->getPicSym()->getSlice(0)->getPOC();
+        Int refPoc = pReferencePictureSet->getPOC(i);
+        if (!pReferencePictureSet->getCheckLTMSBPresent(i))
+        {
+          curPoc = curPoc & (pocCycle - 1);
+          refPoc = refPoc & (pocCycle - 1);
+        }
+
+        if (rpcPic->getSlice(0)->isReferenced() && curPoc == refPoc)
+        {
+#if ALLOW_RECOVERY_POINT_AS_RAP
+          if(bUseRecoveryPoint && this->getPOC() > pocRandomAccess && this->getPOC() + pReferencePictureSet->getDeltaPOC(i) < pocRandomAccess)
+          {
+            isAvailable = 0;
+          }
+          else
+          {
+            isAvailable = 1;
+            rpcPic->setIsLongTerm(1);
+            break;
+          }
+#else
+          isAvailable = 1;
+          rpcPic->setIsLongTerm(1);
+          break;
+#endif
+        }
+      }
+    }
+    // report that a picture is lost if it is in the Reference Picture Set
+    // but not available as reference picture
+    if(isAvailable == 0)
+    {
+      if (this->getPOC() + pReferencePictureSet->getDeltaPOC(i) >= pocRandomAccess)
+      {
+        if(!pReferencePictureSet->getUsed(i) )
+        {
+          if(printErrors)
+          {
+            printf("\nLong-term reference picture with POC = %3d seems to have been removed or not correctly decoded.", this->getPOC() + pReferencePictureSet->getDeltaPOC(i));
+          }
+          atLeastOneRemoved = 1;
+        }
+        else
+        {
+          if(printErrors)
+          {
+            printf("\nLong-term reference picture with POC = %3d is lost or not correctly decoded!", this->getPOC() + pReferencePictureSet->getDeltaPOC(i));
+          }
+          atLeastOneLost = 1;
+          iPocLost=this->getPOC() + pReferencePictureSet->getDeltaPOC(i);
+        }
+      }
+#if ALLOW_RECOVERY_POINT_AS_RAP
+      else if(bUseRecoveryPoint && this->getPOC() > pocRandomAccess)
+      {
+        atLeastOneUnabledByRecoveryPoint = 1;
+      }
+      else if(bUseRecoveryPoint && (this->getAssociatedIRAPType()==NAL_UNIT_CODED_SLICE_IDR_N_LP || this->getAssociatedIRAPType()==NAL_UNIT_CODED_SLICE_IDR_W_RADL))
+      {
+        atLeastOneFlushedByPreviousIDR = 1;
+      }
+#endif
+    }
+  }
+  // loop through all short-term pictures in the Reference Picture Set
+  // to see if the picture should be kept as reference picture
+  for(i=0;i<pReferencePictureSet->getNumberOfNegativePictures()+pReferencePictureSet->getNumberOfPositivePictures();i++)
+  {
+    isAvailable = 0;
+    // loop through all pictures in the reference picture buffer
+    TComList<TComPic*>::iterator iterPic = rcListPic.begin();
+    while ( iterPic != rcListPic.end())
+    {
+      rpcPic = *(iterPic++);
+
+      if(!rpcPic->getIsLongTerm() && rpcPic->getPicSym()->getSlice(0)->getPOC() == this->getPOC() + pReferencePictureSet->getDeltaPOC(i) && rpcPic->getSlice(0)->isReferenced())
+      {
+#if ALLOW_RECOVERY_POINT_AS_RAP
+        if(bUseRecoveryPoint && this->getPOC() > pocRandomAccess && this->getPOC() + pReferencePictureSet->getDeltaPOC(i) < pocRandomAccess)
+        {
+          isAvailable = 0;
+        }
+        else
+        {
+          isAvailable = 1;
+        }
+#else
+        isAvailable = 1;
+#endif
+      }
+    }
+    // report that a picture is lost if it is in the Reference Picture Set
+    // but not available as reference picture
+    if(isAvailable == 0)
+    {
+#if !UNAVAILABLE_PIC_BUGFIX
+      if (this->getPOC() + pReferencePictureSet->getDeltaPOC(i) >= pocRandomAccess)
+#endif
+      {
+        if(!pReferencePictureSet->getUsed(i) )
+        {
+          if(printErrors)
+          {
+            printf("\nShort-term reference picture with POC = %3d seems to have been removed or not correctly decoded.", this->getPOC() + pReferencePictureSet->getDeltaPOC(i));
+          }
+          atLeastOneRemoved = 1;
+        }
+        else
+        {
+          if(printErrors)
+          {
+            printf("\nShort-term reference picture with POC = %3d is lost or not correctly decoded!", this->getPOC() + pReferencePictureSet->getDeltaPOC(i));
+          }
+          atLeastOneLost = 1;
+          iPocLost=this->getPOC() + pReferencePictureSet->getDeltaPOC(i);
+        }
+      }
+#if ALLOW_RECOVERY_POINT_AS_RAP
+#if UNAVAILABLE_PIC_BUGFIX
+      if(bUseRecoveryPoint && this->getPOC() > pocRandomAccess)
+#else
+      else if(bUseRecoveryPoint && this->getPOC() > pocRandomAccess)
+#endif
+      {
+        atLeastOneUnabledByRecoveryPoint = 1;
+      }
+      else if(bUseRecoveryPoint && (this->getAssociatedIRAPType()==NAL_UNIT_CODED_SLICE_IDR_N_LP || this->getAssociatedIRAPType()==NAL_UNIT_CODED_SLICE_IDR_W_RADL))
+      {
+        atLeastOneFlushedByPreviousIDR = 1;
+      }
+#endif
+    }
+  }
+
+#if ALLOW_RECOVERY_POINT_AS_RAP
+  if(atLeastOneUnabledByRecoveryPoint || atLeastOneFlushedByPreviousIDR)
+  {
+    return -1;
+  }    
+#endif
+  if(atLeastOneLost)
+  {
+    return iPocLost+1;
+  }
+  if(atLeastOneRemoved)
+  {
+    return -2;
+  }
+  else
+  {
+    return 0;
+  }
+}
+
+/** Function for constructing an explicit Reference Picture Set out of the available pictures in a referenced Reference Picture Set
+*/
+#if ALLOW_RECOVERY_POINT_AS_RAP
+Void TComSlice::createExplicitReferencePictureSetFromReference( TComList<TComPic*>& rcListPic, TComReferencePictureSet *pReferencePictureSet, Bool isRAP, Int pocRandomAccess, Bool bUseRecoveryPoint)
+#else
+Void TComSlice::createExplicitReferencePictureSetFromReference( TComList<TComPic*>& rcListPic, TComReferencePictureSet *pReferencePictureSet, Bool isRAP)
+#endif
+{
+  TComPic* rpcPic;
+  Int i, j;
+  Int k = 0;
+  Int nrOfNegativePictures = 0;
+  Int nrOfPositivePictures = 0;
+  TComReferencePictureSet* pcRPS = this->getLocalRPS();
+#if EFFICIENT_FIELD_IRAP
+  Bool irapIsInRPS = false;
+#endif
+#if P0297_VPS_POC_LSB_ALIGNED_FLAG
+  Bool pocsAdjusted = false;
+#endif
+
+  // 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 P0297_VPS_POC_LSB_ALIGNED_FLAG
+      // poc adjustement by poc reset needs to be taken into account here
+      Int deltaPOC = pReferencePictureSet->getDeltaPOC(i) - rpcPic->getPicSym()->getSlice(0)->getPocResetDeltaPoc();
+      if (rpcPic->getPicSym()->getSlice(0)->getPocResetDeltaPoc() != 0)
+      {
+        pocsAdjusted = true;
+      }
+
+      if (rpcPic->getPicSym()->getSlice(0)->getPOC() == this->getPOC() + deltaPOC && rpcPic->getSlice(0)->isReferenced())
+#else
+      if(rpcPic->getPicSym()->getSlice(0)->getPOC() == this->getPOC() + pReferencePictureSet->getDeltaPOC(i) && rpcPic->getSlice(0)->isReferenced())
+#endif
+      {
+        // This picture exists as a reference picture
+        // and should be added to the explicit Reference Picture Set
+#if P0297_VPS_POC_LSB_ALIGNED_FLAG
+        pcRPS->setDeltaPOC(k, deltaPOC);
+#else
+        pcRPS->setDeltaPOC(k, pReferencePictureSet->getDeltaPOC(i));
+#endif
+        pcRPS->setUsed(k, pReferencePictureSet->getUsed(i) && (!isRAP));
+#if ALLOW_RECOVERY_POINT_AS_RAP
+#if P0297_VPS_POC_LSB_ALIGNED_FLAG
+        pcRPS->setUsed(k, pcRPS->getUsed(k) && !(bUseRecoveryPoint && this->getPOC() > pocRandomAccess && this->getPOC() + deltaPOC < pocRandomAccess) ); 
+#else
+        pcRPS->setUsed(k, pcRPS->getUsed(k) && !(bUseRecoveryPoint && this->getPOC() > pocRandomAccess && this->getPOC() + pReferencePictureSet->getDeltaPOC(i) < pocRandomAccess) ); 
+#endif
+#endif
+        if(pcRPS->getDeltaPOC(k) < 0)
+        {
+          nrOfNegativePictures++;
+        }
+        else
+        {
+#if EFFICIENT_FIELD_IRAP
+          if(rpcPic->getPicSym()->getSlice(0)->getPOC() == this->getAssociatedIRAPPOC() && this->getAssociatedIRAPPOC() == this->getPOC()+1)
+          {
+            irapIsInRPS = true;
+          }
+#endif
+          nrOfPositivePictures++;
+        }
+        k++;
+      }
+    }
+  }
+
+#if EFFICIENT_FIELD_IRAP
+  Bool useNewRPS = false;
+  // if current picture is complimentary field associated to IRAP, add the IRAP to its RPS. 
+  if(m_pcPic->isField() && !irapIsInRPS)
+  {
+    TComList<TComPic*>::iterator iterPic = rcListPic.begin();
+    while ( iterPic != rcListPic.end())
+    {
+      rpcPic = *(iterPic++);
+      if(rpcPic->getPicSym()->getSlice(0)->getPOC() == this->getAssociatedIRAPPOC() && this->getAssociatedIRAPPOC() == this->getPOC()+1)
+      {
+        pcRPS->setDeltaPOC(k, 1);
+        pcRPS->setUsed(k, true);
+        nrOfPositivePictures++;
+        k ++;
+        useNewRPS = true;
+      }
+    }
+  }
+#endif
+  pcRPS->setNumberOfNegativePictures(nrOfNegativePictures);
+  pcRPS->setNumberOfPositivePictures(nrOfPositivePictures);
+  pcRPS->setNumberOfPictures(nrOfNegativePictures+nrOfPositivePictures);
+  // This is a simplistic inter rps example. A smarter encoder will look for a better reference RPS to do the
+  // inter RPS prediction with.  Here we just use the reference used by pReferencePictureSet.
+  // If pReferencePictureSet is not inter_RPS_predicted, then inter_RPS_prediction is for the current RPS also disabled.
+  if (!pReferencePictureSet->getInterRPSPrediction()
+#if EFFICIENT_FIELD_IRAP
+    || useNewRPS
+#endif
+#if P0297_VPS_POC_LSB_ALIGNED_FLAG
+    || pocsAdjusted  // inter RPS prediction does not work if POCs have been adjusted
+#endif
+    )
+  {
+    pcRPS->setInterRPSPrediction(false);
+    pcRPS->setNumRefIdc(0);
+  }
+  else
+  {
+    Int rIdx =  this->getRPSidx() - pReferencePictureSet->getDeltaRIdxMinus1() - 1;
+    Int deltaRPS = pReferencePictureSet->getDeltaRPS();
+    TComReferencePictureSet* pcRefRPS = this->getSPS()->getRPSList()->getReferencePictureSet(rIdx);
+    Int iRefPics = pcRefRPS->getNumberOfPictures();
+    Int iNewIdc=0;
+    for(i=0; i<= iRefPics; i++)
+    {
+      Int deltaPOC = ((i != iRefPics)? pcRefRPS->getDeltaPOC(i) : 0);  // check if the reference abs POC is >= 0
+      Int iRefIdc = 0;
+      for (j=0; j < pcRPS->getNumberOfPictures(); j++) // loop through the  pictures in the new RPS
+      {
+        if ( (deltaPOC + deltaRPS) == pcRPS->getDeltaPOC(j))
+        {
+          if (pcRPS->getUsed(j))
+          {
+            iRefIdc = 1;
+          }
+          else
+          {
+            iRefIdc = 2;
+          }
+        }
+      }
+      pcRPS->setRefIdc(i, iRefIdc);
+      iNewIdc++;
+    }
+    pcRPS->setInterRPSPrediction(true);
+    pcRPS->setNumRefIdc(iNewIdc);
+    pcRPS->setDeltaRPS(deltaRPS);
+    pcRPS->setDeltaRIdxMinus1(pReferencePictureSet->getDeltaRIdxMinus1() + this->getSPS()->getRPSList()->getNumberOfReferencePictureSets() - this->getRPSidx());
+  }
+
+  this->setRPS(pcRPS);
+  this->setRPSidx(-1);
+}
+
+/** get AC and DC values for weighted pred
+ * \param *wp
+ * \returns Void
+ */
+Void  TComSlice::getWpAcDcParam(WPACDCParam *&wp)
+{
+  wp = m_weightACDCParam;
+}
+
+/** init AC and DC values for weighted pred
+ * \returns Void
+ */
+Void  TComSlice::initWpAcDcParam()
+{
+  for(Int iComp = 0; iComp < MAX_NUM_COMPONENT; 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 )
+{
+  assert (e<NUM_REF_PIC_LIST_01);
+  wp = m_weightPredTable[e][iRefIdx];
+}
+
+/** reset Default WP tables settings : no weight.
+ * \param WPScalingParam
+ * \returns Void
+ */
+Void  TComSlice::resetWpScaling()
+{
+  for ( Int e=0 ; e<NUM_REF_PIC_LIST_01 ; e++ )
+  {
+    for ( Int i=0 ; i<MAX_NUM_REF ; i++ )
+    {
+      for ( Int yuv=0 ; yuv<MAX_NUM_COMPONENT ; 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()
+{
+  const Bool bUseHighPrecisionPredictionWeighting = getSPS()->getUseHighPrecisionPredictionWeighting();
+  for ( Int e=0 ; e<NUM_REF_PIC_LIST_01 ; e++ )
+  {
+    for ( Int i=0 ; i<MAX_NUM_REF ; i++ )
+    {
+      for ( Int yuv=0 ; yuv<MAX_NUM_COMPONENT ; yuv++ )
+      {
+        WPScalingParam  *pwp = &(m_weightPredTable[e][i][yuv]);
+        if ( !pwp->bPresentFlag )
+        {
+          // Inferring values not present :
+          pwp->iWeight = (1 << pwp->uiLog2WeightDenom);
+          pwp->iOffset = 0;
+        }
+
+        const Int offsetScalingFactor = bUseHighPrecisionPredictionWeighting ? 1 : (1 << (g_bitDepth[toChannelType(ComponentID(yuv))]-8));
+
+        pwp->w      = pwp->iWeight;
+        pwp->o      = pwp->iOffset * offsetScalingFactor; //NOTE: This value of the ".o" variable is never used - .o is set immediately before it gets used
+        pwp->shift  = pwp->uiLog2WeightDenom;
+        pwp->round  = (pwp->uiLog2WeightDenom>=1) ? (1 << (pwp->uiLog2WeightDenom-1)) : (0);
+      }
+    }
+  }
+}
+
+// ------------------------------------------------------------------------------------------------
+// Video parameter set (VPS)
+// ------------------------------------------------------------------------------------------------
+#if SVC_EXTENSION
+TComVPS::TComVPS()
+: m_VPSId                     (  0)
+#if VPS_RESERVED_FLAGS
+, m_baseLayerInternalFlag     (true)
+, m_baseLayerAvailableFlag    (true)
+#endif
+, m_uiMaxTLayers              (  1)
+, m_uiMaxLayers               (  1)
+, m_bTemporalIdNestingFlag    (false)
+, m_numHrdParameters          (  0)
+, m_hrdParameters             (NULL)
+, m_hrdOpSetIdx               (NULL)
+, m_cprmsPresentFlag          (NULL)
+, m_maxLayerId                (0)
+, m_numLayerSets              (0)
+#if VPS_EXTN_OP_LAYER_SETS
+, m_numOutputLayerSets        (0)  
+#endif
+, m_numProfileTierLevel       (0)
+#if !VPS_EXTN_UEV_CODING
+, m_moreOutputLayerSetsThanDefaultFlag (false)
+#endif
+, m_numAddOutputLayerSets     (0)
+#if P0295_DEFAULT_OUT_LAYER_IDC
+, m_defaultTargetOutputLayerIdc     (0)
+#else
+#if O0109_DEFAULT_ONE_OUT_LAYER_IDC
+, m_defaultOneTargetOutputLayerIdc     (0)
+#else
+, m_defaultOneTargetOutputLayerFlag    (false)
+#endif
+#endif
+, m_bitRatePresentVpsFlag     (false)
+, m_picRatePresentVpsFlag     (false)
+#if REPN_FORMAT_IN_VPS
+#if Q0195_REP_FORMAT_CLEANUP
+, m_repFormatIdxPresentFlag   (false)
+#else
+, m_repFormatIdxPresentFlag   (true)
+#endif
+, m_vpsNumRepFormats          (1)
+#endif
+#if VIEW_ID_RELATED_SIGNALING 
+#if O0109_VIEW_ID_LEN
+, m_viewIdLen                (0)
+#else
+, m_viewIdLenMinus1           (0)
+#endif
+#endif
+#if !P0307_REMOVE_VPS_VUI_OFFSET
+#if VPS_VUI_OFFSET
+, m_vpsVuiOffset (0)
+#endif
+#endif
+#if P0307_VPS_NON_VUI_EXTENSION
+, m_vpsNonVuiExtLength (0)
+#endif
+#if P0297_VPS_POC_LSB_ALIGNED_FLAG
+, m_vpsPocLsbAlignedFlag(false)
+#endif
+{
+  for( Int i = 0; i < MAX_TLAYER; i++)
+  {
+    m_numReorderPics[i] = 0;
+    m_uiMaxDecPicBuffering[i] = 1;
+    m_uiMaxLatencyIncrease[i] = 0;
+  }
+
+#if VPS_EXTN_MASK_AND_DIM_INFO
+#if VPS_AVC_BL_FLAG_REMOVAL
+  m_nonHEVCBaseLayerFlag = false;
+#else
+  m_avcBaseLayerFlag = false;
+#endif
+  m_splittingFlag = false;
+  ::memset(m_scalabilityMask, 0, sizeof(m_scalabilityMask));
+  ::memset(m_dimensionIdLen, 0, sizeof(m_dimensionIdLen));
+  m_nuhLayerIdPresentFlag = false;
+  ::memset(m_layerIdInNuh, 0, sizeof(m_layerIdInNuh));
+  ::memset(m_dimensionId, 0, sizeof(m_dimensionId));
+
+  m_numScalabilityTypes = 0;
+  ::memset(m_layerIdxInVps, 0, sizeof(m_layerIdxInVps));
+#endif
+#if VPS_EXTN_PROFILE_INFO
+  ::memset(m_profilePresentFlag, 0, sizeof(m_profilePresentFlag));
+#if !P0048_REMOVE_PROFILE_REF
+  ::memset(m_profileLayerSetRef, 0, sizeof(m_profileLayerSetRef));
+#endif
+#endif
+#if VPS_EXTN_OP_LAYER_SETS
+  ::memset(m_layerIdIncludedFlag, 0, sizeof(m_layerIdIncludedFlag));
+  // Consider dynamic allocation for outputLayerSetIdx and outputLayerFlag
+  ::memset(m_outputLayerSetIdx, 0, sizeof(m_outputLayerSetIdx));
+  ::memset(m_outputLayerFlag, 0, sizeof(m_outputLayerFlag));
+#endif
+#if VPS_EXTN_DIRECT_REF_LAYERS
+  ::memset(m_directDependencyFlag, 0, sizeof(m_directDependencyFlag));
+  ::memset(m_numDirectRefLayers,   0, sizeof(m_numDirectRefLayers  ));
+  ::memset(m_refLayerId,           0, sizeof(m_refLayerId          ));
+  m_directDepTypeLen = 2;
+  ::memset(m_directDependencyType, 0, sizeof(m_directDependencyType));
+#endif
+#if !NECESSARY_LAYER_FLAG
+#if DERIVE_LAYER_ID_LIST_VARIABLES
+  ::memset(m_layerSetLayerIdList,  0, sizeof(m_layerSetLayerIdList));
+  ::memset(m_numLayerInIdList,     0, sizeof(m_numLayerInIdList   )); 
+#endif
+#endif
+#if !PER_LAYER_PTL
+  ::memset(m_profileLevelTierIdx,  0, sizeof(m_profileLevelTierIdx));
+#endif
+  m_maxOneActiveRefLayerFlag = true;
+#if O0062_POC_LSB_NOT_PRESENT_FLAG
+  ::memset(m_pocLsbNotPresentFlag, 0, sizeof(m_pocLsbNotPresentFlag));
+#endif
+#if O0223_PICTURE_TYPES_ALIGN_FLAG
+  m_crossLayerPictureTypeAlignFlag = true;
+#endif 
+  m_crossLayerIrapAlignFlag = true;
+#if P0068_CROSS_LAYER_ALIGNED_IDR_ONLY_FOR_IRAP_FLAG
+  m_crossLayerAlignedIdrOnlyFlag = false;
+#endif
+  m_maxTidRefPresentFlag = true;
+  for( Int i = 0; i < MAX_VPS_LAYER_IDX_PLUS1 - 1; i++)
+  {
+    for( Int j = 0; j < MAX_VPS_LAYER_IDX_PLUS1; j++)
+    {
+      m_maxTidIlRefPicsPlus1[i][j] = m_uiMaxTLayers + 1;
+    }
+  }
+#if VPS_VUI_TILES_NOT_IN_USE__FLAG
+  m_tilesNotInUseFlag = true;
+  ::memset(m_tilesInUseFlag,  0, sizeof(m_tilesInUseFlag));
+  ::memset(m_loopFilterNotAcrossTilesFlag,  0, sizeof(m_loopFilterNotAcrossTilesFlag));
+#endif
+  ::memset(m_tileBoundariesAlignedFlag,  0, sizeof(m_tileBoundariesAlignedFlag));
+#if VPS_VUI_WPP_NOT_IN_USE__FLAG
+  m_wppNotInUseFlag = true;
+  ::memset(m_wppInUseFlag,  0, sizeof(m_wppInUseFlag));
+#endif
+#if N0160_VUI_EXT_ILP_REF
+  m_ilpRestrictedRefLayersFlag = false;
+  ::memset(m_minSpatialSegmentOffsetPlus1,  0, sizeof(m_minSpatialSegmentOffsetPlus1));
+  ::memset(m_ctuBasedOffsetEnabledFlag,     0, sizeof(m_ctuBasedOffsetEnabledFlag));
+  ::memset(m_minHorizontalCtuOffsetPlus1,   0, sizeof(m_minHorizontalCtuOffsetPlus1));
+#endif
+#if VPS_VUI_VIDEO_SIGNAL
+  m_vidSigPresentVpsFlag=true;
+  m_vpsVidSigInfo=1;
+  ::memset( m_vpsVidSigIdx, 0, sizeof(m_vpsVidSigIdx) );
+  m_vpsVidSigIdx[0]=0;
+  for (Int i=0; i < 16; i++)
+  {
+    m_vpsVidFormat[i] = 5;
+    m_vpsFullRangeFlag[i] = false;
+    m_vpsColorPrimaries[i] = 2;
+    m_vpsTransChar[i] = 2;
+    m_vpsMatCoeff[i] = 2;
+  }
+#endif
+  ::memset(m_bitRatePresentFlag, 0, sizeof(m_bitRatePresentFlag));
+  ::memset(m_picRatePresentFlag, 0, sizeof(m_picRatePresentFlag));
+  ::memset(m_avgBitRate        , 0, sizeof(m_avgBitRate)        );
+  ::memset(m_maxBitRate        , 0, sizeof(m_maxBitRate)        );
+  ::memset(m_constPicRateIdc   , 0, sizeof(m_constPicRateIdc)   );
+  ::memset(m_avgPicRate        , 0, sizeof(m_avgPicRate)        );
+#if REPN_FORMAT_IN_VPS
+  ::memset( m_vpsRepFormatIdx, 0, sizeof(m_vpsRepFormatIdx) );
+#endif
+#if VIEW_ID_RELATED_SIGNALING 
+  ::memset(m_viewIdVal, 0, sizeof(m_viewIdVal));
+#endif
+#if O0092_0094_DEPENDENCY_CONSTRAINT
+  for (Int i = 0; i < MAX_NUM_LAYER_IDS; i++)
+  {
+    m_numberRefLayers[i] = 0;
+    for (Int j = 0; j < MAX_NUM_LAYER_IDS; j++)
+    {
+      m_recursiveRefLayerFlag[i][j] = 0;
+    }
+  }
+#endif
+#if VPS_DPB_SIZE_TABLE
+  ::memset( m_subLayerFlagInfoPresentFlag,  0, sizeof(m_subLayerFlagInfoPresentFlag ) );
+  ::memset( m_subLayerDpbInfoPresentFlag,   0, sizeof(m_subLayerDpbInfoPresentFlag )  );
+  ::memset( m_maxVpsDecPicBufferingMinus1,  0, sizeof(m_maxVpsDecPicBufferingMinus1 ) );
+#if RESOLUTION_BASED_DPB
+  ::memset( m_maxVpsLayerDecPicBuffMinus1,  0, sizeof(m_maxVpsLayerDecPicBuffMinus1 ) );
+#endif
+  ::memset( m_maxVpsNumReorderPics,         0, sizeof(m_maxVpsNumReorderPics )        );
+  ::memset( m_maxVpsLatencyIncreasePlus1,   0, sizeof(m_maxVpsLatencyIncreasePlus1 )  );
+  ::memset( m_numSubDpbs                ,   0, sizeof(m_numSubDpbs)                   );
+#endif
+  ::memset( m_baseLayerPSCompatibilityFlag, 0, sizeof(m_baseLayerPSCompatibilityFlag) );
+}
+#else
+TComVPS::TComVPS()
+: m_VPSId                     (  0)
+, m_uiMaxTLayers              (  1)
+, m_uiMaxLayers               (  1)
+, m_bTemporalIdNestingFlag    (false)
+, m_numHrdParameters          (  0)
+, m_maxNuhReservedZeroLayerId (  0)
+, 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;
+  }
+}
+#endif //SVC_EXTENSION
+
+TComVPS::~TComVPS()
+{
+  if( m_hrdParameters    != NULL )     delete[] m_hrdParameters;
+  if( m_hrdOpSetIdx      != NULL )     delete[] m_hrdOpSetIdx;
+  if( m_cprmsPresentFlag != NULL )     delete[] m_cprmsPresentFlag;
+}
+
+// ------------------------------------------------------------------------------------------------
+// Sequence parameter set (SPS)
+// ------------------------------------------------------------------------------------------------
+
+TComSPS::TComSPS()
+: m_SPSId                     (  0)
+, m_VPSId                     (  0)
+, m_chromaFormatIdc           (CHROMA_420)
+, m_uiMaxTLayers              (  1)
+#if R0279_REP_FORMAT_INBL
+, m_bV1CompatibleSPSFlag      (  0)
+#endif
+// Structure
+, m_picWidthInLumaSamples     (352)
+, m_picHeightInLumaSamples    (288)
+, m_log2MinCodingBlockSize    (  0)
+, m_log2DiffMaxMinCodingBlockSize(0)
+, m_uiMaxCUWidth              ( 32)
+, m_uiMaxCUHeight             ( 32)
+, m_uiMaxCUDepth              (  3)
+, m_bLongTermRefsPresent      (false)
+, m_uiQuadtreeTULog2MaxSize   (  0)
+, m_uiQuadtreeTULog2MinSize   (  0)
+, m_uiQuadtreeTUMaxDepthInter (  0)
+, m_uiQuadtreeTUMaxDepthIntra (  0)
+// Tool list
+, m_usePCM                    (false)
+, m_pcmLog2MaxSize            (  5)
+, m_uiPCMLog2MinSize          (  7)
+, m_useExtendedPrecision      (false)
+, m_useHighPrecisionPredictionWeighting(false)
+, m_useResidualRotation       (false)
+, m_useSingleSignificanceMapContext(false)
+, m_useGolombRiceParameterAdaptation(false)
+, m_alignCABACBeforeBypass    (false)
+, m_bPCMFilterDisableFlag     (false)
+, m_disableIntraReferenceSmoothing(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 SVC_EXTENSION
+, m_layerId                   ( 0 )
+, m_extensionFlag             ( false )
+#if !MOVE_SCALED_OFFSET_TO_PPS
+, m_numScaledRefLayerOffsets  ( 0 )
+#endif
+#if REPN_FORMAT_IN_VPS
+, m_updateRepFormatFlag       (false)
+#if O0096_REP_FORMAT_INDEX
+, m_updateRepFormatIndex      (0)
+#endif
+#endif
+#if SCALINGLIST_INFERRING
+, m_inferScalingListFlag ( false )
+, m_scalingListRefLayerId ( 0 )
+#endif
+#endif //SVC_EXTENSION
+{
+  for(Int ch=0; ch<MAX_NUM_CHANNEL_TYPE; ch++)
+  {
+    m_uiBitDepth   [ch] = 8;
+    m_uiPCMBitDepth[ch] = 8;
+    m_qpBDOffset   [ch] = 0;
+  }
+
+  for ( Int i = 0; i < MAX_TLAYER; i++ )
+  {
+    m_uiMaxLatencyIncrease[i] = 0;
+    m_uiMaxDecPicBuffering[i] = 1;
+    m_numReorderPics[i]       = 0;
+  }
+
+  for (UInt signallingModeIndex = 0; signallingModeIndex < NUMBER_OF_RDPCM_SIGNALLING_MODES; signallingModeIndex++)
+  {
+    m_useResidualDPCM[signallingModeIndex] = false;
+  }
+
+  m_scalingList = new TComScalingList;
+  ::memset(m_ltRefPicPocLsbSps, 0, sizeof(m_ltRefPicPocLsbSps));
+  ::memset(m_usedByCurrPicLtSPSFlag, 0, sizeof(m_usedByCurrPicLtSPSFlag));
+
+#if !MOVE_SCALED_OFFSET_TO_PPS
+#if P0312_VERT_PHASE_ADJ 
+  ::memset(m_vertPhasePositionEnableFlag, 0, sizeof(m_vertPhasePositionEnableFlag));
+#endif
+#endif
+}
+
+TComSPS::~TComSPS()
+{
+#if SCALINGLIST_INFERRING
+  if( !m_inferScalingListFlag )
+#endif
+  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();
+#if SVC_EXTENSION
+  if( m_layerId > 0 )
+  {
+    timingInfo->setTimingInfoPresentFlag( false );
+    return;
+  }
+#endif
+
+  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 bitrateValue, 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 );
+
+    bitrateValue = bitRate;
+    cpbSizeValue = bitRate;                                     // 1 second
+    duCpbSizeValue = bitRate/numDU;
+    duBitRateValue = bitRate;
+
+    for( j = 0; j < ( hrd->getCpbCntMinus1( i ) + 1 ); j ++ )
+    {
+      hrd->setBitRateValueMinus1( i, j, 0, ( bitrateValue - 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, ( bitrateValue - 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};
+
+#if !MOVE_SCALED_OFFSET_TO_PPS
+#if O0098_SCALED_REF_LAYER_ID
+Window& TComSPS::getScaledRefLayerWindowForLayer(Int layerId)
+{
+  static Window win;
+
+  for (Int i = 0; i < m_numScaledRefLayerOffsets; i++)
+  {
+    if (layerId == m_scaledRefLayerId[i])
+    {
+      return m_scaledRefLayerWindow[i];
+    }
+  }
+
+  win.resetWindow();  // scaled reference layer offsets are inferred to be zero when not present
+  return win;
+}
+#endif
+#if REF_REGION_OFFSET
+Window& TComSPS::getRefLayerWindowForLayer(Int layerId)
+{
+  static Window win;
+
+  for (Int i = 0; i < m_numRefLayerOffsets; i++)
+  {
+    if (layerId == m_refLayerId[i])
+    {
+      return m_refLayerWindow[i];
+    }
+  }
+
+  win.resetWindow();  // reference region offsets are inferred to be zero when not present
+  return win;
+}
+#endif
+#endif
+
+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_MaxCuChromaQpAdjDepth            (0)
+, m_MinCuChromaQpAdjSize             (0)
+, m_ChromaQpAdjTableSize             (0)
+, m_chromaCbQpOffset                 (0)
+, m_chromaCrQpOffset                 (0)
+, m_numRefIdxL0DefaultActive         (1)
+, m_numRefIdxL1DefaultActive         (1)
+, m_useCrossComponentPrediction      (false)
+, m_TransquantBypassEnableFlag       (false)
+, m_useTransformSkip                 (false)
+, m_transformSkipLog2MaxSize         (2)
+, m_dependentSliceSegmentsEnabledFlag(false)
+, m_tilesEnabledFlag                 (false)
+, m_entropyCodingSyncEnabledFlag     (false)
+, m_loopFilterAcrossTilesEnabledFlag (true)
+, m_uniformSpacingFlag               (false)
+, m_numTileColumnsMinus1             (0)
+, m_numTileRowsMinus1                (0)
+, m_numSubstreams                    (1)
+, m_signHideFlag                     (0)
+, m_cabacInitPresentFlag             (false)
+, m_encCABACTableIdx                 (I_SLICE)
+, m_sliceHeaderExtensionPresentFlag  (false)
+, m_loopFilterAcrossSlicesEnabledFlag(false)
+, m_listsModificationPresentFlag     (0)
+, m_numExtraSliceHeaderBits          (0)
+
+#if SVC_EXTENSION
+, m_extensionFlag(false)
+#if SCALINGLIST_INFERRING
+, m_layerId(0)
+, m_inferScalingListFlag ( false )
+, m_scalingListRefLayerId ( 0 )
+#endif
+#if POC_RESET_IDC
+, m_pocResetInfoPresentFlag   (false)
+#endif
+#if MOVE_SCALED_OFFSET_TO_PPS
+, m_numRefLayerLocationOffsets  ( 0 )
+#endif
+#if Q0048_CGS_3D_ASYMLUT
+, m_nCGSFlag(0)
+, m_nCGSOutputBitDepthY(0)
+, m_nCGSOutputBitDepthC(0)
+#endif
+#endif //SVC_EXTENSION
+{
+  m_scalingList = new TComScalingList;
+  for(Int ch=0; ch<MAX_NUM_CHANNEL_TYPE; ch++)
+  {
+    m_saoOffsetBitShift[ch] = 0;
+  }
+  m_ChromaQpAdjTable[0].u.comp.CbOffset = 0;
+  m_ChromaQpAdjTable[0].u.comp.CrOffset = 0;
+
+#if SVC_EXTENSION
+#if REF_REGION_OFFSET
+  ::memset(m_scaledRefLayerOffsetPresentFlag,   0, sizeof(m_scaledRefLayerOffsetPresentFlag));
+  ::memset(m_refRegionOffsetPresentFlag,   0, sizeof(m_refRegionOffsetPresentFlag));
+#endif
+#if R0209_GENERIC_PHASE
+  ::memset(m_resamplePhaseSetPresentFlag,   0, sizeof(m_resamplePhaseSetPresentFlag));
+  ::memset(m_phaseHorLuma,   0, sizeof(m_phaseHorLuma));
+  ::memset(m_phaseVerLuma,   0, sizeof(m_phaseVerLuma));
+  ::memset(m_phaseHorChroma, 0, sizeof(m_phaseHorChroma));
+  ::memset(m_phaseVerChroma, 0, sizeof(m_phaseVerChroma));
+#endif
+#endif //SVC_EXTENSION
+}
+
+TComPPS::~TComPPS()
+{
+#if SCALINGLIST_INFERRING
+  if( !m_inferScalingListFlag )
+#endif
+  delete m_scalingList;
+}
+
+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()
+{
+  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<SCALING_LIST_NUM;listId++)
+    {
+      getScalingList()->processDefaultMatrix(sizeId, listId);
+    }
+  }
+}
+/** check if use default quantization matrix
+ * \returns true if use default quantization matrix in all size
+*/
+Bool TComSlice::checkDefaultScalingList()
+{
+  UInt defaultCounter=0;
+
+  for(UInt sizeId = 0; sizeId < SCALING_LIST_SIZE_NUM; sizeId++)
+  {
+    for(UInt listId=0;listId<SCALING_LIST_NUM;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 )) ? false : true;
+}
+
+/** 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
+ */
+
+static Void outputScalingListHelp(std::ostream &os)
+{
+  os << "The scaling list file specifies all matrices and their DC values; none can be missing,\n"
+         "but their order is arbitrary.\n\n"
+         "The matrices are specified by:\n"
+         "<matrix name><unchecked data>\n"
+         "  <value>,<value>,<value>,....\n\n"
+         "  Line-feeds can be added arbitrarily between values, and the number of values needs to be\n"
+         "  at least the number of entries for the matrix (superfluous entries are ignored).\n"
+         "  The <unchecked data> is text on the same line as the matrix that is not checked\n"
+         "  except to ensure that the matrix name token is unique. It is recommended that it is ' ='\n"
+         "  The values in the matrices are the absolute values (0-255), not the delta values as\n"
+         "  exchanged between the encoder and decoder\n\n"
+         "The DC values (for matrix sizes larger than 8x8) are specified by:\n"
+         "<matrix name>_DC<unchecked data>\n"
+         "  <value>\n";
+
+  os << "The permitted matrix names are:\n";
+  for(UInt sizeIdc = 0; sizeIdc < SCALING_LIST_SIZE_NUM; sizeIdc++)
+  {
+    for(UInt listIdc = 0; listIdc < SCALING_LIST_NUM; listIdc++)
+    {
+      if ((sizeIdc!=SCALING_LIST_32x32) || (listIdc%(SCALING_LIST_NUM/NUMBER_OF_PREDICTION_MODES) == 0))
+      {
+        os << "  " << MatrixType[sizeIdc][listIdc] << '\n';
+      }
+    }
+  }
+}
+
+Void TComScalingList::outputScalingLists(std::ostream &os) const
+{
+  for(UInt sizeIdc = 0; sizeIdc < SCALING_LIST_SIZE_NUM; sizeIdc++)
+  {
+    const UInt size = min(8,4<<(sizeIdc));
+    for(UInt listIdc = 0; listIdc < SCALING_LIST_NUM; listIdc++)
+    {
+      if ((sizeIdc!=SCALING_LIST_32x32) || (listIdc%(SCALING_LIST_NUM/NUMBER_OF_PREDICTION_MODES) == 0))
+      {
+        const Int *src = getScalingListAddress(sizeIdc, listIdc);
+        os << (MatrixType[sizeIdc][listIdc]) << " =\n  ";
+        for(UInt y=0; y<size; y++)
+        {
+          for(UInt x=0; x<size; x++, src++)
+          {
+            os << std::setw(3) << (*src) << ", ";
+          }
+          os << (y+1<size?"\n  ":"\n");
+        }
+        if(sizeIdc > SCALING_LIST_8x8)
+        {
+          os << MatrixType_DC[sizeIdc][listIdc] << " = \n  " << std::setw(3) << getScalingListDC(sizeIdc, listIdc) << "\n";
+        }
+        os << "\n";
+      }
+    }
+  }
+}
+
+Bool TComScalingList::xParseScalingList(Char* pchFile)
+{
+  static const Int LINE_SIZE=1024;
+  FILE *fp = NULL;
+  Char line[LINE_SIZE];
+
+  if (pchFile == NULL)
+  {
+    fprintf(stderr, "Error: no scaling list file specified. Help on scaling lists being output\n");
+    outputScalingListHelp(std::cout);
+    std::cout << "\n\nExample scaling list file using default values:\n\n";
+    outputScalingLists(std::cout);
+    exit (1);
+    return true;
+  }
+  else if ((fp = fopen(pchFile,"r")) == (FILE*)NULL)
+  {
+    fprintf(stderr, "Error: cannot open scaling list file %s for reading\n",pchFile);
+    return true;
+  }
+
+  for(UInt sizeIdc = 0; sizeIdc < SCALING_LIST_SIZE_NUM; sizeIdc++)
+  {
+    const UInt size = min(MAX_MATRIX_COEF_NUM,(Int)g_scalingListSize[sizeIdc]);
+
+    for(UInt listIdc = 0; listIdc < SCALING_LIST_NUM; listIdc++)
+    {
+      Int * const src = getScalingListAddress(sizeIdc, listIdc);
+
+      if ((sizeIdc==SCALING_LIST_32x32) && (listIdc%(SCALING_LIST_NUM/NUMBER_OF_PREDICTION_MODES) != 0)) // derive chroma32x32 from chroma16x16
+      {
+        const Int *srcNextSmallerSize = getScalingListAddress(sizeIdc-1, listIdc);
+        for(UInt i=0; i<size; i++)
+        {
+          src[i] = srcNextSmallerSize[i];
+        }
+        setScalingListDC(sizeIdc,listIdc,(sizeIdc > SCALING_LIST_8x8) ? getScalingListDC(sizeIdc-1, listIdc) : src[0]);
+      }
+      else
+      {
+        {
+          fseek(fp, 0, SEEK_SET);
+          Bool bFound=false;
+          while ((!feof(fp)) && (!bFound))
+          {
+            Char *ret = fgets(line, LINE_SIZE, fp);
+            Char *findNamePosition= ret==NULL ? NULL : strstr(line, MatrixType[sizeIdc][listIdc]);
+            // This could be a match against the DC string as well, so verify it isn't
+            if (findNamePosition!= NULL && (MatrixType_DC[sizeIdc][listIdc]==NULL || strstr(line, MatrixType_DC[sizeIdc][listIdc])==NULL))
+            {
+              bFound=true;
+            }
+          }
+          if (!bFound)
+          {
+            fprintf(stderr, "Error: cannot find Matrix %s from scaling list file %s\n", MatrixType[sizeIdc][listIdc], pchFile);
+            return true;
+          }
+        }
+        for (UInt i=0; i<size; i++)
+        {
+          Int data;
+          if (fscanf(fp, "%d,", &data)!=1)
+          {
+            fprintf(stderr, "Error: cannot read value #%d for Matrix %s from scaling list file %s at file position %ld\n", i, MatrixType[sizeIdc][listIdc], pchFile, ftell(fp));
+            return true;
+          }
+          if (data<0 || data>255)
+          {
+            fprintf(stderr, "Error: QMatrix entry #%d of value %d for Matrix %s from scaling list file %s at file position %ld is out of range (0 to 255)\n", i, data, MatrixType[sizeIdc][listIdc], pchFile, ftell(fp));
+            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, SEEK_SET);
+            Bool bFound=false;
+            while ((!feof(fp)) && (!bFound))
+            {
+              Char *ret = fgets(line, LINE_SIZE, fp);
+              Char *findNamePosition= ret==NULL ? NULL : strstr(line, MatrixType_DC[sizeIdc][listIdc]);
+              if (findNamePosition!= NULL)
+              {
+                // This won't be a match against the non-DC string.
+                bFound=true;
+              }
+            }
+            if (!bFound)
+            {
+              fprintf(stderr, "Error: cannot find DC Matrix %s from scaling list file %s\n", MatrixType_DC[sizeIdc][listIdc], pchFile);
+              return true;
+            }
+          }
+          Int data;
+          if (fscanf(fp, "%d,", &data)!=1)
+          {
+            fprintf(stderr, "Error: cannot read DC %s from scaling list file %s at file position %ld\n", MatrixType_DC[sizeIdc][listIdc], pchFile, ftell(fp));
+            return true;
+          }
+          if (data<0 || data>255)
+          {
+            fprintf(stderr, "Error: DC value %d for Matrix %s from scaling list file %s at file position %ld is out of range (0 to 255)\n", data, MatrixType[sizeIdc][listIdc], pchFile, ftell(fp));
+            return true;
+          }
+          //overwrite DC value when size of matrix is larger than 16x16
+          setScalingListDC(sizeIdc,listIdc,data);
+        }
+      }
+    }
+  }
+//  std::cout << "\n\nRead scaling lists of:\n\n";
+//  outputScalingLists(std::cout);
+
+  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 < SCALING_LIST_NUM; listId++)
+    {
+      m_scalingListCoef[sizeId][listId] = new Int [min(MAX_MATRIX_COEF_NUM,(Int)g_scalingListSize[sizeId])];
+    }
+  }
+}
+
+/** destroy quantization matrix array
+ */
+Void TComScalingList::destroy()
+{
+  for(UInt sizeId = 0; sizeId < SCALING_LIST_SIZE_NUM; sizeId++)
+  {
+    for(UInt listId = 0; listId < SCALING_LIST_NUM; 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:
+    case SCALING_LIST_16x16:
+    case SCALING_LIST_32x32:
+      src = (listId < (SCALING_LIST_NUM/NUMBER_OF_PREDICTION_MODES) ) ? g_quantIntraDefault8x8 : g_quantInterDefault8x8;
+      break;
+    default:
+      assert(0);
+      src = NULL;
+      break;
+  }
+  return src;
+}
+
+/** process of default matrix
+ * \param sizeId size index
+ * \param Index of input matrix
+ */
+Void TComScalingList::processDefaultMatrix(UInt sizeId, UInt listId)
+{
+  ::memcpy(getScalingListAddress(sizeId, listId),getScalingListDefaultAddress(sizeId,listId),sizeof(Int)*min(MAX_MATRIX_COEF_NUM,(Int)g_scalingListSize[sizeId]));
+  setScalingListDC(sizeId,listId,SCALING_LIST_DC);
+}
+
+/** check DC value of matrix for default matrix signaling
+ */
+Void TComScalingList::checkDcOfMatrix()
+{
+  for(UInt sizeId = 0; sizeId < SCALING_LIST_SIZE_NUM; sizeId++)
+  {
+    for(UInt listId = 0; listId < SCALING_LIST_NUM; listId++)
+    {
+      //check default matrix?
+      if(getScalingListDC(sizeId,listId) == 0)
+      {
+        processDefaultMatrix(sizeId, listId);
+      }
+    }
+  }
+}
+
+ParameterSetManager::ParameterSetManager()
+#if SVC_EXTENSION
+: m_activeSPSId(-1)
+, m_activePPSId(-1)
+#else
+: m_vpsMap(MAX_NUM_VPS)
+, m_spsMap(MAX_NUM_SPS)
+, m_ppsMap(MAX_NUM_PPS)
+, m_activeVPSId(-1)
+, m_activeSPSId(-1)
+, m_activePPSId(-1)
+#endif
+{
+}
+
+
+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 (!isIRAP && (spsId != m_activeSPSId))
+    {
+      printf("Warning: tried to activate PPS referring to a inactive SPS at non-IDR.");
+      return false;
+    }
+    TComSPS *sps = m_spsMap.getPS(spsId);
+    if (sps)
+    {
+      Int vpsId = sps->getVPSId();
+      if (!isIRAP && (vpsId != m_activeVPSId))
+      {
+        printf("Warning: tried to activate PPS referring to a inactive VPS at non-IDR.");
+        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        (Level::MAIN)
+  , m_profileIdc      (Profile::NONE)
+  , m_levelIdc        (Level::NONE)
+  , 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 VPS_EXTN_PROFILE_INFO
+Void ProfileTierLevel::copyProfileInfo(ProfileTierLevel *ptl)
+{
+  this->setProfileSpace          ( ptl->getProfileSpace()      );
+  this->setTierFlag              ( ptl->getTierFlag()          );
+  this->setProfileIdc            ( ptl->getProfileIdc()        );
+  for(Int j = 0; j < 32; j++)
+  {
+    this->setProfileCompatibilityFlag(j, ptl->getProfileCompatibilityFlag(j));
+  }
+  this->setProgressiveSourceFlag  ( ptl->getProgressiveSourceFlag()  );
+  this->setInterlacedSourceFlag   ( ptl->getInterlacedSourceFlag()   );
+  this->setNonPackedConstraintFlag( ptl->getNonPackedConstraintFlag());
+  this->setFrameOnlyConstraintFlag( ptl->getFrameOnlyConstraintFlag());  
+}
+#endif
+
+#if MOVE_SCALED_OFFSET_TO_PPS
+#if O0098_SCALED_REF_LAYER_ID
+Window& TComPPS::getScaledRefLayerWindowForLayer(Int layerId)
+{
+  static Window win;
+
+  for( Int i = m_numRefLayerLocationOffsets-1; i >= 0; i-- )
+  {
+    if( layerId == m_refLocationOffsetLayerId[i] )
+    {
+      return m_scaledRefLayerWindow[i];
+    }
+  }
+
+  win.resetWindow();  // scaled reference layer offsets are inferred to be zero when not present
+  return win;
+}
+#endif
+#if REF_REGION_OFFSET
+Window& TComPPS::getRefLayerWindowForLayer(Int layerId)
+{
+  static Window win;
+
+  for( Int i = m_numRefLayerLocationOffsets-1; i >= 0; i-- )
+  {
+    if( layerId == m_refLocationOffsetLayerId[i] )
+    {
+      return m_refLayerWindow[i];
+    }
+  }
+
+  win.resetWindow();  // reference region offsets are inferred to be zero when not present
+  return win;
+}
+#endif
+
+#if RESAMPLING_FIX
+#if R0209_GENERIC_PHASE
+Bool TComPPS::hasZeroResamplingPhase(Int refLayerId)
+{
+  Bool phaseSetPresentFlag;
+  Int phaseHorLuma, phaseVerLuma, phaseHorChroma, phaseVerChroma;
+
+  getResamplingPhase(refLayerId, phaseSetPresentFlag, phaseHorLuma, phaseVerLuma, phaseHorChroma, phaseVerChroma);
+
+  return ( phaseHorLuma == 0 && phaseHorChroma == 0 && phaseVerLuma == 0 && phaseVerChroma == 0);
+}
+
+Void TComPPS::getResamplingPhase(Int refLayerId, Bool& phaseSetPresentFlag, Int& phaseHorLuma, Int& phaseVerLuma, Int& phaseHorChroma, Int& phaseVerChroma)
+{
+  phaseSetPresentFlag = false;
+  phaseHorLuma = 0, phaseVerLuma = 0, phaseHorChroma = 0, phaseVerChroma = 0;
+
+  for( Int i = m_numRefLayerLocationOffsets-1; i >= 0; i-- )
+  {
+    if( refLayerId == m_refLocationOffsetLayerId[i] )
+    {
+      phaseSetPresentFlag = m_resamplePhaseSetPresentFlag[i];
+      phaseHorLuma        = m_phaseHorLuma[i];
+      phaseVerLuma        = m_phaseVerLuma[i];
+      phaseHorChroma      = m_phaseHorChroma[i];
+      phaseVerChroma      = m_phaseVerChroma[i];
+
+      return;
+    }
+  }
+}
+#endif
+#endif
+
+#endif
+
+
+#if DERIVE_LAYER_ID_LIST_VARIABLES
+#if NECESSARY_LAYER_FLAG
+Void TComVPS::deriveLayerIdListVariables()
+{
+  // For layer 0
+  m_numLayerInIdList.push_back(1);
+#if FIX_LAYER_ID_INIT
+  m_layerSetLayerIdList.resize(m_vpsNumLayerSetsMinus1 + 1);
+#else
+  m_layerSetLayerIdList.resize(m_numLayerSets);
+#endif
+  m_layerSetLayerIdList[0].push_back(0);
+  
+  // For other layers
+#if FIX_LAYER_ID_INIT
+  for (Int i = 1; i <= m_vpsNumLayerSetsMinus1; i++)
+#else
+  for( Int i = 1; i < m_numLayerSets; i++ )
+#endif
+  {
+    for( Int m = 0; m <= m_maxLayerId; m++)
+    {
+      if( m_layerIdIncludedFlag[i][m] )
+      {
+        m_layerSetLayerIdList[i].push_back(m);
+      }
+    }
+    m_numLayerInIdList.push_back((Int)m_layerSetLayerIdList[i].size());
+  }
+}
+#else
+Void TComVPS::deriveLayerIdListVariables()
+{
+  // For layer 0
+  m_numLayerInIdList[0] = 1;
+  m_layerSetLayerIdList[0][0] = 0;
+  
+  // For other layers
+  Int i, m, n;
+  for( i = 1; i < m_numLayerSets; i++ )
+  {
+    n = 0;
+    for( m = 0; m <= m_maxLayerId; m++)
+    {
+      if( m_layerIdIncludedFlag[i][m] )
+      {
+        m_layerSetLayerIdList[i][n++] = m;
+      }
+    }
+    m_numLayerInIdList[i] = n;
+  }
+}
+#endif
+#endif
+#if !RESOLUTION_BASED_DPB
+#if VPS_DPB_SIZE_TABLE
+Void TComVPS::deriveNumberOfSubDpbs()
+{
+  // Derive number of sub-DPBs
+#if CHANGE_NUMSUBDPB_IDX
+  // For layer set 0
+  m_numSubDpbs[0] = 1;
+  // For other layer sets
+  for( Int i = 1; i < m_numLayerSets; i++)
+  {
+    m_numSubDpbs[i] = m_numLayerInIdList[i];
+  }
+#else
+  // For output layer set 0
+  setNumSubDpbs(0, 1);
+  // For other output layer sets
+  for( Int i = 1; i < getNumOutputLayerSets(); i++)
+  {
+    setNumSubDpbs( i, getNumLayersInIdList( getOutputLayerSetIdx(i)) );
+  }
+#endif
+}
+#endif
+#endif
+#if VPS_VUI_TILES_NOT_IN_USE__FLAG
+Void TComVPS::setTilesNotInUseFlag(Bool x)
+{
+  m_tilesNotInUseFlag = x;
+  if (m_tilesNotInUseFlag)
+  {
+    for (int i = 0; i < getMaxLayers(); i++)
+    {
+      m_tilesInUseFlag[i] = m_loopFilterNotAcrossTilesFlag[i] = m_tilesNotInUseFlag;
+    }
+  }
+
+  if (m_tilesNotInUseFlag)
+  {
+    for (int i = 1; i < getMaxLayers(); i++)
+    {
+      for(int j = 0; j < getNumDirectRefLayers(getLayerIdInNuh(i)); j++)
+      {
+        setTileBoundariesAlignedFlag(i, j, m_tilesNotInUseFlag);
+      }
+    }
+  }
+}
+#endif
+
+#if VPS_VUI_WPP_NOT_IN_USE__FLAG
+Void TComVPS::setWppNotInUseFlag(Bool x)
+{
+  m_wppNotInUseFlag = x;
+  if (m_wppNotInUseFlag)
+  {
+    for (int i = 0; i < getMaxLayers(); i++)
+    {
+      m_wppInUseFlag[i] = m_wppNotInUseFlag;
+    }
+  }
+}
+#endif
+#if O0092_0094_DEPENDENCY_CONSTRAINT
+Void TComVPS::setRefLayersFlags(Int currLayerId)
+{
+  for (Int i = 0; i < m_numDirectRefLayers[currLayerId]; i++)
+  {
+    UInt refLayerId = getRefLayerId(currLayerId, i);
+    m_recursiveRefLayerFlag[currLayerId][refLayerId] = true;
+    for (Int k = 0; k < MAX_NUM_LAYER_IDS; k++)
+    {
+      m_recursiveRefLayerFlag[currLayerId][k] = m_recursiveRefLayerFlag[currLayerId][k] | m_recursiveRefLayerFlag[refLayerId][k];
+    }
+  }
+}
+
+Void TComVPS::setNumRefLayers()
+{
+  memset( m_numberRefLayers, 0, sizeof( m_numberRefLayers ) );
+
+  for (Int i = 0; i < m_uiMaxLayers; i++)
+  {
+    UInt iNuhLId = m_layerIdInNuh[i];
+    setRefLayersFlags(iNuhLId);
+    for (UInt j = 0; j < MAX_NUM_LAYER_IDS; j++)
+    {
+      m_numberRefLayers[iNuhLId] += (m_recursiveRefLayerFlag[iNuhLId][j] == true ? 1 : 0);
+    }
+  }
+}
+#endif
+
+#if Q0078_ADD_LAYER_SETS
+Void TComVPS::setPredictedLayerIds()
+{
+  for (UInt i = 0; i < m_uiMaxLayers - 1; i++)
+  {
+    UInt iNuhLId = m_layerIdInNuh[i];
+    UInt predIdx = 0;
+    for (UInt j = iNuhLId + 1; j < MAX_NUM_LAYER_IDS; j++)
+    {
+      if( m_recursiveRefLayerFlag[j][iNuhLId] )
+      {
+        m_predictedLayerId[iNuhLId][predIdx] = j;
+        predIdx++;
+      }
+    }
+    m_numPredictedLayers[iNuhLId] = predIdx;
+  }
+  m_numPredictedLayers[m_layerIdInNuh[m_uiMaxLayers-1]] = 0;
+}
+
+Void TComVPS::setTreePartitionLayerIdList()
+{
+  Bool countedLayerIdxFlag[MAX_NUM_LAYER_IDS];
+  memset( countedLayerIdxFlag, 0, sizeof(countedLayerIdxFlag) );
+
+  Int numIndependentLayers = 0;
+
+  for (UInt i = 0; i < m_uiMaxLayers; i++)
+  {
+    UInt iNuhLId = m_layerIdInNuh[i];
+    if( m_numDirectRefLayers[iNuhLId] == 0 )
+    {
+      m_treePartitionLayerIdList[numIndependentLayers][0] = iNuhLId;
+      m_numLayersInTreePartition[numIndependentLayers] = 1;
+      for( UInt j = 0; j < m_numPredictedLayers[iNuhLId]; j++ )
+      {
+        if( !countedLayerIdxFlag[m_layerIdxInVps[iNuhLId]] )
+        {
+          m_treePartitionLayerIdList[numIndependentLayers][m_numLayersInTreePartition[numIndependentLayers]] = m_predictedLayerId[iNuhLId][j];
+          m_numLayersInTreePartition[numIndependentLayers] = m_numLayersInTreePartition[numIndependentLayers] + 1;
+          countedLayerIdxFlag[m_layerIdxInVps[m_predictedLayerId[iNuhLId][j]]] = true;
+        }
+      }
+      numIndependentLayers++;
+    }
+  }
+
+  m_numIndependentLayers = numIndependentLayers;
+}
+
+#if FIX_LAYER_ID_INIT
+void TComVPS::deriveLayerIdListVariablesForAddLayerSets()
+{
+  m_layerSetLayerIdList.resize(m_vpsNumLayerSetsMinus1 + 1 + m_numAddLayerSets);
+
+  for (UInt i = 0; i < m_numAddLayerSets; i++)
+  {
+    Int layerNum = 0;
+    Int lsIdx = m_vpsNumLayerSetsMinus1 + 1 + i;
+    for (Int treeIdx = 1; treeIdx < m_numIndependentLayers; treeIdx++)
+    {
+      for (Int layerCnt = 0; layerCnt < m_highestLayerIdxPlus1[i][treeIdx]; layerCnt++)
+      {
+        m_layerSetLayerIdList[lsIdx].push_back(m_treePartitionLayerIdList[treeIdx][layerCnt]);
+        layerNum++;
+      }
+    }
+    m_numLayerInIdList.push_back(layerNum);
+  }
+}
+#else
+void TComVPS::setLayerIdIncludedFlagsForAddLayerSets()
+{
+  for (UInt i = 0; i < m_numAddLayerSets; i++)
+  {
+    for (UInt j = 1; j < m_numIndependentLayers; j++)
+    {
+      Int layerNum = 0;
+      Int lsIdx = m_vpsNumLayerSetsMinus1 + 1 + i;
+      for (Int layerId = 0; layerId < MAX_VPS_LAYER_IDX_PLUS1; layerId++)
+      {
+        m_layerIdIncludedFlag[lsIdx][layerId] = false;
+      }
+      for (Int treeIdx = 1; treeIdx < m_numIndependentLayers; treeIdx++)
+      {
+        for (Int layerCnt = 0; layerCnt < m_highestLayerIdxPlus1[i][j]; layerCnt++)
+        {
+          m_layerSetLayerIdList[lsIdx][layerNum] = m_treePartitionLayerIdList[treeIdx][layerCnt];
+          m_layerIdIncludedFlag[lsIdx][m_treePartitionLayerIdList[treeIdx][layerCnt]] = true;
+          layerNum++;
+        }
+      }
+      m_numLayerInIdList[lsIdx] = layerNum;
+    }
+  }
+}
+#endif
+
+#endif
+
+#if VIEW_ID_RELATED_SIGNALING 
+Int TComVPS::getNumViews()
+{
+  Int numViews = 1; 
+  for( Int i = 0; i <= getMaxLayers() - 1; i++ )
+  {
+    Int lId = getLayerIdInNuh( i ); 
+    if ( i > 0 && ( getViewIndex( lId ) != getScalabilityId( i - 1, VIEW_ORDER_INDEX ) ) )
+    {
+      numViews++; 
+    }    
+  }
+
+  return numViews;
+}
+Int TComVPS::getScalabilityId( Int layerIdInVps, ScalabilityType scalType )
+{
+  return getScalabilityMask( scalType ) ? getDimensionId( layerIdInVps, scalTypeToScalIdx( scalType ) ) : 0;
+}  
+Int TComVPS::scalTypeToScalIdx( ScalabilityType scalType )
+{
+  assert( scalType >= 0 && scalType <= MAX_VPS_NUM_SCALABILITY_TYPES ); 
+  assert( scalType == MAX_VPS_NUM_SCALABILITY_TYPES || getScalabilityMask( scalType ) );
+  Int scalIdx = 0; 
+  for( Int curScalType = 0; curScalType < scalType; curScalType++ )
+  {
+    scalIdx += ( getScalabilityMask( curScalType ) ? 1 : 0 );
+
+  }
+
+  return scalIdx; 
+}
+#endif
+#if VPS_DPB_SIZE_TABLE
+Int TComVPS::getLayerIdcForOls( Int olsIdx, Int layerId )
+{
+  Int layerIdc = -1;
+  UInt lsIdx = m_outputLayerSetIdx[olsIdx];
+
+  std::vector<Int>::iterator it = std::find( m_layerSetLayerIdList[lsIdx].begin(), m_layerSetLayerIdList[lsIdx].end(), layerId );
+
+  if( it != m_layerSetLayerIdList[lsIdx].end() )
+  {
+    layerIdc = (Int)std::distance( m_layerSetLayerIdList[lsIdx].begin(), it );
+  }
+
+  assert( layerIdc >= 0 );
+
+  return layerIdc;
+}
+
+Void TComVPS::determineSubDpbInfoFlags()
+{
+  for(Int i = 1; i < getNumOutputLayerSets(); i++)
+  {
+    Int layerSetIdxForOutputLayerSet = getOutputLayerSetIdx( i );
+    // For each output layer set, set the DPB size for each layer and the reorder/latency value the maximum for all layers
+    Bool checkFlagOuter = false;      // Used to calculate sub_layer_flag_info_present_flag
+    Bool checkFlagInner[MAX_TLAYER];  // Used to calculate sub_layer_dpb_info_present_flag
+
+    for(Int j = 0; j < getMaxTLayers(); j++)
+    {
+      // --------------------------------------------------------
+      // To determine value of m_subLayerDpbInfoPresentFlag
+      // --------------------------------------------------------
+      if( j == 0 )  // checkFlagInner[0] is always 1
+      {
+        checkFlagInner[j] = true;     // Always signal sub-layer DPB information for the first sub-layer
+      }
+      else
+      {
+        checkFlagInner[j] = false;    // Initialize to be false. If the values of the current sub-layers matches with the earlier sub-layer, 
+                                      // then will be continue to be false - i.e. the j-th sub-layer DPB info is not signaled
+        checkFlagInner[j] |= ( getMaxVpsNumReorderPics(i, j) != getMaxVpsNumReorderPics(i, j - 1) );
+#if CHANGE_NUMSUBDPB_IDX
+        for(Int subDpbIdx = 0; subDpbIdx < getNumSubDpbs(layerSetIdxForOutputLayerSet) && !checkFlagInner[j]; subDpbIdx++)  // If checkFlagInner[j] is true, break and signal the values
+#else
+        for(Int k = 0; k < getNumSubDpbs(i) && !checkFlagInner[j]; k++)  // If checkFlagInner[j] is true, break and signal the values
+#endif
+        {
+          checkFlagInner[j] |= ( getMaxVpsDecPicBufferingMinus1(i, subDpbIdx, j - 1) != getMaxVpsDecPicBufferingMinus1(i, subDpbIdx, j) );
+        }
+#if RESOLUTION_BASED_DPB
+        for(Int layerIdx = 0; layerIdx < this->getNumLayersInIdList(layerSetIdxForOutputLayerSet) && !checkFlagInner[j]; layerIdx++)  // If checkFlagInner[j] is true, break and signal the values
+        {
+          checkFlagInner[j] |= ( getMaxVpsLayerDecPicBuffMinus1(i, layerIdx, j - 1) != getMaxVpsLayerDecPicBuffMinus1(i, layerIdx, j) );
+        }
+#endif
+      }
+      // If checkFlagInner[j] = true, then some value needs to be signalled for the j-th sub-layer
+      setSubLayerDpbInfoPresentFlag( i, j, checkFlagInner[j] );
+    }
+
+    // --------------------------------------------------------
+    // To determine value of m_subLayerFlagInfoPresentFlag
+    // --------------------------------------------------------
+
+    for(Int j = 1; j < getMaxTLayers(); j++) // Check if DPB info of any of non-zero sub-layers is signaled. If so set flag to one
+    {
+      if( getSubLayerDpbInfoPresentFlag(i, j) )
+      {
+        checkFlagOuter = true;
+        break;
+      }
+    }
+    setSubLayerFlagInfoPresentFlag( i, checkFlagOuter );
+  }
+}
+#endif
+#if RESOLUTION_BASED_DPB
+Void TComVPS::assignSubDpbIndices()
+{
+  RepFormat layerRepFormat  [MAX_LAYERS];
+  RepFormat subDpbRepFormat [MAX_LAYERS];
+
+  for(Int lsIdx = 0; lsIdx < this->getNumLayerSets(); lsIdx++)
+  {
+    for(Int j = 0; j < MAX_LAYERS; j++)
+    {
+      layerRepFormat [j].init();
+      subDpbRepFormat[j].init();
+    }
+
+    // Assign resolution, bit-depth, colour format for each layer in the layer set
+    for(Int i = 0; i < this->getNumLayersInIdList( lsIdx ); i++)
+    {
+      Int layerIdxInVps = this->getLayerIdxInVps( this->getLayerSetLayerIdList(lsIdx, i) );
+      Int repFormatIdx  = this->getVpsRepFormatIdx( layerIdxInVps );
+      RepFormat* repFormat = this->getVpsRepFormat( repFormatIdx );
+
+      // Assign the rep_format() to the layer
+      layerRepFormat[i] = *repFormat;
+    }
+
+    // ----------------------------------------
+    // Sub-DPB assignment
+    // ----------------------------------------
+    // For the base layer 
+    m_subDpbAssigned[lsIdx][0] = 0;
+    subDpbRepFormat[0] = layerRepFormat[0];
+
+    // Sub-DPB counter
+    Int subDpbCtr = 1;
+
+    for(Int i = 1; i < this->getNumLayersInIdList( lsIdx ); i++)
+    {
+      Bool newSubDpbFlag = true;
+      for(Int j = 0; (j < subDpbCtr) && (newSubDpbFlag); j++)
+      {
+        if( RepFormat::checkSameSubDpb( layerRepFormat[i], subDpbRepFormat[j] ) )
+        {
+          // Belong to i-th sub-DPB
+          m_subDpbAssigned[lsIdx][i] = j;
+          newSubDpbFlag = false;
+        }
+      }
+      if( newSubDpbFlag )
+      {
+        // New sub-DPB
+        subDpbRepFormat[subDpbCtr] = layerRepFormat[i];
+        m_subDpbAssigned[lsIdx][i] = subDpbCtr;
+        subDpbCtr++;                                    // Increment # subDpbs
+      }
+    }
+    m_numSubDpbs[lsIdx] = subDpbCtr;
+  }
+}
+Int  TComVPS::findLayerIdxInLayerSet ( Int lsIdx, Int nuhLayerId )
+{
+  for(Int i = 0; i < this->getNumLayersInIdList(lsIdx); i++)
+  {
+    if( this->getLayerSetLayerIdList( lsIdx, i) == nuhLayerId )
+    {
+      return i;
+    }
+  }
+  return -1;  // Layer not found
+}
+#endif
+#if O0164_MULTI_LAYER_HRD
+Void TComVPS::setBspHrdParameters( UInt hrdIdx, UInt frameRate, UInt numDU, UInt bitRate, Bool randomAccess )
+{
+  if( !getVpsVuiBspHrdPresentFlag() )
+  {
+    return;
+  }
+
+  TComHRD *hrd = getBspHrd(hrdIdx);
+
+  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 ) );
+    }
+  }
+}
+#endif
+#if NECESSARY_LAYER_FLAG
+Void TComVPS::deriveNecessaryLayerFlag()
+{
+  m_necessaryLayerFlag.empty();
+  m_numNecessaryLayers.empty();
+  // Assumed that output layer sets and variables RecursiveRefLayer are already derived
+  for( Int olsIdx = 0; olsIdx < m_numOutputLayerSets; olsIdx++)
+  {
+    deriveNecessaryLayerFlag(olsIdx);
+  }
+}
+Void TComVPS::deriveNecessaryLayerFlag(Int const olsIdx)
+{
+  Int lsIdx = m_outputLayerSetIdx[olsIdx];
+  Int numLayersInLs = m_numLayerInIdList[lsIdx];
+  assert( m_necessaryLayerFlag.size() == olsIdx );   // Function should be called in the correct order.
+  m_necessaryLayerFlag.push_back( std::vector<Bool>( numLayersInLs, false ) ); // Initialize to false
+  for( Int lsLayerIdx = 0; lsLayerIdx < numLayersInLs; lsLayerIdx++ )
+  {
+    if( m_outputLayerFlag[olsIdx][lsLayerIdx] )
+    {
+      m_necessaryLayerFlag[olsIdx][lsLayerIdx] = true;
+      Int currNuhLayerId = m_layerSetLayerIdList[lsIdx][lsLayerIdx];
+      for( Int rLsLayerIdx = 0; rLsLayerIdx < lsLayerIdx; rLsLayerIdx++ )
+      {
+        Int refNuhLayerId = m_layerSetLayerIdList[lsIdx][rLsLayerIdx];
+        if( m_recursiveRefLayerFlag[currNuhLayerId][refNuhLayerId] )
+        {
+          m_necessaryLayerFlag[olsIdx][rLsLayerIdx] = true;
+        }
+      }
+    }
+  }
+  m_numNecessaryLayers.push_back(std::accumulate(m_necessaryLayerFlag[olsIdx].begin(), m_necessaryLayerFlag[olsIdx].end(), 0));
+}
+Void TComVPS::checkNecessaryLayerFlagCondition()
+{
+  /* It is a requirement of bitstream conformance that for each layer index layerIdx in the range of 
+  ( vps_base_layer_internal_flag ? 0 : 1 ) to MaxLayersMinus1, inclusive, there shall be at least one OLS with index olsIdx such that 
+  NecessaryLayerFlag[ olsIdx ][ lsLayerIdx ] is equal to 1 for the value of lsLayerIdx 
+  for which LayerSetLayerIdList[ OlsIdxToLsIdx[ olsIdx ] ][ lsLayerIdx ] is equal to layer_id_in_nuh[ layerIdx ]. */
+  for(Int layerIdx = m_baseLayerInternalFlag ? 0 : 1; layerIdx < m_uiMaxLayers; layerIdx++)
+  {
+    Bool layerFoundNecessaryLayerFlag = false;
+    for(Int olsIdx = 0; olsIdx < m_numOutputLayerSets; olsIdx++)
+    {
+      Int lsIdx = m_outputLayerSetIdx[olsIdx];
+      Int currNuhLayerId = m_layerIdInNuh[layerIdx];
+      std::vector<Int>::iterator iter = std::find( m_layerSetLayerIdList[lsIdx].begin(), m_layerSetLayerIdList[lsIdx].end(), currNuhLayerId );
+      if( iter != m_layerSetLayerIdList[lsIdx].end() ) // Layer present in layer set
+      {
+        size_t positionLayer = iter - m_layerSetLayerIdList[lsIdx].begin();
+        if( *(m_necessaryLayerFlag[olsIdx].begin() + positionLayer) == true )
+        {
+          layerFoundNecessaryLayerFlag = true;
+          break;
+        }
+      }
+    }
+    assert( layerFoundNecessaryLayerFlag );
+  }
+}
+#endif
+#if PER_LAYER_PTL
+Int TComVPS::calculateLenOfSyntaxElement( Int const numVal )
+{
+  Int numBits = 1;
+  while((1 << numBits) < numVal)
+  {
+    numBits++;
+  }
+  return numBits;
+}
+#endif
+#if SUB_LAYERS_IN_LAYER_SET
+Void TComVPS::calculateMaxSLInLayerSets()
+{
+  for(Int lsIdx = 0; lsIdx < getNumLayerSets(); lsIdx++)
+  {
+    UInt maxSLMinus1 = 0;
+    for(Int k = 0; k < getNumLayersInIdList(lsIdx); k++ ) {
+      Int  lId = getLayerSetLayerIdList(lsIdx, k);
+      maxSLMinus1 = std::max(maxSLMinus1, getMaxTSLayersMinus1(getLayerIdxInVps(lId)));
+    }
+    setMaxSLayersInLayerSetMinus1(lsIdx,maxSLMinus1);
+  }
+}
+#endif
+
+#if RESOLUTION_BASED_DPB
+// RepFormat Assignment operator
+RepFormat& RepFormat::operator= (const RepFormat &other)
+{
+  if( this != &other)
+  {
+    m_chromaAndBitDepthVpsPresentFlag = other.m_chromaAndBitDepthVpsPresentFlag;
+    m_chromaFormatVpsIdc              = other.m_chromaFormatVpsIdc;
+    m_separateColourPlaneVpsFlag      = other.m_separateColourPlaneVpsFlag;
+    m_picWidthVpsInLumaSamples        = other.m_picWidthVpsInLumaSamples;
+    m_picHeightVpsInLumaSamples       = other.m_picHeightVpsInLumaSamples;
+    m_bitDepthVpsLuma                 = other.m_bitDepthVpsLuma;
+    m_bitDepthVpsChroma               = other.m_bitDepthVpsChroma;
+#if R0156_CONF_WINDOW_IN_REP_FORMAT
+    m_conformanceWindowVps            = other.m_conformanceWindowVps;
+#endif
+  }
+  return *this;
+}
+
+// Check whether x and y share the same resolution, chroma format and bit-depth.
+Bool RepFormat::checkSameSubDpb(const RepFormat &x, const RepFormat &y)
+{
+  return (    (x.m_chromaFormatVpsIdc              == y.m_chromaFormatVpsIdc)
+          &&  (x.m_picWidthVpsInLumaSamples        == y.m_picWidthVpsInLumaSamples)
+          &&  (x.m_picHeightVpsInLumaSamples       == y.m_picHeightVpsInLumaSamples)
+          &&  (x.m_bitDepthVpsLuma                 == y.m_bitDepthVpsLuma)
+          &&  (x.m_bitDepthVpsChroma               == y.m_bitDepthVpsChroma)
+          );
+}
+#endif
+
+#if REPN_FORMAT_IN_VPS
+UInt TComSlice::getPicWidthInLumaSamples()
+{
+  TComSPS *sps = getSPS();
+  TComVPS *vps = getVPS();
+  UInt retVal, layerId = getLayerId();
+#if O0096_REP_FORMAT_INDEX
+#if R0279_REP_FORMAT_INBL
+  if ( layerId == 0 || sps->getV1CompatibleSPSFlag() == 1 )
+  {
+#if VPS_AVC_BL_FLAG_REMOVAL
+    if( layerId == 0 && vps->getNonHEVCBaseLayerFlag() )
+#else
+    if( layerId == 0 && vps->getAvcBaseLayerFlag() )
+#endif
+#else
+  if ( layerId == 0 )
+  {
+    if( vps->getAvcBaseLayerFlag() )
+#endif
+    {
+      retVal = vps->getVpsRepFormat(layerId)->getPicWidthVpsInLumaSamples();
+    }
+    else
+    {
+      retVal = sps->getPicWidthInLumaSamples();
+    }
+  }
+  else
+  {
+    retVal = vps->getVpsRepFormat(sps->getUpdateRepFormatFlag() ? sps->getUpdateRepFormatIndex() : vps->getVpsRepFormatIdx(vps->getLayerIdxInVps(layerId)))->getPicWidthVpsInLumaSamples();
+  }
+#else
+  if( ( layerId == 0 ) || sps->getUpdateRepFormatFlag() )
+  {
+    retVal = sps->getPicWidthInLumaSamples();
+  }
+  else
+  {
+    retVal = vps->getVpsRepFormat( vps->getVpsRepFormatIdx(vps->getLayerIdxInVps(layerId)) )->getPicWidthVpsInLumaSamples();
+  }
+#endif
+  return retVal;
+}
+UInt TComSlice::getPicHeightInLumaSamples()
+{
+  TComSPS *sps = getSPS();
+  TComVPS *vps = getVPS();
+  UInt retVal, layerId = getLayerId();
+#if O0096_REP_FORMAT_INDEX
+#if R0279_REP_FORMAT_INBL
+  if ( layerId == 0 || sps->getV1CompatibleSPSFlag() == 1 )
+  {
+#if VPS_AVC_BL_FLAG_REMOVAL
+    if( layerId == 0 && vps->getNonHEVCBaseLayerFlag() )
+#else
+    if( layerId == 0 && vps->getAvcBaseLayerFlag() )
+#endif
+#else
+  if ( layerId == 0 )
+  {
+    if( vps->getAvcBaseLayerFlag() )
+#endif
+    {
+      retVal = vps->getVpsRepFormat(layerId)->getPicHeightVpsInLumaSamples();
+    }
+    else
+    {
+      retVal = sps->getPicHeightInLumaSamples();
+    }
+  }
+  else
+  {
+    retVal = vps->getVpsRepFormat(sps->getUpdateRepFormatFlag() ? sps->getUpdateRepFormatIndex() : vps->getVpsRepFormatIdx(vps->getLayerIdxInVps(layerId)))->getPicHeightVpsInLumaSamples();
+  }
+#else
+  if( ( layerId == 0 ) || sps->getUpdateRepFormatFlag() )
+  {
+    retVal = sps->getPicHeightInLumaSamples();
+  }
+  else
+  {
+    retVal = vps->getVpsRepFormat( vps->getVpsRepFormatIdx(vps->getLayerIdxInVps(layerId)) )->getPicHeightVpsInLumaSamples();
+  }
+#endif
+  return retVal;
+}
+#if AUXILIARY_PICTURES
+ChromaFormat TComSlice::getChromaFormatIdc()
+#else
+UInt TComSlice::getChromaFormatIdc()
+#endif
+{
+  TComSPS *sps = getSPS();
+  TComVPS *vps = getVPS();
+#if AUXILIARY_PICTURES
+  ChromaFormat retVal;
+  UInt layerId = getLayerId();
+#else
+  UInt retVal, layerId = getLayerId();
+#endif
+#if O0096_REP_FORMAT_INDEX
+#if R0279_REP_FORMAT_INBL
+  if ( layerId == 0 || sps->getV1CompatibleSPSFlag() == 1 )
+  {
+#if VPS_AVC_BL_FLAG_REMOVAL
+    if( layerId == 0 && vps->getNonHEVCBaseLayerFlag() )
+#else
+    if( layerId == 0 && vps->getAvcBaseLayerFlag() )
+#endif
+#else
+  if ( layerId == 0 )
+  {
+    if( vps->getAvcBaseLayerFlag() )
+#endif
+    {
+      retVal = vps->getVpsRepFormat(layerId)->getChromaFormatVpsIdc();
+    }
+    else
+    {
+      retVal = sps->getChromaFormatIdc();
+    }
+  }
+  else
+  {
+    retVal = vps->getVpsRepFormat(sps->getUpdateRepFormatFlag() ? sps->getUpdateRepFormatIndex() : vps->getVpsRepFormatIdx(vps->getLayerIdxInVps(layerId)))->getChromaFormatVpsIdc();
+  }
+#else
+  if( ( layerId == 0 ) || sps->getUpdateRepFormatFlag() )
+  {
+    retVal = sps->getChromaFormatIdc();
+  }
+  else
+  {
+    retVal = vps->getVpsRepFormat( vps->getVpsRepFormatIdx(vps->getLayerIdxInVps(layerId)) )->getChromaFormatVpsIdc();
+  }
+#endif
+  return retVal;
+}
+UInt TComSlice::getBitDepthY()
+{
+  TComSPS *sps = getSPS();
+  TComVPS *vps = getVPS();
+  UInt retVal, layerId = getLayerId();
+#if O0096_REP_FORMAT_INDEX
+#if R0279_REP_FORMAT_INBL
+  if ( layerId == 0 || sps->getV1CompatibleSPSFlag() == 1 )
+  {
+#else
+  if ( layerId == 0 )
+  {
+#endif
+#if VPS_AVC_BL_FLAG_REMOVAL
+    if( layerId == 0 && vps->getNonHEVCBaseLayerFlag() )
+#else
+    if( layerId == 0 && vps->getAvcBaseLayerFlag() )
+#endif
+    {
+      retVal = vps->getVpsRepFormat(layerId)->getBitDepthVpsLuma();
+    }
+    else
+    {
+      retVal = sps->getBitDepth(CHANNEL_TYPE_LUMA);
+    }
+  }
+  else
+  {
+    retVal = vps->getVpsRepFormat(sps->getUpdateRepFormatFlag() ? sps->getUpdateRepFormatIndex() : vps->getVpsRepFormatIdx(vps->getLayerIdxInVps(layerId)))->getBitDepthVpsLuma();
+  }
+#else
+  if( ( layerId == 0 ) || sps->getUpdateRepFormatFlag() )
+  {
+    retVal = sps->getBitDepthY();
+  }
+  else
+  {
+    retVal = vps->getVpsRepFormat( vps->getVpsRepFormatIdx(vps->getLayerIdxInVps(layerId)) )->getBitDepthVpsLuma();
+  }
+#endif
+  return retVal;
+}
+UInt TComSlice::getBitDepthC()
+{
+  TComSPS *sps = getSPS();
+  TComVPS *vps = getVPS();
+  UInt retVal, layerId = getLayerId();
+#if O0096_REP_FORMAT_INDEX
+#if R0279_REP_FORMAT_INBL
+  if ( layerId == 0 || sps->getV1CompatibleSPSFlag() == 1 )
+  {
+#else
+  if ( layerId == 0 )
+  {
+#endif
+#if VPS_AVC_BL_FLAG_REMOVAL
+    if( layerId == 0 && vps->getNonHEVCBaseLayerFlag() )
+#else
+    if( layerId == 0 && vps->getAvcBaseLayerFlag() )
+#endif
+    {
+      retVal = vps->getVpsRepFormat(layerId)->getBitDepthVpsChroma();
+    }
+    else
+    {
+      retVal = sps->getBitDepth(CHANNEL_TYPE_CHROMA);
+    }
+  }
+  else
+  {
+    retVal = vps->getVpsRepFormat(sps->getUpdateRepFormatFlag() ? sps->getUpdateRepFormatIndex() : vps->getVpsRepFormatIdx(vps->getLayerIdxInVps(layerId)))->getBitDepthVpsChroma();
+  }
+#else
+  if( ( layerId == 0 ) || sps->getUpdateRepFormatFlag() )
+  {
+    retVal = sps->getBitDepth(CHANNEL_TYPE_CHROMA);
+  }
+  else
+  {
+    retVal = vps->getVpsRepFormat( vps->getVpsRepFormatIdx(vps->getLayerIdxInVps(layerId)) )->getBitDepthVpsChroma();
+  }
+#endif
+  return retVal;
+}
+Int TComSlice::getQpBDOffsetY()
+{
+  return (getBitDepthY() - 8) * 6;
+}
+Int TComSlice::getQpBDOffsetC()
+{
+  return (getBitDepthC() - 8) * 6;
+}
+
+#if R0156_CONF_WINDOW_IN_REP_FORMAT
+Window& TComSlice::getConformanceWindow()
+{
+  TComSPS *sps = getSPS();
+  TComVPS *vps = getVPS();
+  UInt layerId = getLayerId();
+#if O0096_REP_FORMAT_INDEX
+#if R0279_REP_FORMAT_INBL
+  if ( layerId == 0 || sps->getV1CompatibleSPSFlag() == 1 )
+  {
+#if VPS_AVC_BL_FLAG_REMOVAL
+    if( layerId == 0 && vps->getNonHEVCBaseLayerFlag() )
+#else
+    if( layerId == 0 && vps->getAvcBaseLayerFlag() )
+#endif
+#else
+  if ( layerId == 0 )
+  {
+    if( vps->getAvcBaseLayerFlag() )
+#endif
+    {
+      return vps->getVpsRepFormat(layerId)->getConformanceWindowVps();
+    }
+    else
+    {
+      return sps->getConformanceWindow();
+    }
+  }
+  else
+  {
+    return vps->getVpsRepFormat(sps->getUpdateRepFormatFlag() ? sps->getUpdateRepFormatIndex() : vps->getVpsRepFormatIdx(vps->getLayerIdxInVps(layerId)))->getConformanceWindowVps();
+  }
+#else
+  if( ( layerId == 0 ) || sps->getUpdateRepFormatFlag() )
+  {
+    return sps->getConformanceWindow();
+  }
+  else
+  {
+    return vps->getVpsRepFormat( vps->getVpsRepFormatIdx(vps->getLayerIdxInVps(vps->getLayerIdxInVps(layerId))) )->getConformanceWindowVps();
+  }
+#endif
+}
+#endif
+
+RepFormat::RepFormat()
+#if AUXILIARY_PICTURES
+: m_chromaFormatVpsIdc          (CHROMA_420)
+#else
+: m_chromaFormatVpsIdc          (0)
+#endif
+, m_separateColourPlaneVpsFlag  (false)
+, m_picWidthVpsInLumaSamples    (0)
+, m_picHeightVpsInLumaSamples   (0)
+, m_bitDepthVpsLuma             (0)
+, m_bitDepthVpsChroma           (0)
+{}
+#if RESOLUTION_BASED_DPB
+Void RepFormat::init()
+{
+  m_chromaFormatVpsIdc          = CHROMA_420;
+  m_separateColourPlaneVpsFlag  = false;
+  m_picWidthVpsInLumaSamples    = 0;
+  m_picHeightVpsInLumaSamples   = 0;
+  m_bitDepthVpsLuma             = 0;
+  m_bitDepthVpsChroma           = 0;
+#if R0156_CONF_WINDOW_IN_REP_FORMAT
+  m_conformanceWindowVps.resetWindow();
+#endif
+}
+#endif
+#endif
+
+#if VPS_EXTN_PROFILE_INFO
+Void TComPTL::copyProfileInfo(TComPTL *ptl)
+{
+  // Copy all information related to general profile
+  this->getGeneralPTL()->copyProfileInfo(ptl->getGeneralPTL());
+}
+#endif
+
+#if SVC_EXTENSION
+Bool TComSlice::setBaseColPic(  TComList<TComPic*>& rcListPic, UInt refLayerIdc )
+{  
+  if(m_layerId == 0)
+  {
+    memset( m_pcBaseColPic, 0, sizeof( m_pcBaseColPic ) );
+    return false;
+  }        
+#if POC_RESET_FLAG || POC_RESET_IDC_DECODER
+#if POC_RESET_IDC_DECODER
+  TComPic* pic = xGetRefPic( rcListPic, getPOC() );
+#else
+  TComPic* pic = xGetRefPic( rcListPic, m_bPocResetFlag ? 0 : m_iPOC );
+#endif
+
+  if( pic )
+  {
+    setBaseColPic(refLayerIdc, pic );
+  }
+  else
+  {
+    return false;
+  }
+  
+  return true;
+#else
+  setBaseColPic(refLayerIdc, xGetRefPic(rcListPic, getPOC()));
+  return true;
+#endif
+}
+
+#if MFM_ENCCONSTRAINT
+TComPic* TComSlice::getBaseColPic(  TComList<TComPic*>& rcListPic )
+{
+#if POC_RESET_FLAG
+  return xGetRefPic( rcListPic, m_bPocResetFlag ? 0 : m_iPOC );
+#else
+  return xGetRefPic( rcListPic, m_iPOC );
+#endif
+}
+#endif
+
+Void TComSlice::setILRPic(TComPic **pcIlpPic)
+{
+  for( Int i = 0; i < m_activeNumILRRefIdx; i++ )
+  {
+    Int refLayerIdc = m_interLayerPredLayerIdc[i];
+
+    if( pcIlpPic[refLayerIdc] )
+    {
+      TComPic* pcRefPicBL = m_pcBaseColPic[refLayerIdc];
+
+      // copy scalability ratio, it is needed to get the correct location for the motion field of the corresponding reference layer block
+      pcIlpPic[refLayerIdc]->setSpatialEnhLayerFlag( refLayerIdc, m_pcPic->isSpatialEnhLayer(refLayerIdc) );
+
+      pcIlpPic[refLayerIdc]->copyUpsampledPictureYuv( m_pcPic->getFullPelBaseRec( refLayerIdc ), pcIlpPic[refLayerIdc]->getPicYuvRec() );      
+      pcIlpPic[refLayerIdc]->getSlice(0)->setBaseColPic( refLayerIdc, pcRefPicBL );
+
+      //set reference picture POC of each ILP reference 
+      pcIlpPic[refLayerIdc]->getSlice(0)->setPOC( m_iPOC );
+
+      //set temporal Id 
+      pcIlpPic[refLayerIdc]->getSlice(0)->setTLayer( m_uiTLayer );
+
+      //copy layer id from the reference layer 
+      pcIlpPic[refLayerIdc]->setLayerId( pcRefPicBL->getLayerId() );
+      pcIlpPic[refLayerIdc]->getSlice(0)->setLayerId(pcRefPicBL->getLayerId());
+
+      pcIlpPic[refLayerIdc]->getPicYuvRec()->setBorderExtension( false );
+      pcIlpPic[refLayerIdc]->getPicYuvRec()->extendPicBorder();
+      for (Int j=0; j<pcIlpPic[refLayerIdc]->getPicSym()->getNumberOfCtusInFrame(); j++)    // set reference CU layerId
+      {
+        pcIlpPic[refLayerIdc]->getPicSym()->getCtu(j)->setLayerId( pcIlpPic[refLayerIdc]->getLayerId() );
+      }
+      pcIlpPic[refLayerIdc]->setIsLongTerm(1);
+
+      // assign PPS to ILRP to be used for reference location offsets
+      pcIlpPic[refLayerIdc]->getSlice(0)->setPPS( m_pcPic->getSlice(0)->getPPS() );
+
+      // assing VPS to ILRP to be used for deriving layerIdx
+      pcIlpPic[refLayerIdc]->getSlice(0)->setVPS( m_pcPic->getSlice(0)->getVPS() );
+
+#if REF_IDX_MFM
+      if( m_bMFMEnabledFlag && !(m_eNalUnitType >= NAL_UNIT_CODED_SLICE_BLA_W_LP && m_eNalUnitType <= NAL_UNIT_CODED_SLICE_CRA) )
+      {
+        //set reference picture POC of each ILP reference 
+        assert( pcIlpPic[refLayerIdc]->getPOC() == pcRefPicBL->getPOC() );
+
+        //copy slice type from the reference layer
+        pcIlpPic[refLayerIdc]->getSlice(0)->setSliceType( pcRefPicBL->getSlice(0)->getSliceType() );
+
+        //copy "used for reference"
+        pcIlpPic[refLayerIdc]->getSlice(0)->setReferenced( pcRefPicBL->getSlice(0)->isReferenced() );
+
+        for( Int refList = 0; refList < 2; refList++ )
+        {
+          RefPicList refPicList = RefPicList( refList );
+
+          //set reference POC of ILP
+          pcIlpPic[refLayerIdc]->getSlice(0)->setNumRefIdx(refPicList, pcRefPicBL->getSlice(0)->getNumRefIdx(refPicList));
+          assert(pcIlpPic[refLayerIdc]->getSlice(0)->getNumRefIdx(refPicList) >= 0);
+          assert(pcIlpPic[refLayerIdc]->getSlice(0)->getNumRefIdx(refPicList) <= MAX_NUM_REF);
+
+          //initialize reference POC of ILP
+          for(Int refIdx = 0; refIdx < pcRefPicBL->getSlice(0)->getNumRefIdx(refPicList); refIdx++)
+          {
+            pcIlpPic[refLayerIdc]->getSlice(0)->setRefPOC(pcRefPicBL->getSlice(0)->getRefPOC(refPicList, refIdx), refPicList, refIdx);
+            pcIlpPic[refLayerIdc]->getSlice(0)->setRefPic(pcRefPicBL->getSlice(0)->getRefPic(refPicList, refIdx), refPicList, refIdx);
+          }
+
+          for(Int refIdx = pcRefPicBL->getSlice(0)->getNumRefIdx(refPicList); refIdx < MAX_NUM_REF; refIdx++) 
+          { 
+            pcIlpPic[refLayerIdc]->getSlice(0)->setRefPOC(0, refPicList, refIdx); 
+            pcIlpPic[refLayerIdc]->getSlice(0)->setRefPic(NULL, refPicList, refIdx); 
+          }
+
+          //copy reference pictures' marking from the reference layer
+          for(Int j = 0; j < MAX_NUM_REF + 1; j++)
+          {
+            pcIlpPic[refLayerIdc]->getSlice(0)->setIsUsedAsLongTerm(refList, j, pcRefPicBL->getSlice(0)->getIsUsedAsLongTerm(refList, j));
+          }
+        }
+
+        pcIlpPic[refLayerIdc]->copyUpsampledMvField( refLayerIdc, m_pcBaseColPic[refLayerIdc] );
+      }
+      else
+      {
+        pcIlpPic[refLayerIdc]->initUpsampledMvField();
+      }
+#endif
+
+      Int maxTidIlRefPicsPlus1 = m_pcVPS->getMaxTidIlRefPicsPlus1( pcIlpPic[refLayerIdc]->getSlice(0)->getLayerIdx(), getLayerIdx() );
+      assert( (Int)pcIlpPic[refLayerIdc]->getSlice(0)->getTLayer() < maxTidIlRefPicsPlus1 || ( !maxTidIlRefPicsPlus1 && pcIlpPic[refLayerIdc]->getSlice(0)->getRapPicFlag() ) );
+
+    }
+  }
+}
+
+Int TComSlice::getReferenceLayerIdc( UInt refLayerId )
+{ 
+  for( Int i = 0; i < m_activeNumILRRefIdx; i++ )
+  {
+    if( m_pcVPS->getRefLayerId(m_layerId, m_interLayerPredLayerIdc[i]) == refLayerId )
+    {
+      return m_interLayerPredLayerIdc[i];
+    }
+  }
+
+  return -1;
+}
+
+#if NO_OUTPUT_OF_PRIOR_PICS
+Bool TComSlice::getBlaPicFlag       ()
+{
+    return  getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_N_LP
+    || getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_RADL
+    || getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_LP;
+}
+Bool TComSlice::getCraPicFlag       ()
+{
+    return getNalUnitType() == NAL_UNIT_CODED_SLICE_CRA;
+}
+#endif
+#if POC_RESET_IDC_DECODER
+Bool TComSlice::getRaslPicFlag      ()
+{
+  return  getNalUnitType() == NAL_UNIT_CODED_SLICE_RASL_R
+  || getNalUnitType() == NAL_UNIT_CODED_SLICE_RASL_N;
+}
+Bool TComSlice::getRadlPicFlag      ()
+{
+  return  getNalUnitType() == NAL_UNIT_CODED_SLICE_RADL_R
+  || getNalUnitType() == NAL_UNIT_CODED_SLICE_RADL_N;
+}
+#endif
+#if POC_RESET_IDC_ENCODER
+Void TComSlice::decrementRefPocValues(Int const decrementValue)
+{
+  for(Int listNum = 0; listNum < 2; listNum++)
+  {
+    RefPicList dpbPicSliceList = (listNum == 1) ? REF_PIC_LIST_1 : REF_PIC_LIST_0;
+    for(Int listIdx = 0; listIdx < getNumRefIdx( dpbPicSliceList ); listIdx++)
+    {
+      setRefPOC( getRefPOC(dpbPicSliceList, listIdx) - decrementValue, 
+                  dpbPicSliceList,
+                  listIdx
+                  );
+    }
+  }
+}
+
+Int TComSlice::getCurrMsb( Int currLsb, Int prevLsb, Int prevMsb, Int maxLsbVal )
+{
+  if( prevLsb - currLsb >= (maxLsbVal >> 1) )
+  {
+    return prevMsb + maxLsbVal;
+  }
+  else if( currLsb - prevLsb > (maxLsbVal >> 1) )
+  {
+    return prevMsb - maxLsbVal;
+  }
+  else
+  {
+    return prevMsb;
+  }
+}
+#endif
+
+Void TComSlice::setRefPicListModificationSvc()
+{
+  if( !m_pcPPS->getListsModificationPresentFlag()) 
+  {
+    return;
+  }
+
+  if(m_eNalUnitType >= NAL_UNIT_CODED_SLICE_BLA_W_LP && m_eNalUnitType <= NAL_UNIT_CODED_SLICE_CRA)
+  {
+    return;
+  }
+
+  TComRefPicListModification* refPicListModification = &m_RefPicListModification;
+  Int numberOfRpsCurrTempList = this->getNumRpsCurrTempList();  // total number of ref pics in listTemp0 including inter-layer ref pics
+#if RPL_INIT_N0316_N0082
+  Int numberOfPocBeforeCurr = this->getNumNegativeRpsCurrTempList();  // number of negative temporal ref pics 
+#endif
+
+  assert(m_aiNumRefIdx[REF_PIC_LIST_0] > 0);
+  assert(m_aiNumRefIdx[REF_PIC_LIST_1] > 0);
+
+  //set L0 inter-layer reference picture modification
+#if RPL_INIT_N0316_N0082
+  Bool hasModification = (m_aiNumRefIdx[REF_PIC_LIST_0] == (numberOfPocBeforeCurr + m_activeNumILRRefIdx)) ? false : true;
+
+  if( m_activeNumILRRefIdx > 1 )
+  {
+    hasModification = (m_aiNumRefIdx[REF_PIC_LIST_0] >= (numberOfPocBeforeCurr + m_activeNumILRRefIdx)) ? false : true;
+  }
+#else
+  Bool hasModification = (m_aiNumRefIdx[REF_PIC_LIST_0] == numberOfRpsCurrTempList) ? false : true;
+#endif
+  hasModification = hasModification && ( m_aiNumRefIdx[REF_PIC_LIST_0] > 1 );
+  refPicListModification->setRefPicListModificationFlagL0(hasModification);
+  if(hasModification)
+  { 
+    for(Int i = 0; i < min(m_aiNumRefIdx[REF_PIC_LIST_0], numberOfRpsCurrTempList); i++)
+    {
+      refPicListModification->setRefPicSetIdxL0(i, i);
+    }
+
+    if(m_aiNumRefIdx[REF_PIC_LIST_0] > numberOfRpsCurrTempList)
+    {
+      // repeat last ref pic when the number of active ref idx are more than RPS entries
+      for (Int i = numberOfRpsCurrTempList; i < m_aiNumRefIdx[REF_PIC_LIST_0]; i ++)
+      {
+        refPicListModification->setRefPicSetIdxL0(i, numberOfRpsCurrTempList - 1);
+      }
+    }
+    else
+    {
+      // number of ILRPs included into the reference picture list with the list modification
+      Int includeNumILRP = min( max(1, m_aiNumRefIdx[REF_PIC_LIST_0]-numberOfPocBeforeCurr), m_activeNumILRRefIdx);
+
+      for(Int i = includeNumILRP; i > 0; i-- )
+      {
+#if RPL_INIT_N0316_N0082
+        if((numberOfPocBeforeCurr) >= m_aiNumRefIdx[REF_PIC_LIST_0])
+        {
+          refPicListModification->setRefPicSetIdxL0(m_aiNumRefIdx[REF_PIC_LIST_0] - i, numberOfPocBeforeCurr + includeNumILRP - i);
+        }
+        else
+        {
+          refPicListModification->setRefPicSetIdxL0(m_aiNumRefIdx[REF_PIC_LIST_0] - i, numberOfPocBeforeCurr + includeNumILRP - i);
+          for (Int j = numberOfPocBeforeCurr; j < (m_aiNumRefIdx[REF_PIC_LIST_0] - i); j++)
+          {
+            assert( j + includeNumILRP < numberOfRpsCurrTempList );
+            refPicListModification->setRefPicSetIdxL0(j, j + includeNumILRP);
+          }
+        }
+#else
+        refPicListModification->setRefPicSetIdxL0(m_aiNumRefIdx[REF_PIC_LIST_0] - i, numberOfRpsCurrTempList - i);
+#endif
+      }
+    }
+  }
+
+  //set L1 inter-layer reference picture modification
+  hasModification = (m_aiNumRefIdx[REF_PIC_LIST_1] >= numberOfRpsCurrTempList) ? false : true;
+  hasModification = hasModification && ( m_aiNumRefIdx[REF_PIC_LIST_1] > 1 );
+
+  refPicListModification->setRefPicListModificationFlagL1(hasModification);
+  if(hasModification)
+  { 
+    for(Int i = 0; i < min(m_aiNumRefIdx[REF_PIC_LIST_1], numberOfRpsCurrTempList); i++)
+    {
+      refPicListModification->setRefPicSetIdxL1(i, i);
+    }
+    if(m_aiNumRefIdx[REF_PIC_LIST_1] > numberOfRpsCurrTempList)
+    {
+      for (Int i = numberOfRpsCurrTempList; i < m_aiNumRefIdx[REF_PIC_LIST_1]; i ++)
+      {
+        // repeat last ref pic when the number of active ref idx are more than RPS entries
+        refPicListModification->setRefPicSetIdxL1(i, numberOfRpsCurrTempList - 1);  
+      }
+    }
+    else
+    {
+      Int includeNumILRP = min(m_aiNumRefIdx[REF_PIC_LIST_1], m_activeNumILRRefIdx);
+
+      for(Int i = includeNumILRP; i > 0; i-- )
+      {
+        refPicListModification->setRefPicSetIdxL1(m_aiNumRefIdx[REF_PIC_LIST_1] - i, numberOfRpsCurrTempList - i);
+      }
+    }
+  }
+  return;
+}
+
+#if RPL_INIT_N0316_N0082
+Int TComSlice::getNumNegativeRpsCurrTempList()
+{
+  if( m_eSliceType == I_SLICE ) 
+  {
+    return 0;
+  }
+
+  Int numPocBeforeCurr = 0;
+  for( UInt i = 0; i < m_pcRPS->getNumberOfNegativePictures(); i++ )
+  {
+    if(m_pcRPS->getUsed(i))
+    {
+      numPocBeforeCurr++;
+    }
+  }
+
+  return numPocBeforeCurr;
+}
+#endif
+#endif //SVC_EXTENSION
+
+//! \}
Index: /tags/SHM-9.0/source/Lib/TLibCommon/TComSlice.h
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibCommon/TComSlice.h	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibCommon/TComSlice.h	(revision 1088)
@@ -0,0 +1,2954 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TComSlice.h
+    \brief    slice header and SPS class (header)
+*/
+
+#ifndef __TCOMSLICE__
+#define __TCOMSLICE__
+
+#include <cstring>
+#include <map>
+#include <vector>
+#include "CommonDef.h"
+#include "TComRom.h"
+#include "TComList.h"
+#include "TComChromaFormat.h"
+
+//! \ingroup TLibCommon
+//! \{
+
+class TComPic;
+class TComTrQuant;
+
+#if SVC_EXTENSION
+class TComPicYuv;
+#endif
+// ====================================================================================================================
+// Constants
+// ====================================================================================================================
+
+static const UInt REF_PIC_LIST_NUM_IDX=32;
+
+// ====================================================================================================================
+// 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; }
+  Int*           getScalingListAddress    (UInt sizeId, UInt listId)           { return m_scalingListCoef[sizeId][listId]; } //!< get matrix coefficient
+  const Int*     getScalingListAddress    (UInt sizeId, UInt listId) const     { return m_scalingListCoef[sizeId][listId]; } //!< get matrix coefficient
+  Bool     checkPredMode                  (UInt sizeId, UInt listId);
+  Void     setRefMatrixId                 (UInt sizeId, UInt listId, UInt u)   { m_refMatrixId[sizeId][listId] = u;    }     //!< set reference matrix ID
+  UInt     getRefMatrixId                 (UInt sizeId, UInt listId)           { return m_refMatrixId[sizeId][listId]; }     //!< get reference matrix ID
+  Int*     getScalingListDefaultAddress   (UInt sizeId, UInt listId);                                                        //!< get default matrix coefficient
+  Void     processDefaultMatrix           (UInt sizeId, UInt listId);
+  Void     setScalingListDC               (UInt sizeId, UInt listId, UInt u)   { m_scalingListDC[sizeId][listId] = u; }      //!< set DC value
+
+  Int      getScalingListDC               (UInt sizeId, UInt listId) const     { 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                 ();
+  Void     outputScalingLists(std::ostream &os) const;
+  Int      m_scalingListDC               [SCALING_LIST_SIZE_NUM][SCALING_LIST_NUM]; //!< the DC value of the matrix coefficient for 16x16
+  Bool     m_useDefaultScalingMatrixFlag [SCALING_LIST_SIZE_NUM][SCALING_LIST_NUM]; //!< UseDefaultScalingMatrixFlag
+  UInt     m_refMatrixId                 [SCALING_LIST_SIZE_NUM][SCALING_LIST_NUM]; //!< RefMatrixID
+  Bool     m_scalingListPresentFlag;                                                //!< flag for using default matrix
+  UInt     m_predMatrixId                [SCALING_LIST_SIZE_NUM][SCALING_LIST_NUM]; //!< reference list index
+  Int      *m_scalingListCoef            [SCALING_LIST_SIZE_NUM][SCALING_LIST_NUM]; //!< quantization matrix
+};
+
+class ProfileTierLevel
+{
+  Int               m_profileSpace;
+  Level::Tier       m_tierFlag;
+  Profile::Name     m_profileIdc;
+  Bool              m_profileCompatibilityFlag[32];
+  Level::Name       m_levelIdc;
+
+  Bool              m_progressiveSourceFlag;
+  Bool              m_interlacedSourceFlag;
+  Bool              m_nonPackedConstraintFlag;
+  Bool              m_frameOnlyConstraintFlag;
+  UInt              m_bitDepthConstraintValue;
+  ChromaFormat      m_chromaFormatConstraintValue;
+  Bool              m_intraConstraintFlag;
+  Bool              m_lowerBitRateConstraintFlag;
+
+public:
+  ProfileTierLevel();
+
+  Int  getProfileSpace() const                     { return m_profileSpace; }
+  Void setProfileSpace(Int x)                      { m_profileSpace = x; }
+
+  Level::Tier  getTierFlag() const                 { return m_tierFlag; }
+  Void setTierFlag(Level::Tier x)                  { m_tierFlag = x; }
+
+  Profile::Name   getProfileIdc() const            { return m_profileIdc; }
+  Void setProfileIdc(Profile::Name x)              { m_profileIdc = x; }
+
+  Bool getProfileCompatibilityFlag(Int i) const    { return m_profileCompatibilityFlag[i]; }
+  Void setProfileCompatibilityFlag(Int i, Bool x)  { m_profileCompatibilityFlag[i] = x; }
+
+  Level::Name   getLevelIdc() const                { return m_levelIdc; }
+  Void setLevelIdc(Level::Name 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; }
+
+  UInt getBitDepthConstraint() const               { return m_bitDepthConstraintValue; }
+  Void setBitDepthConstraint(UInt bitDepth)        { m_bitDepthConstraintValue=bitDepth; }
+
+  ChromaFormat getChromaFormatConstraint() const   { return m_chromaFormatConstraintValue; }
+  Void setChromaFormatConstraint(ChromaFormat fmt) { m_chromaFormatConstraintValue=fmt; }
+
+  Bool getIntraConstraintFlag() const              { return m_intraConstraintFlag; }
+  Void setIntraConstraintFlag(Bool b)              { m_intraConstraintFlag = b; }
+
+  Bool getLowerBitRateConstraintFlag() const       { return m_lowerBitRateConstraintFlag; }
+  Void setLowerBitRateConstraintFlag(Bool b)       { m_lowerBitRateConstraintFlag = b; }
+
+#if VPS_EXTN_PROFILE_INFO
+  Void copyProfileInfo(ProfileTierLevel *ptl);
+#endif
+};
+
+
+class TComPTL
+{
+  ProfileTierLevel m_generalPTL;
+  ProfileTierLevel m_subLayerPTL    [MAX_TLAYER-1];      // max. value of max_sub_layers_minus1 is MAX_TLAYER-1 (= 6)
+  Bool m_subLayerProfilePresentFlag [MAX_TLAYER-1];
+  Bool m_subLayerLevelPresentFlag   [MAX_TLAYER-1];
+
+public:
+  TComPTL();
+  Bool getSubLayerProfilePresentFlag(Int i) const { return m_subLayerProfilePresentFlag[i]; }
+  Void setSubLayerProfilePresentFlag(Int i, Bool x) { m_subLayerProfilePresentFlag[i] = x; }
+
+  Bool getSubLayerLevelPresentFlag(Int i) const { return m_subLayerLevelPresentFlag[i]; }
+  Void setSubLayerLevelPresentFlag(Int i, Bool x) { m_subLayerLevelPresentFlag[i] = x; }
+
+  ProfileTierLevel* getGeneralPTL()  { return &m_generalPTL; }
+  ProfileTierLevel* getSubLayerPTL(Int i)  { return &m_subLayerPTL[i]; }
+
+#if VPS_EXTN_PROFILE_INFO
+  Void copyProfileInfo(TComPTL *ptl);
+#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(23)
+  ,m_cpbRemovalDelayLengthMinus1(23)
+  ,m_dpbOutputDelayLengthMinus1(23)
+  {}
+
+  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(); }
+
+#if VPS_VUI_BSP_HRD_PARAMS
+Void copyCommonInformation( TComHRD *refHrd )
+{
+  m_nalHrdParametersPresentFlag         = refHrd->getNalHrdParametersPresentFlag();
+  m_vclHrdParametersPresentFlag         = refHrd->getVclHrdParametersPresentFlag();
+  m_subPicCpbParamsPresentFlag          = refHrd->getSubPicCpbParamsPresentFlag();
+  m_tickDivisorMinus2                   = refHrd->getTickDivisorMinus2();
+  m_duCpbRemovalDelayLengthMinus1       = refHrd->getDuCpbRemovalDelayLengthMinus1();
+  m_subPicCpbParamsInPicTimingSEIFlag   = refHrd->getSubPicCpbParamsInPicTimingSEIFlag();
+  m_dpbOutputDelayDuLengthMinus1        = refHrd->getDpbOutputDelayDuLengthMinus1();
+  m_bitRateScale                        = refHrd->getBitRateScale();
+  m_cpbSizeScale                        = refHrd->getCpbSizeScale();
+  m_ducpbSizeScale                      = refHrd->getDuCpbSizeScale();
+  m_initialCpbRemovalDelayLengthMinus1  = refHrd->getInitialCpbRemovalDelayLengthMinus1();
+  m_cpbRemovalDelayLengthMinus1         = refHrd->getCpbRemovalDelayLengthMinus1();
+  m_dpbOutputDelayLengthMinus1          = refHrd->getDpbOutputDelayLengthMinus1();
+}
+#endif
+};
+
+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;               }
+};
+
+struct ChromaQpAdj
+{
+  union
+  {
+    struct {
+      Int CbOffset;
+      Int CrOffset;
+    } comp;
+    Int offset[2]; /* two chroma components */
+  } u;
+};
+
+
+class Window
+{
+private:
+  Bool          m_enabledFlag;
+  Int           m_winLeftOffset;
+  Int           m_winRightOffset;
+  Int           m_winTopOffset;
+  Int           m_winBottomOffset;
+#if P0312_VERT_PHASE_ADJ
+  Bool          m_vertPhasePositionEnableFlag;
+#endif
+public:
+  Window()
+  : m_enabledFlag (false)
+  , m_winLeftOffset     (0)
+  , m_winRightOffset    (0)
+  , m_winTopOffset      (0)
+  , m_winBottomOffset   (0)
+#if P0312_VERT_PHASE_ADJ
+  , m_vertPhasePositionEnableFlag(false)  
+#endif
+  { }
+
+  Bool          getWindowEnabledFlag() const      { return m_enabledFlag; }
+#if P0312_VERT_PHASE_ADJ
+  Void          resetWindow()                     { m_enabledFlag = false; m_winLeftOffset = m_winRightOffset = m_winTopOffset = m_winBottomOffset = 0; m_vertPhasePositionEnableFlag = false; } 
+#else
+  Void          resetWindow()                     { m_enabledFlag = false; m_winLeftOffset = m_winRightOffset = m_winTopOffset = m_winBottomOffset = 0; }
+#endif
+  Int           getWindowLeftOffset() const       { return m_enabledFlag ? m_winLeftOffset : 0; }
+  Void          setWindowLeftOffset(Int val)      { m_winLeftOffset = val; m_enabledFlag = true; }
+  Int           getWindowRightOffset() const      { return m_enabledFlag ? m_winRightOffset : 0; }
+  Void          setWindowRightOffset(Int val)     { m_winRightOffset = val; m_enabledFlag = true; }
+  Int           getWindowTopOffset() const        { return m_enabledFlag ? m_winTopOffset : 0; }
+  Void          setWindowTopOffset(Int val)       { m_winTopOffset = val; m_enabledFlag = true; }
+  Int           getWindowBottomOffset() const     { return m_enabledFlag ? m_winBottomOffset: 0; }
+  Void          setWindowBottomOffset(Int val)    { m_winBottomOffset = val; m_enabledFlag = true; }
+
+#if P0312_VERT_PHASE_ADJ
+  Bool          getVertPhasePositionEnableFlag() const     { return m_vertPhasePositionEnableFlag;  }
+  Void          setVertPhasePositionEnableFlag(Bool val)    { m_vertPhasePositionEnableFlag = val;  }
+#endif
+#if REF_REGION_OFFSET && RESAMPLING_FIX
+  Bool          hasEqualOffset(const Window& ref) const
+  {
+    return (    this->getWindowLeftOffset()   == ref.getWindowLeftOffset()
+             && this->getWindowTopOffset()    == ref.getWindowTopOffset()
+             && this->getWindowRightOffset()  == ref.getWindowRightOffset()
+             && this->getWindowBottomOffset() == ref.getWindowBottomOffset() );
+  }
+#endif
+
+#if P0312_VERT_PHASE_ADJ
+  Void          setWindow(Int offsetLeft, Int offsetLRight, Int offsetLTop, Int offsetLBottom, Bool vertPhasePositionEnableFlag = 0)
+#else
+  Void          setWindow(Int offsetLeft, Int offsetLRight, Int offsetLTop, Int offsetLBottom)
+#endif
+  {
+    m_enabledFlag       = true;
+    m_winLeftOffset     = offsetLeft;
+    m_winRightOffset    = offsetLRight;
+    m_winTopOffset      = offsetLTop;
+    m_winBottomOffset   = offsetLBottom;
+
+#if P0312_VERT_PHASE_ADJ
+    m_vertPhasePositionEnableFlag = vertPhasePositionEnableFlag;    
+#endif
+  }
+};
+
+#if REPN_FORMAT_IN_VPS
+class RepFormat
+{
+#if REPN_FORMAT_CONTROL_FLAG
+  Bool m_chromaAndBitDepthVpsPresentFlag;
+#endif 
+#if AUXILIARY_PICTURES
+  ChromaFormat m_chromaFormatVpsIdc;
+#else
+  Int  m_chromaFormatVpsIdc;
+#endif
+  Bool m_separateColourPlaneVpsFlag;
+  Int  m_picWidthVpsInLumaSamples;
+  Int  m_picHeightVpsInLumaSamples;
+  Int  m_bitDepthVpsLuma;               // coded as minus8
+  Int  m_bitDepthVpsChroma;             // coded as minus8
+
+#if R0156_CONF_WINDOW_IN_REP_FORMAT
+  Window m_conformanceWindowVps;
+#endif
+
+public:
+  RepFormat();
+#if RESOLUTION_BASED_DPB
+  Void init();
+  RepFormat& operator= (const RepFormat &);
+  static Bool checkSameSubDpb(const RepFormat &x, const RepFormat &y);
+#endif
+#if REPN_FORMAT_CONTROL_FLAG
+  Bool getChromaAndBitDepthVpsPresentFlag() { return m_chromaAndBitDepthVpsPresentFlag; }
+  void setChromaAndBitDepthVpsPresentFlag(Bool x) { m_chromaAndBitDepthVpsPresentFlag = x; }
+#endif 
+
+#if AUXILIARY_PICTURES
+  ChromaFormat getChromaFormatVpsIdc()        { return m_chromaFormatVpsIdc; }
+  Void setChromaFormatVpsIdc(ChromaFormat x)  { m_chromaFormatVpsIdc = x;    }
+#else
+  Int  getChromaFormatVpsIdc()        { return m_chromaFormatVpsIdc; }
+  Void setChromaFormatVpsIdc(Int x)   { m_chromaFormatVpsIdc = x;    }
+#endif
+
+  Bool getSeparateColourPlaneVpsFlag()        { return m_separateColourPlaneVpsFlag; }
+  Void setSeparateColourPlaneVpsFlag(Bool x)  { m_separateColourPlaneVpsFlag = x;    }
+
+  Int  getPicWidthVpsInLumaSamples()        { return m_picWidthVpsInLumaSamples; }
+  Void setPicWidthVpsInLumaSamples(Int x)   { m_picWidthVpsInLumaSamples = x;    }
+
+  Int  getPicHeightVpsInLumaSamples()        { return m_picHeightVpsInLumaSamples; }
+  Void setPicHeightVpsInLumaSamples(Int x)   { m_picHeightVpsInLumaSamples = x;    }
+
+  Int  getBitDepthVpsLuma()           { return m_bitDepthVpsLuma;   }
+  Void setBitDepthVpsLuma(Int x)      { m_bitDepthVpsLuma = x;      }
+    
+  Int  getBitDepthVpsChroma()           { return m_bitDepthVpsChroma;   }
+  Void setBitDepthVpsChroma(Int x)      { m_bitDepthVpsChroma = x;      }
+
+  Int  getBitDepthVps(ChannelType type)           { return isLuma(type) ? m_bitDepthVpsLuma : m_bitDepthVpsChroma;   }
+
+#if R0156_CONF_WINDOW_IN_REP_FORMAT
+  Window& getConformanceWindowVps()                           { return  m_conformanceWindowVps;             }
+  Void    setConformanceWindowVps(Window& conformanceWindow ) { m_conformanceWindowVps = conformanceWindow; }
+#endif
+};
+#endif
+
+class TComVPS
+{
+private:
+  Int         m_VPSId;
+#if VPS_RESERVED_FLAGS
+  Bool        m_baseLayerInternalFlag;
+  Bool        m_baseLayerAvailableFlag;
+#endif
+  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 !SVC_EXTENSION
+  UInt        m_maxNuhReservedZeroLayerId;
+#endif
+  TComHRD*    m_hrdParameters;
+  UInt*       m_hrdOpSetIdx;
+  Bool*       m_cprmsPresentFlag;
+#if !SVC_EXTENSION
+  UInt        m_numOpSets;
+  Bool        m_layerIdIncludedFlag[MAX_VPS_OP_SETS_PLUS1][MAX_VPS_NUH_RESERVED_ZERO_LAYER_ID_PLUS1];
+#endif
+#if !MULTIPLE_PTL_SUPPORT
+  TComPTL     m_pcPTL;
+#endif
+  TimingInfo  m_timingInfo;
+
+#if SVC_EXTENSION
+#if MULTIPLE_PTL_SUPPORT
+  TComPTL     m_pcPTLList[MAX_NUM_LAYER_IDS + 1];
+#endif
+#if DERIVE_LAYER_ID_LIST_VARIABLES
+#if Q0078_ADD_LAYER_SETS
+#if NECESSARY_LAYER_FLAG
+  std::vector< std::vector<Int> >     m_layerSetLayerIdList;
+  std::vector<Int>                    m_numLayerInIdList;
+#else
+  Int         m_layerSetLayerIdList[MAX_VPS_LAYER_SETS_PLUS1 + MAX_NUM_ADD_LAYER_SETS][MAX_VPS_LAYER_IDX_PLUS1];
+  Int         m_numLayerInIdList[MAX_VPS_LAYER_SETS_PLUS1 + MAX_NUM_ADD_LAYER_SETS];
+#endif
+#else
+  Int         m_layerSetLayerIdList[MAX_VPS_LAYER_SETS_PLUS1][MAX_VPS_LAYER_IDX_PLUS1];
+  Int         m_numLayerInIdList[MAX_VPS_LAYER_SETS_PLUS1];
+#endif
+#endif
+#if !P0125_REVERT_VPS_EXTN_OFFSET_TO_RESERVED
+#if VPS_EXTN_OFFSET
+  UInt        m_extensionOffset;
+#endif
+#endif
+  UInt        m_maxLayerId;
+  UInt        m_numLayerSets;
+#if Q0078_ADD_LAYER_SETS
+  UInt        m_vpsNumLayerSetsMinus1;
+  Bool        m_layerIdIncludedFlag[MAX_VPS_LAYER_SETS_PLUS1 + MAX_NUM_ADD_LAYER_SETS][MAX_NUM_LAYER_IDS];
+#else
+  Bool        m_layerIdIncludedFlag[MAX_VPS_LAYER_SETS_PLUS1][MAX_VPS_LAYER_IDX_PLUS1];
+#endif
+
+  // ------------------------------------------
+  // Variables related to VPS extensions
+  // ------------------------------------------
+#if VPS_EXTN_MASK_AND_DIM_INFO
+#if VPS_AVC_BL_FLAG_REMOVAL
+  Bool       m_nonHEVCBaseLayerFlag; 
+#else
+  Bool       m_avcBaseLayerFlag;                                // For now, always set to true.
+#endif
+  Bool       m_splittingFlag;
+  Bool       m_scalabilityMask[MAX_VPS_NUM_SCALABILITY_TYPES];
+  UInt       m_dimensionIdLen[MAX_VPS_NUM_SCALABILITY_TYPES];
+  Bool       m_nuhLayerIdPresentFlag;
+  UInt       m_layerIdInNuh[MAX_VPS_LAYER_IDX_PLUS1];            // Maps layer ID in the VPS with layer_id_in_nuh
+  UInt       m_dimensionId[MAX_VPS_LAYER_IDX_PLUS1][MAX_VPS_NUM_SCALABILITY_TYPES];
+
+  // Below are derived variables
+  UInt       m_numScalabilityTypes;
+  UInt       m_layerIdxInVps[MAX_NUM_LAYER_IDS];            // Maps layer_id_in_nuh with the layer ID in the VPS
+#endif
+#if BITRATE_PICRATE_SIGNALLING
+#if Q0078_ADD_LAYER_SETS
+  UInt       m_maxSLInLayerSetMinus1[MAX_VPS_LAYER_SETS_PLUS1 + MAX_NUM_ADD_LAYER_SETS];
+#else
+  UInt       m_maxSLInLayerSetMinus1[MAX_VPS_LAYER_SETS_PLUS1];
+#endif
+#endif
+    
+  Bool       m_ilpSshSignalingEnabledFlag;
+#if VPS_EXTN_PROFILE_INFO
+  // Profile-tier-level signalling related
+  Bool       m_profilePresentFlag[MAX_VPS_LAYER_SETS_PLUS1];    // The value with index 0 will not be used.
+#if !P0048_REMOVE_PROFILE_REF
+  UInt       m_profileLayerSetRef[MAX_VPS_LAYER_SETS_PLUS1];    // The value with index 0 will not be used.
+#endif
+#if !MULTIPLE_PTL_SUPPORT
+  std::vector<TComPTL>    m_pcPTLForExtn;  
+#endif
+#endif
+#if VPS_EXTN_OP_LAYER_SETS
+  // .. More declarations here
+  // Target output layer signalling related
+  UInt       m_numOutputLayerSets;
+#if Q0078_ADD_LAYER_SETS
+  UInt       m_outputLayerSetIdx[MAX_VPS_LAYER_SETS_PLUS1 + 2*MAX_NUM_ADD_LAYER_SETS];
+  Bool       m_outputLayerFlag[MAX_VPS_LAYER_SETS_PLUS1 + 2*MAX_NUM_ADD_LAYER_SETS][MAX_VPS_LAYER_IDX_PLUS1];
+#else
+  UInt       m_outputLayerSetIdx[MAX_VPS_LAYER_SETS_PLUS1];
+  Bool       m_outputLayerFlag[MAX_VPS_LAYER_SETS_PLUS1][MAX_VPS_LAYER_IDX_PLUS1];
+#endif
+#endif
+#if VPS_EXTN_DIRECT_REF_LAYERS
+  Bool       m_directDependencyFlag[MAX_VPS_LAYER_IDX_PLUS1][MAX_VPS_LAYER_IDX_PLUS1];
+  UInt       m_numDirectRefLayers[MAX_VPS_LAYER_IDX_PLUS1];
+  UInt       m_refLayerId[MAX_VPS_LAYER_IDX_PLUS1][MAX_VPS_LAYER_IDX_PLUS1];
+  UInt       m_directDepTypeLen;
+#if O0096_DEFAULT_DEPENDENCY_TYPE
+  Bool       m_defaultDirectDependencyTypeFlag;
+  UInt       m_defaultDirectDependencyType;
+#endif
+  UInt       m_directDependencyType[MAX_VPS_LAYER_IDX_PLUS1][MAX_VPS_LAYER_IDX_PLUS1];
+#endif
+  UInt       m_numProfileTierLevel;
+#if !VPS_EXTN_UEV_CODING
+  Bool       m_moreOutputLayerSetsThanDefaultFlag;
+#endif
+  Int        m_numAddOutputLayerSets;
+#if P0295_DEFAULT_OUT_LAYER_IDC
+  UInt       m_defaultTargetOutputLayerIdc;
+#else
+#if O0109_DEFAULT_ONE_OUT_LAYER_IDC
+  UInt       m_defaultOneTargetOutputLayerIdc;
+#else
+  Bool       m_defaultOneTargetOutputLayerFlag;
+#endif
+#endif
+#if PER_LAYER_PTL
+  std::vector< std::vector<Int> >  m_profileLevelTierIdx;
+#else
+  Int        m_profileLevelTierIdx[64];     
+#endif
+  Bool       m_maxOneActiveRefLayerFlag;
+#if O0062_POC_LSB_NOT_PRESENT_FLAG
+  Bool       m_pocLsbNotPresentFlag[MAX_VPS_LAYER_IDX_PLUS1];
+#endif
+#if O0223_PICTURE_TYPES_ALIGN_FLAG
+  Bool       m_crossLayerPictureTypeAlignFlag;
+#endif
+  Bool       m_crossLayerIrapAlignFlag;
+#if P0068_CROSS_LAYER_ALIGNED_IDR_ONLY_FOR_IRAP_FLAG
+  Bool       m_crossLayerAlignedIdrOnlyFlag;
+#endif
+  UInt       m_maxTidIlRefPicsPlus1[MAX_VPS_LAYER_IDX_PLUS1 - 1][MAX_VPS_LAYER_IDX_PLUS1];
+  Bool       m_maxTidRefPresentFlag;
+#if VPS_TSLAYERS
+  Bool       m_maxTSLayersPresentFlag;
+  UInt       m_maxTSLayerMinus1[MAX_LAYERS];
+#endif
+#if M0040_ADAPTIVE_RESOLUTION_CHANGE
+  Bool       m_singleLayerForNonIrapFlag;
+#endif
+#if HIGHER_LAYER_IRAP_SKIP_FLAG
+  Bool       m_higherLayerIrapSkipFlag;
+#endif
+#if VPS_VUI_TILES_NOT_IN_USE__FLAG
+  Bool       m_tilesNotInUseFlag;
+  Bool       m_tilesInUseFlag[MAX_VPS_LAYER_IDX_PLUS1];
+  Bool       m_loopFilterNotAcrossTilesFlag[MAX_VPS_LAYER_IDX_PLUS1];
+#endif 
+  Bool       m_tileBoundariesAlignedFlag[MAX_VPS_LAYER_IDX_PLUS1][MAX_VPS_LAYER_IDX_PLUS1];
+#if VPS_VUI_WPP_NOT_IN_USE__FLAG
+  Bool       m_wppNotInUseFlag;
+  Bool       m_wppInUseFlag[MAX_VPS_LAYER_IDX_PLUS1];
+#endif 
+#if N0160_VUI_EXT_ILP_REF    
+  Bool       m_ilpRestrictedRefLayersFlag;
+  Int        m_minSpatialSegmentOffsetPlus1[MAX_VPS_LAYER_IDX_PLUS1][MAX_VPS_LAYER_IDX_PLUS1];
+  Bool       m_ctuBasedOffsetEnabledFlag   [MAX_VPS_LAYER_IDX_PLUS1][MAX_VPS_LAYER_IDX_PLUS1];
+  Int        m_minHorizontalCtuOffsetPlus1 [MAX_VPS_LAYER_IDX_PLUS1][MAX_VPS_LAYER_IDX_PLUS1];
+#endif 
+#if VPS_VUI_VIDEO_SIGNAL
+  Bool       m_vidSigPresentVpsFlag;
+  Int        m_vpsVidSigInfo;
+  Int        m_vpsVidSigIdx[MAX_VPS_LAYER_IDX_PLUS1];
+  Int        m_vpsVidFormat[16];
+  Bool       m_vpsFullRangeFlag[16];
+  Int        m_vpsColorPrimaries[16];
+  Int        m_vpsTransChar[16];
+  Int        m_vpsMatCoeff[16];
+#endif
+
+  Bool       m_bitRatePresentVpsFlag;
+  Bool       m_picRatePresentVpsFlag;
+  Bool       m_bitRatePresentFlag  [MAX_VPS_LAYER_SETS_PLUS1][MAX_TLAYER];
+  Bool       m_picRatePresentFlag  [MAX_VPS_LAYER_SETS_PLUS1][MAX_TLAYER];
+  Int        m_avgBitRate          [MAX_VPS_LAYER_SETS_PLUS1][MAX_TLAYER];
+  Int        m_maxBitRate          [MAX_VPS_LAYER_SETS_PLUS1][MAX_TLAYER];
+  Int        m_constPicRateIdc     [MAX_VPS_LAYER_SETS_PLUS1][MAX_TLAYER];
+  Int        m_avgPicRate          [MAX_VPS_LAYER_SETS_PLUS1][MAX_TLAYER];
+  
+#if P0312_VERT_PHASE_ADJ
+  Bool       m_vpsVuiVertPhaseInUseFlag;
+#endif
+
+#if P0300_ALT_OUTPUT_LAYER_FLAG
+#if Q0078_ADD_LAYER_SETS
+  Bool       m_altOutputLayerFlag[MAX_VPS_LAYER_SETS_PLUS1 + 2*MAX_NUM_ADD_LAYER_SETS];
+#else
+  Bool       m_altOutputLayerFlag[MAX_VPS_LAYER_SETS_PLUS1];
+#endif
+#else
+#if O0153_ALT_OUTPUT_LAYER_FLAG
+  Bool       m_altOutputLayerFlag;
+#endif
+#endif
+#if REPN_FORMAT_IN_VPS
+  Bool       m_repFormatIdxPresentFlag;
+  Int        m_vpsNumRepFormats;            // coded as minus1
+  RepFormat  m_vpsRepFormat[16];
+  Int        m_vpsRepFormatIdx[16];
+#endif
+#if VIEW_ID_RELATED_SIGNALING 
+#if O0109_VIEW_ID_LEN
+  Int        m_viewIdLen;
+#else
+  Int        m_viewIdLenMinus1;
+#endif
+  Int        m_viewIdVal                [MAX_LAYERS];
+#endif
+
+#if O0215_PHASE_ALIGNMENT
+  Bool       m_phaseAlignFlag;
+#endif
+
+#if O0092_0094_DEPENDENCY_CONSTRAINT
+  Int        m_numberRefLayers[MAX_NUM_LAYER_IDS];  // number of direct and indirect reference layers of a coding layer
+  Bool       m_recursiveRefLayerFlag[MAX_NUM_LAYER_IDS][MAX_NUM_LAYER_IDS];  // flag to indicate if j-th layer is a direct or indirect reference layer of i-th layer
+#endif
+#if Q0078_ADD_LAYER_SETS
+  Int        m_numAddLayerSets;
+  UInt       m_highestLayerIdxPlus1[MAX_NUM_ADD_LAYER_SETS][MAX_NUM_LAYER_IDS];
+  UInt       m_predictedLayerId[MAX_NUM_LAYER_IDS][MAX_NUM_LAYER_IDS];
+  UInt       m_numPredictedLayers[MAX_NUM_LAYER_IDS];
+  Int        m_numIndependentLayers;
+  Int        m_numLayersInTreePartition[MAX_LAYERS];
+  UInt       m_treePartitionLayerIdList[MAX_LAYERS][MAX_LAYERS];
+#endif
+#if SPS_DPB_PARAMS
+  Int        m_TolsIdx;
+#endif
+#if VPS_DPB_SIZE_TABLE
+  Bool       m_subLayerFlagInfoPresentFlag [MAX_VPS_OP_LAYER_SETS_PLUS1];
+  Bool       m_subLayerDpbInfoPresentFlag  [MAX_VPS_OP_LAYER_SETS_PLUS1][MAX_LAYERS];
+  Int        m_maxVpsDecPicBufferingMinus1 [MAX_VPS_OP_LAYER_SETS_PLUS1][MAX_LAYERS][MAX_TLAYER];
+#if RESOLUTION_BASED_DPB
+  Int        m_maxVpsLayerDecPicBuffMinus1 [MAX_VPS_OP_LAYER_SETS_PLUS1][MAX_LAYERS][MAX_TLAYER];  
+#endif
+  Int        m_maxVpsNumReorderPics        [MAX_VPS_OP_LAYER_SETS_PLUS1][MAX_LAYERS];
+  Int        m_maxVpsLatencyIncreasePlus1  [MAX_VPS_OP_LAYER_SETS_PLUS1][MAX_LAYERS];
+#if CHANGE_NUMSUBDPB_IDX
+#if Q0078_ADD_LAYER_SETS
+  Int        m_numSubDpbs                  [MAX_VPS_LAYER_SETS_PLUS1 + 2*MAX_NUM_ADD_LAYER_SETS];
+#else
+  Int        m_numSubDpbs                  [MAX_VPS_LAYER_SETS_PLUS1];
+#endif
+#else
+  Int        m_numSubDpbs                  [MAX_VPS_OP_LAYER_SETS_PLUS1];
+#endif
+#endif
+
+#if O0109_MOVE_VPS_VUI_FLAG
+  Bool       m_vpsVuiPresentFlag;
+#endif
+  Bool       m_vpsExtensionFlag;
+
+#if O0164_MULTI_LAYER_HRD
+  Bool       m_vpsVuiBspHrdPresentFlag;
+#if VPS_VUI_BSP_HRD_PARAMS
+  Int                 m_vpsNumAddHrdParams;
+  std::vector<Bool>   m_cprmsAddPresentFlag;
+  std::vector<Int>    m_numSubLayerHrdMinus1;
+  std::vector<TComHRD> m_bspHrd;
+  Int    m_numSignalledPartitioningSchemes[MAX_VPS_OUTPUT_LAYER_SETS_PLUS1];
+  Int    m_numPartitionsInSchemeMinus1    [MAX_VPS_OUTPUT_LAYER_SETS_PLUS1][16];
+  Int    m_layerIncludedInPartitionFlag   [MAX_VPS_OUTPUT_LAYER_SETS_PLUS1][16][MAX_LAYERS][MAX_LAYERS];
+  Int    m_numBspSchedulesMinus1          [MAX_VPS_OUTPUT_LAYER_SETS_PLUS1][16][MAX_TLAYER];
+  Int    m_bspHrdIdx                      [MAX_VPS_OUTPUT_LAYER_SETS_PLUS1][16][MAX_TLAYER][31][MAX_LAYERS];
+  Int    m_bspSchedIdx                    [MAX_VPS_OUTPUT_LAYER_SETS_PLUS1][16][MAX_TLAYER][31][MAX_LAYERS];
+#else
+  UInt       m_vpsNumBspHrdParametersMinus1;
+  Bool       m_bspCprmsPresentFlag[MAX_VPS_LAYER_SETS_PLUS1];
+  TComHRD    *m_bspHrd;
+  UInt       m_numBitstreamPartitions[MAX_VPS_LAYER_SETS_PLUS1];
+  Bool       m_layerInBspFlag[MAX_VPS_LAYER_SETS_PLUS1][8][MAX_LAYERS];
+  UInt       m_numBspSchedCombinations[MAX_VPS_LAYER_SETS_PLUS1];
+  UInt       m_bspCombHrdIdx[MAX_VPS_LAYER_SETS_PLUS1][16][16];
+  UInt       m_bspCombSchedIdx[MAX_VPS_LAYER_SETS_PLUS1][16][16];
+#endif
+#endif
+
+#if P0182_VPS_VUI_PS_FLAG
+  UInt       m_baseLayerPSCompatibilityFlag[MAX_LAYERS];
+#endif
+
+#if !P0307_REMOVE_VPS_VUI_OFFSET
+#if VPS_VUI_OFFSET
+  Int        m_vpsVuiOffset;
+#endif
+#endif
+#if P0307_VPS_NON_VUI_EXTENSION
+  Int        m_vpsNonVuiExtLength;
+#endif
+#if P0297_VPS_POC_LSB_ALIGNED_FLAG
+  Bool       m_vpsPocLsbAlignedFlag;
+#endif
+#if RESOLUTION_BASED_DPB
+  Int        m_subDpbAssigned            [MAX_VPS_LAYER_SETS_PLUS1][MAX_LAYERS];
+#endif
+#if NECESSARY_LAYER_FLAG
+  std::vector< std::vector<Bool> > m_necessaryLayerFlag;
+  std::vector<Int>               m_numNecessaryLayers;
+#endif
+#endif //SVC_EXTENSION
+public:
+  TComVPS();
+  virtual ~TComVPS();
+
+#if VPS_RESERVED_FLAGS
+  Void        setBaseLayerInternalFlag(Bool x) { m_baseLayerInternalFlag = x; }
+  Bool        getBaseLayerInternalFlag()         { return m_baseLayerInternalFlag; }
+  Void        setBaseLayerAvailableFlag(Bool x) { m_baseLayerAvailableFlag = x; }
+  Bool        getBaseLayerAvailableFlag()         { return m_baseLayerAvailableFlag; }
+#endif
+
+  Void    createHrdParamBuffer()
+  {
+    m_hrdParameters    = new TComHRD[ getNumHrdParameters() ];
+    m_hrdOpSetIdx      = new UInt   [ getNumHrdParameters() ];
+    m_cprmsPresentFlag = new Bool   [ getNumHrdParameters() ];
+  }
+
+#if O0164_MULTI_LAYER_HRD
+  Void    createBspHrdParamBuffer(UInt numHrds)
+  {
+#if VPS_VUI_BSP_HRD_PARAMS
+    m_bspHrd.resize( numHrds );
+    m_cprmsAddPresentFlag.resize( numHrds );
+    m_numSubLayerHrdMinus1.resize( numHrds );
+#else
+    m_bspHrd    = new TComHRD[ numHrds ];
+#endif
+//    m_hrdOpSetIdx      = new UInt   [ getNumHrdParameters() ];
+//    m_cprmsPresentFlag = new Bool   [ getNumHrdParameters() ];
+  }
+#endif
+#if HRD_BPB
+  Int getBspHrdParamBufferCpbCntMinus1(UInt i, UInt sl)
+  {
+#if VPS_VUI_BSP_HRD_PARAMS
+    return m_bspHrd[i].getCpbCntMinus1(sl);
+#else
+    return m_bspHrd->getCpbCntMinus1(sl);
+#endif
+  }
+#endif
+
+  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)            { assert(tLayer < MAX_TLAYER); m_uiMaxDecPicBuffering[tLayer] = v;    }
+  UInt    getMaxDecPicBuffering(UInt tLayer)                    { return m_uiMaxDecPicBuffering[tLayer]; }
+
+  Void    setMaxLatencyIncrease(UInt v, UInt tLayer)            { m_uiMaxLatencyIncrease[tLayer] = v;    }
+  UInt    getMaxLatencyIncrease(UInt tLayer)                    { return m_uiMaxLatencyIncrease[tLayer]; }
+
+  UInt    getNumHrdParameters()                                 { return m_numHrdParameters; }
+  Void    setNumHrdParameters(UInt v)                           { m_numHrdParameters = v;    }
+  
+#if !SVC_EXTENSION
+  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 !MULTIPLE_PTL_SUPPORT
+  TComPTL* getPTL() { return &m_pcPTL; }
+#endif
+
+  TimingInfo* getTimingInfo() { return &m_timingInfo; }
+
+#if SVC_EXTENSION
+#if MULTIPLE_PTL_SUPPORT
+  TComPTL* getPTL() { return &m_pcPTLList[0]; }
+  TComPTL* getPTL(UInt idx) { return &m_pcPTLList[idx]; }
+#endif
+#if DERIVE_LAYER_ID_LIST_VARIABLES
+  Int     getLayerSetLayerIdList(Int set, Int layerId)          { return m_layerSetLayerIdList[set][layerId]; }
+  Void    setLayerSetLayerIdList(Int set, Int layerId, Int x)   { m_layerSetLayerIdList[set][layerId] = x;    }
+
+  Int     getNumLayersInIdList(Int set)                          { return m_numLayerInIdList[set]; }
+  Void    setNumLayersInIdList(Int set, Int x)                   { m_numLayerInIdList[set] = x;    }
+
+  Void    deriveLayerIdListVariables();
+#endif
+#if VPS_DPB_SIZE_TABLE
+Void      deriveNumberOfSubDpbs();
+#endif
+
+#if O0092_0094_DEPENDENCY_CONSTRAINT
+  Void    setRefLayersFlags(Int currLayerId);
+  Bool    getRecursiveRefLayerFlag(Int currLayerId, Int refLayerId)              { return m_recursiveRefLayerFlag[currLayerId][refLayerId];}
+  Void    setRecursiveRefLayerFlag(Int currLayerId, Int refLayerId, Bool x)      { m_recursiveRefLayerFlag[currLayerId][refLayerId] = x;   }
+  Int     getNumRefLayers(Int currLayerId)                                       { return m_numberRefLayers[currLayerId];                  }
+  Void    setNumRefLayers();
+#endif
+#if Q0078_ADD_LAYER_SETS
+#if FIX_LAYER_ID_INIT
+  void    deriveLayerIdListVariablesForAddLayerSets();
+#else
+  void    setLayerIdIncludedFlagsForAddLayerSets();
+#endif
+  UInt    getVpsNumLayerSetsMinus1()                                             { return m_vpsNumLayerSetsMinus1; }
+  Void    setVpsNumLayerSetsMinus1(UInt x)                                       { m_vpsNumLayerSetsMinus1 = x; }
+  UInt    getNumAddLayerSets()                                                   { return m_numAddLayerSets; }
+  Void    setNumAddLayerSets(UInt x)                                             { m_numAddLayerSets = x; }
+  UInt    getHighestLayerIdxPlus1(UInt set, UInt idx)                            { return m_highestLayerIdxPlus1[set][idx]; }
+  Void    setHighestLayerIdxPlus1(UInt set, UInt idx, UInt layerIdx)             { m_highestLayerIdxPlus1[set][idx] = layerIdx; }
+  Void    setPredictedLayerIds();
+  UInt    getPredictedLayerId(UInt layerId, UInt predIdx)                        { return m_predictedLayerId[layerId][predIdx]; }
+  Void    setPredictedLayerId(UInt layerId, UInt predIdx, UInt x)                { m_predictedLayerId[layerId][predIdx] = x; }
+  UInt    getNumPredictedLayers(UInt layerId)                                    { return m_numPredictedLayers[layerId]; }
+  Void    setNumPredictedLayers(UInt layerId, UInt x)                            { m_numPredictedLayers[layerId] = x; }
+  Void    setTreePartitionLayerIdList();
+  Int     getNumIndependentLayers()                                              { return m_numIndependentLayers; }
+  Void    setNumIndependentLayers(Int x)                                         { m_numIndependentLayers = x; }
+  Int     getNumLayersInTreePartition(Int idx)                                   { return m_numLayersInTreePartition[idx]; }
+  Void    setNumLayersInTreePartition(Int idx, Int x)                            { m_numLayersInTreePartition[idx] = x; }
+  UInt    getTreePartitionLayerId(Int idx, Int layerIdx)                         { return m_treePartitionLayerIdList[idx][layerIdx]; }
+  Void    setTreePartitionLayerId(Int idx, Int layerIdx, UInt layerId)           { m_treePartitionLayerIdList[idx][layerIdx] = layerId; }
+#endif
+  UInt    getMaxLayerId()                                       { return m_maxLayerId;   }
+  Void    setMaxLayerId(UInt v)                                 { m_maxLayerId = v;      }
+  UInt    getNumLayerSets()                                     { return m_numLayerSets; }
+  Void    setNumLayerSets(UInt v)                               { m_numLayerSets = v;    }
+#if VPS_EXTN_MASK_AND_DIM_INFO
+#if VPS_AVC_BL_FLAG_REMOVAL
+  Bool   getNonHEVCBaseLayerFlag()                              { return m_nonHEVCBaseLayerFlag;   }
+  Void   setNonHEVCBaseLayerFlag(Bool x)                        { m_nonHEVCBaseLayerFlag = x;      }
+#else
+  Bool   getAvcBaseLayerFlag()                                  { return m_avcBaseLayerFlag;       }
+  Void   setAvcBaseLayerFlag(Bool x)                            { m_avcBaseLayerFlag = x;          }
+#endif
+
+  Bool   getSplittingFlag()                                     { return m_splittingFlag;          }
+  Void   setSplittingFlag(Bool x)                               { m_splittingFlag = x;             }
+
+  Bool   getScalabilityMask(Int id)                             { return m_scalabilityMask[id];    }
+  Void   setScalabilityMask(Int id, Bool x)                     { m_scalabilityMask[id] = x;       }
+
+  UInt   getDimensionIdLen(Int id)                              { return m_dimensionIdLen[id];     }
+  Void   setDimensionIdLen(Int id, UInt x)                      { m_dimensionIdLen[id] = x;        }
+
+  Bool   getNuhLayerIdPresentFlag()                             { return m_nuhLayerIdPresentFlag;  }
+  Void   setNuhLayerIdPresentFlag(Bool x)                       { m_nuhLayerIdPresentFlag = x;     }
+
+  UInt   getLayerIdInNuh(Int layerIdx)                          { return m_layerIdInNuh[layerIdx];    }
+  Void   setLayerIdInNuh(Int layerIdx, UInt layerId)            { m_layerIdInNuh[layerIdx] = layerId; }
+
+  UInt   getDimensionId(Int layerIdx, Int id)                   { return m_dimensionId[layerIdx][id]; }
+  Void   setDimensionId(Int layerIdx, Int id, UInt x)           { m_dimensionId[layerIdx][id] = x;    }
+
+  UInt   getNumScalabilityTypes()                               { return m_numScalabilityTypes;    }
+  Void   setNumScalabilityTypes(UInt x)                         { m_numScalabilityTypes = x;       }
+
+  UInt   getLayerIdxInVps(Int layerId)                          { return m_layerIdxInVps[layerId];     }
+  Void   setLayerIdxInVps(Int layerId, UInt layerIdx)           { m_layerIdxInVps[layerId] = layerIdx; }
+#endif
+#if BITRATE_PICRATE_SIGNALLING
+  UInt   getMaxSLayersInLayerSetMinus1(Int ls)                  { return m_maxSLInLayerSetMinus1[ls]; }
+  Void   setMaxSLayersInLayerSetMinus1(Int ls, Int x)           { m_maxSLInLayerSetMinus1[ls] = x;    }
+#endif
+  Bool   getIlpSshSignalingEnabledFlag()                        { return m_ilpSshSignalingEnabledFlag;}
+  Void   setIlpSshSignalingEnabledFlag(Bool x)                  { m_ilpSshSignalingEnabledFlag = x;}
+#if VPS_EXTN_PROFILE_INFO
+  Bool   getProfilePresentFlag(Int id)                          { return m_profilePresentFlag[id]; }
+  Void   setProfilePresentFlag(Int id, Bool x)                  { m_profilePresentFlag[id] = x;    }
+
+#if !P0048_REMOVE_PROFILE_REF
+  UInt   getProfileLayerSetRef(Int id)                          { return m_profileLayerSetRef[id]; }
+  Void   setProfileLayerSetRef(Int id, Bool x)                  { m_profileLayerSetRef[id] = x;    }
+#endif
+
+#if !MULTIPLE_PTL_SUPPORT
+  std::vector<TComPTL>* getPTLForExtnPtr()                      { return &m_pcPTLForExtn;          }
+  TComPTL* getPTLForExtn(Int id)                                { return &m_pcPTLForExtn[id];      }
+#endif
+#endif
+#if VPS_EXTN_OP_LAYER_SETS
+  // Target output layer signalling related
+  UInt   getNumOutputLayerSets()                                { return m_numOutputLayerSets;     } 
+  Void   setNumOutputLayerSets(Int x)                           { m_numOutputLayerSets = x;        }
+  
+  UInt   getOutputLayerSetIdx(Int idx)                          { return m_outputLayerSetIdx[idx]; }
+  Void   setOutputLayerSetIdx(Int idx, UInt x)                  { m_outputLayerSetIdx[idx] = x;    }
+
+  Bool   getOutputLayerFlag(Int layerSet, Int layerIdx)          { return m_outputLayerFlag[layerSet][layerIdx]; }
+  Void   setOutputLayerFlag(Int layerSet, Int layerIdx, Bool x)  { m_outputLayerFlag[layerSet][layerIdx] = x;    }
+#endif
+#if VPS_EXTN_DIRECT_REF_LAYERS
+  // Direct dependency of layers
+  Bool   getDirectDependencyFlag(Int currLayerIdx, Int refLayerIdx)             { return m_directDependencyFlag[currLayerIdx][refLayerIdx]; }
+  Void   setDirectDependencyFlag(Int currLayerIdx, Int refLayerIdx, Bool x)     { m_directDependencyFlag[currLayerIdx][refLayerIdx] = x;    }
+  
+  UInt   getNumDirectRefLayers(Int layerId)                                     { return m_numDirectRefLayers[layerId];                   }
+  Void   setNumDirectRefLayers(Int layerId, UInt refLayerNum)                   { m_numDirectRefLayers[layerId] = refLayerNum;            }
+
+  UInt   getRefLayerId(Int layerId, Int refLayerIdc)                            { return m_refLayerId[layerId][refLayerIdc];              }
+  Void   setRefLayerId(Int layerId, Int refLayerIdc, UInt refLayerId)           { m_refLayerId[layerId][refLayerIdc] = refLayerId;        }
+
+  UInt   getDirectDepTypeLen()                                                  { return m_directDepTypeLen;                              }
+  Void   setDirectDepTypeLen(UInt x)                                            { m_directDepTypeLen = x;                                 }
+#if O0096_DEFAULT_DEPENDENCY_TYPE
+  Bool   getDefaultDirectDependencyTypeFlag()                                   { return m_defaultDirectDependencyTypeFlag;               }
+  Void   setDefaultDirectDependecyTypeFlag(Bool x)                              { m_defaultDirectDependencyTypeFlag = x;                  }
+  UInt   getDefaultDirectDependencyType()                                       { return m_defaultDirectDependencyType;                   }
+  Void   setDefaultDirectDependecyType(UInt x)                                  { m_defaultDirectDependencyType = x;                      }
+#endif
+  UInt   getDirectDependencyType(Int currLayerIdx, Int refLayerIdx)             { return m_directDependencyType[currLayerIdx][refLayerIdx]; }
+  Void   setDirectDependencyType(Int currLayerIdx, Int refLayerIdx, UInt x)     { m_directDependencyType[currLayerIdx][refLayerIdx] = x;    }
+  Bool   isSamplePredictionType(Int currLayerIdx, Int refLayerIdx)              { assert(currLayerIdx != refLayerIdx); return ( ( m_directDependencyType[currLayerIdx][refLayerIdx] + 1 ) & 1 ) ? true : false; }
+  Bool   isMotionPredictionType(Int currLayerIdx, Int refLayerIdx)              { assert(currLayerIdx != refLayerIdx); return ( ( ( m_directDependencyType[currLayerIdx][refLayerIdx] + 1 ) & 2 ) >> 1 ) ? true : false; }
+#endif
+  UInt   getNumProfileTierLevel()                                { return m_numProfileTierLevel; }
+  Void   setNumProfileTierLevel(Int x)                           { m_numProfileTierLevel = x;    }
+
+#if !VPS_EXTN_UEV_CODING
+  Bool   getMoreOutputLayerSetsThanDefaultFlag()                 { return m_moreOutputLayerSetsThanDefaultFlag;}
+  Void   setMoreOutputLayerSetsThanDefaultFlag(Bool x)           { m_moreOutputLayerSetsThanDefaultFlag = x   ;}
+#endif
+
+  Int    getNumAddOutputLayerSets()                              { return m_numAddOutputLayerSets; }
+  Void   setNumAddOutputLayerSets(Int x)                         { m_numAddOutputLayerSets = x   ; }
+
+#if P0295_DEFAULT_OUT_LAYER_IDC
+  UInt   getDefaultTargetOutputLayerIdc()                 { return m_defaultTargetOutputLayerIdc;}
+  Void   setDefaultTargetOutputLayerIdc(UInt x)           { m_defaultTargetOutputLayerIdc = x    ;}
+#else
+#if O0109_DEFAULT_ONE_OUT_LAYER_IDC
+  UInt   getDefaultOneTargetOutputLayerIdc()                 { return m_defaultOneTargetOutputLayerIdc;}
+  Void   setDefaultOneTargetOutputLayerIdc(UInt x)           { m_defaultOneTargetOutputLayerIdc= x    ;}
+#else
+  Bool   getDefaultOneTargetOutputLayerFlag()                 { return m_defaultOneTargetOutputLayerFlag;}
+  Void   setDefaultOneTargetOutputLayerFlag(Bool x)           { m_defaultOneTargetOutputLayerFlag= x    ;}
+#endif
+#endif
+#if PER_LAYER_PTL
+  Bool getNecessaryLayerFlag(Int const i, Int const j) { return m_necessaryLayerFlag[i][j]; }
+  std::vector< std::vector<Int> >* getProfileLevelTierIdx() { return &m_profileLevelTierIdx; }
+  std::vector<Int>* getProfileLevelTierIdx(Int const olsIdx) { return &m_profileLevelTierIdx[olsIdx]; }
+  Int    getProfileLevelTierIdx(Int const olsIdx, Int const layerIdx)     { return m_profileLevelTierIdx[olsIdx][layerIdx]; }
+  Void   setProfileLevelTierIdx(Int const olsIdx, Int const layerIdx, Int const ptlIdx)     { m_profileLevelTierIdx[olsIdx][layerIdx] = ptlIdx; }
+#if MULTIPLE_PTL_SUPPORT
+  Void   addProfileLevelTierIdx(Int const olsIdx, Int const ptlIdx)     { m_profileLevelTierIdx[olsIdx].push_back(ptlIdx); }
+#endif
+  Int    calculateLenOfSyntaxElement( Int const numVal );
+#else
+  Int    getProfileLevelTierIdx(Int i)                        { return m_profileLevelTierIdx[i]; }
+  Void   setProfileLevelTierIdx(Int i, Int x)                 { m_profileLevelTierIdx[i] = x   ; }
+#endif
+  Bool   getMaxOneActiveRefLayerFlag()                                          { return m_maxOneActiveRefLayerFlag;                      }
+  Void   setMaxOneActiveRefLayerFlag(Bool x)                                    { m_maxOneActiveRefLayerFlag = x;                         }
+#if O0062_POC_LSB_NOT_PRESENT_FLAG
+  UInt   getPocLsbNotPresentFlag(Int i)                                         { return m_pocLsbNotPresentFlag[i]; }
+  Void   setPocLsbNotPresentFlag(Int i, Bool x)                                 { m_pocLsbNotPresentFlag[i] = x;    }
+#endif
+#if P0297_VPS_POC_LSB_ALIGNED_FLAG
+  Bool   getVpsPocLsbAlignedFlag()                                              { return m_vpsPocLsbAlignedFlag; }
+  Void   setVpsPocLsbAlignedFlag(Bool x)                                        { m_vpsPocLsbAlignedFlag = x; }
+#endif
+#if O0223_PICTURE_TYPES_ALIGN_FLAG
+  Bool   getCrossLayerPictureTypeAlignFlag()                                    { return m_crossLayerPictureTypeAlignFlag;                      }
+  Void   setCrossLayerPictureTypeAlignFlag(Bool x)                              { m_crossLayerPictureTypeAlignFlag = x;                         }
+#endif 
+#if P0068_CROSS_LAYER_ALIGNED_IDR_ONLY_FOR_IRAP_FLAG
+  Bool   getCrossLayerAlignedIdrOnlyFlag()                                    { return m_crossLayerAlignedIdrOnlyFlag;                      }
+  Void   setCrossLayerAlignedIdrOnlyFlag(Bool x)                              { m_crossLayerAlignedIdrOnlyFlag = x;                         }
+#endif 
+  Bool   getCrossLayerIrapAlignFlag()                                           { return m_crossLayerIrapAlignFlag;                      }
+  Void   setCrossLayerIrapAlignFlag(Bool x)                                     { m_crossLayerIrapAlignFlag = x;                         }
+  UInt   getMaxTidIlRefPicsPlus1(Int refLayerIdx, Int layerIdx)                     { return m_maxTidIlRefPicsPlus1[refLayerIdx][layerIdx];           }
+  Void   setMaxTidIlRefPicsPlus1(Int refLayerIdx, Int layerIdx, UInt maxSublayer)   { m_maxTidIlRefPicsPlus1[refLayerIdx][layerIdx] = maxSublayer;    }
+  Bool   getMaxTidRefPresentFlag()                                  { return m_maxTidRefPresentFlag ;}
+  Void   setMaxTidRefPresentFlag(Bool x)                            { m_maxTidRefPresentFlag = x;}
+#if VPS_TSLAYERS
+  Bool   getMaxTSLayersPresentFlag()                                  { return m_maxTSLayersPresentFlag ;}
+  Void   setMaxTSLayersPresentFlag(Bool x)                            { m_maxTSLayersPresentFlag = x;}
+  UInt   getMaxTSLayersMinus1(Int layerIdx)                            { return m_maxTSLayerMinus1[layerIdx];}
+  Void   setMaxTSLayersMinus1(Int layerIdx, UInt maxTSublayer)         { m_maxTSLayerMinus1[layerIdx] = maxTSublayer;}
+#endif
+#if M0040_ADAPTIVE_RESOLUTION_CHANGE
+  Bool   getSingleLayerForNonIrapFlag()                             { return m_singleLayerForNonIrapFlag; }
+  Void   setSingleLayerForNonIrapFlag(Bool x)                       { m_singleLayerForNonIrapFlag = x;    }
+#endif
+#if HIGHER_LAYER_IRAP_SKIP_FLAG
+  Bool   getHigherLayerIrapSkipFlag()                             { return m_higherLayerIrapSkipFlag; }
+  Void   setHigherLayerIrapSkipFlag(Bool x)                       { m_higherLayerIrapSkipFlag = x;    }
+#endif
+#if VPS_VUI_TILES_NOT_IN_USE__FLAG  
+  Bool   getTilesNotInUseFlag()         { return m_tilesNotInUseFlag; }
+  Void   setTilesNotInUseFlag(Bool x); 
+  Bool   getTilesInUseFlag(Int currLayerId)    { return m_tilesInUseFlag[currLayerId]; }
+  Void   setTilesInUseFlag(Int currLayerId, Bool x)    { m_tilesInUseFlag[currLayerId] = x; } 
+  Bool   getLoopFilterNotAcrossTilesFlag(Int currLayerId)    { return m_loopFilterNotAcrossTilesFlag[currLayerId]; }
+  Void   setLoopFilterNotAcrossTilesFlag(Int currLayerId, Bool x)    { m_loopFilterNotAcrossTilesFlag[currLayerId] = x; } 
+#endif 
+  Bool   getTileBoundariesAlignedFlag(Int currLayerId, Int refLayerId)           { return m_tileBoundariesAlignedFlag[currLayerId][refLayerId]; }
+  Void   setTileBoundariesAlignedFlag(Int currLayerId, Int refLayerId, Bool x)   { m_tileBoundariesAlignedFlag[currLayerId][refLayerId] = x; } 
+#if VPS_VUI_WPP_NOT_IN_USE__FLAG  
+  Bool   getWppNotInUseFlag()         { return m_wppNotInUseFlag; }
+  Void   setWppNotInUseFlag(Bool x); 
+  Bool   getWppInUseFlag(Int currLayerId)    { return m_wppInUseFlag[currLayerId]; }
+  Void   setWppInUseFlag(Int currLayerId, Bool x)    { m_wppInUseFlag[currLayerId] = x; } 
+#endif 
+#if N0160_VUI_EXT_ILP_REF  
+  Bool   getIlpRestrictedRefLayersFlag   ( )                                        { return m_ilpRestrictedRefLayersFlag        ;}
+  Void   setIlpRestrictedRefLayersFlag   ( Int val )                                { m_ilpRestrictedRefLayersFlag         = val;}
+  
+  Int    getMinSpatialSegmentOffsetPlus1( Int currLayerId, Int refLayerId )          { return m_minSpatialSegmentOffsetPlus1[currLayerId][refLayerId];}
+  Void   setMinSpatialSegmentOffsetPlus1( Int currLayerId, Int refLayerId, Int val ) { m_minSpatialSegmentOffsetPlus1[currLayerId][refLayerId] = val;}
+  
+  Bool   getCtuBasedOffsetEnabledFlag   ( Int currLayerId, Int refLayerId )            { return m_ctuBasedOffsetEnabledFlag[currLayerId][refLayerId];}
+  Void   setCtuBasedOffsetEnabledFlag   ( Int currLayerId, Int refLayerId, Bool flag ) { m_ctuBasedOffsetEnabledFlag[currLayerId][refLayerId] = flag;}
+  
+  Int    getMinHorizontalCtuOffsetPlus1 ( Int currLayerId, Int refLayerId )            { return m_minHorizontalCtuOffsetPlus1[currLayerId][refLayerId];}
+  Void   setMinHorizontalCtuOffsetPlus1 ( Int currLayerId, Int refLayerId, Int val )   { m_minHorizontalCtuOffsetPlus1[currLayerId][refLayerId] = val;}  
+#endif
+#if VPS_VUI_VIDEO_SIGNAL
+  Bool   getVideoSigPresentVpsFlag()           { return m_vidSigPresentVpsFlag; }
+  Void   setVideoSigPresentVpsFlag(Bool x)     { m_vidSigPresentVpsFlag = x;    }
+  Int    getNumVideoSignalInfo()               { return m_vpsVidSigInfo;        }
+  Void   setNumVideoSignalInfo(Int x)          { m_vpsVidSigInfo = x;           }
+  Int    getVideoSignalInfoIdx(Int idx)        { return m_vpsVidSigIdx[idx];    }
+  Void   setVideoSignalInfoIdx(Int idx, Int x) { m_vpsVidSigIdx[idx] = x;       }
+  Int    getVideoVPSFormat(Int idx)            { return m_vpsVidFormat[idx];    }
+  Void   setVideoVPSFormat(Int idx, Int x)     { m_vpsVidFormat[idx] = x;       }
+  Bool   getVideoFullRangeVpsFlag(Int idx)     { return m_vpsFullRangeFlag[idx];}
+  Void   setVideoFullRangeVpsFlag(Int idx, Bool x) { m_vpsFullRangeFlag[idx] = x;   }
+  Int    getColorPrimaries(Int idx)            { return m_vpsColorPrimaries[idx];   }
+  Void   setColorPrimaries(Int idx, Int x)     { m_vpsColorPrimaries[idx] = x;      }
+  Int    getTransCharacter(Int idx)            { return m_vpsTransChar[idx];    }
+  Void   setTransCharacter(Int idx, Int x)     { m_vpsTransChar[idx] = x;       }
+  Int    getMaxtrixCoeff(Int idx)              { return m_vpsMatCoeff[idx];     }
+  Void   setMaxtrixCoeff(Int idx, Int x)       { m_vpsMatCoeff[idx] = x;        }
+#endif
+  Bool   getBitRatePresentVpsFlag()       { return m_bitRatePresentVpsFlag; }
+  Void   setBitRatePresentVpsFlag(Bool x) { m_bitRatePresentVpsFlag = x;    }
+  Bool   getPicRatePresentVpsFlag()       { return m_picRatePresentVpsFlag; }
+  Void   setPicRatePresentVpsFlag(Bool x) { m_picRatePresentVpsFlag = x;    }
+         
+  Bool   getBitRatePresentFlag(Int i, Int j)          { return m_bitRatePresentFlag[i][j]; }
+  Void   setBitRatePresentFlag(Int i, Int j, Bool x)  { m_bitRatePresentFlag[i][j] = x;    }
+  Bool   getPicRatePresentFlag(Int i, Int j)          { return m_picRatePresentFlag[i][j]; }
+  Void   setPicRatePresentFlag(Int i, Int j, Bool x)  { m_picRatePresentFlag[i][j] = x;    }
+         
+  Int    getAvgBitRate(Int i, Int j)          { return m_avgBitRate[i][j]; }
+  Void   setAvgBitRate(Int i, Int j, Int x)   { m_avgBitRate[i][j] = x;    }
+  Int    getMaxBitRate(Int i, Int j)          { return m_maxBitRate[i][j]; }
+  Void   setMaxBitRate(Int i, Int j, Int x)   { m_maxBitRate[i][j] = x;    }
+         
+  Int    getConstPicRateIdc(Int i, Int j)          { return m_constPicRateIdc[i][j]; }
+  Void   setConstPicRateIdc(Int i, Int j, Int x)   { m_constPicRateIdc[i][j] = x;    }
+  Int    getAvgPicRate(Int i, Int j)          { return m_avgPicRate[i][j]; }
+  Void   setAvgPicRate(Int i, Int j, Int x)   { m_avgPicRate[i][j] = x;    }
+#if O0164_MULTI_LAYER_HRD
+  Bool     getVpsVuiBspHrdPresentFlag()                         { return m_vpsVuiBspHrdPresentFlag;      }
+  Void     setVpsVuiBspHrdPresentFlag(Bool x)                   { m_vpsVuiBspHrdPresentFlag = x;         }
+#if VPS_VUI_BSP_HRD_PARAMS
+  Int      getVpsNumAddHrdParams()                              { return m_vpsNumAddHrdParams; }
+  Void     setVpsNumAddHrdParams(Int  i)                   { m_vpsNumAddHrdParams = i;    }
+
+  Bool     getCprmsAddPresentFlag(Int i)                        { return m_cprmsAddPresentFlag[i];       }
+  Void     setCprmsAddPresentFlag(Int  i, Bool  val)  { m_cprmsAddPresentFlag[i] = val;        }
+
+  Int      getNumSubLayerHrdMinus1(Int i)           { return m_numSubLayerHrdMinus1[i]; }
+  Void     setNumSubLayerHrdMinus1(Int i, Int val)  { m_numSubLayerHrdMinus1[i] = val; }
+
+  TComHRD*  getBspHrd(Int i)           {return &m_bspHrd[i];}
+
+  Int      getNumSignalledPartitioningSchemes(Int  i)                    { return m_numSignalledPartitioningSchemes[i];    }
+  Void     setNumSignalledPartitioningSchemes(Int  i, Int  val)          { m_numSignalledPartitioningSchemes[i] = val;     }
+
+  Int      getNumPartitionsInSchemeMinus1(Int  i, Int j)  { return m_numPartitionsInSchemeMinus1[i][j];}
+  Void     setNumPartitionsInSchemeMinus1(Int i, Int j, Int val) { m_numPartitionsInSchemeMinus1[i][j] = val; }
+
+  Int      getLayerIncludedInPartitionFlag(Int  i, Int j, Int k, Int l)  { return m_layerIncludedInPartitionFlag[i][j][k][l];}
+  Void     setLayerIncludedInPartitionFlag(Int i, Int j, Int k, Int l, Int val) { m_layerIncludedInPartitionFlag[i][j][k][l] = val; }
+
+  Int      getNumBspSchedulesMinus1(Int  i, Int j, Int k)         { return m_numBspSchedulesMinus1[i][j][k];}
+  Void     setNumBspSchedulesMinus1(Int i, Int j, Int k, Int val) { m_numBspSchedulesMinus1[i][j][k] = val; }
+
+  Int      getBspSchedIdx(Int  i, Int j, Int k, Int l, Int m)  { return m_bspSchedIdx[i][j][k][l][m];}
+  Void     setBspSchedIdx(Int  i, Int j, Int k, Int l, Int m, Int val) { m_bspSchedIdx[i][j][k][l][m] = val; }
+
+  Int      getBspHrdIdx(Int  i, Int j, Int k, Int l, Int m)  { return m_bspHrdIdx[i][j][k][l][m];}
+  Void     setBspHrdIdx(Int  i, Int j, Int k, Int l, Int m, Int val) { m_bspHrdIdx[i][j][k][l][m] = val; }
+#else
+  UInt     getVpsNumBspHrdParametersMinus1()                    { return m_vpsNumBspHrdParametersMinus1; }
+  Void     setVpsNumBspHrdParametersMinus1(UInt i)              { m_vpsNumBspHrdParametersMinus1 = i;    }
+  Bool     getBspCprmsPresentFlag(UInt i)                       { return m_bspCprmsPresentFlag[i];       }
+  Void     setBspCprmsPresentFlag(UInt i, Bool val)             { m_bspCprmsPresentFlag[i] = val;        }
+  TComHRD* getBspHrd(UInt i)                                    { return &m_bspHrd[i];                    }
+  UInt     getNumBitstreamPartitions(UInt i)                    { return m_numBitstreamPartitions[i];    }
+  Void     setNumBitstreamPartitions(UInt i, UInt val)          { m_numBitstreamPartitions[i] = val;     }
+  UInt     getLayerInBspFlag(UInt h, UInt i, UInt j)            { return m_layerInBspFlag[h][i][j];      }
+  Void     setLayerInBspFlag(UInt h, UInt i, UInt j, UInt val)  { m_layerInBspFlag[h][i][j] = val;       }
+  UInt     getNumBspSchedCombinations(UInt i)                   { return m_numBspSchedCombinations[i];   }
+  Void     setNumBspSchedCombinations(UInt i, UInt val)         { m_numBspSchedCombinations[i] = val;    }
+  UInt     getBspCombHrdIdx(UInt h, UInt i, UInt j)             { return m_bspCombHrdIdx[h][i][j];       }
+  Void     setBspCombHrdIdx(UInt h, UInt i, UInt j, UInt val)   { m_bspCombHrdIdx[h][i][j] = val;        }
+  UInt     getBspCombSchedIdx(UInt h, UInt i, UInt j)           { return m_bspCombSchedIdx[h][i][j];     }
+  Void     setBspCombSchedIdx(UInt h, UInt i, UInt j, UInt val) { m_bspCombSchedIdx[h][i][j] = val;      }
+#endif
+#endif
+#if P0182_VPS_VUI_PS_FLAG
+  Void   setBaseLayerPSCompatibilityFlag (Int layer, int val)        { m_baseLayerPSCompatibilityFlag[layer] = val; }
+  Int    getBaseLayerPSCompatibilityFlag (Int layer)   { return m_baseLayerPSCompatibilityFlag[layer];}
+#endif
+
+#if P0312_VERT_PHASE_ADJ
+  Bool   getVpsVuiVertPhaseInUseFlag()       { return m_vpsVuiVertPhaseInUseFlag; }
+  Void   setVpsVuiVertPhaseInUseFlag(Bool x) { m_vpsVuiVertPhaseInUseFlag = x;    }
+#endif
+
+#if P0300_ALT_OUTPUT_LAYER_FLAG
+  Bool   getAltOuputLayerFlag(Int idx)         { return m_altOutputLayerFlag[idx]; }
+  Void   setAltOuputLayerFlag(Int idx, Bool x) { m_altOutputLayerFlag[idx] = x;    }
+#else
+#if O0153_ALT_OUTPUT_LAYER_FLAG
+  Bool   getAltOuputLayerFlag()             { return m_altOutputLayerFlag; }
+  Void   setAltOuputLayerFlag(Bool x)       { m_altOutputLayerFlag = x;    }
+#endif
+#endif
+#if REPN_FORMAT_IN_VPS
+  Bool   getRepFormatIdxPresentFlag()       { return m_repFormatIdxPresentFlag; }
+  Void   setRepFormatIdxPresentFlag(Bool x) { m_repFormatIdxPresentFlag = x;    }
+
+  Int    getVpsNumRepFormats()              { return m_vpsNumRepFormats;        }
+  Void   setVpsNumRepFormats(Int x)         { m_vpsNumRepFormats = x;           }
+
+  RepFormat* getVpsRepFormat(Int idx)       { return &m_vpsRepFormat[idx];      }
+
+  Int    getVpsRepFormatIdx(Int idx)        { return m_vpsRepFormatIdx[idx];    }
+  Void   setVpsRepFormatIdx(Int idx, Int x) { m_vpsRepFormatIdx[idx] = x;       }         
+#endif
+#if VIEW_ID_RELATED_SIGNALING
+#if O0109_VIEW_ID_LEN
+  Void   setViewIdLen( Int  val )                                   { m_viewIdLen = val;  } 
+  Int    getViewIdLen(  )                                           { return m_viewIdLen; } 
+#else
+  Void   setViewIdLenMinus1( Int  val )                             { m_viewIdLenMinus1 = val;  } 
+  Int    getViewIdLenMinus1(  )                                     { return m_viewIdLenMinus1; } 
+#endif
+
+  Void   setViewIdVal( Int viewOrderIndex, Int  val )               { m_viewIdVal[viewOrderIndex] = val;  } 
+  Int    getViewIdVal( Int viewOrderIndex )                         { return m_viewIdVal[viewOrderIndex]; } 
+  Int    getScalabilityId(Int, ScalabilityType scalType );
+
+  Int    getViewIndex    ( Int layerIdInNuh )                       { return getScalabilityId( getLayerIdxInVps(layerIdInNuh), VIEW_ORDER_INDEX  ); }    
+
+  Int    getNumViews();
+  Int    scalTypeToScalIdx( ScalabilityType scalType );
+#endif
+#if !P0125_REVERT_VPS_EXTN_OFFSET_TO_RESERVED
+#if VPS_EXTN_OFFSET
+  Int    getExtensionOffset()                 { return m_extensionOffset;   }
+  Void   setExtensionOffset( UInt offset )    { m_extensionOffset = offset; }
+#endif
+#endif
+#if O0215_PHASE_ALIGNMENT
+  Bool   getPhaseAlignFlag()                             { return m_phaseAlignFlag; }
+  Void   setPhaseAlignFlag(Bool x)                       { m_phaseAlignFlag = x;    }
+#endif
+#if VPS_DPB_SIZE_TABLE
+  Bool   getSubLayerFlagInfoPresentFlag(Int olsIdx)         { return m_subLayerFlagInfoPresentFlag[olsIdx]; }
+  Void   setSubLayerFlagInfoPresentFlag(Int olsIdx, Bool x) { m_subLayerFlagInfoPresentFlag[olsIdx] = x;    }
+
+  Bool   getSubLayerDpbInfoPresentFlag(Int olsIdx, Int subLayerIdx)         { return m_subLayerDpbInfoPresentFlag[olsIdx][subLayerIdx]; }
+  Void   setSubLayerDpbInfoPresentFlag(Int olsIdx, Int subLayerIdx, Bool x) { m_subLayerDpbInfoPresentFlag[olsIdx][subLayerIdx] = x;    }
+
+  // For the 0-th output layer set, use the date from the active SPS for base layer.
+  Int    getMaxVpsDecPicBufferingMinus1(Int olsIdx, Int subDpbIdx, Int subLayerIdx)        { assert(olsIdx != 0); return m_maxVpsDecPicBufferingMinus1[olsIdx][subDpbIdx][subLayerIdx]; }
+  Void   setMaxVpsDecPicBufferingMinus1(Int olsIdx, Int subDpbIdx, Int subLayerIdx, Int x) { m_maxVpsDecPicBufferingMinus1[olsIdx][subDpbIdx][subLayerIdx] = x;    }
+  Int    getLayerIdcForOls( Int olsIdx, Int layerId );
+
+#if RESOLUTION_BASED_DPB
+  Int    getMaxVpsLayerDecPicBuffMinus1(Int i, Int k, Int j)        { assert(i != 0); return m_maxVpsLayerDecPicBuffMinus1[i][k][j]; }
+  Void   setMaxVpsLayerDecPicBuffMinus1(Int i, Int k, Int j, Int x) { m_maxVpsLayerDecPicBuffMinus1[i][k][j] = x;    }
+#endif
+
+  Int    getMaxVpsNumReorderPics(Int olsIdx, Int subLayerIdx)        { assert(olsIdx != 0); return m_maxVpsNumReorderPics[olsIdx][subLayerIdx]; }
+  Void   setMaxVpsNumReorderPics(Int olsIdx, Int subLayerIdx, Int x) { m_maxVpsNumReorderPics[olsIdx][subLayerIdx] = x;    }
+
+  Int    getMaxVpsLatencyIncreasePlus1(Int olsIdx, Int subLayerIdx)        { assert(olsIdx != 0); return m_maxVpsLatencyIncreasePlus1[olsIdx][subLayerIdx]; }
+  Void   setMaxVpsLatencyIncreasePlus1(Int olsIdx, Int subLayerIdx, Int x) { m_maxVpsLatencyIncreasePlus1[olsIdx][subLayerIdx] = x;    }
+
+  Int    getNumSubDpbs(Int olsIdx)                          { return m_numSubDpbs[olsIdx]; }
+  Void   setNumSubDpbs(Int olsIdx, Int x)                   { m_numSubDpbs[olsIdx] = x;    }
+  Void   determineSubDpbInfoFlags();
+#endif
+
+#if O0109_MOVE_VPS_VUI_FLAG
+  Bool   getVpsVuiPresentFlag()                        { return m_vpsVuiPresentFlag; }
+  Void   setVpsVuiPresentFlag(Bool x)                  { m_vpsVuiPresentFlag = x;    }
+#endif
+  Bool   getVpsExtensionFlag()                         { return m_vpsExtensionFlag;  }
+  Void   setVpsExtensionFlag(Bool x)                   { m_vpsExtensionFlag = x;     }
+
+#if !P0307_REMOVE_VPS_VUI_OFFSET
+#if VPS_VUI_OFFSET
+  Int    getVpsVuiOffset()         { return m_vpsVuiOffset; }
+  Void   setVpsVuiOffset(Int x)    { m_vpsVuiOffset = x; }
+#endif
+#endif
+#if P0307_VPS_NON_VUI_EXTENSION
+  Int    getVpsNonVuiExtLength()         { return m_vpsNonVuiExtLength; }
+  Void   setVpsNonVuiExtLength(Int x)    { m_vpsNonVuiExtLength = x; }
+#endif
+#if RESOLUTION_BASED_DPB
+  Void   assignSubDpbIndices();
+  Int    getSubDpbAssigned  (Int lsIdx, Int layerIdx) { return m_subDpbAssigned[lsIdx][layerIdx]; }
+  Int    findLayerIdxInLayerSet ( Int lsIdx, Int nuhLayerId );
+#endif
+#if O0164_MULTI_LAYER_HRD
+  Void setBspHrdParameters( UInt hrdIdx, UInt frameRate, UInt numDU, UInt bitRate, Bool randomAccess );
+#endif
+#if NECESSARY_LAYER_FLAG
+  Void  deriveNecessaryLayerFlag();
+  Void  deriveNecessaryLayerFlag(Int const olsIdx);
+  Void  checkNecessaryLayerFlagCondition();
+#endif
+#if SUB_LAYERS_IN_LAYER_SET
+  Void  calculateMaxSLInLayerSets();
+#endif
+#endif //SVC_EXTENSION
+};
+
+class TComVUI
+{
+private:
+  Bool m_aspectRatioInfoPresentFlag;
+  Int  m_aspectRatioIdc;
+  Int  m_sarWidth;
+  Int  m_sarHeight;
+  Bool m_overscanInfoPresentFlag;
+  Bool m_overscanAppropriateFlag;
+  Bool m_videoSignalTypePresentFlag;
+  Int  m_videoFormat;
+  Bool m_videoFullRangeFlag;
+  Bool m_colourDescriptionPresentFlag;
+  Int  m_colourPrimaries;
+  Int  m_transferCharacteristics;
+  Int  m_matrixCoefficients;
+  Bool m_chromaLocInfoPresentFlag;
+  Int  m_chromaSampleLocTypeTopField;
+  Int  m_chromaSampleLocTypeBottomField;
+  Bool m_neutralChromaIndicationFlag;
+  Bool m_fieldSeqFlag;
+  Window m_defaultDisplayWindow;
+  Bool m_frameFieldInfoPresentFlag;
+  Bool m_hrdParametersPresentFlag;
+  Bool m_bitstreamRestrictionFlag;
+  Bool m_tilesFixedStructureFlag;
+  Bool m_motionVectorsOverPicBoundariesFlag;
+  Bool m_restrictedRefPicListsFlag;
+  Int  m_minSpatialSegmentationIdc;
+  Int  m_maxBytesPerPicDenom;
+  Int  m_maxBitsPerMinCuDenom;
+  Int  m_log2MaxMvLengthHorizontal;
+  Int  m_log2MaxMvLengthVertical;
+  TComHRD m_hrdParameters;
+  TimingInfo m_timingInfo;
+
+public:
+  TComVUI()
+    :m_aspectRatioInfoPresentFlag(false) //TODO: This initialiser list contains magic numbers
+    ,m_aspectRatioIdc(0)
+    ,m_sarWidth(0)
+    ,m_sarHeight(0)
+    ,m_overscanInfoPresentFlag(false)
+    ,m_overscanAppropriateFlag(false)
+    ,m_videoSignalTypePresentFlag(false)
+    ,m_videoFormat(5)
+    ,m_videoFullRangeFlag(false)
+    ,m_colourDescriptionPresentFlag(false)
+    ,m_colourPrimaries(2)
+    ,m_transferCharacteristics(2)
+    ,m_matrixCoefficients(2)
+    ,m_chromaLocInfoPresentFlag(false)
+    ,m_chromaSampleLocTypeTopField(0)
+    ,m_chromaSampleLocTypeBottomField(0)
+    ,m_neutralChromaIndicationFlag(false)
+    ,m_fieldSeqFlag(false)
+    ,m_frameFieldInfoPresentFlag(false)
+    ,m_hrdParametersPresentFlag(false)
+    ,m_bitstreamRestrictionFlag(false)
+    ,m_tilesFixedStructureFlag(false)
+    ,m_motionVectorsOverPicBoundariesFlag(true)
+    ,m_restrictedRefPicListsFlag(1)
+    ,m_minSpatialSegmentationIdc(0)
+    ,m_maxBytesPerPicDenom(2)
+    ,m_maxBitsPerMinCuDenom(1)
+    ,m_log2MaxMvLengthHorizontal(15)
+    ,m_log2MaxMvLengthVertical(15)
+  {}
+
+  virtual ~TComVUI() {}
+
+  Bool getAspectRatioInfoPresentFlag() { return m_aspectRatioInfoPresentFlag; }
+  Void setAspectRatioInfoPresentFlag(Bool i) { m_aspectRatioInfoPresentFlag = i; }
+
+  Int getAspectRatioIdc() { return m_aspectRatioIdc; }
+  Void setAspectRatioIdc(Int i) { m_aspectRatioIdc = i; }
+
+  Int getSarWidth() { return m_sarWidth; }
+  Void setSarWidth(Int i) { m_sarWidth = i; }
+
+  Int getSarHeight() { return m_sarHeight; }
+  Void setSarHeight(Int i) { m_sarHeight = i; }
+
+  Bool getOverscanInfoPresentFlag() { return m_overscanInfoPresentFlag; }
+  Void setOverscanInfoPresentFlag(Bool i) { m_overscanInfoPresentFlag = i; }
+
+  Bool getOverscanAppropriateFlag() { return m_overscanAppropriateFlag; }
+  Void setOverscanAppropriateFlag(Bool i) { m_overscanAppropriateFlag = i; }
+
+  Bool getVideoSignalTypePresentFlag() { return m_videoSignalTypePresentFlag; }
+  Void setVideoSignalTypePresentFlag(Bool i) { m_videoSignalTypePresentFlag = i; }
+
+  Int getVideoFormat() { return m_videoFormat; }
+  Void setVideoFormat(Int i) { m_videoFormat = i; }
+
+  Bool getVideoFullRangeFlag() { return m_videoFullRangeFlag; }
+  Void setVideoFullRangeFlag(Bool i) { m_videoFullRangeFlag = i; }
+
+  Bool getColourDescriptionPresentFlag() { return m_colourDescriptionPresentFlag; }
+  Void setColourDescriptionPresentFlag(Bool i) { m_colourDescriptionPresentFlag = i; }
+
+  Int getColourPrimaries() { return m_colourPrimaries; }
+  Void setColourPrimaries(Int i) { m_colourPrimaries = i; }
+
+  Int getTransferCharacteristics() { return m_transferCharacteristics; }
+  Void setTransferCharacteristics(Int i) { m_transferCharacteristics = i; }
+
+  Int getMatrixCoefficients() { return m_matrixCoefficients; }
+  Void setMatrixCoefficients(Int i) { m_matrixCoefficients = i; }
+
+  Bool getChromaLocInfoPresentFlag() { return m_chromaLocInfoPresentFlag; }
+  Void setChromaLocInfoPresentFlag(Bool i) { m_chromaLocInfoPresentFlag = i; }
+
+  Int getChromaSampleLocTypeTopField() { return m_chromaSampleLocTypeTopField; }
+  Void setChromaSampleLocTypeTopField(Int i) { m_chromaSampleLocTypeTopField = i; }
+
+  Int getChromaSampleLocTypeBottomField() { return m_chromaSampleLocTypeBottomField; }
+  Void setChromaSampleLocTypeBottomField(Int i) { m_chromaSampleLocTypeBottomField = i; }
+
+  Bool getNeutralChromaIndicationFlag() { return m_neutralChromaIndicationFlag; }
+  Void setNeutralChromaIndicationFlag(Bool i) { m_neutralChromaIndicationFlag = i; }
+
+  Bool getFieldSeqFlag() { return m_fieldSeqFlag; }
+  Void setFieldSeqFlag(Bool i) { m_fieldSeqFlag = i; }
+
+  Bool getFrameFieldInfoPresentFlag() { return m_frameFieldInfoPresentFlag; }
+  Void setFrameFieldInfoPresentFlag(Bool i) { m_frameFieldInfoPresentFlag = i; }
+
+  Window& getDefaultDisplayWindow()                              { return m_defaultDisplayWindow;                }
+  Void    setDefaultDisplayWindow(Window& defaultDisplayWindow ) { m_defaultDisplayWindow = defaultDisplayWindow; }
+
+  Bool getHrdParametersPresentFlag() { return m_hrdParametersPresentFlag; }
+  Void setHrdParametersPresentFlag(Bool i) { m_hrdParametersPresentFlag = i; }
+
+  Bool getBitstreamRestrictionFlag() { return m_bitstreamRestrictionFlag; }
+  Void setBitstreamRestrictionFlag(Bool i) { m_bitstreamRestrictionFlag = i; }
+
+  Bool getTilesFixedStructureFlag() { return m_tilesFixedStructureFlag; }
+  Void setTilesFixedStructureFlag(Bool i) { m_tilesFixedStructureFlag = i; }
+
+  Bool getMotionVectorsOverPicBoundariesFlag() { return m_motionVectorsOverPicBoundariesFlag; }
+  Void setMotionVectorsOverPicBoundariesFlag(Bool i) { m_motionVectorsOverPicBoundariesFlag = i; }
+
+  Bool getRestrictedRefPicListsFlag() { return m_restrictedRefPicListsFlag; }
+  Void setRestrictedRefPicListsFlag(Bool b) { m_restrictedRefPicListsFlag = b; }
+
+  Int getMinSpatialSegmentationIdc() { return m_minSpatialSegmentationIdc; }
+  Void setMinSpatialSegmentationIdc(Int i) { m_minSpatialSegmentationIdc = i; }
+
+  Int getMaxBytesPerPicDenom() { return m_maxBytesPerPicDenom; }
+  Void setMaxBytesPerPicDenom(Int i) { m_maxBytesPerPicDenom = i; }
+
+  Int getMaxBitsPerMinCuDenom() { return m_maxBitsPerMinCuDenom; }
+  Void setMaxBitsPerMinCuDenom(Int i) { m_maxBitsPerMinCuDenom = i; }
+
+  Int getLog2MaxMvLengthHorizontal() { return m_log2MaxMvLengthHorizontal; }
+  Void setLog2MaxMvLengthHorizontal(Int i) { m_log2MaxMvLengthHorizontal = i; }
+
+  Int getLog2MaxMvLengthVertical() { return m_log2MaxMvLengthVertical; }
+  Void setLog2MaxMvLengthVertical(Int i) { m_log2MaxMvLengthVertical = i; }
+
+  TComHRD* getHrdParameters                 ()             { return &m_hrdParameters; }
+
+  TimingInfo* getTimingInfo() { return &m_timingInfo; }
+};
+
+/// SPS class
+class TComSPS
+{
+private:
+  Int          m_SPSId;
+  Int          m_VPSId;
+  ChromaFormat m_chromaFormatIdc;
+
+  UInt        m_uiMaxTLayers;           // maximum number of temporal layers
+
+#if R0279_REP_FORMAT_INBL
+  Bool        m_bV1CompatibleSPSFlag;
+#endif
+
+  // Structure
+  UInt        m_picWidthInLumaSamples;
+  UInt        m_picHeightInLumaSamples;
+
+  Int         m_log2MinCodingBlockSize;
+  Int         m_log2DiffMaxMinCodingBlockSize;
+  UInt        m_uiMaxCUWidth;
+  UInt        m_uiMaxCUHeight;
+  UInt        m_uiMaxCUDepth;
+
+  Window      m_conformanceWindow;
+
+  TComRPSList m_RPSList;
+  Bool        m_bLongTermRefsPresent;
+  Bool        m_TMVPFlagsPresent;
+  Int         m_numReorderPics[MAX_TLAYER];
+
+  // Tool list
+  UInt        m_uiQuadtreeTULog2MaxSize;
+  UInt        m_uiQuadtreeTULog2MinSize;
+  UInt        m_uiQuadtreeTUMaxDepthInter;
+  UInt        m_uiQuadtreeTUMaxDepthIntra;
+  Bool        m_usePCM;
+  UInt        m_pcmLog2MaxSize;
+  UInt        m_uiPCMLog2MinSize;
+  Bool        m_useAMP;
+
+  // Parameter
+  Int         m_uiBitDepth[MAX_NUM_CHANNEL_TYPE];
+  Int         m_qpBDOffset[MAX_NUM_CHANNEL_TYPE];
+  Bool        m_useExtendedPrecision;
+  Bool        m_useHighPrecisionPredictionWeighting;
+  Bool        m_useResidualRotation;
+  Bool        m_useSingleSignificanceMapContext;
+  Bool        m_useGolombRiceParameterAdaptation;
+  Bool        m_alignCABACBeforeBypass;
+  Bool        m_useResidualDPCM[NUMBER_OF_RDPCM_SIGNALLING_MODES];
+  UInt        m_uiPCMBitDepth[MAX_NUM_CHANNEL_TYPE];
+  Bool        m_bPCMFilterDisableFlag;
+  Bool        m_disableIntraReferenceSmoothing;
+
+  UInt        m_uiBitsForPOC;
+  UInt        m_numLongTermRefPicSPS;
+  UInt        m_ltRefPicPocLsbSps[MAX_NUM_LONG_TERM_REF_PICS];
+  Bool        m_usedByCurrPicLtSPSFlag[MAX_NUM_LONG_TERM_REF_PICS];
+  // 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 O0043_BEST_EFFORT_DECODING
+  UInt        m_forceDecodeBitDepth; // 0 = do not force the decoder's bit depth, other = force the decoder's bit depth to this value (best effort decoding)
+#endif
+
+#if SVC_EXTENSION
+  UInt        m_layerId;
+  Bool        m_extensionFlag;
+  UInt        m_numScaledRefLayerOffsets;
+  Bool        m_multiLayerExtSpsFlag;
+#if R0042_PROFILE_INDICATION  
+  Int         m_NumDirectRefLayers;
+#endif
+#if P0312_VERT_PHASE_ADJ
+ Bool         m_vertPhasePositionEnableFlag[MAX_LAYERS];
+#endif
+#if !MOVE_SCALED_OFFSET_TO_PPS
+#if O0098_SCALED_REF_LAYER_ID
+  UInt        m_scaledRefLayerId[MAX_LAYERS];
+#endif
+  Window      m_scaledRefLayerWindow[MAX_LAYERS];
+#endif
+#if REPN_FORMAT_IN_VPS
+  Bool m_updateRepFormatFlag;
+#if O0096_REP_FORMAT_INDEX
+  UInt        m_updateRepFormatIndex;
+#endif
+#endif
+#if SCALINGLIST_INFERRING
+  Bool        m_inferScalingListFlag;
+  UInt        m_scalingListRefLayerId;
+#endif
+#endif //SVC_EXTENSION
+
+public:
+  TComSPS();
+  virtual ~TComSPS();
+#if O0043_BEST_EFFORT_DECODING
+  Void setForceDecodeBitDepth(UInt bitDepth) { m_forceDecodeBitDepth = bitDepth; }
+  UInt getForceDecodeBitDepth()        const { return m_forceDecodeBitDepth;     }
+#endif
+
+  Int  getVPSId       ()         { return m_VPSId;          }
+  Void setVPSId       (Int i)    { m_VPSId = i;             }
+  Int  getSPSId       ()         { return m_SPSId;          }
+  Void setSPSId       (Int i)    { m_SPSId = i;             }
+  ChromaFormat  getChromaFormatIdc ()         { return m_chromaFormatIdc;       }
+  Void setChromaFormatIdc (ChromaFormat 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];      }
+
+#if R0279_REP_FORMAT_INBL //These two functions shall be used / called when the syntax element sps_ext_or_max_sub_layers_minus1 and V1CompatibleSPSFlag are implemented
+  Bool getV1CompatibleSPSFlag()        {return m_bV1CompatibleSPSFlag;}
+  Void setV1CompatibleSPSFlag(Bool x)       { m_bV1CompatibleSPSFlag = x;}
+#endif
+
+  // 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)             { assert( index < MAX_NUM_LONG_TERM_REF_PICS ); return m_ltRefPicPocLsbSps[index]; }
+  Void  setLtRefPicPocLsbSps(UInt index, UInt val)   { assert( index < MAX_NUM_LONG_TERM_REF_PICS ); m_ltRefPicPocLsbSps[index] = val; }
+
+  Bool getUsedByCurrPicLtSPSFlag(Int i)              { assert( i < MAX_NUM_LONG_TERM_REF_PICS ); return m_usedByCurrPicLtSPSFlag[i];}
+  Void setUsedByCurrPicLtSPSFlag(Int i, Bool x)      { assert( i < MAX_NUM_LONG_TERM_REF_PICS ); m_usedByCurrPicLtSPSFlag[i] = x;}
+
+  Int  getLog2MinCodingBlockSize() const           { return m_log2MinCodingBlockSize; }
+  Void setLog2MinCodingBlockSize(Int val)          { m_log2MinCodingBlockSize = val; }
+  Int  getLog2DiffMaxMinCodingBlockSize() const    { return m_log2DiffMaxMinCodingBlockSize; }
+  Void setLog2DiffMaxMinCodingBlockSize(Int val)   { m_log2DiffMaxMinCodingBlockSize = val; }
+
+  Void setMaxCUWidth  ( UInt u ) { m_uiMaxCUWidth = u;      }
+  UInt getMaxCUWidth  ()         { return  m_uiMaxCUWidth;  }
+  Void setMaxCUHeight ( UInt u ) { m_uiMaxCUHeight = u;     }
+  UInt getMaxCUHeight ()         { return  m_uiMaxCUHeight; }
+  Void setMaxCUDepth  ( UInt u ) { m_uiMaxCUDepth = u;      }
+  UInt getMaxCUDepth  ()         { return  m_uiMaxCUDepth;  }
+  Void setUsePCM      ( Bool b ) { m_usePCM = b;           }
+  Bool getUsePCM      ()         { return m_usePCM;        }
+  Void setPCMLog2MaxSize  ( UInt u ) { m_pcmLog2MaxSize = u;      }
+  UInt getPCMLog2MaxSize  ()         { return  m_pcmLog2MaxSize;  }
+  Void setPCMLog2MinSize  ( UInt u ) { m_uiPCMLog2MinSize = u;      }
+  UInt getPCMLog2MinSize  ()         { return  m_uiPCMLog2MinSize;  }
+  Void setBitsForPOC  ( UInt u ) { m_uiBitsForPOC = u;      }
+  UInt getBitsForPOC  ()         { return m_uiBitsForPOC;   }
+  Bool getUseAMP() { return m_useAMP; }
+  Void setUseAMP( Bool b ) { m_useAMP = b; }
+  Void setQuadtreeTULog2MaxSize( UInt u ) { m_uiQuadtreeTULog2MaxSize = u;    }
+  UInt getQuadtreeTULog2MaxSize()         { return m_uiQuadtreeTULog2MaxSize; }
+  Void setQuadtreeTULog2MinSize( UInt u ) { m_uiQuadtreeTULog2MinSize = u;    }
+  UInt getQuadtreeTULog2MinSize()         { return m_uiQuadtreeTULog2MinSize; }
+  Void setQuadtreeTUMaxDepthInter( UInt u ) { m_uiQuadtreeTUMaxDepthInter = u;    }
+  Void setQuadtreeTUMaxDepthIntra( UInt u ) { m_uiQuadtreeTUMaxDepthIntra = u;    }
+  UInt getQuadtreeTUMaxDepthInter()         { return m_uiQuadtreeTUMaxDepthInter; }
+  UInt getQuadtreeTUMaxDepthIntra()         { return m_uiQuadtreeTUMaxDepthIntra; }
+  Void setNumReorderPics(Int i, UInt tlayer)              { m_numReorderPics[tlayer] = i;    }
+  Int  getNumReorderPics(UInt tlayer)                     { return m_numReorderPics[tlayer]; }
+  Void         createRPSList( Int numRPS );
+  TComRPSList* getRPSList()                      { return &m_RPSList;          }
+  Bool      getLongTermRefsPresent()         { return m_bLongTermRefsPresent; }
+  Void      setLongTermRefsPresent(Bool b)   { m_bLongTermRefsPresent=b;      }
+  Bool      getTMVPFlagsPresent()         { return m_TMVPFlagsPresent; }
+  Void      setTMVPFlagsPresent(Bool b)   { m_TMVPFlagsPresent=b;      }
+  // physical transform
+  Void setMaxTrSize   ( UInt u ) { m_uiMaxTrSize = u;       }
+  UInt getMaxTrSize   ()         { return  m_uiMaxTrSize;   }
+
+  // AMP accuracy
+  Int       getAMPAcc   ( UInt uiDepth ) { return m_iAMPAcc[uiDepth]; }
+  Void      setAMPAcc   ( UInt uiDepth, Int iAccu ) { assert( uiDepth < g_uiMaxCUDepth);  m_iAMPAcc[uiDepth] = iAccu; }
+
+  // Bit-depth
+  Int       getBitDepth     (ChannelType type)         { return m_uiBitDepth[type];   }
+  Void      setBitDepth     (ChannelType type, Int u ) { m_uiBitDepth[type] = u;      }
+  Int       getDifferentialLumaChromaBitDepth() const  { return Int(m_uiBitDepth[CHANNEL_TYPE_LUMA]) - Int(m_uiBitDepth[CHANNEL_TYPE_CHROMA]); }
+  Int       getQpBDOffset   (ChannelType type) const   { return m_qpBDOffset[type];   }
+  Void      setQpBDOffset   (ChannelType type, Int i)  { m_qpBDOffset[type] = i;      }
+  Bool      getUseExtendedPrecision()          const   { return m_useExtendedPrecision;  }
+  Void      setUseExtendedPrecision(Bool value)        { m_useExtendedPrecision = value; }
+  Bool      getUseHighPrecisionPredictionWeighting() const { return m_useHighPrecisionPredictionWeighting; }
+  Void      setUseHighPrecisionPredictionWeighting(Bool value) { m_useHighPrecisionPredictionWeighting = value; }
+
+  Void      setUseSAO                  (Bool bVal)  {m_bUseSAO = bVal;}
+  Bool      getUseSAO                  ()           {return m_bUseSAO;}
+
+  Bool      getUseResidualRotation            ()                 const { return m_useResidualRotation;  }
+  Void      setUseResidualRotation            (const Bool value)       { m_useResidualRotation = value; }
+
+  Bool      getUseSingleSignificanceMapContext()                 const { return m_useSingleSignificanceMapContext;  }
+  Void      setUseSingleSignificanceMapContext(const Bool value)       { m_useSingleSignificanceMapContext = value; }
+
+  Bool      getUseGolombRiceParameterAdaptation()                 const { return m_useGolombRiceParameterAdaptation;  }
+  Void      setUseGolombRiceParameterAdaptation(const Bool value)       { m_useGolombRiceParameterAdaptation = value; }
+
+  Bool      getAlignCABACBeforeBypass         ()                 const { return m_alignCABACBeforeBypass;  }
+  Void      setAlignCABACBeforeBypass         (const Bool value)       { m_alignCABACBeforeBypass = value; }
+
+  Bool      getUseResidualDPCM (const RDPCMSignallingMode signallingMode)        const      { return m_useResidualDPCM[signallingMode];  }
+  Void      setUseResidualDPCM (const RDPCMSignallingMode signallingMode, const Bool value) { m_useResidualDPCM[signallingMode] = value; }
+
+  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      getPCMBitDepth         (ChannelType type) const   { return m_uiPCMBitDepth[type]; }
+  Void      setPCMBitDepth         (ChannelType type, UInt u) { m_uiPCMBitDepth[type] = u;    }
+  Void      setPCMFilterDisableFlag     ( Bool   bValue  )    { m_bPCMFilterDisableFlag = bValue; }
+  Bool      getPCMFilterDisableFlag     ()                    { return m_bPCMFilterDisableFlag;   }
+  Void      setDisableIntraReferenceSmoothing (Bool bValue)   { m_disableIntraReferenceSmoothing=bValue; }
+  Bool      getDisableIntraReferenceSmoothing ()        const { return m_disableIntraReferenceSmoothing; }
+
+  Bool getScalingListFlag       ()         { return m_scalingListEnabledFlag;     }
+  Void setScalingListFlag       ( Bool b ) { m_scalingListEnabledFlag  = b;       }
+  Bool getScalingListPresentFlag()         { return m_scalingListPresentFlag;     }
+  Void setScalingListPresentFlag( Bool b ) { m_scalingListPresentFlag  = b;       }
+
+#if SCALINGLIST_INFERRING
+  Void setScalingList( TComScalingList *scalingList ) { m_scalingList = scalingList; }
+#else
+  Void setScalingList      ( TComScalingList *scalingList);
+#endif
+  TComScalingList* getScalingList ()       { return m_scalingList; }               //!< get ScalingList class pointer in SPS
+  UInt getMaxDecPicBuffering  (UInt tlayer)            { return m_uiMaxDecPicBuffering[tlayer]; }
+  Void setMaxDecPicBuffering  ( UInt ui, UInt tlayer ) { assert(tlayer < MAX_TLAYER);  m_uiMaxDecPicBuffering[tlayer] = ui;   }
+  UInt getMaxLatencyIncrease  (UInt tlayer)            { return m_uiMaxLatencyIncrease[tlayer];   }
+  Void setMaxLatencyIncrease  ( UInt ui , UInt tlayer) { m_uiMaxLatencyIncrease[tlayer] = ui;      }
+
+  Void setUseStrongIntraSmoothing (Bool bVal)  {m_useStrongIntraSmoothing = bVal;}
+  Bool getUseStrongIntraSmoothing ()           {return m_useStrongIntraSmoothing;}
+
+  Bool getVuiParametersPresentFlag() { return m_vuiParametersPresentFlag; }
+  Void setVuiParametersPresentFlag(Bool b) { m_vuiParametersPresentFlag = b; }
+  TComVUI* getVuiParameters() { return &m_vuiParameters; }
+  Void setHrdParameters( UInt frameRate, UInt numDU, UInt bitRate, Bool randomAccess );
+
+  TComPTL* getPTL()     { return &m_pcPTL; }
+
+#if SVC_EXTENSION
+  Void     setLayerId(UInt layerId)                 { m_layerId = layerId;           }
+  UInt     getLayerId()                             { return m_layerId;              }
+  Int      getExtensionFlag()                       { return m_extensionFlag;        }
+  Void     setExtensionFlag(Int n)                  { m_extensionFlag = n;           }
+  Bool     getMultiLayerExtSpsFlag()                { return m_multiLayerExtSpsFlag; }
+  Void     setMultiLayerExtSpsFlag(Bool flag)       { m_multiLayerExtSpsFlag = flag; }
+#if R0042_PROFILE_INDICATION
+  Int      getNumDirectRefLayers()                  { return  m_NumDirectRefLayers;  }
+  Void     setNumDirectRefLayers(Int n)             {  m_NumDirectRefLayers = n;     }
+#endif
+#if !MOVE_SCALED_OFFSET_TO_PPS
+  UInt     getNumScaledRefLayerOffsets()       { return m_numScaledRefLayerOffsets; }
+  Void     setNumScaledRefLayerOffsets(Int x)  { m_numScaledRefLayerOffsets = x;    }
+#if P0312_VERT_PHASE_ADJ
+  Bool     getVertPhasePositionEnableFlag(Int x)          { return m_vertPhasePositionEnableFlag[x]; }
+  Void     setVertPhasePositionEnableFlag(Int x, Bool b)  { m_vertPhasePositionEnableFlag[x] = b;    } 
+#endif
+#if O0098_SCALED_REF_LAYER_ID
+  UInt     getScaledRefLayerId(Int x)          { return m_scaledRefLayerId[x]; }
+  Void     setScaledRefLayerId(Int x, UInt id) { m_scaledRefLayerId[x] = id;   }
+  Window&  getScaledRefLayerWindowForLayer( Int layerId );
+#endif
+  Window&  getScaledRefLayerWindow( Int x )   { return m_scaledRefLayerWindow[x]; }
+#endif
+#if REPN_FORMAT_IN_VPS
+  Bool     getUpdateRepFormatFlag()       { return m_updateRepFormatFlag; }
+  Void     setUpdateRepFormatFlag(Bool x) { m_updateRepFormatFlag = x;    }
+#if O0096_REP_FORMAT_INDEX
+  Int      getUpdateRepFormatIndex()      { return m_updateRepFormatIndex; }
+  Void     setUpdateRepFormatIndex(UInt index)  { m_updateRepFormatIndex = index; }
+#endif
+#endif
+#if SCALINGLIST_INFERRING
+  Bool     getInferScalingListFlag()  { return m_inferScalingListFlag;  }
+  UInt     getScalingListRefLayerId() { return m_scalingListRefLayerId; }
+  Void     setInferScalingListFlag( Bool flag )     { m_inferScalingListFlag = flag;     }
+  Void     setScalingListRefLayerId( UInt layerId ) { m_scalingListRefLayerId = layerId; }
+#endif
+#endif //SVC_EXTENSION
+};
+
+/// Reference Picture Lists class
+
+class TComRefPicListModification
+{
+private:
+  UInt      m_bRefPicListModificationFlagL0;
+  UInt      m_bRefPicListModificationFlagL1;
+  UInt      m_RefPicSetIdxL0[REF_PIC_LIST_NUM_IDX];
+  UInt      m_RefPicSetIdxL1[REF_PIC_LIST_NUM_IDX];
+
+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) { assert(idx<REF_PIC_LIST_NUM_IDX); m_RefPicSetIdxL0[idx] = refPicSetIdx; }
+  UInt       getRefPicSetIdxL0(UInt idx) { assert(idx<REF_PIC_LIST_NUM_IDX); return m_RefPicSetIdxL0[idx]; }
+  Void       setRefPicSetIdxL1(UInt idx, UInt refPicSetIdx) { assert(idx<REF_PIC_LIST_NUM_IDX); m_RefPicSetIdxL1[idx] = refPicSetIdx; }
+  UInt       getRefPicSetIdxL1(UInt idx) { assert(idx<REF_PIC_LIST_NUM_IDX); return m_RefPicSetIdxL1[idx]; }
+};
+
+/// 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;
+
+  /* Chroma QP Adjustments*/
+  Int         m_MaxCuChromaQpAdjDepth;
+  Int         m_MinCuChromaQpAdjSize;
+  Int         m_ChromaQpAdjTableSize;
+  ChromaQpAdj m_ChromaQpAdjTable[7];
+
+  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_useCrossComponentPrediction;
+  UInt        m_saoOffsetBitShift[MAX_NUM_CHANNEL_TYPE];
+  Bool        m_TransquantBypassEnableFlag; // Indicates presence of cu_transquant_bypass_flag in CUs.
+  Bool        m_useTransformSkip;
+  Int         m_transformSkipLog2MaxSize;
+  Bool        m_dependentSliceSegmentsEnabledFlag;     //!< Indicates the presence of dependent slices
+  Bool        m_tilesEnabledFlag;              //!< Indicates the presence of tiles
+  Bool        m_entropyCodingSyncEnabledFlag;  //!< Indicates the presence of wavefronts
+
+  Bool             m_loopFilterAcrossTilesEnabledFlag;
+  Bool             m_uniformSpacingFlag;
+  Int              m_numTileColumnsMinus1;
+  Int              m_numTileRowsMinus1;
+  std::vector<Int> m_tileColumnWidth;
+  std::vector<Int> m_tileRowHeight;
+
+  Int      m_numSubstreams;
+
+  Int      m_signHideFlag;
+
+  Bool     m_cabacInitPresentFlag;
+  UInt     m_encCABACTableIdx;           // Used to transmit table selection across slices
+
+  Bool     m_sliceHeaderExtensionPresentFlag;
+  Bool     m_loopFilterAcrossSlicesEnabledFlag;
+  Bool     m_deblockingFilterControlPresentFlag;
+  Bool     m_deblockingFilterOverrideEnabledFlag;
+  Bool     m_picDisableDeblockingFilterFlag;
+  Int      m_deblockingFilterBetaOffsetDiv2;    //< beta offset for deblocking filter
+  Int      m_deblockingFilterTcOffsetDiv2;      //< tc offset for deblocking filter
+  Bool     m_scalingListPresentFlag;
+  TComScalingList*     m_scalingList;   //!< ScalingList class pointer
+  Bool     m_listsModificationPresentFlag;
+  UInt     m_log2ParallelMergeLevelMinus2;
+  Int      m_numExtraSliceHeaderBits;
+
+#if SVC_EXTENSION
+  Bool     m_extensionFlag;
+#if SCALINGLIST_INFERRING
+  UInt     m_layerId;
+  Bool     m_inferScalingListFlag;
+  UInt     m_scalingListRefLayerId;
+#endif
+#if POC_RESET_IDC
+  Bool     m_pocResetInfoPresentFlag;
+#endif
+#if MOVE_SCALED_OFFSET_TO_PPS
+  UInt     m_numRefLayerLocationOffsets;
+#if O0098_SCALED_REF_LAYER_ID
+  UInt     m_refLocationOffsetLayerId[MAX_LAYERS];
+#endif
+  Window   m_scaledRefLayerWindow[MAX_LAYERS];
+#if REF_REGION_OFFSET
+  Window   m_refLayerWindow[MAX_LAYERS];
+  Bool     m_scaledRefLayerOffsetPresentFlag[MAX_LAYERS];
+  Bool     m_refRegionOffsetPresentFlag[MAX_LAYERS];
+#endif
+#if R0209_GENERIC_PHASE
+  Int      m_phaseHorLuma[MAX_LAYERS];
+  Int      m_phaseVerLuma[MAX_LAYERS];
+  Int      m_phaseHorChroma[MAX_LAYERS];
+  Int      m_phaseVerChroma[MAX_LAYERS];
+  Bool     m_resamplePhaseSetPresentFlag[MAX_LAYERS];
+#endif
+#endif
+#if Q0048_CGS_3D_ASYMLUT
+  Int      m_nCGSFlag;
+  Int      m_nCGSOutputBitDepthY; // not for syntax
+  Int      m_nCGSOutputBitDepthC; // not for syntax
+#endif
+#endif
+
+public:
+  TComPPS();
+  virtual ~TComPPS();
+
+  Int       getPPSId ()      { return m_PPSId; }
+  Void      setPPSId (Int i) { m_PPSId = i; }
+  Int       getSPSId ()      { return m_SPSId; }
+  Void      setSPSId (Int i) { m_SPSId = i; }
+
+  Int       getPicInitQPMinus26 ()         { return  m_picInitQPMinus26; }
+  Void      setPicInitQPMinus26 ( Int i )  { m_picInitQPMinus26 = i;     }
+  Bool      getUseDQP ()                   { return m_useDQP;        }
+  Void      setUseDQP ( Bool b )           { m_useDQP   = b;         }
+  Bool      getConstrainedIntraPred ()         { return  m_bConstrainedIntraPred; }
+  Void      setConstrainedIntraPred ( Bool b ) { m_bConstrainedIntraPred = b;     }
+  Bool      getSliceChromaQpFlag ()         { return  m_bSliceChromaQpFlag; }
+  Void      setSliceChromaQpFlag ( Bool b ) { m_bSliceChromaQpFlag = b;     }
+
+  Void      setSPS              ( TComSPS* pcSPS ) { m_pcSPS = pcSPS; }
+  TComSPS*  getSPS              ()         { return m_pcSPS;          }
+  Void      setMaxCuDQPDepth    ( UInt u ) { m_uiMaxCuDQPDepth = u;   }
+  UInt      getMaxCuDQPDepth    ()         { return m_uiMaxCuDQPDepth;}
+  Void      setMinCuDQPSize     ( UInt u ) { m_uiMinCuDQPSize = u;    }
+  UInt      getMinCuDQPSize     ()         { return m_uiMinCuDQPSize; }
+
+  Void      setQpOffset(ComponentID compID, Int i ) { if (compID==COMPONENT_Cb) m_chromaCbQpOffset = i; else if (compID==COMPONENT_Cr) m_chromaCrQpOffset = i; else assert(0); }
+  Int       getQpOffset(ComponentID compID) const { return (compID==COMPONENT_Y) ? 0 : (compID==COMPONENT_Cb ? m_chromaCbQpOffset : m_chromaCrQpOffset ); }
+
+  Void      setMaxCuChromaQpAdjDepth ( UInt u ) { m_MaxCuChromaQpAdjDepth = u; }
+  UInt      getMaxCuChromaQpAdjDepth ()         { return m_MaxCuChromaQpAdjDepth; }
+  Void      setMinCuChromaQpAdjSize ( UInt u ) { m_MinCuChromaQpAdjSize = u; }
+  UInt      getMinCuChromaQpAdjSize ()         { return m_MinCuChromaQpAdjSize; }
+  Void      clearChromaQpAdjTable() { m_ChromaQpAdjTableSize = 0; }
+  Int       getChromaQpAdjTableSize() { return m_ChromaQpAdjTableSize; }
+  const ChromaQpAdj& getChromaQpAdjTableAt( Int idx ) const { return m_ChromaQpAdjTable[idx]; }
+  Void      setChromaQpAdjTableAt( Int idx, Int cbOffset, Int crOffset )
+  {
+    m_ChromaQpAdjTable[idx].u.comp.CbOffset = cbOffset;
+    m_ChromaQpAdjTable[idx].u.comp.CrOffset = crOffset;
+    m_ChromaQpAdjTableSize = max(m_ChromaQpAdjTableSize, idx);
+  }
+
+  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;  }
+
+  Bool      getUseCrossComponentPrediction()         const { return m_useCrossComponentPrediction;  }
+  Void      setUseCrossComponentPrediction(Bool value)     { m_useCrossComponentPrediction = value; }
+
+  UInt      getSaoOffsetBitShift(ChannelType type) const            { return m_saoOffsetBitShift[type];       }
+  Void      setSaoOffsetBitShift(ChannelType type, UInt uiBitShift) { m_saoOffsetBitShift[type] = uiBitShift; }
+
+  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;       }
+  UInt      getTransformSkipLog2MaxSize ()         { return m_transformSkipLog2MaxSize;     }
+  Void      setTransformSkipLog2MaxSize ( UInt u ) { m_transformSkipLog2MaxSize  = u;       }
+
+  Void    setLoopFilterAcrossTilesEnabledFlag  (Bool b)    { m_loopFilterAcrossTilesEnabledFlag = b; }
+  Bool    getLoopFilterAcrossTilesEnabledFlag  ()          { return m_loopFilterAcrossTilesEnabledFlag;   }
+  Bool    getDependentSliceSegmentsEnabledFlag() const     { return m_dependentSliceSegmentsEnabledFlag; }
+  Void    setDependentSliceSegmentsEnabledFlag(Bool val)   { m_dependentSliceSegmentsEnabledFlag = val; }
+  Bool    getEntropyCodingSyncEnabledFlag() const          { return m_entropyCodingSyncEnabledFlag; }
+  Void    setEntropyCodingSyncEnabledFlag(Bool val)        { m_entropyCodingSyncEnabledFlag = val; }
+
+  Void     setTilesEnabledFlag       (Bool val)                             { m_tilesEnabledFlag = val; }
+  Bool     getTilesEnabledFlag       () const                               { return m_tilesEnabledFlag; }
+  Void     setTileUniformSpacingFlag (Bool b)                               { m_uniformSpacingFlag = b; }
+  Bool     getTileUniformSpacingFlag () const                               { return m_uniformSpacingFlag; }
+  Void     setNumTileColumnsMinus1   (Int i)                                { m_numTileColumnsMinus1 = i; }
+  Int      getNumTileColumnsMinus1   () const                               { return m_numTileColumnsMinus1; }
+  Void     setTileColumnWidth        (const std::vector<Int>& columnWidth ) { m_tileColumnWidth = columnWidth; }
+  UInt     getTileColumnWidth        (UInt columnIdx) const                 { return  m_tileColumnWidth[columnIdx]; }
+  Void     setNumTileRowsMinus1      (Int i)                                { m_numTileRowsMinus1 = i; }
+  Int      getNumTileRowsMinus1      () const                               { return m_numTileRowsMinus1; }
+  Void     setTileRowHeight          (const std::vector<Int>& rowHeight)    { m_tileRowHeight = rowHeight;  }
+  UInt     getTileRowHeight          (UInt rowIdx) const                    { return m_tileRowHeight[rowIdx]; }
+
+  Void     setNumSubstreams    (Int numSubstreams)                     { m_numSubstreams = numSubstreams; }
+  Int      getNumSubstreams    ()                                      { return m_numSubstreams; }
+
+  Void      setSignHideFlag( Int signHideFlag ) { m_signHideFlag = signHideFlag; }
+  Int       getSignHideFlag()                    { return m_signHideFlag; }
+
+  Void     setCabacInitPresentFlag( Bool flag )     { m_cabacInitPresentFlag = flag;    }
+  Void     setEncCABACTableIdx( Int idx )           { m_encCABACTableIdx = idx;         }
+  Bool     getCabacInitPresentFlag()                { return m_cabacInitPresentFlag;    }
+  UInt     getEncCABACTableIdx()                    { return m_encCABACTableIdx;        }
+  Void     setDeblockingFilterControlPresentFlag( Bool val )  { m_deblockingFilterControlPresentFlag = val; }
+  Bool     getDeblockingFilterControlPresentFlag()            { return m_deblockingFilterControlPresentFlag; }
+  Void     setDeblockingFilterOverrideEnabledFlag( Bool val ) { m_deblockingFilterOverrideEnabledFlag = val; }
+  Bool     getDeblockingFilterOverrideEnabledFlag()           { return m_deblockingFilterOverrideEnabledFlag; }
+  Void     setPicDisableDeblockingFilterFlag(Bool val)        { m_picDisableDeblockingFilterFlag = val; }       //!< set offset for deblocking filter disabled
+  Bool     getPicDisableDeblockingFilterFlag()                { return m_picDisableDeblockingFilterFlag; }      //!< get offset for deblocking filter disabled
+  Void     setDeblockingFilterBetaOffsetDiv2(Int val)         { m_deblockingFilterBetaOffsetDiv2 = val; }       //!< set beta offset for deblocking filter
+  Int      getDeblockingFilterBetaOffsetDiv2()                { return m_deblockingFilterBetaOffsetDiv2; }      //!< get beta offset for deblocking filter
+  Void     setDeblockingFilterTcOffsetDiv2(Int val)           { m_deblockingFilterTcOffsetDiv2 = val; }               //!< set tc offset for deblocking filter
+  Int      getDeblockingFilterTcOffsetDiv2()                  { return m_deblockingFilterTcOffsetDiv2; }              //!< get tc offset for deblocking filter
+  Bool     getScalingListPresentFlag()         { return m_scalingListPresentFlag;     }
+  Void     setScalingListPresentFlag( Bool b ) { m_scalingListPresentFlag  = b;       }
+
+#if SCALINGLIST_INFERRING
+  Void     setScalingList( TComScalingList *scalingList ) { m_scalingList = scalingList; }
+#else
+  Void     setScalingList      ( TComScalingList *scalingList);
+#endif
+  TComScalingList* getScalingList ()          { return m_scalingList; }         //!< get ScalingList class pointer in PPS
+  Bool getListsModificationPresentFlag ()          { return m_listsModificationPresentFlag; }
+  Void setListsModificationPresentFlag ( Bool b )  { m_listsModificationPresentFlag = b;    }
+  UInt getLog2ParallelMergeLevelMinus2      ()                    { return m_log2ParallelMergeLevelMinus2; }
+  Void setLog2ParallelMergeLevelMinus2      (UInt mrgLevel)       { m_log2ParallelMergeLevelMinus2 = mrgLevel; }
+  Int getNumExtraSliceHeaderBits() { return m_numExtraSliceHeaderBits; }
+  Void setNumExtraSliceHeaderBits(Int i) { m_numExtraSliceHeaderBits = i; }
+  Void      setLoopFilterAcrossSlicesEnabledFlag ( Bool   bValue  )    { m_loopFilterAcrossSlicesEnabledFlag = bValue; }
+  Bool      getLoopFilterAcrossSlicesEnabledFlag ()                    { return m_loopFilterAcrossSlicesEnabledFlag;   }
+    Bool getSliceHeaderExtensionPresentFlag   ()                    { return m_sliceHeaderExtensionPresentFlag; }
+  Void setSliceHeaderExtensionPresentFlag   (Bool val)            { m_sliceHeaderExtensionPresentFlag = val; }
+#if SVC_EXTENSION
+  Int     getExtensionFlag()                { return m_extensionFlag;  }
+  Void    setExtensionFlag(Int n)           { m_extensionFlag = n;     }
+#if SCALINGLIST_INFERRING
+  UInt     getLayerId() { return m_layerId; }
+  Void     setLayerId( UInt layerId ) { m_layerId = layerId;            }
+  Bool     getInferScalingListFlag()  { return m_inferScalingListFlag;  }
+  UInt     getScalingListRefLayerId() { return m_scalingListRefLayerId; }
+  Void     setInferScalingListFlag( Bool flag )     { m_inferScalingListFlag = flag;     }
+  Void     setScalingListRefLayerId( UInt layerId ) { m_scalingListRefLayerId = layerId; }
+#endif
+#if POC_RESET_IDC
+  Bool getPocResetInfoPresentFlag   ()                    { return m_pocResetInfoPresentFlag; }
+  Void setPocResetInfoPresentFlag   (const Bool val)      { m_pocResetInfoPresentFlag = val; }
+#endif
+#if MOVE_SCALED_OFFSET_TO_PPS
+  UInt     getNumRefLayerLocationOffsets()       { return m_numRefLayerLocationOffsets; }
+  Void     setNumRefLayerLocationOffsets(Int x)  { m_numRefLayerLocationOffsets = x;    }
+#if O0098_SCALED_REF_LAYER_ID
+  UInt     getRefLocationOffsetLayerId(Int x)          { return m_refLocationOffsetLayerId[x]; }
+  Void     setRefLocationOffsetLayerId(Int x, UInt id) { m_refLocationOffsetLayerId[x] = id;   }
+  Window&  getScaledRefLayerWindowForLayer( Int layerId );
+#endif
+  Window&  getScaledRefLayerWindow( Int x )   { return m_scaledRefLayerWindow[x]; }
+#if REF_REGION_OFFSET
+  Window&  getRefLayerWindowForLayer( Int layerId );
+  Window&  getRefLayerWindow( Int x )   { return m_refLayerWindow[x]; }
+  Bool getScaledRefLayerOffsetPresentFlag(Int x) { return m_scaledRefLayerOffsetPresentFlag[x]; }
+  Void setScaledRefLayerOffsetPresentFlag(Int x, Bool b) { m_scaledRefLayerOffsetPresentFlag[x] = b; }
+  Bool getRefRegionOffsetPresentFlag(Int x) { return m_refRegionOffsetPresentFlag[x]; }
+  Void setRefRegionOffsetPresentFlag(Int x, Bool b) { m_refRegionOffsetPresentFlag[x] = b; }
+#endif
+#if R0209_GENERIC_PHASE
+  Int getPhaseHorLuma(Int x) { return m_phaseHorLuma[x]; }
+  Int getPhaseVerLuma(Int x) { return m_phaseVerLuma[x]; }
+  Int getPhaseHorChroma(Int x) { return m_phaseHorChroma[x]; }
+  Int getPhaseVerChroma(Int x) { return m_phaseVerChroma[x]; }
+  Void setPhaseHorLuma(Int x, Int val) { m_phaseHorLuma[x] = val; }
+  Void setPhaseVerLuma(Int x, Int val) { m_phaseVerLuma[x] = val; }
+  Void setPhaseHorChroma(Int x, Int val) { m_phaseHorChroma[x] = val; }
+  Void setPhaseVerChroma(Int x, Int val) { m_phaseVerChroma[x] = val; }
+  Bool getResamplePhaseSetPresentFlag(Int x) { return m_resamplePhaseSetPresentFlag[x]; }
+  Void setResamplePhaseSetPresentFlag(Int x, Bool b) { m_resamplePhaseSetPresentFlag[x] = b; }
+#if RESAMPLING_FIX
+  Bool hasZeroResamplingPhase(Int refLayerId);
+  Void getResamplingPhase(Int refLayerId, Bool& phaseSetPresentFlag, Int& phaseHorLuma, Int& phaseVerLuma, Int& phaseHorChroma, Int& phaseVerChroma);
+#endif
+#endif
+#endif
+#if Q0048_CGS_3D_ASYMLUT
+  Int     getCGSFlag()                { return m_nCGSFlag;  }
+  Void    setCGSFlag(Int n)           { m_nCGSFlag = n;     }
+  Int     getCGSOutputBitDepthY()     { return m_nCGSOutputBitDepthY;  }
+  Void    setCGSOutputBitDepthY(Int n){ m_nCGSOutputBitDepthY = n;     }
+  Int     getCGSOutputBitDepthC()     { return m_nCGSOutputBitDepthC;  }
+  Void    setCGSOutputBitDepthC(Int n){ m_nCGSOutputBitDepthC = n;     }
+#endif
+#endif //SVC_EXTENSION
+};
+
+struct WPScalingParam
+{
+  // 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;
+  Int  o;
+  Int  offset;
+  Int  shift;
+  Int  round;
+};
+
+struct WPACDCParam
+{
+  Int64 iAC;
+  Int64 iDC;
+#if O0194_WEIGHTED_PREDICTION_CGS
+  Int iSamples;
+#endif
+};
+
+/// slice header class
+class TComSlice
+{
+  
+private:
+  //  Bitstream writing
+  Bool        m_saoEnabledFlag[MAX_NUM_CHANNEL_TYPE];
+  Int         m_iPPSId;               ///< picture parameter set ID
+  Bool        m_PicOutputFlag;        ///< pic_output_flag
+  Int         m_iPOC;
+  Int         m_iLastIDR;
+  Int         m_iAssociatedIRAP;
+#if POC_RESET_IDC_ENCODER
+  Int         m_associatedIrapPocBeforeReset;
+#endif
+  NalUnitType m_iAssociatedIRAPType;
+  static Int  m_prevTid0POC;
+  TComReferencePictureSet *m_pcRPS;
+  TComReferencePictureSet m_LocalRPS;
+  Int         m_iBDidx;
+  TComRefPicListModification m_RefPicListModification;
+  NalUnitType m_eNalUnitType;         ///< Nal unit type for the slice
+  SliceType   m_eSliceType;
+  Int         m_iSliceQp;
+  Bool        m_dependentSliceSegmentFlag;
+#if ADAPTIVE_QP_SELECTION
+  Int         m_iSliceQpBase;
+#endif
+  Bool        m_ChromaQpAdjEnabled;
+  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   [NUM_REF_PIC_LIST_01];    //  for multiple reference of current slice
+
+  Bool        m_bCheckLDC;
+
+  //  Data
+  Int         m_iSliceQpDelta;
+  Int         m_iSliceChromaQpDelta[MAX_NUM_COMPONENT];
+  TComPic*    m_apcRefPicList [NUM_REF_PIC_LIST_01][MAX_NUM_REF+1];
+  Int         m_aiRefPOCList  [NUM_REF_PIC_LIST_01][MAX_NUM_REF+1];
+  Bool        m_bIsUsedAsLongTerm[NUM_REF_PIC_LIST_01][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
+  
+  Bool        m_noOutputPriorPicsFlag;
+  Bool        m_noRaslOutputFlag;
+  Bool        m_handleCraAsBlaFlag;
+  
+  UInt        m_colRefIdx;
+  UInt        m_maxNumMergeCand;
+
+  Double      m_lambdas[MAX_NUM_COMPONENT];
+
+  Bool        m_abEqualRef  [NUM_REF_PIC_LIST_01][MAX_NUM_REF][MAX_NUM_REF];
+  UInt        m_uiTLayer;
+  Bool        m_bTLayerSwitchingFlag;
+
+  SliceConstraint m_sliceMode;
+  UInt        m_sliceArgument;
+  UInt        m_sliceCurStartCtuTsAddr;
+  UInt        m_sliceCurEndCtuTsAddr;
+  UInt        m_sliceIdx;
+  SliceConstraint m_sliceSegmentMode;
+  UInt        m_sliceSegmentArgument;
+  UInt        m_sliceSegmentCurStartCtuTsAddr;
+  UInt        m_sliceSegmentCurEndCtuTsAddr;
+  Bool        m_nextSlice;
+  Bool        m_nextSliceSegment;
+  UInt        m_sliceBits;
+  UInt        m_sliceSegmentBits;
+  Bool        m_bFinalized;
+
+  WPScalingParam  m_weightPredTable[NUM_REF_PIC_LIST_01][MAX_NUM_REF][MAX_NUM_COMPONENT]; // [REF_PIC_LIST_0 or REF_PIC_LIST_1][refIdx][0:Y, 1:U, 2:V]
+  WPACDCParam    m_weightACDCParam[MAX_NUM_COMPONENT];
+
+  std::vector<UInt> m_substreamSizes;
+
+  TComScalingList*     m_scalingList;                 //!< pointer of quantization matrix
+  Bool        m_cabacInitFlag;
+
+  Bool       m_bLMvdL1Zero;
+  Bool       m_temporalLayerNonReferenceFlag;
+  Bool       m_LFCrossSliceBoundaryFlag;
+
+  Bool       m_enableTMVPFlag;
+
+#if SVC_EXTENSION
+#if R0226_SLICE_TMVP
+  Bool       m_availableForTMVPRefFlag;
+#endif
+  UInt        m_layerId;
+  TComPic*    m_pcBaseColPic[MAX_LAYERS];
+  TComPicYuv* m_pcFullPelBaseRec[MAX_LAYERS];
+  Int         m_numMotionPredRefLayers;
+#if REF_IDX_MFM
+  Bool        m_bMFMEnabledFlag;
+  Int         m_colRefLayerIdx;
+  Bool        m_altColIndicationFlag;
+  TComPic*    m_pcIlpPic;
+#endif
+
+  Bool        m_interLayerPredEnabledFlag;
+  Int         m_activeNumILRRefIdx;        //< Active inter-layer reference pictures
+  Int         m_interLayerPredLayerIdc  [MAX_VPS_LAYER_IDX_PLUS1];
+#if P0312_VERT_PHASE_ADJ
+  Bool        m_vertPhasePositionFlag[MAX_VPS_LAYER_IDX_PLUS1];
+#endif
+#if POC_RESET_FLAG
+  Bool        m_bPocResetFlag;
+  Int         m_pocValueBeforeReset;
+#endif  
+  Bool        m_bDiscardableFlag;
+#if O0149_CROSS_LAYER_BLA_FLAG
+  Bool        m_bCrossLayerBLAFlag;
+#endif
+#if POC_RESET_IDC_SIGNALLING
+  Int         m_pocResetIdc;
+  Int         m_pocResetPeriodId;
+  Bool        m_fullPocResetFlag;
+  Int         m_pocLsbVal;
+  Int         m_pocMsbVal;
+  Bool        m_pocMsbValRequiredFlag;
+  Bool        m_pocMsbValPresentFlag;
+#if P0297_VPS_POC_LSB_ALIGNED_FLAG
+  Bool        m_pocMsbValNeeded;
+  Int         m_pocResetDeltaPoc;
+#endif
+#endif
+#if POC_RESET_IDC_ENCODER
+  Int         m_pocValueBeforeReset;
+#endif
+#if POC_RESET_IDC_DECODER || POC_RESET_IDC_ENCODER
+  Int         m_picOrderCntLsb;
+#endif
+#if Q0048_CGS_3D_ASYMLUT
+  Int        m_nCGSOverWritePPS;  // for optimization, not output to bitstream
+#endif
+#endif //SVC_EXTENSION
+
+public:
+  TComSlice();
+  virtual ~TComSlice();
+#if SVC_EXTENSION
+  Void      initSlice       ( UInt layerId );
+#else
+  Void      initSlice       ();
+#endif
+  Void      initTiles();
+
+  Void      setVPS          ( TComVPS* pcVPS ) { m_pcVPS = pcVPS; }
+  TComVPS*  getVPS          () { return m_pcVPS; }
+  Void      setSPS          ( TComSPS* pcSPS ) { m_pcSPS = pcSPS; }
+  TComSPS*  getSPS          () { return m_pcSPS; }
+  const TComSPS*  getSPS() const  { return m_pcSPS; }
+
+  Void      setPPS          ( TComPPS* pcPPS )         { assert(pcPPS!=NULL); m_pcPPS = pcPPS; m_iPPSId = pcPPS->getPPSId(); }
+  TComPPS*  getPPS          () { return m_pcPPS; }
+  const TComPPS*  getPPS() const { 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(ChannelType chType, Bool s) {m_saoEnabledFlag[chType] =s; }
+  Bool      getSaoEnabledFlag(ChannelType chType) { return m_saoEnabledFlag[chType]; }
+  Void      setRPS          ( TComReferencePictureSet *pcRPS ) { m_pcRPS = pcRPS; }
+  TComReferencePictureSet*  getRPS          () { return m_pcRPS; }
+  TComReferencePictureSet*  getLocalRPS     () { return &m_LocalRPS; }
+
+  Void      setRPSidx          ( Int iBDidx ) { m_iBDidx = iBDidx; }
+  Int       getRPSidx          () { return m_iBDidx; }
+  Int       getPrevTid0POC      ()                        { return  m_prevTid0POC;       }
+  TComRefPicListModification* getRefPicListModification() { return &m_RefPicListModification; }
+  Void      setLastIDR(Int iIDRPOC)                       { m_iLastIDR = iIDRPOC; }
+  Int       getLastIDR()                                  { return m_iLastIDR; }
+  Void      setAssociatedIRAPPOC(Int iAssociatedIRAPPOC)             { m_iAssociatedIRAP = iAssociatedIRAPPOC; }
+  Int       getAssociatedIRAPPOC()                        { return m_iAssociatedIRAP; }
+  Void      setAssociatedIRAPType(NalUnitType associatedIRAPType)    { m_iAssociatedIRAPType = associatedIRAPType; }
+  NalUnitType getAssociatedIRAPType()                        { return m_iAssociatedIRAPType; }
+  SliceType getSliceType    ()                          { return  m_eSliceType;         }
+  Int       getPOC          ()                          { return  m_iPOC;           }
+  Int       getSliceQp      ()                          { return  m_iSliceQp;           }
+  Bool      getDependentSliceSegmentFlag()             const { return m_dependentSliceSegmentFlag; }
+  Void      setDependentSliceSegmentFlag(Bool val)           { m_dependentSliceSegmentFlag = val; }
+#if ADAPTIVE_QP_SELECTION
+  Int       getSliceQpBase  ()                         const { return  m_iSliceQpBase;       }
+#endif
+  Int       getSliceQpDelta ()                         const { return  m_iSliceQpDelta;      }
+  Int       getSliceChromaQpDelta (ComponentID compID) const { return  isLuma(compID) ? 0 : m_iSliceChromaQpDelta[compID]; }
+  Bool      getUseChromaQpAdj()                        const { return m_ChromaQpAdjEnabled; }
+  Bool      getDeblockingFilterDisable()               const { return  m_deblockingFilterDisable; }
+  Bool      getDeblockingFilterOverrideFlag()          const { return  m_deblockingFilterOverrideFlag; }
+  Int       getDeblockingFilterBetaOffsetDiv2()        const { return  m_deblockingFilterBetaOffsetDiv2; }
+  Int       getDeblockingFilterTcOffsetDiv2()          const { return  m_deblockingFilterTcOffsetDiv2; }
+
+  Int       getNumRefIdx        ( RefPicList e )       const    { 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];   }
+  Int       getDepth            ()                              { return  m_iDepth;                     }
+  UInt      getColFromL0Flag    ()                              { return  m_colFromL0Flag;              }
+  UInt      getColRefIdx        ()                              { return  m_colRefIdx;                  }
+  Void      checkColRefIdx      (UInt curSliceIdx, TComPic* pic);
+  Bool      getIsUsedAsLongTerm (Int i, Int j)                  { return m_bIsUsedAsLongTerm[i][j]; }
+  Void      setIsUsedAsLongTerm (Int i, Int j, Bool value)      { m_bIsUsedAsLongTerm[i][j] = value; }
+  Bool      getCheckLDC     ()                                  { return m_bCheckLDC; }
+  Bool      getMvdL1ZeroFlag ()                                 { return m_bLMvdL1Zero;    }
+  Int       getNumRpsCurrTempList();
+  Int       getList1IdxToList0Idx ( Int list1Idx )              { return m_list1IdxToList0Idx[list1Idx]; }
+  Void      setReferenced(Bool b)                               { m_bRefenced = b; }
+  Bool      isReferenced()                                      { return m_bRefenced; }
+  Bool      isReferenceNalu()                                   { return ((getNalUnitType() <= NAL_UNIT_RESERVED_VCL_R15) && (getNalUnitType()%2 != 0)) || ((getNalUnitType() >= NAL_UNIT_CODED_SLICE_BLA_W_LP) && (getNalUnitType() <= NAL_UNIT_RESERVED_IRAP_VCL23) ); }
+  Void      setPOC              ( Int i )                       { m_iPOC              = i; if ((getTLayer()==0) && (isReferenceNalu() && (getNalUnitType()!=NAL_UNIT_CODED_SLICE_RASL_R)&& (getNalUnitType()!=NAL_UNIT_CODED_SLICE_RADL_R))) {m_prevTid0POC=i;} }
+  Void      setNalUnitType      ( NalUnitType e )               { m_eNalUnitType      = e;      }
+  NalUnitType getNalUnitType    () const                        { return m_eNalUnitType;        }
+  Bool      getRapPicFlag       ();
+  Bool      getIdrPicFlag       ()                              { return getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_W_RADL || getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_N_LP; }
+  Bool      isIRAP              () const                        { return (getNalUnitType() >= 16) && (getNalUnitType() <= 23); }
+  Void      checkCRA(TComReferencePictureSet *pReferencePictureSet, Int& pocCRA, NalUnitType& associatedIRAPType, TComList<TComPic *>& rcListPic);
+#if NO_CLRAS_OUTPUT_FLAG
+#if R0235_SMALLEST_LAYER_ID
+  Void      decodingRefreshMarking( TComList<TComPic*>& rcListPic, Bool noClrasOutputFlag, UInt smallestLayerId = 0 );
+#else
+  Void      decodingRefreshMarking( TComList<TComPic*>& rcListPic, Bool noClrasOutputFlag );
+#endif
+  Void      decodingRefreshMarking(Int& pocCRA, Bool& bRefreshPending, TComList<TComPic*>& rcListPic, Bool noClrasOutputFlag);
+#else
+  Void      decodingRefreshMarking(Int& pocCRA, Bool& bRefreshPending, TComList<TComPic*>& rcListPic);
+#endif
+  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      setSliceChromaQpDelta( ComponentID compID, Int i )  { m_iSliceChromaQpDelta[compID] = isLuma(compID) ? 0 : i;  }
+  Void      setUseChromaQpAdj   ( Bool b )                      { m_ChromaQpAdjEnabled = b;     }
+  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 SVC_EXTENSION
+#if PREVTID0_POC_RESET
+  Void      adjustPrevTid0POC      (Int adj)             { m_prevTid0POC=m_prevTid0POC-adj; }
+#endif
+#if POC_RESET_IDC_DECODER
+  Void      setPrevTid0POC( Int x ) { m_prevTid0POC = x; }
+#endif
+#if POC_RESET_IDC_ENCODER
+  Void      setAssociatedIrapPocBeforeReset(Int x) { m_associatedIrapPocBeforeReset = x; }
+  Int       getAssociatedIrapPocBeforeReset(     ) { return m_associatedIrapPocBeforeReset; }
+#endif
+
+  Void      setRefPicList       ( TComList<TComPic*>& rcListPic, Bool checkNumPocTotalCurr = false, TComPic** ilpPic = NULL );
+#if Q0048_CGS_3D_ASYMLUT
+  Int       getCGSOverWritePPS()              { return m_nCGSOverWritePPS;    }
+  Void      setCGSOverWritePPS(Int n)         { m_nCGSOverWritePPS = n;       }
+#endif
+#else
+  Void      setRefPicList       ( TComList<TComPic*>& rcListPic, Bool checkNumPocTotalCurr = false );
+#endif
+  Void      setRefPOCList       ();
+  Void      setColFromL0Flag    ( UInt colFromL0 ) { m_colFromL0Flag = colFromL0; }
+  Void      setColRefIdx        ( UInt refIdx) { m_colRefIdx = refIdx; }
+  Void      setCheckLDC         ( Bool b )                      { m_bCheckLDC = b; }
+  Void      setMvdL1ZeroFlag     ( Bool b)                       { m_bLMvdL1Zero = b; }
+
+  Bool      isIntra         ()                          { return  m_eSliceType == I_SLICE;  }
+  Bool      isInterB        ()                          { return  m_eSliceType == B_SLICE;  }
+  Bool      isInterP        ()                          { return  m_eSliceType == P_SLICE;  }
+
+  Void      setLambdas ( const Double lambdas[MAX_NUM_COMPONENT] ) { for (Int component = 0; component < MAX_NUM_COMPONENT; component++) m_lambdas[component] = lambdas[component]; }
+  const Double* getLambdas() const { return m_lambdas; }
+
+  Void      initEqualRef();
+  Bool      isEqualRef  ( RefPicList e, Int iRefIdx1, Int iRefIdx2 )
+  {
+    assert(e<NUM_REF_PIC_LIST_01);
+    if (iRefIdx1 < 0 || iRefIdx2 < 0) return false;
+    return m_abEqualRef[e][iRefIdx1][iRefIdx2];
+  }
+
+  Void setEqualRef( RefPicList e, Int iRefIdx1, Int iRefIdx2, Bool b)
+  {
+    assert(e<NUM_REF_PIC_LIST_01);
+    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 );
+#if POC_RESET_IDC_ENCODER
+  Void checkLeadingPictureRestrictions(TComList<TComPic*>& rcListPic, Bool usePocBeforeReset = false);
+#else
+  Void checkLeadingPictureRestrictions( TComList<TComPic*>& rcListPic );
+#endif
+  Void applyReferencePictureSet( TComList<TComPic*>& rcListPic, TComReferencePictureSet *RPSList);
+  Bool isTemporalLayerSwitchingPoint( TComList<TComPic*>& rcListPic );
+  Bool isStepwiseTemporalLayerSwitchingPointCandidate( TComList<TComPic*>& rcListPic );
+#if ALLOW_RECOVERY_POINT_AS_RAP
+  Int  checkThatAllRefPicsAreAvailable( TComList<TComPic*>& rcListPic, TComReferencePictureSet *pReferencePictureSet, Bool printErrors, Int pocRandomAccess = 0, Bool bUseRecoveryPoint = false);
+  Void createExplicitReferencePictureSetFromReference( TComList<TComPic*>& rcListPic, TComReferencePictureSet *pReferencePictureSet, Bool isRAP, Int pocRandomAccess = 0, Bool bUseRecoveryPoint = false);
+#else
+  Int  checkThatAllRefPicsAreAvailable( TComList<TComPic*>& rcListPic, TComReferencePictureSet *pReferencePictureSet, Bool printErrors, Int pocRandomAccess = 0);
+  Void createExplicitReferencePictureSetFromReference( TComList<TComPic*>& rcListPic, TComReferencePictureSet *pReferencePictureSet, Bool isRAP);
+#endif
+  Void setMaxNumMergeCand               (UInt val )          { m_maxNumMergeCand = val;                 }
+  UInt getMaxNumMergeCand               ()                   { return m_maxNumMergeCand;                }
+
+  Void setNoOutputPriorPicsFlag         ( Bool val )         { m_noOutputPriorPicsFlag = val;           }
+  Bool getNoOutputPriorPicsFlag         ()                   { return m_noOutputPriorPicsFlag;          }
+
+  Void setNoRaslOutputFlag              ( Bool val )         { m_noRaslOutputFlag = val;                }
+  Bool getNoRaslOutputFlag              ()                   { return m_noRaslOutputFlag;               }
+
+  Void setHandleCraAsBlaFlag            ( Bool val )         { m_handleCraAsBlaFlag = val;              }
+  Bool getHandleCraAsBlaFlag            ()                   { return m_handleCraAsBlaFlag;             }
+
+  Void setSliceMode                     ( SliceConstraint mode ) { m_sliceMode = mode;                  }
+  SliceConstraint getSliceMode          () const            { return m_sliceMode;                       }
+  Void setSliceArgument                 ( UInt uiArgument ) { m_sliceArgument = uiArgument;             }
+  UInt getSliceArgument                 ()                  { return m_sliceArgument;                   }
+  Void setSliceCurStartCtuTsAddr        ( UInt ctuTsAddr )  { m_sliceCurStartCtuTsAddr = ctuTsAddr;     } // CTU Tile-scan address (as opposed to raster-scan)
+  UInt getSliceCurStartCtuTsAddr        () const            { return m_sliceCurStartCtuTsAddr;          } // CTU Tile-scan address (as opposed to raster-scan)
+  Void setSliceCurEndCtuTsAddr          ( UInt ctuTsAddr )  { m_sliceCurEndCtuTsAddr = ctuTsAddr;       } // CTU Tile-scan address (as opposed to raster-scan)
+  UInt getSliceCurEndCtuTsAddr          () const            { return m_sliceCurEndCtuTsAddr;            } // CTU Tile-scan address (as opposed to raster-scan)
+  Void setSliceIdx                      ( UInt i)           { m_sliceIdx = i;                           }
+  UInt getSliceIdx                      ()                  { return  m_sliceIdx;                       }
+  Void copySliceInfo                    (TComSlice *pcSliceSrc);
+  Void setSliceSegmentMode              ( SliceConstraint mode ) { m_sliceSegmentMode = mode;           }
+  SliceConstraint getSliceSegmentMode   () const            { return m_sliceSegmentMode;                }
+  Void setSliceSegmentArgument          ( UInt uiArgument ) { m_sliceSegmentArgument = uiArgument;      }
+  UInt getSliceSegmentArgument          ()                  { return m_sliceSegmentArgument;            }
+  Void setSliceSegmentCurStartCtuTsAddr ( UInt ctuTsAddr )  { m_sliceSegmentCurStartCtuTsAddr = ctuTsAddr; } // CTU Tile-scan address (as opposed to raster-scan)
+  UInt getSliceSegmentCurStartCtuTsAddr () const            { return m_sliceSegmentCurStartCtuTsAddr;      } // CTU Tile-scan address (as opposed to raster-scan)
+  Void setSliceSegmentCurEndCtuTsAddr   ( UInt ctuTsAddr )  { m_sliceSegmentCurEndCtuTsAddr = ctuTsAddr;   } // CTU Tile-scan address (as opposed to raster-scan)
+  UInt getSliceSegmentCurEndCtuTsAddr   () const            { return m_sliceSegmentCurEndCtuTsAddr;        } // CTU Tile-scan address (as opposed to raster-scan)
+  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[NUM_REF_PIC_LIST_01][MAX_NUM_REF][MAX_NUM_COMPONENT] ) { memcpy(m_weightPredTable, wp, sizeof(WPScalingParam)*NUM_REF_PIC_LIST_01*MAX_NUM_REF*MAX_NUM_COMPONENT); }
+  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[MAX_NUM_COMPONENT] ) { memcpy(m_weightACDCParam, wp, sizeof(WPACDCParam)*MAX_NUM_COMPONENT); }
+  Void  getWpAcDcParam  ( WPACDCParam *&wp );
+  Void  initWpAcDcParam ();
+
+  Void clearSubstreamSizes       ( )                        { return m_substreamSizes.clear();        }
+  UInt getNumberOfSubstreamSizes ( )                        { return (UInt) m_substreamSizes.size();  }
+  Void addSubstreamSize          ( UInt size )              { m_substreamSizes.push_back(size);       }
+  UInt getSubstreamSize          ( Int idx )                { assert(idx<getNumberOfSubstreamSizes()); return m_substreamSizes[idx]; }
+
+  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
+  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 SVC_EXTENSION
+#if R0226_SLICE_TMVP
+  Void      setAvailableForTMVPRefFlag     ( Bool   b )    { m_availableForTMVPRefFlag = b; }
+  Bool      getAvailableForTMVPRefFlag     ()              { return m_availableForTMVPRefFlag;}
+#endif
+  Bool      setBaseColPic       ( TComList<TComPic*>& rcListPic , UInt refLayerIdc );
+  Void      setBaseColPic       (UInt refLayerIdc, TComPic* p)     { m_pcBaseColPic[refLayerIdc] = p; }
+  TComPic*  getBaseColPic       (UInt refLayerIdc)                { return m_pcBaseColPic[refLayerIdc]; }
+  TComPic** getBaseColPic       ()                { return &m_pcBaseColPic[0]; }
+#if MFM_ENCCONSTRAINT
+  TComPic*  getBaseColPic( TComList<TComPic*>& rcListPic );
+#endif
+
+  Void      setLayerId (UInt layerId)   { m_layerId = layerId; }
+  UInt      getLayerId ()               { return m_layerId;    }
+  UInt      getLayerIdx()               { return m_pcVPS->getLayerIdxInVps(m_layerId); }
+
+  Void        setFullPelBaseRec   (UInt refLayerIdc, TComPicYuv* p) { m_pcFullPelBaseRec[refLayerIdc] = p; }
+  TComPicYuv* getFullPelBaseRec   (UInt refLayerIdc)               { return  m_pcFullPelBaseRec[refLayerIdc];  }
+
+  Void      setRefPicListModificationSvc();
+  Int       getNumILRRefIdx     ( )                     { return  m_pcVPS->getNumDirectRefLayers( m_layerId ); }
+
+  Int       getActiveNumILRRefIdx     ( )               { return  m_activeNumILRRefIdx; }
+  Void      setActiveNumILRRefIdx     ( Int i )         { m_activeNumILRRefIdx = i;     }  
+
+  Int       getInterLayerPredLayerIdc (UInt layerIdc)                        { return  m_interLayerPredLayerIdc[layerIdc];}
+  Void      setInterLayerPredLayerIdc (UInt refLayerIdc, UInt layerIdc)      { m_interLayerPredLayerIdc[layerIdc] = refLayerIdc;  }
+
+  Void      setInterLayerPredEnabledFlag     ( Bool   val )    { m_interLayerPredEnabledFlag = val; }
+  Bool      getInterLayerPredEnabledFlag     ()                { return m_interLayerPredEnabledFlag;}
+
+#if P0312_VERT_PHASE_ADJ
+  Int       getVertPhasePositionFlag (UInt layerIdx)              { return   m_vertPhasePositionFlag[layerIdx];}
+  Void      setVertPhasePositionFlag (Bool b, UInt layerIdx)      {  m_vertPhasePositionFlag[layerIdx] = b;  }
+#endif
+
+  Void      setNumMotionPredRefLayers(int i)            { m_numMotionPredRefLayers = i; }
+  Int       getNumMotionPredRefLayers()                 { return m_numMotionPredRefLayers; }
+#if REF_IDX_MFM
+  Void      setMFMEnabledFlag(Bool flag)                { m_bMFMEnabledFlag = flag; }
+  Bool      getMFMEnabledFlag()                         { return m_bMFMEnabledFlag; }
+#endif
+
+  TComPic* getRefPic(TComList<TComPic*>& rcListPic, Int poc) { return xGetRefPic( rcListPic, poc ); } 
+
+  Bool     isRADL()   { return (m_eNalUnitType == NAL_UNIT_CODED_SLICE_RADL_N || m_eNalUnitType == NAL_UNIT_CODED_SLICE_RADL_R); }
+  Bool     isRASL()   { return (m_eNalUnitType == NAL_UNIT_CODED_SLICE_RASL_N || m_eNalUnitType == NAL_UNIT_CODED_SLICE_RASL_R); }
+
+#if POC_RESET_RESTRICTIONS
+  Bool     isIDR()    { return (m_eNalUnitType == NAL_UNIT_CODED_SLICE_IDR_W_RADL
+                                  || m_eNalUnitType == NAL_UNIT_CODED_SLICE_IDR_N_LP); }
+  Bool     isCRA()    { return m_eNalUnitType == NAL_UNIT_CODED_SLICE_CRA; }
+  Bool     isBLA()    { return (m_eNalUnitType == NAL_UNIT_CODED_SLICE_BLA_W_LP
+                                  || m_eNalUnitType == NAL_UNIT_CODED_SLICE_BLA_W_RADL
+                                  || m_eNalUnitType == NAL_UNIT_CODED_SLICE_BLA_N_LP ); }
+  Bool     isSLNR()   { return (m_eNalUnitType == NAL_UNIT_CODED_SLICE_TRAIL_N
+                                  || m_eNalUnitType == NAL_UNIT_CODED_SLICE_TSA_N
+                                  || m_eNalUnitType == NAL_UNIT_CODED_SLICE_STSA_N
+                                  || m_eNalUnitType == NAL_UNIT_CODED_SLICE_RADL_N
+                                  || m_eNalUnitType == NAL_UNIT_CODED_SLICE_RASL_N
+                                  || m_eNalUnitType == NAL_UNIT_RESERVED_VCL_N10
+                                  || m_eNalUnitType == NAL_UNIT_RESERVED_VCL_N12
+                                  || m_eNalUnitType == NAL_UNIT_RESERVED_VCL_N14 ); }
+#endif
+#if POC_RESET_FLAG
+  Bool      getPocResetFlag  ()                              { return m_bPocResetFlag;       }
+  Void      setPocResetFlag  (Bool b)                        { m_bPocResetFlag = b;          }
+  Int       getPocValueBeforeReset ()                        { return m_pocValueBeforeReset; }
+  Void      setPocValueBeforeReset (Int x)                   { m_pocValueBeforeReset = x ;   }
+#endif
+  Bool      getDiscardableFlag  ()                           { return m_bDiscardableFlag;    }
+  Void      setDiscardableFlag  (Bool b)                     { m_bDiscardableFlag = b;       }
+#if O0149_CROSS_LAYER_BLA_FLAG
+  Bool      getCrossLayerBLAFlag  ()                         { return m_bCrossLayerBLAFlag;  }
+  Void      setCrossLayerBLAFlag  (Bool b)                   { m_bCrossLayerBLAFlag = b;     }
+#endif
+
+#if RPL_INIT_N0316_N0082
+  Int       getNumNegativeRpsCurrTempList();
+#endif
+
+#if REPN_FORMAT_IN_VPS
+  UInt getPicWidthInLumaSamples();
+  UInt getPicHeightInLumaSamples();
+#if AUXILIARY_PICTURES
+  ChromaFormat getChromaFormatIdc();
+#else
+  UInt getChromaFormatIdc();
+#endif
+  UInt getBitDepthY();
+  UInt getBitDepthC();
+  Int  getQpBDOffsetY();
+  Int  getQpBDOffsetC();
+
+#if R0156_CONF_WINDOW_IN_REP_FORMAT
+  Window& getConformanceWindow();
+#endif
+#endif
+
+  Void setILRPic(TComPic **pcIlpPic);
+#if POC_RESET_IDC_SIGNALLING
+  Int       getPocResetIdc       ()                              { return m_pocResetIdc;       }
+  Void      setPocResetIdc       (Int b)                         { m_pocResetIdc = b;          }
+  Int       getPocResetPeriodId  ()                              { return m_pocResetPeriodId;       }
+  Void      setPocResetPeriodId  (Int b)                         { m_pocResetPeriodId = b;          }
+  Bool      getFullPocResetFlag  ()                              { return m_fullPocResetFlag;       }
+  Void      setFullPocResetFlag  (Bool b)                        { m_fullPocResetFlag = b;          }
+  Int       getPocLsbVal         ()                              { return m_pocLsbVal;       }
+  Void      setPocLsbVal       (Int b)                           { m_pocLsbVal = b;          }
+#if P0297_VPS_POC_LSB_ALIGNED_FLAG
+  Void      setPocMsbNeeded      (Bool x)                        { m_pocMsbValNeeded = x; }
+  Bool      getPocMsbNeeded      ()                              { return m_pocMsbValNeeded; }
+  Int       getPocResetDeltaPoc  ()                              { return m_pocResetDeltaPoc; }
+  Void      setPocResetDeltaPoc  (Int x)                         { m_pocResetDeltaPoc = x; }
+#endif
+  Int       getPocMsbVal         ()                              { return m_pocMsbVal;       }
+  Void      setPocMsbVal       (Int b)                           { m_pocMsbVal = b;          }
+  Bool      getPocMsbValPresentFlag ()                           { return m_pocMsbValPresentFlag; }
+  Void      setPocMsbValPresentFlag (Bool x)                     { m_pocMsbValPresentFlag = x; }
+  Bool      getPocMsbValRequiredFlag ()                           { return m_pocMsbValRequiredFlag; }
+  Void      setPocMsbValRequiredFlag (Bool x)                     { m_pocMsbValRequiredFlag = x; }
+#endif
+
+#if NO_OUTPUT_OF_PRIOR_PICS
+  Bool      getBlaPicFlag       ();
+  Bool      getCraPicFlag       ();
+#endif
+#if POC_RESET_IDC_DECODER
+  Bool      getRaslPicFlag      ();
+  Bool      getRadlPicFlag      ();
+#endif
+#if POC_RESET_IDC_DECODER || POC_RESET_IDC_ENCODER
+  Int       getPicOrderCntLsb() { return m_picOrderCntLsb; }
+  Void      setPicOrderCntLsb(Int x) { m_picOrderCntLsb = x; }
+#endif
+
+#if POC_RESET_IDC_ENCODER
+  Int       getPocValueBeforeReset ()                        { return m_pocValueBeforeReset; }
+  Void      setPocValueBeforeReset (Int x)                   { m_pocValueBeforeReset = x ;   }
+  Void      decrementRefPocValues(Int const decrementValue);
+  Int       getCurrMsb( Int currLsb, Int prevLsb, Int prevMsb, Int maxLsbVal );
+#endif
+  Int       getReferenceLayerIdc( UInt refLayerId );
+
+#endif //SVC_EXTENSION
+protected:
+  TComPic*  xGetRefPic        (TComList<TComPic*>& rcListPic, Int poc);
+  TComPic*  xGetLongTermRefPic(TComList<TComPic*>& rcListPic, Int poc, Bool pocHasMsb);
+};// 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:
+
+#if SVC_EXTENSION
+  static ParameterSetMap<TComVPS> m_vpsMap;
+  static ParameterSetMap<TComSPS> m_spsMap; 
+  static ParameterSetMap<TComPPS> m_ppsMap;
+#else
+  ParameterSetMap<TComVPS> m_vpsMap;
+  ParameterSetMap<TComSPS> m_spsMap;
+  ParameterSetMap<TComPPS> m_ppsMap;
+#endif
+
+#if SVC_EXTENSION
+  static Int m_activeVPSId;
+#else
+  Int m_activeVPSId;
+#endif
+  Int m_activeSPSId;
+  Int m_activePPSId;
+};
+
+//! \}
+
+#endif // __TCOMSLICE__
Index: /tags/SHM-9.0/source/Lib/TLibCommon/TComTU.cpp
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibCommon/TComTU.cpp	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibCommon/TComTU.cpp	(revision 1088)
@@ -0,0 +1,254 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+
+#include "TComTU.h"
+#include "TComRom.h"
+#include "TComDataCU.h"
+#include "TComPic.h"
+
+//----------------------------------------------------------------------------------------------------------------------
+
+/*static*/ const UInt TComTU::NUMBER_OF_SECTIONS[TComTU::NUMBER_OF_SPLIT_MODES] = { 1, 2, 4 };
+
+static     const UInt         partIdxStepShift  [TComTU::NUMBER_OF_SPLIT_MODES] = { 0, 1, 2 };
+
+//----------------------------------------------------------------------------------------------------------------------
+
+TComTU::TComTU(TComDataCU *pcCU, const UInt absPartIdxCU, const UInt cuDepth, const UInt initTrDepthRelCU)
+  : mChromaFormat(pcCU->getSlice()->getSPS()->getChromaFormatIdc()),
+    mbProcessLastOfLevel(true), // does not matter. the top level is not 4 quadrants.
+    mCuDepth(cuDepth),
+    mSection(0),
+    mSplitMode(DONT_SPLIT),
+    mAbsPartIdxCU(absPartIdxCU),
+    mAbsPartIdxTURelCU(0),
+    mAbsPartIdxStep(pcCU->getPic()->getNumPartitionsInCtu() >> (pcCU->getDepth(absPartIdxCU)<<1)),
+    mpcCU(pcCU),
+    mLog2TrLumaSize(0),
+    mpParent(NULL)
+{
+  TComSPS *pSPS=pcCU->getSlice()->getSPS();
+  mLog2TrLumaSize = g_aucConvertToBit[pSPS->getMaxCUWidth() >> (mCuDepth+initTrDepthRelCU)]+2;
+
+  const UInt baseOffset444=pcCU->getPic()->getMinCUWidth()*pcCU->getPic()->getMinCUHeight()*absPartIdxCU;
+
+  for(UInt i=0; i<MAX_NUM_COMPONENT; i++)
+  {
+    mTrDepthRelCU[i] = initTrDepthRelCU;
+    const UInt csx=getComponentScaleX(ComponentID(i), mChromaFormat);
+    const UInt csy=getComponentScaleY(ComponentID(i), mChromaFormat);
+    mOrigWidth[i]=mRect[i].width = (i < getNumberValidComponents(mChromaFormat)) ? (pcCU->getWidth( absPartIdxCU) >> csx) : 0;
+    mRect[i].height              = (i < getNumberValidComponents(mChromaFormat)) ? (pcCU->getHeight(absPartIdxCU) >> csy) : 0;
+    mRect[i].x0=0;
+    mRect[i].y0=0;
+    mCodeAll[i]=true;
+    mOffsets[i]=baseOffset444>>(csx+csy);
+  }
+}
+
+
+
+TComTURecurse::TComTURecurse(      TComDataCU *pcCU,
+                             const UInt        absPartIdxCU)
+  : TComTU(pcCU, absPartIdxCU, pcCU->getDepth(absPartIdxCU), 0)
+{ }
+
+
+
+TComTU::TComTU(TComTU &parent, const Bool bProcessLastOfLevel, const TU_SPLIT_MODE splitMode, const Bool splitAtCurrentDepth, const ComponentID absPartIdxSourceComponent)
+  : mChromaFormat(parent.mChromaFormat),
+    mbProcessLastOfLevel(bProcessLastOfLevel),
+    mCuDepth(parent.mCuDepth),
+    mSection(0),
+    mSplitMode(splitMode),
+    mAbsPartIdxCU(parent.mAbsPartIdxCU),
+    mAbsPartIdxTURelCU(parent.GetRelPartIdxTU(absPartIdxSourceComponent)),
+    mAbsPartIdxStep(std::max<UInt>(1, (parent.GetAbsPartIdxNumParts(absPartIdxSourceComponent) >> partIdxStepShift[splitMode]))),
+    mpcCU(parent.mpcCU),
+    mLog2TrLumaSize(parent.mLog2TrLumaSize - ((splitMode != QUAD_SPLIT) ? 0 : 1)), //no change in width for vertical split
+    mpParent(&parent)
+{
+  for(UInt i=0; i<MAX_NUM_COMPONENT; i++)
+  {
+    mTrDepthRelCU[i] = parent.mTrDepthRelCU[i] + ((splitAtCurrentDepth || (splitMode == DONT_SPLIT)) ? 0 : 1);
+  }
+
+  if (mSplitMode==DONT_SPLIT)
+  {
+    for(UInt i=0; i<MAX_NUM_COMPONENT; i++)
+    {
+      mRect[i] = (parent.mRect[i]);
+      mOffsets[i]=parent.mOffsets[i];
+      mCodeAll[i]=true; // The 1 TU at this level is coded.
+      mOrigWidth[i]=mRect[i].width;
+    }
+    return;
+  }
+  else if (mSplitMode==VERTICAL_SPLIT)
+  {
+    for(UInt i=0; i<MAX_NUM_COMPONENT; i++)
+    {
+      mRect[i].x0 = (parent.mRect[i].x0);
+      mRect[i].y0 = (parent.mRect[i].y0);
+      mRect[i].width  = (parent.mRect[i].width);
+      mRect[i].height = (parent.mRect[i].height)>>1;
+      mOffsets[i]=parent.mOffsets[i];
+      mCodeAll[i]=true; // The 2 TUs at this level is coded.
+      mOrigWidth[i]=mRect[i].width;
+    }
+    return;
+  }
+
+  for(UInt i=0; i<MAX_NUM_COMPONENT; i++)
+  {
+    mRect[i].width = (parent.mRect[i].width >> 1);
+    mRect[i].height= (parent.mRect[i].height>> 1);
+    mRect[i].x0=parent.mRect[i].x0;
+    mRect[i].y0=parent.mRect[i].y0;
+    mOffsets[i]=parent.mOffsets[i];
+
+    if ((mRect[i].width < MIN_TU_SIZE || mRect[i].height < MIN_TU_SIZE) && mRect[i].width!=0)
+    {
+      const UInt numPels=mRect[i].width * mRect[i].height;
+      if (numPels < (MIN_TU_SIZE*MIN_TU_SIZE))
+      {
+        // this level doesn't have enough pixels to have 4 blocks of any relative dimension
+        mRect[i].width = parent.mRect[i].width;
+        mRect[i].height= parent.mRect[i].height;
+        mCodeAll[i]=false; // go up a level, so only process one entry of a quadrant
+        mTrDepthRelCU[i]--;
+      }
+      else if (mRect[i].width < mRect[i].height)
+      {
+        mRect[i].width=MIN_TU_SIZE;
+        mRect[i].height=numPels/MIN_TU_SIZE;
+        mCodeAll[i]=true;
+      }
+      else
+      {
+        mRect[i].height=MIN_TU_SIZE;
+        mRect[i].width=numPels/MIN_TU_SIZE;
+        mCodeAll[i]=true;
+      }
+    }
+    else
+    {
+      mCodeAll[i]=true;
+    }
+
+    mOrigWidth[i]=mRect[i].width;
+    if (!mCodeAll[i] && mbProcessLastOfLevel) mRect[i].width=0;
+  }
+}
+
+Bool TComTURecurse::nextSection(const TComTU &parent)
+{
+  if (mSplitMode==DONT_SPLIT)
+  {
+    mSection++;
+    return false;
+  }
+  else
+  {
+    for(UInt i=0; i<MAX_NUM_COMPONENT; i++)
+    {
+      mOffsets[i]+=mRect[i].width*mRect[i].height;
+      if (mbProcessLastOfLevel) mRect[i].width=mOrigWidth[i];
+      mRect[i].x0+=mRect[i].width;
+      const TComRectangle &parentRect=parent.getRect(ComponentID(i));
+      if (mRect[i].x0 >= parentRect.x0+parentRect.width)
+      {
+        mRect[i].x0=parentRect.x0;
+        mRect[i].y0+=mRect[i].height;
+      }
+      if (!mCodeAll[i])
+      {
+        if (!mbProcessLastOfLevel || mSection!=2) mRect[i].width=0;
+      }
+    }
+    assert(mRect[COMPONENT_Cb].x0==mRect[COMPONENT_Cr].x0);
+    assert(mRect[COMPONENT_Cb].y0==mRect[COMPONENT_Cr].y0);
+    assert(mRect[COMPONENT_Cb].width==mRect[COMPONENT_Cr].width);
+    assert(mRect[COMPONENT_Cb].height==mRect[COMPONENT_Cr].height);
+
+    mAbsPartIdxTURelCU+=mAbsPartIdxStep;
+    mSection++;
+    return mSection< (1<<mSplitMode);
+  }
+}
+
+
+UInt TComTU::GetEquivalentLog2TrSize(const ComponentID compID)     const
+{
+  return g_aucConvertToBit[ getRect(compID).height ] + 2;
+}
+
+
+Bool TComTU::useDST(const ComponentID compID)
+{
+        TComDataCU *const pcCU       = getCU();
+  const UInt              absPartIdx = GetAbsPartIdxTU(compID);
+
+  return isLuma(compID) && pcCU->isIntra(absPartIdx);
+}
+
+
+Bool TComTU::isNonTransformedResidualRotated(const ComponentID compID)
+{
+  // rotation only for 4x4 intra, and is only used for non-transformed blocks (the latter is not checked here)
+  return    getCU()->getSlice()->getSPS()->getUseResidualRotation()
+         && mRect[compID].width == 4
+         && getCU()->isIntra(GetAbsPartIdxTU());
+}
+
+
+UInt TComTU::getGolombRiceStatisticsIndex(const ComponentID compID)
+{
+        TComDataCU *const pcCU             = getCU();
+  const UInt              absPartIdx       = GetAbsPartIdxTU(compID);
+  const Bool              transformSkip    = pcCU->getTransformSkip(absPartIdx, compID);
+  const Bool              transquantBypass = pcCU->getCUTransquantBypass(absPartIdx);
+
+  //--------
+
+  const UInt channelTypeOffset    =  isChroma(compID)                   ? 2 : 0;
+  const UInt nonTransformedOffset = (transformSkip || transquantBypass) ? 1 : 0;
+
+  //--------
+
+  const UInt selectedIndex = channelTypeOffset + nonTransformedOffset;
+  assert(selectedIndex < RExt__GOLOMB_RICE_ADAPTATION_STATISTICS_SETS);
+
+  return selectedIndex;
+}
Index: /tags/SHM-9.0/source/Lib/TLibCommon/TComTU.h
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibCommon/TComTU.h	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibCommon/TComTU.h	(revision 1088)
@@ -0,0 +1,167 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef __TCOMTU__
+#define __TCOMTU__
+
+class TComTU; // forward declaration
+
+#include "CommonDef.h"
+#include "TComRectangle.h"
+#include "TComChromaFormat.h"
+
+class TComDataCU; // forward declaration
+
+//----------------------------------------------------------------------------------------------------------------------
+
+
+class TComTU
+{
+  public:
+    typedef enum TU_SPLIT_MODE { DONT_SPLIT=0, VERTICAL_SPLIT=1, QUAD_SPLIT=2, NUMBER_OF_SPLIT_MODES=3 } SPLIT_MODE;
+
+    static const UInt NUMBER_OF_SECTIONS[NUMBER_OF_SPLIT_MODES];
+
+  protected:
+    ChromaFormat  mChromaFormat;
+    Bool          mbProcessLastOfLevel; // if true, then if size n/2 x n/2 is invalid, the nxn block for a channel is processed only for the last block, not the first.
+    UInt          mCuDepth;
+    UInt          mTrDepthRelCU[MAX_NUM_COMPONENT];
+    UInt          mSection;
+    TU_SPLIT_MODE mSplitMode;
+    TComRectangle mRect[MAX_NUM_COMPONENT];
+    Bool          mCodeAll[MAX_NUM_COMPONENT];
+    UInt          mOrigWidth[MAX_NUM_COMPONENT];
+    UInt          mOffsets[MAX_NUM_COMPONENT];
+    UInt          mAbsPartIdxCU;
+    UInt          mAbsPartIdxTURelCU;
+    UInt          mAbsPartIdxStep;
+    TComDataCU   *mpcCU;
+    UInt          mLog2TrLumaSize;
+    TComTU       *mpParent;
+
+    TComTU(const TComTU &);           // not defined - do not use
+    TComTU&operator=(const TComTU &); // not defined - do not use
+
+  public:
+    TComTU(      TComDataCU *pcCU,
+           const UInt        absPartIdxCU,
+           const UInt        cuDepth,
+           const UInt        initTrDepthRelCU);
+
+  protected:
+    TComTU(      TComTU        &parentLevel,
+           const Bool           bProcessLastOfLevel,
+           const TU_SPLIT_MODE  splitMode                 = QUAD_SPLIT,
+           const Bool           splitAtCurrentDepth       = false,
+           const ComponentID    absPartIdxSourceComponent = COMPONENT_Y
+           );
+
+  public:
+          TComTU *Parent()       { return mpParent; }
+    const TComTU *Parent() const { return mpParent; }
+
+    UInt getCoefficientOffset(const ComponentID compID)        const { return mOffsets[compID]; }
+
+    const TComRectangle &getRect(const ComponentID compID)     const { return mRect[compID];    }
+
+    Bool ProcessingAllQuadrants(const ComponentID compID)      const { return mCodeAll[compID]; }
+    Bool ProcessComponentSection(const ComponentID compID)     const { return mRect[compID].width != 0; }
+    Bool ProcessChannelSection(const ChannelType chType)       const { return mRect[chType].width != 0; }
+    UInt GetSectionNumber()                                    const { return mSection; }
+
+    UInt getCUDepth()                                          const { return mCuDepth; }
+
+    UInt GetTransformDepthTotal()                              const { return mCuDepth+GetTransformDepthRel(); }
+    UInt GetTransformDepthTotalAdj(const ComponentID compID)   const { return mCuDepth+GetTransformDepthRelAdj(compID); }
+
+    UInt GetTransformDepthRel()                                const { return mTrDepthRelCU[COMPONENT_Y]; }
+    UInt GetTransformDepthRelAdj(const ComponentID compID)     const { return mTrDepthRelCU[compID]; }
+    UInt GetTransformDepthRelAdj(const ChannelType chType)     const
+    {
+      assert(isLuma(chType) || (mTrDepthRelCU[COMPONENT_Cb] == mTrDepthRelCU[COMPONENT_Cr]));
+      return mTrDepthRelCU[isLuma(chType) ? COMPONENT_Y : COMPONENT_Cb];
+    }
+
+    UInt GetAbsPartIdxCU()                                     const { return mAbsPartIdxCU; }
+    UInt GetRelPartIdxTU()                                     const { return mAbsPartIdxTURelCU; }
+    UInt GetRelPartIdxTU(const ComponentID compID)             const { return ProcessingAllQuadrants(compID) ? mAbsPartIdxTURelCU : (mAbsPartIdxTURelCU & (~0x3)); }
+    UInt GetAbsPartIdxTU()                                     const { return GetAbsPartIdxCU() + GetRelPartIdxTU(); }
+    UInt GetAbsPartIdxTU(const ComponentID compID)             const { return GetAbsPartIdxCU() + GetRelPartIdxTU(compID); }
+    UInt GetAbsPartIdxNumParts()                               const { return mAbsPartIdxStep; }
+    UInt GetAbsPartIdxNumParts(const ComponentID compID)       const { return ProcessingAllQuadrants(compID) ? mAbsPartIdxStep : (mAbsPartIdxStep * NUMBER_OF_SECTIONS[mSplitMode]); }
+
+    ChromaFormat GetChromaFormat()                             const { return mChromaFormat; }
+
+    TComDataCU *getCU()                                              { return mpcCU; }
+    const TComDataCU *getCU()                                  const { return mpcCU; }
+    Bool IsLastSection() const { return mSection+1>=((1<<mSplitMode)); }
+
+    UInt GetLog2LumaTrSize()                                   const { return mLog2TrLumaSize; }
+    UInt GetEquivalentLog2TrSize(const ComponentID compID)     const;
+    TU_SPLIT_MODE GetSplitMode()                               const { return mSplitMode; }
+
+    Bool useDST(const ComponentID compID);
+    Bool isNonTransformedResidualRotated(const ComponentID compID);
+
+    UInt getGolombRiceStatisticsIndex(const ComponentID compID);
+};
+
+
+
+class TComTURecurse : public TComTU
+{
+  public:
+
+    TComTURecurse(      TComDataCU *pcCU,
+                  const UInt        absPartIdxCU,
+                  const UInt        forcedDepthOfCU)
+      : TComTU(pcCU, absPartIdxCU, forcedDepthOfCU, 0) { }
+
+    TComTURecurse(      TComDataCU *pcCU,
+                  const UInt        absPartIdxCU); // CU's depth is taken from CU->getDepth(idx)
+
+    TComTURecurse(      TComTU        &parentLevel,                            //Parent TU from which recursion children are derived
+                  const Bool           bProcessLastOfLevel,                    //If true (and the split results in a "step-up" for chroma), the chroma TU is colocated with the last luma TU instead of the first
+                  const TU_SPLIT_MODE  splitMode                 = QUAD_SPLIT, //DONT_SPLIT = create one new TU as a copy of its parent, VERTICAL_SPLIT = split the TU into top and bottom halves, QUAD_SPLIT = split the TU into four equal quadrants
+                  const Bool           splitAtCurrentDepth       = false,      //Set true to keep the current depth when applying a vertical or quad split
+                  const ComponentID    absPartIdxSourceComponent = COMPONENT_Y //Specifies which component of the parent TU should be used to initialise the absPartIdx of the first child and the absPartIdx step (this is needed when splitting a "stepped-up" chroma TU)
+                  )
+                  : TComTU(parentLevel, bProcessLastOfLevel, splitMode, splitAtCurrentDepth, absPartIdxSourceComponent) { }
+
+    Bool nextSection(const TComTU &parent); // returns true if there is another section to process, and prepares internal structures, else returns false
+};
+
+//----------------------------------------------------------------------------------------------------------------------
+
+#endif
Index: /tags/SHM-9.0/source/Lib/TLibCommon/TComTrQuant.cpp
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibCommon/TComTrQuant.cpp	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibCommon/TComTrQuant.cpp	(revision 1088)
@@ -0,0 +1,3341 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TComTrQuant.cpp
+    \brief    transform and quantization class
+*/
+
+#include <stdlib.h>
+#include <math.h>
+#include <limits>
+#include <memory.h>
+#include "TComTrQuant.h"
+#include "TComPic.h"
+#include "ContextTables.h"
+#include "TComTU.h"
+#include "Debug.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
+
+
+// ====================================================================================================================
+// QpParam constructor
+// ====================================================================================================================
+
+QpParam::QpParam(const Int           qpy,
+                 const ChannelType   chType,
+                 const Int           qpBdOffset,
+                 const Int           chromaQPOffset,
+                 const ChromaFormat  chFmt )
+{
+  Int baseQp;
+
+  if(isLuma(chType))
+  {
+    baseQp = qpy + qpBdOffset;
+  }
+  else
+  {
+    baseQp = Clip3( -qpBdOffset, (chromaQPMappingTableSize - 1), qpy + chromaQPOffset );
+
+    if(baseQp < 0)
+    {
+      baseQp = baseQp + qpBdOffset;
+    }
+    else
+    {
+      baseQp = getScaledChromaQP(baseQp, chFmt) + qpBdOffset;
+    }
+  }
+
+  Qp =baseQp;
+  per=baseQp/6;
+  rem=baseQp%6;
+}
+
+QpParam::QpParam(const TComDataCU &cu, const ComponentID compID)
+{
+  Int chromaQpOffset = 0;
+
+  if (isChroma(compID))
+  {
+    chromaQpOffset += cu.getSlice()->getPPS()->getQpOffset(compID);
+    chromaQpOffset += cu.getSlice()->getSliceChromaQpDelta(compID);
+
+    chromaQpOffset += cu.getSlice()->getPPS()->getChromaQpAdjTableAt(cu.getChromaQpAdj(0)).u.offset[Int(compID)-1];
+  }
+
+#if REPN_FORMAT_IN_VPS
+  TComSlice* slice = const_cast<TComSlice*> (cu.getSlice());
+#endif
+
+  *this = QpParam(cu.getQP( 0 ),
+                  toChannelType(compID),
+#if REPN_FORMAT_IN_VPS
+                  isLuma(compID) ? slice->getQpBDOffsetY() : slice->getQpBDOffsetC(),
+#else
+                  cu.getSlice()->getSPS()->getQpBDOffset(toChannelType(compID)),
+#endif
+                  chromaQpOffset,
+                  cu.getPic()->getChromaFormat());
+}
+
+
+// ====================================================================================================================
+// TComTrQuant class member functions
+// ====================================================================================================================
+
+TComTrQuant::TComTrQuant()
+{
+  // allocate temporary buffers
+  m_plTempCoeff  = new TCoeff[ 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)
+{
+  // NOTE: does this work with negative QPs or when some blocks are transquant-bypass enabled?
+
+  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
+
+
+
+#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, TCoeff *coeff, UInt uiStride, UInt uiTrSize, Bool useDST, const Int maxTrDynamicRange)
+{
+  UInt i,j,k;
+  TCoeff iSum;
+  TCoeff tmp[MAX_TU_SIZE * MAX_TU_SIZE];
+  const TMatrixCoeff *iT;
+  UInt uiLog2TrSize = g_aucConvertToBit[ uiTrSize ] + 2;
+
+  if (uiTrSize==4)
+  {
+    iT  = (useDST ? g_as_DST_MAT_4[TRANSFORM_FORWARD][0] : g_aiT4[TRANSFORM_FORWARD][0]);
+  }
+  else if (uiTrSize==8)
+  {
+    iT = g_aiT8[TRANSFORM_FORWARD][0];
+  }
+  else if (uiTrSize==16)
+  {
+    iT = g_aiT16[TRANSFORM_FORWARD][0];
+  }
+  else if (uiTrSize==32)
+  {
+    iT = g_aiT32[TRANSFORM_FORWARD][0];
+  }
+  else
+  {
+    assert(0);
+  }
+
+  static const Int TRANSFORM_MATRIX_SHIFT = g_transformMatrixShift[TRANSFORM_FORWARD];
+
+  const Int shift_1st = (uiLog2TrSize +  bitDepth + TRANSFORM_MATRIX_SHIFT) - maxTrDynamicRange;
+  const Int shift_2nd = uiLog2TrSize + TRANSFORM_MATRIX_SHIFT;
+  const Int add_1st = (shift_1st>0) ? (1<<(shift_1st-1)) : 0;
+  const Int add_2nd = 1<<(shift_2nd-1);
+
+  /* Horizontal transform */
+
+  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 */
+  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 bitDepth, TCoeff *coeff, Pel *block, UInt uiStride, UInt uiTrSize, Bool useDST, const Int maxTrDynamicRange)
+{
+  UInt i,j,k;
+  TCoeff iSum;
+  TCoeff tmp[MAX_TU_SIZE * MAX_TU_SIZE];
+  const TMatrixCoeff *iT;
+
+  if (uiTrSize==4)
+  {
+    iT  = (useDST ? g_as_DST_MAT_4[TRANSFORM_INVERSE][0] : g_aiT4[TRANSFORM_INVERSE][0]);
+  }
+  else if (uiTrSize==8)
+  {
+    iT = g_aiT8[TRANSFORM_INVERSE][0];
+  }
+  else if (uiTrSize==16)
+  {
+    iT = g_aiT16[TRANSFORM_INVERSE][0];
+  }
+  else if (uiTrSize==32)
+  {
+    iT = g_aiT32[TRANSFORM_INVERSE][0];
+  }
+  else
+  {
+    assert(0);
+  }
+
+  static const Int TRANSFORM_MATRIX_SHIFT = g_transformMatrixShift[TRANSFORM_INVERSE];
+
+  const Int shift_1st = TRANSFORM_MATRIX_SHIFT + 1; //1 has been added to shift_1st at the expense of shift_2nd
+  const Int shift_2nd = (TRANSFORM_MATRIX_SHIFT + maxTrDynamicRange - 1) - bitDepth;
+  const TCoeff clipMinimum = -(1 << maxTrDynamicRange);
+  const TCoeff clipMaximum =  (1 << maxTrDynamicRange) - 1;
+  assert(shift_2nd>=0);
+  const Int add_1st = 1<<(shift_1st-1);
+  const Int add_2nd = (shift_2nd>0) ? (1<<(shift_2nd-1)) : 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];
+      }
+
+      // Clipping here is not in the standard, but is used to protect the "Pel" data type into which the inverse-transformed samples will be copied
+      tmp[i*uiTrSize+j] = Clip3<TCoeff>(clipMinimum, clipMaximum, (iSum + add_1st)>>shift_1st);
+    }
+  }
+
+  /* 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<TCoeff>(std::numeric_limits<Pel>::min(), std::numeric_limits<Pel>::max(), (iSum + add_2nd)>>shift_2nd);
+    }
+  }
+}
+
+#endif //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(TCoeff *src, TCoeff *dst, Int shift, Int line)
+{
+  Int j;
+  TCoeff E[2],O[2];
+  TCoeff add = (shift > 0) ? (1<<(shift-1)) : 0;
+
+  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[TRANSFORM_FORWARD][0][0]*E[0] + g_aiT4[TRANSFORM_FORWARD][0][1]*E[1] + add)>>shift;
+    dst[2*line] = (g_aiT4[TRANSFORM_FORWARD][2][0]*E[0] + g_aiT4[TRANSFORM_FORWARD][2][1]*E[1] + add)>>shift;
+    dst[line]   = (g_aiT4[TRANSFORM_FORWARD][1][0]*O[0] + g_aiT4[TRANSFORM_FORWARD][1][1]*O[1] + add)>>shift;
+    dst[3*line] = (g_aiT4[TRANSFORM_FORWARD][3][0]*O[0] + g_aiT4[TRANSFORM_FORWARD][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(TCoeff *block, TCoeff *coeff, Int shift)  // input block, output coeff
+{
+  Int i;
+  TCoeff c[4];
+  TCoeff rnd_factor = (shift > 0) ? (1<<(shift-1)) : 0;
+  for (i=0; i<4; i++)
+  {
+    // Intermediate Variables
+    c[0] = block[4*i+0];
+    c[1] = block[4*i+1];
+    c[2] = block[4*i+2];
+    c[3] = block[4*i+3];
+
+    for (Int row = 0; row < 4; row++)
+    {
+      TCoeff result = 0;
+      for (Int column = 0; column < 4; column++)
+        result += c[column] * g_as_DST_MAT_4[TRANSFORM_FORWARD][row][column]; // use the defined matrix, rather than hard-wired numbers
+
+      coeff[(row * 4) + i] = rightShift((result + rnd_factor), shift);
+    }
+  }
+}
+
+Void fastInverseDst(TCoeff *tmp, TCoeff *block, Int shift, const TCoeff outputMinimum, const TCoeff outputMaximum)  // input tmp, output block
+{
+  Int i;
+  TCoeff c[4];
+  TCoeff rnd_factor = (shift > 0) ? (1<<(shift-1)) : 0;
+  for (i=0; i<4; i++)
+  {
+    // Intermediate Variables
+    c[0] = tmp[   i];
+    c[1] = tmp[4 +i];
+    c[2] = tmp[8 +i];
+    c[3] = tmp[12+i];
+
+    for (Int column = 0; column < 4; column++)
+    {
+      TCoeff &result = block[(i * 4) + column];
+
+      result = 0;
+      for (Int row = 0; row < 4; row++)
+        result += c[row] * g_as_DST_MAT_4[TRANSFORM_INVERSE][row][column]; // use the defined matrix, rather than hard-wired numbers
+
+      result = Clip3( outputMinimum, outputMaximum, rightShift((result + rnd_factor), shift));
+    }
+  }
+}
+
+/** 4x4 inverse transform implemented using partial butterfly structure (1D)
+ *  \param src   input data (transform coefficients)
+ *  \param dst   output data (residual)
+ *  \param shift specifies right shift after 1D transform
+ */
+Void partialButterflyInverse4(TCoeff *src, TCoeff *dst, Int shift, Int line, const TCoeff outputMinimum, const TCoeff outputMaximum)
+{
+  Int j;
+  TCoeff E[2],O[2];
+  TCoeff add = (shift > 0) ? (1<<(shift-1)) : 0;
+
+  for (j=0; j<line; j++)
+  {
+    /* Utilizing symmetry properties to the maximum to minimize the number of multiplications */
+    O[0] = g_aiT4[TRANSFORM_INVERSE][1][0]*src[line] + g_aiT4[TRANSFORM_INVERSE][3][0]*src[3*line];
+    O[1] = g_aiT4[TRANSFORM_INVERSE][1][1]*src[line] + g_aiT4[TRANSFORM_INVERSE][3][1]*src[3*line];
+    E[0] = g_aiT4[TRANSFORM_INVERSE][0][0]*src[0]    + g_aiT4[TRANSFORM_INVERSE][2][0]*src[2*line];
+    E[1] = g_aiT4[TRANSFORM_INVERSE][0][1]*src[0]    + g_aiT4[TRANSFORM_INVERSE][2][1]*src[2*line];
+
+    /* Combining even and odd terms at each hierarchy levels to calculate the final spatial domain vector */
+    dst[0] = Clip3( outputMinimum, outputMaximum, (E[0] + O[0] + add)>>shift );
+    dst[1] = Clip3( outputMinimum, outputMaximum, (E[1] + O[1] + add)>>shift );
+    dst[2] = Clip3( outputMinimum, outputMaximum, (E[1] - O[1] + add)>>shift );
+    dst[3] = Clip3( outputMinimum, outputMaximum, (E[0] - O[0] + add)>>shift );
+
+    src   ++;
+    dst += 4;
+  }
+}
+
+/** 8x8 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 partialButterfly8(TCoeff *src, TCoeff *dst, Int shift, Int line)
+{
+  Int j,k;
+  TCoeff E[4],O[4];
+  TCoeff EE[2],EO[2];
+  TCoeff add = (shift > 0) ? (1<<(shift-1)) : 0;
+
+  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[TRANSFORM_FORWARD][0][0]*EE[0] + g_aiT8[TRANSFORM_FORWARD][0][1]*EE[1] + add)>>shift;
+    dst[4*line] = (g_aiT8[TRANSFORM_FORWARD][4][0]*EE[0] + g_aiT8[TRANSFORM_FORWARD][4][1]*EE[1] + add)>>shift;
+    dst[2*line] = (g_aiT8[TRANSFORM_FORWARD][2][0]*EO[0] + g_aiT8[TRANSFORM_FORWARD][2][1]*EO[1] + add)>>shift;
+    dst[6*line] = (g_aiT8[TRANSFORM_FORWARD][6][0]*EO[0] + g_aiT8[TRANSFORM_FORWARD][6][1]*EO[1] + add)>>shift;
+
+    dst[line]   = (g_aiT8[TRANSFORM_FORWARD][1][0]*O[0] + g_aiT8[TRANSFORM_FORWARD][1][1]*O[1] + g_aiT8[TRANSFORM_FORWARD][1][2]*O[2] + g_aiT8[TRANSFORM_FORWARD][1][3]*O[3] + add)>>shift;
+    dst[3*line] = (g_aiT8[TRANSFORM_FORWARD][3][0]*O[0] + g_aiT8[TRANSFORM_FORWARD][3][1]*O[1] + g_aiT8[TRANSFORM_FORWARD][3][2]*O[2] + g_aiT8[TRANSFORM_FORWARD][3][3]*O[3] + add)>>shift;
+    dst[5*line] = (g_aiT8[TRANSFORM_FORWARD][5][0]*O[0] + g_aiT8[TRANSFORM_FORWARD][5][1]*O[1] + g_aiT8[TRANSFORM_FORWARD][5][2]*O[2] + g_aiT8[TRANSFORM_FORWARD][5][3]*O[3] + add)>>shift;
+    dst[7*line] = (g_aiT8[TRANSFORM_FORWARD][7][0]*O[0] + g_aiT8[TRANSFORM_FORWARD][7][1]*O[1] + g_aiT8[TRANSFORM_FORWARD][7][2]*O[2] + g_aiT8[TRANSFORM_FORWARD][7][3]*O[3] + add)>>shift;
+
+    src += 8;
+    dst ++;
+  }
+}
+
+/** 8x8 inverse transform implemented using partial butterfly structure (1D)
+ *  \param src   input data (transform coefficients)
+ *  \param dst   output data (residual)
+ *  \param shift specifies right shift after 1D transform
+ */
+Void partialButterflyInverse8(TCoeff *src, TCoeff *dst, Int shift, Int line, const TCoeff outputMinimum, const TCoeff outputMaximum)
+{
+  Int j,k;
+  TCoeff E[4],O[4];
+  TCoeff EE[2],EO[2];
+  TCoeff add = (shift > 0) ? (1<<(shift-1)) : 0;
+
+  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[TRANSFORM_INVERSE][ 1][k]*src[line]   + g_aiT8[TRANSFORM_INVERSE][ 3][k]*src[3*line] +
+             g_aiT8[TRANSFORM_INVERSE][ 5][k]*src[5*line] + g_aiT8[TRANSFORM_INVERSE][ 7][k]*src[7*line];
+    }
+
+    EO[0] = g_aiT8[TRANSFORM_INVERSE][2][0]*src[ 2*line ] + g_aiT8[TRANSFORM_INVERSE][6][0]*src[ 6*line ];
+    EO[1] = g_aiT8[TRANSFORM_INVERSE][2][1]*src[ 2*line ] + g_aiT8[TRANSFORM_INVERSE][6][1]*src[ 6*line ];
+    EE[0] = g_aiT8[TRANSFORM_INVERSE][0][0]*src[ 0      ] + g_aiT8[TRANSFORM_INVERSE][4][0]*src[ 4*line ];
+    EE[1] = g_aiT8[TRANSFORM_INVERSE][0][1]*src[ 0      ] + g_aiT8[TRANSFORM_INVERSE][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( outputMinimum, outputMaximum, (E[k] + O[k] + add)>>shift );
+      dst[ k+4 ] = Clip3( outputMinimum, outputMaximum, (E[3-k] - O[3-k] + add)>>shift );
+    }
+    src ++;
+    dst += 8;
+  }
+}
+
+/** 16x16 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 partialButterfly16(TCoeff *src, TCoeff *dst, Int shift, Int line)
+{
+  Int j,k;
+  TCoeff E[8],O[8];
+  TCoeff EE[4],EO[4];
+  TCoeff EEE[2],EEO[2];
+  TCoeff add = (shift > 0) ? (1<<(shift-1)) : 0;
+
+  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[TRANSFORM_FORWARD][ 0][0]*EEE[0] + g_aiT16[TRANSFORM_FORWARD][ 0][1]*EEE[1] + add)>>shift;
+    dst[ 8*line ] = (g_aiT16[TRANSFORM_FORWARD][ 8][0]*EEE[0] + g_aiT16[TRANSFORM_FORWARD][ 8][1]*EEE[1] + add)>>shift;
+    dst[ 4*line ] = (g_aiT16[TRANSFORM_FORWARD][ 4][0]*EEO[0] + g_aiT16[TRANSFORM_FORWARD][ 4][1]*EEO[1] + add)>>shift;
+    dst[ 12*line] = (g_aiT16[TRANSFORM_FORWARD][12][0]*EEO[0] + g_aiT16[TRANSFORM_FORWARD][12][1]*EEO[1] + add)>>shift;
+
+    for (k=2;k<16;k+=4)
+    {
+      dst[ k*line ] = (g_aiT16[TRANSFORM_FORWARD][k][0]*EO[0] + g_aiT16[TRANSFORM_FORWARD][k][1]*EO[1] +
+                       g_aiT16[TRANSFORM_FORWARD][k][2]*EO[2] + g_aiT16[TRANSFORM_FORWARD][k][3]*EO[3] + add)>>shift;
+    }
+
+    for (k=1;k<16;k+=2)
+    {
+      dst[ k*line ] = (g_aiT16[TRANSFORM_FORWARD][k][0]*O[0] + g_aiT16[TRANSFORM_FORWARD][k][1]*O[1] +
+                       g_aiT16[TRANSFORM_FORWARD][k][2]*O[2] + g_aiT16[TRANSFORM_FORWARD][k][3]*O[3] +
+                       g_aiT16[TRANSFORM_FORWARD][k][4]*O[4] + g_aiT16[TRANSFORM_FORWARD][k][5]*O[5] +
+                       g_aiT16[TRANSFORM_FORWARD][k][6]*O[6] + g_aiT16[TRANSFORM_FORWARD][k][7]*O[7] + add)>>shift;
+    }
+
+    src += 16;
+    dst ++;
+
+  }
+}
+
+/** 16x16 inverse transform implemented using partial butterfly structure (1D)
+ *  \param src   input data (transform coefficients)
+ *  \param dst   output data (residual)
+ *  \param shift specifies right shift after 1D transform
+ */
+Void partialButterflyInverse16(TCoeff *src, TCoeff *dst, Int shift, Int line, const TCoeff outputMinimum, const TCoeff outputMaximum)
+{
+  Int j,k;
+  TCoeff E[8],O[8];
+  TCoeff EE[4],EO[4];
+  TCoeff EEE[2],EEO[2];
+  TCoeff add = (shift > 0) ? (1<<(shift-1)) : 0;
+
+  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[TRANSFORM_INVERSE][ 1][k]*src[ line]   + g_aiT16[TRANSFORM_INVERSE][ 3][k]*src[ 3*line] +
+             g_aiT16[TRANSFORM_INVERSE][ 5][k]*src[ 5*line] + g_aiT16[TRANSFORM_INVERSE][ 7][k]*src[ 7*line] +
+             g_aiT16[TRANSFORM_INVERSE][ 9][k]*src[ 9*line] + g_aiT16[TRANSFORM_INVERSE][11][k]*src[11*line] +
+             g_aiT16[TRANSFORM_INVERSE][13][k]*src[13*line] + g_aiT16[TRANSFORM_INVERSE][15][k]*src[15*line];
+    }
+    for (k=0;k<4;k++)
+    {
+      EO[k] = g_aiT16[TRANSFORM_INVERSE][ 2][k]*src[ 2*line] + g_aiT16[TRANSFORM_INVERSE][ 6][k]*src[ 6*line] +
+              g_aiT16[TRANSFORM_INVERSE][10][k]*src[10*line] + g_aiT16[TRANSFORM_INVERSE][14][k]*src[14*line];
+    }
+    EEO[0] = g_aiT16[TRANSFORM_INVERSE][4][0]*src[ 4*line ] + g_aiT16[TRANSFORM_INVERSE][12][0]*src[ 12*line ];
+    EEE[0] = g_aiT16[TRANSFORM_INVERSE][0][0]*src[ 0      ] + g_aiT16[TRANSFORM_INVERSE][ 8][0]*src[ 8*line  ];
+    EEO[1] = g_aiT16[TRANSFORM_INVERSE][4][1]*src[ 4*line ] + g_aiT16[TRANSFORM_INVERSE][12][1]*src[ 12*line ];
+    EEE[1] = g_aiT16[TRANSFORM_INVERSE][0][1]*src[ 0      ] + g_aiT16[TRANSFORM_INVERSE][ 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( outputMinimum, outputMaximum, (E[k] + O[k] + add)>>shift );
+      dst[k+8] = Clip3( outputMinimum, outputMaximum, (E[7-k] - O[7-k] + add)>>shift );
+    }
+    src ++;
+    dst += 16;
+  }
+}
+
+/** 32x32 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 partialButterfly32(TCoeff *src, TCoeff *dst, Int shift, Int line)
+{
+  Int j,k;
+  TCoeff E[16],O[16];
+  TCoeff EE[8],EO[8];
+  TCoeff EEE[4],EEO[4];
+  TCoeff EEEE[2],EEEO[2];
+  TCoeff add = (shift > 0) ? (1<<(shift-1)) : 0;
+
+  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[TRANSFORM_FORWARD][ 0][0]*EEEE[0] + g_aiT32[TRANSFORM_FORWARD][ 0][1]*EEEE[1] + add)>>shift;
+    dst[ 16*line ] = (g_aiT32[TRANSFORM_FORWARD][16][0]*EEEE[0] + g_aiT32[TRANSFORM_FORWARD][16][1]*EEEE[1] + add)>>shift;
+    dst[ 8*line  ] = (g_aiT32[TRANSFORM_FORWARD][ 8][0]*EEEO[0] + g_aiT32[TRANSFORM_FORWARD][ 8][1]*EEEO[1] + add)>>shift;
+    dst[ 24*line ] = (g_aiT32[TRANSFORM_FORWARD][24][0]*EEEO[0] + g_aiT32[TRANSFORM_FORWARD][24][1]*EEEO[1] + add)>>shift;
+    for (k=4;k<32;k+=8)
+    {
+      dst[ k*line ] = (g_aiT32[TRANSFORM_FORWARD][k][0]*EEO[0] + g_aiT32[TRANSFORM_FORWARD][k][1]*EEO[1] +
+                       g_aiT32[TRANSFORM_FORWARD][k][2]*EEO[2] + g_aiT32[TRANSFORM_FORWARD][k][3]*EEO[3] + add)>>shift;
+    }
+    for (k=2;k<32;k+=4)
+    {
+      dst[ k*line ] = (g_aiT32[TRANSFORM_FORWARD][k][0]*EO[0] + g_aiT32[TRANSFORM_FORWARD][k][1]*EO[1] +
+                       g_aiT32[TRANSFORM_FORWARD][k][2]*EO[2] + g_aiT32[TRANSFORM_FORWARD][k][3]*EO[3] +
+                       g_aiT32[TRANSFORM_FORWARD][k][4]*EO[4] + g_aiT32[TRANSFORM_FORWARD][k][5]*EO[5] +
+                       g_aiT32[TRANSFORM_FORWARD][k][6]*EO[6] + g_aiT32[TRANSFORM_FORWARD][k][7]*EO[7] + add)>>shift;
+    }
+    for (k=1;k<32;k+=2)
+    {
+      dst[ k*line ] = (g_aiT32[TRANSFORM_FORWARD][k][ 0]*O[ 0] + g_aiT32[TRANSFORM_FORWARD][k][ 1]*O[ 1] +
+                       g_aiT32[TRANSFORM_FORWARD][k][ 2]*O[ 2] + g_aiT32[TRANSFORM_FORWARD][k][ 3]*O[ 3] +
+                       g_aiT32[TRANSFORM_FORWARD][k][ 4]*O[ 4] + g_aiT32[TRANSFORM_FORWARD][k][ 5]*O[ 5] +
+                       g_aiT32[TRANSFORM_FORWARD][k][ 6]*O[ 6] + g_aiT32[TRANSFORM_FORWARD][k][ 7]*O[ 7] +
+                       g_aiT32[TRANSFORM_FORWARD][k][ 8]*O[ 8] + g_aiT32[TRANSFORM_FORWARD][k][ 9]*O[ 9] +
+                       g_aiT32[TRANSFORM_FORWARD][k][10]*O[10] + g_aiT32[TRANSFORM_FORWARD][k][11]*O[11] +
+                       g_aiT32[TRANSFORM_FORWARD][k][12]*O[12] + g_aiT32[TRANSFORM_FORWARD][k][13]*O[13] +
+                       g_aiT32[TRANSFORM_FORWARD][k][14]*O[14] + g_aiT32[TRANSFORM_FORWARD][k][15]*O[15] + add)>>shift;
+    }
+
+    src += 32;
+    dst ++;
+  }
+}
+
+/** 32x32 inverse transform implemented using partial butterfly structure (1D)
+ *  \param src   input data (transform coefficients)
+ *  \param dst   output data (residual)
+ *  \param shift specifies right shift after 1D transform
+ */
+Void partialButterflyInverse32(TCoeff *src, TCoeff *dst, Int shift, Int line, const TCoeff outputMinimum, const TCoeff outputMaximum)
+{
+  Int j,k;
+  TCoeff E[16],O[16];
+  TCoeff EE[8],EO[8];
+  TCoeff EEE[4],EEO[4];
+  TCoeff EEEE[2],EEEO[2];
+  TCoeff add = (shift > 0) ? (1<<(shift-1)) : 0;
+
+  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[TRANSFORM_INVERSE][ 1][k]*src[ line    ] + g_aiT32[TRANSFORM_INVERSE][ 3][k]*src[ 3*line  ] +
+             g_aiT32[TRANSFORM_INVERSE][ 5][k]*src[ 5*line  ] + g_aiT32[TRANSFORM_INVERSE][ 7][k]*src[ 7*line  ] +
+             g_aiT32[TRANSFORM_INVERSE][ 9][k]*src[ 9*line  ] + g_aiT32[TRANSFORM_INVERSE][11][k]*src[ 11*line ] +
+             g_aiT32[TRANSFORM_INVERSE][13][k]*src[ 13*line ] + g_aiT32[TRANSFORM_INVERSE][15][k]*src[ 15*line ] +
+             g_aiT32[TRANSFORM_INVERSE][17][k]*src[ 17*line ] + g_aiT32[TRANSFORM_INVERSE][19][k]*src[ 19*line ] +
+             g_aiT32[TRANSFORM_INVERSE][21][k]*src[ 21*line ] + g_aiT32[TRANSFORM_INVERSE][23][k]*src[ 23*line ] +
+             g_aiT32[TRANSFORM_INVERSE][25][k]*src[ 25*line ] + g_aiT32[TRANSFORM_INVERSE][27][k]*src[ 27*line ] +
+             g_aiT32[TRANSFORM_INVERSE][29][k]*src[ 29*line ] + g_aiT32[TRANSFORM_INVERSE][31][k]*src[ 31*line ];
+    }
+    for (k=0;k<8;k++)
+    {
+      EO[k] = g_aiT32[TRANSFORM_INVERSE][ 2][k]*src[ 2*line  ] + g_aiT32[TRANSFORM_INVERSE][ 6][k]*src[ 6*line  ] +
+              g_aiT32[TRANSFORM_INVERSE][10][k]*src[ 10*line ] + g_aiT32[TRANSFORM_INVERSE][14][k]*src[ 14*line ] +
+              g_aiT32[TRANSFORM_INVERSE][18][k]*src[ 18*line ] + g_aiT32[TRANSFORM_INVERSE][22][k]*src[ 22*line ] +
+              g_aiT32[TRANSFORM_INVERSE][26][k]*src[ 26*line ] + g_aiT32[TRANSFORM_INVERSE][30][k]*src[ 30*line ];
+    }
+    for (k=0;k<4;k++)
+    {
+      EEO[k] = g_aiT32[TRANSFORM_INVERSE][ 4][k]*src[  4*line ] + g_aiT32[TRANSFORM_INVERSE][12][k]*src[ 12*line ] +
+               g_aiT32[TRANSFORM_INVERSE][20][k]*src[ 20*line ] + g_aiT32[TRANSFORM_INVERSE][28][k]*src[ 28*line ];
+    }
+    EEEO[0] = g_aiT32[TRANSFORM_INVERSE][8][0]*src[ 8*line ] + g_aiT32[TRANSFORM_INVERSE][24][0]*src[ 24*line ];
+    EEEO[1] = g_aiT32[TRANSFORM_INVERSE][8][1]*src[ 8*line ] + g_aiT32[TRANSFORM_INVERSE][24][1]*src[ 24*line ];
+    EEEE[0] = g_aiT32[TRANSFORM_INVERSE][0][0]*src[ 0      ] + g_aiT32[TRANSFORM_INVERSE][16][0]*src[ 16*line ];
+    EEEE[1] = g_aiT32[TRANSFORM_INVERSE][0][1]*src[ 0      ] + g_aiT32[TRANSFORM_INVERSE][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( outputMinimum, outputMaximum, (E[k] + O[k] + add)>>shift );
+      dst[k+16] = Clip3( outputMinimum, outputMaximum, (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, TCoeff *block, TCoeff *coeff, Int iWidth, Int iHeight, Bool useDST, const Int maxTrDynamicRange)
+{
+  static const Int TRANSFORM_MATRIX_SHIFT = g_transformMatrixShift[TRANSFORM_FORWARD];
+
+  const Int shift_1st = ((g_aucConvertToBit[iWidth] + 2) +  bitDepth + TRANSFORM_MATRIX_SHIFT) - maxTrDynamicRange;
+  const Int shift_2nd = (g_aucConvertToBit[iHeight] + 2) + TRANSFORM_MATRIX_SHIFT;
+
+  assert(shift_1st >= 0);
+  assert(shift_2nd >= 0);
+
+  TCoeff tmp[ MAX_TU_SIZE * MAX_TU_SIZE ];
+
+  switch (iWidth)
+  {
+    case 4:
+      {
+        if ((iHeight == 4) && useDST)    // Check for DCT or DST
+        {
+           fastForwardDst( block, tmp, shift_1st );
+        }
+        else partialButterfly4 ( block, tmp, shift_1st, iHeight );
+      }
+      break;
+
+    case 8:     partialButterfly8 ( block, tmp, shift_1st, iHeight );  break;
+    case 16:    partialButterfly16( block, tmp, shift_1st, iHeight );  break;
+    case 32:    partialButterfly32( block, tmp, shift_1st, iHeight );  break;
+    default:
+      assert(0); exit (1); break;
+  }
+
+  switch (iHeight)
+  {
+    case 4:
+      {
+        if ((iWidth == 4) && useDST)    // Check for DCT or DST
+        {
+          fastForwardDst( tmp, coeff, shift_2nd );
+        }
+        else partialButterfly4 ( tmp, coeff, shift_2nd, iWidth );
+      }
+      break;
+
+    case 8:     partialButterfly8 ( tmp, coeff, shift_2nd, iWidth );    break;
+    case 16:    partialButterfly16( tmp, coeff, shift_2nd, iWidth );    break;
+    case 32:    partialButterfly32( tmp, coeff, shift_2nd, iWidth );    break;
+    default:
+      assert(0); exit (1); break;
+  }
+}
+
+
+/** 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, TCoeff *coeff, TCoeff *block, Int iWidth, Int iHeight, Bool useDST, const Int maxTrDynamicRange)
+{
+  static const Int TRANSFORM_MATRIX_SHIFT = g_transformMatrixShift[TRANSFORM_INVERSE];
+
+  Int shift_1st = TRANSFORM_MATRIX_SHIFT + 1; //1 has been added to shift_1st at the expense of shift_2nd
+  Int shift_2nd = (TRANSFORM_MATRIX_SHIFT + maxTrDynamicRange - 1) - bitDepth;
+  const TCoeff clipMinimum = -(1 << maxTrDynamicRange);
+  const TCoeff clipMaximum =  (1 << maxTrDynamicRange) - 1;
+
+  assert(shift_1st >= 0);
+  assert(shift_2nd >= 0);
+
+  TCoeff tmp[MAX_TU_SIZE * MAX_TU_SIZE];
+
+  switch (iHeight)
+  {
+    case 4:
+      {
+        if ((iWidth == 4) && useDST)    // Check for DCT or DST
+        {
+          fastInverseDst( coeff, tmp, shift_1st, clipMinimum, clipMaximum);
+        }
+        else partialButterflyInverse4 ( coeff, tmp, shift_1st, iWidth, clipMinimum, clipMaximum);
+      }
+      break;
+
+    case  8: partialButterflyInverse8 ( coeff, tmp, shift_1st, iWidth, clipMinimum, clipMaximum); break;
+    case 16: partialButterflyInverse16( coeff, tmp, shift_1st, iWidth, clipMinimum, clipMaximum); break;
+    case 32: partialButterflyInverse32( coeff, tmp, shift_1st, iWidth, clipMinimum, clipMaximum); break;
+
+    default:
+      assert(0); exit (1); break;
+  }
+
+  switch (iWidth)
+  {
+    // Clipping here is not in the standard, but is used to protect the "Pel" data type into which the inverse-transformed samples will be copied
+    case 4:
+      {
+        if ((iHeight == 4) && useDST)    // Check for DCT or DST
+        {
+          fastInverseDst( tmp, block, shift_2nd, std::numeric_limits<Pel>::min(), std::numeric_limits<Pel>::max() );
+        }
+        else partialButterflyInverse4 ( tmp, block, shift_2nd, iHeight, std::numeric_limits<Pel>::min(), std::numeric_limits<Pel>::max());
+      }
+      break;
+
+    case  8: partialButterflyInverse8 ( tmp, block, shift_2nd, iHeight, std::numeric_limits<Pel>::min(), std::numeric_limits<Pel>::max()); break;
+    case 16: partialButterflyInverse16( tmp, block, shift_2nd, iHeight, std::numeric_limits<Pel>::min(), std::numeric_limits<Pel>::max()); break;
+    case 32: partialButterflyInverse32( tmp, block, shift_2nd, iHeight, std::numeric_limits<Pel>::min(), std::numeric_limits<Pel>::max()); break;
+
+    default:
+      assert(0); exit (1); break;
+  }
+}
+
+
+// To minimize the distortion only. No rate is considered.
+Void TComTrQuant::signBitHidingHDQ( const ComponentID compID, TCoeff* pQCoef, TCoeff* pCoef, TCoeff* deltaU, const TUEntropyCodingParameters &codingParameters )
+{
+  const UInt width     = codingParameters.widthInGroups  << MLS_CG_LOG2_WIDTH;
+  const UInt height    = codingParameters.heightInGroups << MLS_CG_LOG2_HEIGHT;
+  const UInt groupSize = 1 << MLS_CG_SIZE;
+
+  const TCoeff entropyCodingMinimum = -(1 << g_maxTrDynamicRange[toChannelType(compID)]);
+  const TCoeff entropyCodingMaximum =  (1 << g_maxTrDynamicRange[toChannelType(compID)]) - 1;
+
+  Int lastCG = -1;
+  Int absSum = 0 ;
+  Int n ;
+
+  for( Int subSet = (width*height-1) >> MLS_CG_SIZE; subSet >= 0; subSet-- )
+  {
+    Int  subPos = subSet << MLS_CG_SIZE;
+    Int  firstNZPosInCG=groupSize , lastNZPosInCG=-1 ;
+    absSum = 0 ;
+
+    for(n = groupSize-1; n >= 0; --n )
+    {
+      if( pQCoef[ codingParameters.scan[ n + subPos ]] )
+      {
+        lastNZPosInCG = n;
+        break;
+      }
+    }
+
+    for(n = 0; n <groupSize; n++ )
+    {
+      if( pQCoef[ codingParameters.scan[ n + subPos ]] )
+      {
+        firstNZPosInCG = n;
+        break;
+      }
+    }
+
+    for(n = firstNZPosInCG; n <=lastNZPosInCG; n++ )
+    {
+      absSum += Int(pQCoef[ codingParameters.scan[ n + subPos ]]);
+    }
+
+    if(lastNZPosInCG>=0 && lastCG==-1)
+    {
+      lastCG = 1 ;
+    }
+
+    if( lastNZPosInCG-firstNZPosInCG>=SBH_THRESHOLD )
+    {
+      UInt signbit = (pQCoef[codingParameters.scan[subPos+firstNZPosInCG]]>0?0:1) ;
+      if( signbit!=(absSum&0x1) )  //compare signbit with sum_parity
+      {
+        TCoeff curCost    = std::numeric_limits<TCoeff>::max();
+        TCoeff minCostInc = std::numeric_limits<TCoeff>::max();
+        Int minPos =-1, finalChange=0, curChange=0;
+
+        for( n = (lastCG==1?lastNZPosInCG:groupSize-1) ; n >= 0; --n )
+        {
+          UInt blkPos   = codingParameters.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 = std::numeric_limits<TCoeff>::max();
+              }
+              else
+              {
+                curCost = deltaU[blkPos];
+                curChange =-1;
+              }
+            }
+          }
+          else
+          {
+            if(n<firstNZPosInCG)
+            {
+              UInt thisSignBit = (pCoef[blkPos]>=0?0:1);
+              if(thisSignBit != signbit )
+              {
+                curCost = std::numeric_limits<TCoeff>::max();
+              }
+              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] == entropyCodingMaximum || pQCoef[minPos] == entropyCodingMinimum)
+        {
+          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(       TComTU       &rTu,
+                                TCoeff      * pSrc,
+                                TCoeff      * pDes,
+#if ADAPTIVE_QP_SELECTION
+                                TCoeff      *pArlDes,
+#endif
+                                TCoeff       &uiAbsSum,
+                          const ComponentID   compID,
+                          const QpParam      &cQP )
+{
+  const TComRectangle &rect = rTu.getRect(compID);
+  const UInt uiWidth        = rect.width;
+  const UInt uiHeight       = rect.height;
+  TComDataCU* pcCU          = rTu.getCU();
+  const UInt uiAbsPartIdx   = rTu.GetAbsPartIdxTU();
+
+  TCoeff* piCoef    = pSrc;
+  TCoeff* piQCoef   = pDes;
+#if ADAPTIVE_QP_SELECTION
+  TCoeff* piArlCCoef = pArlDes;
+#endif
+
+  const Bool useTransformSkip = pcCU->getTransformSkip(uiAbsPartIdx, compID);
+
+  Bool useRDOQ = useTransformSkip ? m_useRDOQTS : m_useRDOQ;
+  if ( useRDOQ && (isLuma(compID) || RDOQ_CHROMA) )
+  {
+#if ADAPTIVE_QP_SELECTION
+    xRateDistOptQuant( rTu, piCoef, pDes, pArlDes, uiAbsSum, compID, cQP );
+#else
+    xRateDistOptQuant( rTu, piCoef, pDes, uiAbsSum, compID, cQP );
+#endif
+  }
+  else
+  {
+    TUEntropyCodingParameters codingParameters;
+    getTUEntropyCodingParameters(codingParameters, rTu, compID);
+
+    const TCoeff entropyCodingMinimum = -(1 << g_maxTrDynamicRange[toChannelType(compID)]);
+    const TCoeff entropyCodingMaximum =  (1 << g_maxTrDynamicRange[toChannelType(compID)]) - 1;
+
+    TCoeff deltaU[MAX_TU_SIZE * MAX_TU_SIZE];
+
+    const UInt uiLog2TrSize = rTu.GetEquivalentLog2TrSize(compID);
+
+    Int scalingListType = getScalingListType(pcCU->getPredictionMode(uiAbsPartIdx), compID);
+    assert(scalingListType < SCALING_LIST_NUM);
+    Int *piQuantCoeff = getQuantCoeff(scalingListType, cQP.rem, uiLog2TrSize-2);
+
+    const Bool enableScalingLists             = getUseScalingList(uiWidth, uiHeight, (pcCU->getTransformSkip(uiAbsPartIdx, compID) != 0));
+    const Int  defaultQuantisationCoefficient = g_quantScales[cQP.rem];
+
+    /* for 422 chroma blocks, the effective scaling applied during transformation is not a power of 2, hence it cannot be
+     * implemented as a bit-shift (the quantised result will be sqrt(2) * larger than required). Alternatively, adjust the
+     * uiLog2TrSize applied in iTransformShift, such that the result is 1/sqrt(2) the required result (i.e. smaller)
+     * Then a QP+3 (sqrt(2)) or QP-3 (1/sqrt(2)) method could be used to get the required result
+     */
+
+    // Represents scaling through forward transform
+    Int iTransformShift = getTransformShift(toChannelType(compID), uiLog2TrSize);
+    if (useTransformSkip && pcCU->getSlice()->getSPS()->getUseExtendedPrecision())
+    {
+      iTransformShift = std::max<Int>(0, iTransformShift);
+    }
+
+    const Int iQBits = QUANT_SHIFT + cQP.per + iTransformShift;
+    // QBits will be OK for any internal bit depth as the reduction in transform shift is balanced by an increase in Qp_per due to QpBDOffset
+
+#if ADAPTIVE_QP_SELECTION
+    Int iQBitsC = MAX_INT;
+    Int iAddC   = MAX_INT;
+
+    if (m_bUseAdaptQpSelect)
+    {
+      iQBitsC = iQBits - ARL_C_PRECISION;
+      iAddC   = 1 << (iQBitsC-1);
+    }
+#endif
+
+    const Int iAdd   = (pcCU->getSlice()->getSliceType()==I_SLICE ? 171 : 85) << (iQBits-9);
+    const Int qBits8 = iQBits - 8;
+
+    for( Int uiBlockPos = 0; uiBlockPos < uiWidth*uiHeight; uiBlockPos++ )
+    {
+      const TCoeff iLevel   = piCoef[uiBlockPos];
+      const TCoeff iSign    = (iLevel < 0 ? -1: 1);
+
+      const Int64  tmpLevel = (Int64)abs(iLevel) * (enableScalingLists ? piQuantCoeff[uiBlockPos] : defaultQuantisationCoefficient);
+
+#if ADAPTIVE_QP_SELECTION
+      if( m_bUseAdaptQpSelect )
+      {
+        piArlCCoef[uiBlockPos] = (TCoeff)((tmpLevel + iAddC ) >> iQBitsC);
+      }
+#endif
+
+      const TCoeff quantisedMagnitude = TCoeff((tmpLevel + iAdd ) >> iQBits);
+      deltaU[uiBlockPos] = (TCoeff)((tmpLevel - (quantisedMagnitude<<iQBits) )>> qBits8);
+
+      uiAbsSum += quantisedMagnitude;
+      const TCoeff quantisedCoefficient = quantisedMagnitude * iSign;
+
+      piQCoef[uiBlockPos] = Clip3<TCoeff>( entropyCodingMinimum, entropyCodingMaximum, quantisedCoefficient );
+    } // for n
+
+    if( pcCU->getSlice()->getPPS()->getSignHideFlag() )
+    {
+      if(uiAbsSum >= 2) //this prevents TUs with only one coefficient of value 1 from being tested
+      {
+        signBitHidingHDQ( compID, piQCoef, piCoef, deltaU, codingParameters ) ;
+      }
+    }
+  } //if RDOQ
+  //return;
+}
+
+Void TComTrQuant::xDeQuant(       TComTU        &rTu,
+                            const TCoeff       * pSrc,
+                                  TCoeff       * pDes,
+                            const ComponentID    compID,
+                            const QpParam       &cQP )
+{
+  assert(compID<MAX_NUM_COMPONENT);
+
+        TComDataCU          *pcCU               = rTu.getCU();
+  const UInt                 uiAbsPartIdx       = rTu.GetAbsPartIdxTU();
+  const TComRectangle       &rect               = rTu.getRect(compID);
+  const UInt                 uiWidth            = rect.width;
+  const UInt                 uiHeight           = rect.height;
+  const TCoeff        *const piQCoef            = pSrc;
+        TCoeff        *const piCoef             = pDes;
+  const UInt                 uiLog2TrSize       = rTu.GetEquivalentLog2TrSize(compID);
+  const UInt                 numSamplesInBlock  = uiWidth*uiHeight;
+  const TCoeff               transformMinimum   = -(1 << g_maxTrDynamicRange[toChannelType(compID)]);
+  const TCoeff               transformMaximum   =  (1 << g_maxTrDynamicRange[toChannelType(compID)]) - 1;
+  const Bool                 enableScalingLists = getUseScalingList(uiWidth, uiHeight, (pcCU->getTransformSkip(uiAbsPartIdx, compID) != 0));
+  const Int                  scalingListType    = getScalingListType(pcCU->getPredictionMode(uiAbsPartIdx), compID);
+
+  assert (scalingListType < SCALING_LIST_NUM);
+  assert ( uiWidth <= m_uiMaxTrSize );
+
+  // Represents scaling through forward transform
+  const Bool bClipTransformShiftTo0 = (pcCU->getTransformSkip(uiAbsPartIdx, compID) != 0) && pcCU->getSlice()->getSPS()->getUseExtendedPrecision();
+  const Int  originalTransformShift = getTransformShift(toChannelType(compID), uiLog2TrSize);
+  const Int  iTransformShift        = bClipTransformShiftTo0 ? std::max<Int>(0, originalTransformShift) : originalTransformShift;
+
+  const Int QP_per = cQP.per;
+  const Int QP_rem = cQP.rem;
+
+  const Int rightShift = (IQUANT_SHIFT - (iTransformShift + QP_per)) + (enableScalingLists ? LOG2_SCALING_LIST_NEUTRAL_VALUE : 0);
+
+  if(enableScalingLists)
+  {
+    //from the dequantisation equation:
+    //iCoeffQ                         = ((Intermediate_Int(clipQCoef) * piDequantCoef[deQuantIdx]) + iAdd ) >> rightShift
+    //(sizeof(Intermediate_Int) * 8)  =              inputBitDepth    +    dequantCoefBits                   - rightShift
+    const UInt             dequantCoefBits     = 1 + IQUANT_SHIFT + SCALING_LIST_BITS;
+    const UInt             targetInputBitDepth = std::min<UInt>((g_maxTrDynamicRange[toChannelType(compID)] + 1), (((sizeof(Intermediate_Int) * 8) + rightShift) - dequantCoefBits));
+
+    const Intermediate_Int inputMinimum        = -(1 << (targetInputBitDepth - 1));
+    const Intermediate_Int inputMaximum        =  (1 << (targetInputBitDepth - 1)) - 1;
+
+    Int *piDequantCoef = getDequantCoeff(scalingListType,QP_rem,uiLog2TrSize-2);
+
+    if(rightShift > 0)
+    {
+      const Intermediate_Int iAdd = 1 << (rightShift - 1);
+
+      for( Int n = 0; n < numSamplesInBlock; n++ )
+      {
+        const TCoeff           clipQCoef = TCoeff(Clip3<Intermediate_Int>(inputMinimum, inputMaximum, piQCoef[n]));
+        const Intermediate_Int iCoeffQ   = ((Intermediate_Int(clipQCoef) * piDequantCoef[n]) + iAdd ) >> rightShift;
+
+        piCoef[n] = TCoeff(Clip3<Intermediate_Int>(transformMinimum,transformMaximum,iCoeffQ));
+      }
+    }
+    else
+    {
+      const Int leftShift = -rightShift;
+
+      for( Int n = 0; n < numSamplesInBlock; n++ )
+      {
+        const TCoeff           clipQCoef = TCoeff(Clip3<Intermediate_Int>(inputMinimum, inputMaximum, piQCoef[n]));
+        const Intermediate_Int iCoeffQ   = (Intermediate_Int(clipQCoef) * piDequantCoef[n]) << leftShift;
+
+        piCoef[n] = TCoeff(Clip3<Intermediate_Int>(transformMinimum,transformMaximum,iCoeffQ));
+      }
+    }
+  }
+  else
+  {
+    const Int scale     =  g_invQuantScales[QP_rem];
+    const Int scaleBits =     (IQUANT_SHIFT + 1)   ;
+
+    //from the dequantisation equation:
+    //iCoeffQ                         = Intermediate_Int((Int64(clipQCoef) * scale + iAdd) >> rightShift);
+    //(sizeof(Intermediate_Int) * 8)  =                    inputBitDepth   + scaleBits      - rightShift
+    const UInt             targetInputBitDepth = std::min<UInt>((g_maxTrDynamicRange[toChannelType(compID)] + 1), (((sizeof(Intermediate_Int) * 8) + rightShift) - scaleBits));
+    const Intermediate_Int inputMinimum        = -(1 << (targetInputBitDepth - 1));
+    const Intermediate_Int inputMaximum        =  (1 << (targetInputBitDepth - 1)) - 1;
+
+    if (rightShift > 0)
+    {
+      const Intermediate_Int iAdd = 1 << (rightShift - 1);
+
+      for( Int n = 0; n < numSamplesInBlock; n++ )
+      {
+        const TCoeff           clipQCoef = TCoeff(Clip3<Intermediate_Int>(inputMinimum, inputMaximum, piQCoef[n]));
+        const Intermediate_Int iCoeffQ   = (Intermediate_Int(clipQCoef) * scale + iAdd) >> rightShift;
+
+        piCoef[n] = TCoeff(Clip3<Intermediate_Int>(transformMinimum,transformMaximum,iCoeffQ));
+      }
+    }
+    else
+    {
+      const Int leftShift = -rightShift;
+
+      for( Int n = 0; n < numSamplesInBlock; n++ )
+      {
+        const TCoeff           clipQCoef = TCoeff(Clip3<Intermediate_Int>(inputMinimum, inputMaximum, piQCoef[n]));
+        const Intermediate_Int iCoeffQ   = (Intermediate_Int(clipQCoef) * scale) << leftShift;
+
+        piCoef[n] = TCoeff(Clip3<Intermediate_Int>(transformMinimum,transformMaximum,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(       TComTU        & rTu,
+                                const ComponentID     compID,
+                                      Pel          *  pcResidual,
+                                const UInt            uiStride,
+                                      TCoeff       *  rpcCoeff,
+#if ADAPTIVE_QP_SELECTION
+                                      TCoeff       *  pcArlCoeff,
+#endif
+                                      TCoeff        & uiAbsSum,
+                                const QpParam       & cQP
+                              )
+{
+  const TComRectangle &rect = rTu.getRect(compID);
+  const UInt uiWidth        = rect.width;
+  const UInt uiHeight       = rect.height;
+  TComDataCU* pcCU          = rTu.getCU();
+  const UInt uiAbsPartIdx   = rTu.GetAbsPartIdxTU();
+  const UInt uiOrgTrDepth   = rTu.GetTransformDepthRel();
+
+  uiAbsSum=0;
+
+  RDPCMMode rdpcmMode = RDPCM_OFF;
+  rdpcmNxN( rTu, compID, pcResidual, uiStride, cQP, rpcCoeff, uiAbsSum, rdpcmMode );
+
+  if (rdpcmMode == RDPCM_OFF)
+  {
+    uiAbsSum = 0;
+    //transform and quantise
+    if(pcCU->getCUTransquantBypass(uiAbsPartIdx))
+    {
+      const Bool rotateResidual = rTu.isNonTransformedResidualRotated(compID);
+      const UInt uiSizeMinus1   = (uiWidth * uiHeight) - 1;
+
+      for (UInt y = 0, coefficientIndex = 0; y<uiHeight; y++)
+      {
+        for (UInt x = 0; x<uiWidth; x++, coefficientIndex++)
+        {
+          const Pel currentSample = pcResidual[(y * uiStride) + x];
+
+          rpcCoeff[rotateResidual ? (uiSizeMinus1 - coefficientIndex) : coefficientIndex] = currentSample;
+          uiAbsSum += TCoeff(abs(currentSample));
+        }
+      }
+    }
+    else
+    {
+#ifdef DEBUG_TRANSFORM_AND_QUANTISE
+      std::cout << g_debugCounter << ": " << uiWidth << "x" << uiHeight << " channel " << compID << " TU at input to transform\n";
+      printBlock(pcResidual, uiWidth, uiHeight, uiStride);
+#endif
+
+      assert( (pcCU->getSlice()->getSPS()->getMaxTrSize() >= uiWidth) );
+
+      if(pcCU->getTransformSkip(uiAbsPartIdx, compID) != 0)
+      {
+        xTransformSkip( pcResidual, uiStride, m_plTempCoeff, rTu, compID );
+      }
+      else
+      {
+        xT( compID, rTu.useDST(compID), pcResidual, uiStride, m_plTempCoeff, uiWidth, uiHeight );
+      }
+
+#ifdef DEBUG_TRANSFORM_AND_QUANTISE
+      std::cout << g_debugCounter << ": " << uiWidth << "x" << uiHeight << " channel " << compID << " TU between transform and quantiser\n";
+      printBlock(m_plTempCoeff, uiWidth, uiHeight, uiWidth);
+#endif
+
+      xQuant( rTu, m_plTempCoeff, rpcCoeff,
+
+#if ADAPTIVE_QP_SELECTION
+              pcArlCoeff,
+#endif
+              uiAbsSum, compID, cQP );
+
+#ifdef DEBUG_TRANSFORM_AND_QUANTISE
+      std::cout << g_debugCounter << ": " << uiWidth << "x" << uiHeight << " channel " << compID << " TU at output of quantiser\n";
+      printBlock(rpcCoeff, uiWidth, uiHeight, uiWidth);
+#endif
+    }
+  }
+
+    //set the CBF
+  pcCU->setCbfPartRange((((uiAbsSum > 0) ? 1 : 0) << uiOrgTrDepth), compID, uiAbsPartIdx, rTu.GetAbsPartIdxNumParts(compID));
+}
+
+
+Void TComTrQuant::invTransformNxN(      TComTU        &rTu,
+                                  const ComponentID    compID,
+                                        Pel          *pcResidual,
+                                  const UInt           uiStride,
+                                        TCoeff       * pcCoeff,
+                                  const QpParam       &cQP
+                                        DEBUG_STRING_FN_DECLAREP(psDebug))
+{
+  TComDataCU* pcCU=rTu.getCU();
+  const UInt uiAbsPartIdx = rTu.GetAbsPartIdxTU();
+  const TComRectangle &rect = rTu.getRect(compID);
+  const UInt uiWidth = rect.width;
+  const UInt uiHeight = rect.height;
+
+  if (uiWidth != uiHeight) //for intra, the TU will have been split above this level, so this condition won't be true, hence this only affects inter
+  {
+    //------------------------------------------------
+
+    //recurse deeper
+
+    TComTURecurse subTURecurse(rTu, false, TComTU::VERTICAL_SPLIT, true, compID);
+
+    do
+    {
+      //------------------
+
+      const UInt lineOffset = subTURecurse.GetSectionNumber() * subTURecurse.getRect(compID).height;
+
+      Pel    *subTUResidual     = pcResidual + (lineOffset * uiStride);
+      TCoeff *subTUCoefficients = pcCoeff     + (lineOffset * subTURecurse.getRect(compID).width);
+
+      invTransformNxN(subTURecurse, compID, subTUResidual, uiStride, subTUCoefficients, cQP DEBUG_STRING_PASS_INTO(psDebug));
+
+      //------------------
+
+    }
+    while (subTURecurse.nextSection(rTu));
+
+    //------------------------------------------------
+
+    return;
+  }
+
+#if defined DEBUG_STRING
+  if (psDebug)
+  {
+    std::stringstream ss(stringstream::out);
+    printBlockToStream(ss, (compID==0)?"###InvTran ip Ch0: " : ((compID==1)?"###InvTran ip Ch1: ":"###InvTran ip Ch2: "), pcCoeff, uiWidth, uiHeight, uiWidth);
+    DEBUG_STRING_APPEND((*psDebug), ss.str())
+  }
+#endif
+
+  if(pcCU->getCUTransquantBypass(uiAbsPartIdx))
+  {
+    const Bool rotateResidual = rTu.isNonTransformedResidualRotated(compID);
+    const UInt uiSizeMinus1   = (uiWidth * uiHeight) - 1;
+
+    for (UInt y = 0, coefficientIndex = 0; y<uiHeight; y++)
+    {
+      for (UInt x = 0; x<uiWidth; x++, coefficientIndex++)
+      {
+        pcResidual[(y * uiStride) + x] = Pel(pcCoeff[rotateResidual ? (uiSizeMinus1 - coefficientIndex) : coefficientIndex]);
+      }
+    }
+  }
+  else
+  {
+#ifdef DEBUG_TRANSFORM_AND_QUANTISE
+    std::cout << g_debugCounter << ": " << uiWidth << "x" << uiHeight << " channel " << compID << " TU at input to dequantiser\n";
+    printBlock(pcCoeff, uiWidth, uiHeight, uiWidth);
+#endif
+
+    xDeQuant(rTu, pcCoeff, m_plTempCoeff, compID, cQP);
+
+#ifdef DEBUG_TRANSFORM_AND_QUANTISE
+    std::cout << g_debugCounter << ": " << uiWidth << "x" << uiHeight << " channel " << compID << " TU between dequantiser and inverse-transform\n";
+    printBlock(m_plTempCoeff, uiWidth, uiHeight, uiWidth);
+#endif
+
+#if defined DEBUG_STRING
+    if (psDebug)
+    {
+      std::stringstream ss(stringstream::out);
+      printBlockToStream(ss, "###InvTran deq: ", m_plTempCoeff, uiWidth, uiHeight, uiWidth);
+      (*psDebug)+=ss.str();
+    }
+#endif
+
+    if(pcCU->getTransformSkip(uiAbsPartIdx, compID))
+    {
+      xITransformSkip( m_plTempCoeff, pcResidual, uiStride, rTu, compID );
+
+#if defined DEBUG_STRING
+      if (psDebug)
+      {
+        std::stringstream ss(stringstream::out);
+        printBlockToStream(ss, "###InvTran resi: ", pcResidual, uiWidth, uiHeight, uiStride);
+        (*psDebug)+=ss.str();
+        (*psDebug)+="(<- was a Transform-skipped block)\n";
+      }
+#endif
+    }
+    else
+    {
+      xIT( compID, rTu.useDST(compID), m_plTempCoeff, pcResidual, uiStride, uiWidth, uiHeight );
+
+#if defined DEBUG_STRING
+      if (psDebug)
+      {
+        std::stringstream ss(stringstream::out);
+        printBlockToStream(ss, "###InvTran resi: ", pcResidual, uiWidth, uiHeight, uiStride);
+        (*psDebug)+=ss.str();
+        (*psDebug)+="(<- was a Transformed block)\n";
+      }
+#endif
+    }
+
+#ifdef DEBUG_TRANSFORM_AND_QUANTISE
+    std::cout << g_debugCounter << ": " << uiWidth << "x" << uiHeight << " channel " << compID << " TU at output of inverse-transform\n";
+    printBlock(pcResidual, uiWidth, uiHeight, uiStride);
+    g_debugCounter++;
+#endif
+  }
+
+  invRdpcmNxN( rTu, compID, pcResidual, uiStride );
+}
+
+Void TComTrQuant::invRecurTransformNxN( const ComponentID compID,
+                                        TComYuv *pResidual,
+                                        TComTU &rTu)
+{
+  if (!rTu.ProcessComponentSection(compID)) return;
+
+  TComDataCU* pcCU = rTu.getCU();
+  UInt absPartIdxTU = rTu.GetAbsPartIdxTU();
+  UInt uiTrMode=rTu.GetTransformDepthRel();
+  if( (pcCU->getCbf(absPartIdxTU, compID, uiTrMode) == 0) && (isLuma(compID) || !pcCU->getSlice()->getPPS()->getUseCrossComponentPrediction()) )
+  {
+    return;
+  }
+
+  if( uiTrMode == pcCU->getTransformIdx( absPartIdxTU ) )
+  {
+    const TComRectangle &tuRect      = rTu.getRect(compID);
+    const Int            uiStride    = pResidual->getStride( compID );
+          Pel           *rpcResidual = pResidual->getAddr( compID );
+          UInt           uiAddr      = (tuRect.x0 + uiStride*tuRect.y0);
+          Pel           *pResi       = rpcResidual + uiAddr;
+          TCoeff        *pcCoeff     = pcCU->getCoeff(compID) + rTu.getCoefficientOffset(compID);
+
+    const QpParam cQP(*pcCU, compID);
+
+    if(pcCU->getCbf(absPartIdxTU, compID, uiTrMode) != 0)
+    {
+      DEBUG_STRING_NEW(sTemp)
+#ifdef DEBUG_STRING
+      std::string *psDebug=((DebugOptionList::DebugString_InvTran.getInt()&(pcCU->isIntra(absPartIdxTU)?1:(pcCU->isInter(absPartIdxTU)?2:4)))!=0) ? &sTemp : 0;
+#endif
+
+      invTransformNxN( rTu, compID, pResi, uiStride, pcCoeff, cQP DEBUG_STRING_PASS_INTO(psDebug) );
+
+#ifdef DEBUG_STRING
+      if (psDebug != 0)
+        std::cout << (*psDebug);
+#endif
+    }
+
+    if (isChroma(compID) && (pcCU->getCrossComponentPredictionAlpha(absPartIdxTU, compID) != 0))
+    {
+      const Pel *piResiLuma = pResidual->getAddr( COMPONENT_Y );
+      const Int  strideLuma = pResidual->getStride( COMPONENT_Y );
+      const Int  tuWidth    = rTu.getRect( compID ).width;
+      const Int  tuHeight   = rTu.getRect( compID ).height;
+
+      if(pcCU->getCbf(absPartIdxTU, COMPONENT_Y, uiTrMode) != 0)
+      {
+        pResi = rpcResidual + uiAddr;
+        const Pel *pResiLuma = piResiLuma + uiAddr;
+
+        crossComponentPrediction( rTu, compID, pResiLuma, pResi, pResi, tuWidth, tuHeight, strideLuma, uiStride, uiStride, true );
+      }
+    }
+  }
+  else
+  {
+    TComTURecurse tuRecurseChild(rTu, false);
+    do
+    {
+      invRecurTransformNxN( compID, pResidual, tuRecurseChild );
+    }
+    while (tuRecurseChild.nextSection(rTu));
+  }
+}
+
+Void TComTrQuant::applyForwardRDPCM( TComTU& rTu, const ComponentID compID, Pel* pcResidual, const UInt uiStride, const QpParam& cQP, TCoeff* pcCoeff, TCoeff &uiAbsSum, const RDPCMMode mode )
+{
+  TComDataCU *pcCU=rTu.getCU();
+  const UInt uiAbsPartIdx=rTu.GetAbsPartIdxTU();
+
+  const Bool bLossless      = pcCU->getCUTransquantBypass( uiAbsPartIdx );
+  const UInt uiWidth        = rTu.getRect(compID).width;
+  const UInt uiHeight       = rTu.getRect(compID).height;
+  const Bool rotateResidual = rTu.isNonTransformedResidualRotated(compID);
+  const UInt uiSizeMinus1   = (uiWidth * uiHeight) - 1;
+
+  Pel reconstructedResi[MAX_TU_SIZE * MAX_TU_SIZE];
+
+  UInt uiX = 0;
+  UInt uiY = 0;
+
+        UInt &majorAxis             = (mode == RDPCM_HOR) ? uiX      : uiY;
+        UInt &minorAxis             = (mode == RDPCM_HOR) ? uiY      : uiX;
+  const UInt  majorAxisLimit        = (mode == RDPCM_HOR) ? uiWidth  : uiHeight;
+  const UInt  minorAxisLimit        = (mode == RDPCM_HOR) ? uiHeight : uiWidth;
+  const UInt  referenceSampleOffset = (mode == RDPCM_HOR) ? 1        : uiWidth;
+
+  const Bool bUseHalfRoundingPoint = (mode != RDPCM_OFF);
+
+  uiAbsSum = 0;
+
+  for ( majorAxis = 0; majorAxis < majorAxisLimit; majorAxis++ )
+  {
+    for ( minorAxis = 0; minorAxis < minorAxisLimit; minorAxis++ )
+    {
+      const UInt sampleIndex      = (uiY * uiWidth) + uiX;
+      const UInt coefficientIndex = (rotateResidual ? (uiSizeMinus1-sampleIndex) : sampleIndex);
+      const Pel  currentSample    = pcResidual[(uiY * uiStride) + uiX];
+      const Pel  referenceSample  = ((mode != RDPCM_OFF) && (majorAxis > 0)) ? reconstructedResi[sampleIndex - referenceSampleOffset] : 0;
+
+      const Pel  encoderSideDelta = currentSample - referenceSample;
+
+      Pel reconstructedDelta;
+      if ( bLossless )
+      {
+        pcCoeff[coefficientIndex] = encoderSideDelta;
+        reconstructedDelta        = encoderSideDelta;
+      }
+      else
+      {
+        transformSkipQuantOneSample(rTu, compID, encoderSideDelta, pcCoeff, coefficientIndex, cQP, bUseHalfRoundingPoint);
+        invTrSkipDeQuantOneSample  (rTu, compID, pcCoeff[coefficientIndex], reconstructedDelta, cQP, coefficientIndex);
+      }
+
+      uiAbsSum += abs(pcCoeff[coefficientIndex]);
+
+      reconstructedResi[sampleIndex] = reconstructedDelta + referenceSample;
+    }
+  }
+}
+
+Void TComTrQuant::rdpcmNxN   ( TComTU& rTu, const ComponentID compID, Pel* pcResidual, const UInt uiStride, const QpParam& cQP, TCoeff* pcCoeff, TCoeff &uiAbsSum, RDPCMMode& rdpcmMode )
+{
+  TComDataCU *pcCU=rTu.getCU();
+  const UInt uiAbsPartIdx=rTu.GetAbsPartIdxTU();
+
+  if (!pcCU->isRDPCMEnabled(uiAbsPartIdx) || ((pcCU->getTransformSkip(uiAbsPartIdx, compID) == 0) && !pcCU->getCUTransquantBypass(uiAbsPartIdx)))
+  {
+    rdpcmMode = RDPCM_OFF;
+  }
+  else if ( pcCU->isIntra( uiAbsPartIdx ) )
+  {
+    const ChromaFormat chFmt = pcCU->getPic()->getPicYuvOrg()->getChromaFormat();
+    const ChannelType chType = toChannelType(compID);
+    const UInt uiChPredMode  = pcCU->getIntraDir( chType, uiAbsPartIdx );
+    const UInt uiChCodedMode = (uiChPredMode==DM_CHROMA_IDX && isChroma(compID)) ? pcCU->getIntraDir(CHANNEL_TYPE_LUMA, getChromasCorrespondingPULumaIdx(uiAbsPartIdx, chFmt)) : uiChPredMode;
+    const UInt uiChFinalMode = ((chFmt == CHROMA_422)       && isChroma(compID)) ? g_chroma422IntraAngleMappingTable[uiChCodedMode] : uiChCodedMode;
+
+    if (uiChFinalMode == VER_IDX || uiChFinalMode == HOR_IDX)
+    {
+      rdpcmMode = (uiChFinalMode == VER_IDX) ? RDPCM_VER : RDPCM_HOR;
+      applyForwardRDPCM( rTu, compID, pcResidual, uiStride, cQP, pcCoeff, uiAbsSum, rdpcmMode );
+    }
+    else rdpcmMode = RDPCM_OFF;
+  }
+  else // not intra, need to select the best mode
+  {
+    const UInt uiWidth  = rTu.getRect(compID).width;
+    const UInt uiHeight = rTu.getRect(compID).height;
+
+    RDPCMMode bestMode   = NUMBER_OF_RDPCM_MODES;
+    TCoeff    bestAbsSum = std::numeric_limits<TCoeff>::max();
+    TCoeff    bestCoefficients[MAX_TU_SIZE * MAX_TU_SIZE];
+
+    for (UInt modeIndex = 0; modeIndex < NUMBER_OF_RDPCM_MODES; modeIndex++)
+    {
+      const RDPCMMode mode = RDPCMMode(modeIndex);
+
+      TCoeff currAbsSum = 0;
+
+      applyForwardRDPCM( rTu, compID, pcResidual, uiStride, cQP, pcCoeff, currAbsSum, mode );
+
+      if (currAbsSum < bestAbsSum)
+      {
+        bestMode   = mode;
+        bestAbsSum = currAbsSum;
+        if (mode != RDPCM_OFF)
+        {
+          memcpy(bestCoefficients, pcCoeff, (uiWidth * uiHeight * sizeof(TCoeff)));
+        }
+      }
+    }
+
+    rdpcmMode = bestMode;
+    uiAbsSum  = bestAbsSum;
+
+    if (rdpcmMode != RDPCM_OFF) //the TU is re-transformed and quantised if DPCM_OFF is returned, so there is no need to preserve it here
+    {
+      memcpy(pcCoeff, bestCoefficients, (uiWidth * uiHeight * sizeof(TCoeff)));
+    }
+  }
+
+  pcCU->setExplicitRdpcmModePartRange(rdpcmMode, compID, uiAbsPartIdx, rTu.GetAbsPartIdxNumParts(compID));
+}
+
+Void TComTrQuant::invRdpcmNxN( TComTU& rTu, const ComponentID compID, Pel* pcResidual, const UInt uiStride )
+{
+  TComDataCU *pcCU=rTu.getCU();
+  const UInt uiAbsPartIdx=rTu.GetAbsPartIdxTU();
+
+  if (pcCU->isRDPCMEnabled( uiAbsPartIdx ) && ((pcCU->getTransformSkip(uiAbsPartIdx, compID ) != 0) || pcCU->getCUTransquantBypass(uiAbsPartIdx)))
+  {
+    const UInt uiWidth  = rTu.getRect(compID).width;
+    const UInt uiHeight = rTu.getRect(compID).height;
+
+    RDPCMMode rdpcmMode = RDPCM_OFF;
+
+    if ( pcCU->isIntra( uiAbsPartIdx ) )
+    {
+      const ChromaFormat chFmt = pcCU->getPic()->getPicYuvRec()->getChromaFormat();
+      const ChannelType chType = toChannelType(compID);
+      const UInt uiChPredMode  = pcCU->getIntraDir( chType, uiAbsPartIdx );
+      const UInt uiChCodedMode = (uiChPredMode==DM_CHROMA_IDX && isChroma(compID)) ? pcCU->getIntraDir(CHANNEL_TYPE_LUMA, getChromasCorrespondingPULumaIdx(uiAbsPartIdx, chFmt)) : uiChPredMode;
+      const UInt uiChFinalMode = ((chFmt == CHROMA_422)       && isChroma(compID)) ? g_chroma422IntraAngleMappingTable[uiChCodedMode] : uiChCodedMode;
+
+      if (uiChFinalMode == VER_IDX || uiChFinalMode == HOR_IDX)
+      {
+        rdpcmMode = (uiChFinalMode == VER_IDX) ? RDPCM_VER : RDPCM_HOR;
+      }
+    }
+    else  // not intra case
+    {
+      rdpcmMode = RDPCMMode(pcCU->getExplicitRdpcmMode( compID, uiAbsPartIdx ));
+    }
+
+    if (rdpcmMode == RDPCM_VER)
+    {
+      pcResidual += uiStride; //start from row 1
+
+      for( UInt uiY = 1; uiY < uiHeight; uiY++ )
+      {
+        for( UInt uiX = 0; uiX < uiWidth; uiX++ )
+        {
+          pcResidual[ uiX ] = pcResidual[ uiX ] + pcResidual [ (Int)uiX - (Int)uiStride ];
+        }
+        pcResidual += uiStride;
+      }
+    }
+    else if (rdpcmMode == RDPCM_HOR)
+    {
+      for( UInt uiY = 0; uiY < uiHeight; uiY++ )
+      {
+        for( UInt uiX = 1; uiX < uiWidth; uiX++ )
+        {
+          pcResidual[ uiX ] = pcResidual[ uiX ] + pcResidual [ (Int)uiX-1 ];
+        }
+        pcResidual += uiStride;
+      }
+    }
+  }
+}
+
+// ------------------------------------------------------------------------------------------------
+// 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( const ComponentID compID, Bool useDST, Pel* piBlkResi, UInt uiStride, TCoeff* psCoeff, Int iWidth, Int iHeight )
+{
+#if MATRIX_MULT
+  if( iWidth == iHeight)
+  {
+    xTr(g_bitDepth[toChannelType(compID)], piBlkResi, psCoeff, uiStride, (UInt)iWidth, useDST, g_maxTrDynamicRange[toChannelType(compID)]);
+    return;
+  }
+#endif
+
+  TCoeff block[ MAX_TU_SIZE * MAX_TU_SIZE ];
+  TCoeff coeff[ MAX_TU_SIZE * MAX_TU_SIZE ];
+
+  for (Int y = 0; y < iHeight; y++)
+    for (Int x = 0; x < iWidth; x++)
+    {
+      block[(y * iWidth) + x] = piBlkResi[(y * uiStride) + x];
+    }
+
+  xTrMxN( g_bitDepth[toChannelType(compID)], block, coeff, iWidth, iHeight, useDST, g_maxTrDynamicRange[toChannelType(compID)] );
+
+  memcpy(psCoeff, coeff, (iWidth * iHeight * sizeof(TCoeff)));
+}
+
+/** 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( const ComponentID compID, Bool useDST, TCoeff* plCoef, Pel* pResidual, UInt uiStride, Int iWidth, Int iHeight )
+{
+#if MATRIX_MULT
+  if( iWidth == iHeight )
+  {
+#if O0043_BEST_EFFORT_DECODING
+    xITr(g_bitDepthInStream[toChannelType(compID)], plCoef, pResidual, uiStride, (UInt)iWidth, useDST, g_maxTrDynamicRange[toChannelType(compID)]);
+#else
+    xITr(g_bitDepth[toChannelType(compID)], plCoef, pResidual, uiStride, (UInt)iWidth, useDST, g_maxTrDynamicRange[toChannelType(compID)]);
+#endif
+    return;
+  }
+#endif
+
+  TCoeff block[ MAX_TU_SIZE * MAX_TU_SIZE ];
+  TCoeff coeff[ MAX_TU_SIZE * MAX_TU_SIZE ];
+
+  memcpy(coeff, plCoef, (iWidth * iHeight * sizeof(TCoeff)));
+
+#if O0043_BEST_EFFORT_DECODING
+  xITrMxN( g_bitDepthInStream[toChannelType(compID)], coeff, block, iWidth, iHeight, useDST, g_maxTrDynamicRange[toChannelType(compID)] );
+#else
+  xITrMxN( g_bitDepth[toChannelType(compID)], coeff, block, iWidth, iHeight, useDST, g_maxTrDynamicRange[toChannelType(compID)] );
+#endif
+
+  for (Int y = 0; y < iHeight; y++)
+    for (Int x = 0; x < iWidth; x++)
+    {
+      pResidual[(y * uiStride) + x] = Pel(block[(y * iWidth) + x]);
+    }
+}
+
+/** 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( Pel* piBlkResi, UInt uiStride, TCoeff* psCoeff, TComTU &rTu, const ComponentID component )
+{
+  const TComRectangle &rect = rTu.getRect(component);
+  const Int width           = rect.width;
+  const Int height          = rect.height;
+
+  Int iTransformShift = getTransformShift(toChannelType(component), rTu.GetEquivalentLog2TrSize(component));
+  if (rTu.getCU()->getSlice()->getSPS()->getUseExtendedPrecision())
+  {
+    iTransformShift = std::max<Int>(0, iTransformShift);
+  }
+
+  const Bool rotateResidual = rTu.isNonTransformedResidualRotated(component);
+  const UInt uiSizeMinus1   = (width * height) - 1;
+
+  if (iTransformShift >= 0)
+  {
+    for (UInt y = 0, coefficientIndex = 0; y < height; y++)
+    {
+      for (UInt x = 0; x < width; x++, coefficientIndex++)
+      {
+        psCoeff[rotateResidual ? (uiSizeMinus1 - coefficientIndex) : coefficientIndex] = TCoeff(piBlkResi[(y * uiStride) + x]) << iTransformShift;
+      }
+    }
+  }
+  else //for very high bit depths
+  {
+    iTransformShift = -iTransformShift;
+    const TCoeff offset = 1 << (iTransformShift - 1);
+
+    for (UInt y = 0, coefficientIndex = 0; y < height; y++)
+    {
+      for (UInt x = 0; x < width; x++, coefficientIndex++)
+      {
+        psCoeff[rotateResidual ? (uiSizeMinus1 - coefficientIndex) : coefficientIndex] = (TCoeff(piBlkResi[(y * uiStride) + x]) + offset) >> iTransformShift;
+      }
+    }
+  }
+}
+
+/** 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( TCoeff* plCoef, Pel* pResidual, UInt uiStride, TComTU &rTu, const ComponentID component )
+{
+  const TComRectangle &rect = rTu.getRect(component);
+  const Int width           = rect.width;
+  const Int height          = rect.height;
+
+  Int iTransformShift = getTransformShift(toChannelType(component), rTu.GetEquivalentLog2TrSize(component));
+  if (rTu.getCU()->getSlice()->getSPS()->getUseExtendedPrecision())
+  {
+    iTransformShift = std::max<Int>(0, iTransformShift);
+  }
+
+  const Bool rotateResidual = rTu.isNonTransformedResidualRotated(component);
+  const UInt uiSizeMinus1   = (width * height) - 1;
+
+  if (iTransformShift >= 0)
+  {
+    const TCoeff offset = iTransformShift==0 ? 0 : (1 << (iTransformShift - 1));
+
+    for (UInt y = 0, coefficientIndex = 0; y < height; y++)
+    {
+      for (UInt x = 0; x < width; x++, coefficientIndex++)
+      {
+        pResidual[(y * uiStride) + x] =  Pel((plCoef[rotateResidual ? (uiSizeMinus1 - coefficientIndex) : coefficientIndex] + offset) >> iTransformShift);
+      }
+    }
+  }
+  else //for very high bit depths
+  {
+    iTransformShift = -iTransformShift;
+
+    for (UInt y = 0, coefficientIndex = 0; y < height; y++)
+    {
+      for (UInt x = 0; x < width; x++, coefficientIndex++)
+      {
+        pResidual[(y * uiStride) + x] = Pel(plCoef[rotateResidual ? (uiSizeMinus1 - coefficientIndex) : coefficientIndex] << iTransformShift);
+      }
+    }
+  }
+}
+
+/** 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                 (       TComTU       &rTu,
+                                                            TCoeff      * plSrcCoeff,
+                                                            TCoeff      * piDstCoeff,
+#if ADAPTIVE_QP_SELECTION
+                                                            TCoeff      * piArlDstCoeff,
+#endif
+                                                            TCoeff       &uiAbsSum,
+                                                      const ComponentID   compID,
+                                                      const QpParam      &cQP  )
+{
+  const TComRectangle  & rect             = rTu.getRect(compID);
+  const UInt             uiWidth          = rect.width;
+  const UInt             uiHeight         = rect.height;
+        TComDataCU    *  pcCU             = rTu.getCU();
+  const UInt             uiAbsPartIdx     = rTu.GetAbsPartIdxTU();
+  const ChannelType      channelType      = toChannelType(compID);
+  const UInt             uiLog2TrSize     = rTu.GetEquivalentLog2TrSize(compID);
+
+  const Bool             extendedPrecision = pcCU->getSlice()->getSPS()->getUseExtendedPrecision();
+
+  /* for 422 chroma blocks, the effective scaling applied during transformation is not a power of 2, hence it cannot be
+   * implemented as a bit-shift (the quantised result will be sqrt(2) * larger than required). Alternatively, adjust the
+   * uiLog2TrSize applied in iTransformShift, such that the result is 1/sqrt(2) the required result (i.e. smaller)
+   * Then a QP+3 (sqrt(2)) or QP-3 (1/sqrt(2)) method could be used to get the required result
+   */
+
+  // Represents scaling through forward transform
+  Int iTransformShift            = getTransformShift(channelType, uiLog2TrSize);
+  if ((pcCU->getTransformSkip(uiAbsPartIdx, compID) != 0) && pcCU->getSlice()->getSPS()->getUseExtendedPrecision())
+  {
+    iTransformShift = std::max<Int>(0, iTransformShift);
+  }
+
+  const Bool bUseGolombRiceParameterAdaptation = pcCU->getSlice()->getSPS()->getUseGolombRiceParameterAdaptation();
+  const UInt initialGolombRiceParameter        = m_pcEstBitsSbac->golombRiceAdaptationStatistics[rTu.getGolombRiceStatisticsIndex(compID)] / RExt__GOLOMB_RICE_INCREMENT_DIVISOR;
+        UInt uiGoRiceParam                     = initialGolombRiceParameter;
+  Double     d64BlockUncodedCost               = 0;
+  const UInt uiLog2BlockWidth                  = g_aucConvertToBit[ uiWidth  ] + 2;
+  const UInt uiLog2BlockHeight                 = g_aucConvertToBit[ uiHeight ] + 2;
+  const UInt uiMaxNumCoeff                     = uiWidth * uiHeight;
+  assert(compID<MAX_NUM_COMPONENT);
+
+  Int scalingListType = getScalingListType(pcCU->getPredictionMode(uiAbsPartIdx), compID);
+  assert(scalingListType < SCALING_LIST_NUM);
+
+#if ADAPTIVE_QP_SELECTION
+  memset(piArlDstCoeff, 0, sizeof(TCoeff) *  uiMaxNumCoeff);
+#endif
+
+  Double pdCostCoeff [ MAX_TU_SIZE * MAX_TU_SIZE ];
+  Double pdCostSig   [ MAX_TU_SIZE * MAX_TU_SIZE ];
+  Double pdCostCoeff0[ MAX_TU_SIZE * MAX_TU_SIZE ];
+  memset( pdCostCoeff, 0, sizeof(Double) *  uiMaxNumCoeff );
+  memset( pdCostSig,   0, sizeof(Double) *  uiMaxNumCoeff );
+  Int rateIncUp   [ MAX_TU_SIZE * MAX_TU_SIZE ];
+  Int rateIncDown [ MAX_TU_SIZE * MAX_TU_SIZE ];
+  Int sigRateDelta[ MAX_TU_SIZE * MAX_TU_SIZE ];
+  TCoeff deltaU   [ MAX_TU_SIZE * MAX_TU_SIZE ];
+  memset( rateIncUp,    0, sizeof(Int   ) *  uiMaxNumCoeff );
+  memset( rateIncDown,  0, sizeof(Int   ) *  uiMaxNumCoeff );
+  memset( sigRateDelta, 0, sizeof(Int   ) *  uiMaxNumCoeff );
+  memset( deltaU,       0, sizeof(TCoeff) *  uiMaxNumCoeff );
+
+  const Int iQBits = QUANT_SHIFT + cQP.per + iTransformShift;                   // Right shift of non-RDOQ quantizer;  level = (coeff*uiQ + offset)>>q_bits
+  const Double *const pdErrScale = getErrScaleCoeff(scalingListType, (uiLog2TrSize-2), cQP.rem);
+  const Int    *const piQCoef    = getQuantCoeff(scalingListType, cQP.rem, (uiLog2TrSize-2));
+
+  const Bool   enableScalingLists             = getUseScalingList(uiWidth, uiHeight, (pcCU->getTransformSkip(uiAbsPartIdx, compID) != 0));
+  const Int    defaultQuantisationCoefficient = g_quantScales[cQP.rem];
+  const Double defaultErrorScale              = getErrScaleCoeffNoScalingList(scalingListType, (uiLog2TrSize-2), cQP.rem);
+
+  const TCoeff entropyCodingMinimum = -(1 << g_maxTrDynamicRange[toChannelType(compID)]);
+  const TCoeff entropyCodingMaximum =  (1 << g_maxTrDynamicRange[toChannelType(compID)]) - 1;
+
+#if ADAPTIVE_QP_SELECTION
+  Int iQBitsC = iQBits - ARL_C_PRECISION;
+  Int iAddC =  1 << (iQBitsC-1);
+#endif
+
+  TUEntropyCodingParameters codingParameters;
+  getTUEntropyCodingParameters(codingParameters, rTu, compID);
+  const UInt uiCGSize = (1 << MLS_CG_SIZE);
+
+  Double pdCostCoeffGroupSig[ MLS_GRP_NUM ];
+  UInt uiSigCoeffGroupFlag[ MLS_GRP_NUM ];
+  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;
+
+  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;
+
+  const UInt significanceMapContextOffset = getSignificanceMapContextOffset(compID);
+
+  for (Int iCGScanPos = uiCGNum-1; iCGScanPos >= 0; iCGScanPos--)
+  {
+    UInt uiCGBlkPos = codingParameters.scanCG[ iCGScanPos ];
+    UInt uiCGPosY   = uiCGBlkPos / codingParameters.widthInGroups;
+    UInt uiCGPosX   = uiCGBlkPos - (uiCGPosY * codingParameters.widthInGroups);
+
+    memset( &rdStats, 0, sizeof (coeffGroupRDStats));
+
+    const Int patternSigCtx = TComTrQuant::calcPatternSigCtx(uiSigCoeffGroupFlag, uiCGPosX, uiCGPosY, codingParameters.widthInGroups, codingParameters.heightInGroups);
+
+    for (Int iScanPosinCG = uiCGSize-1; iScanPosinCG >= 0; iScanPosinCG--)
+    {
+      iScanPos = iCGScanPos*uiCGSize + iScanPosinCG;
+      //===== quantization =====
+      UInt    uiBlkPos          = codingParameters.scan[iScanPos];
+      // set coeff
+
+      const Int    quantisationCoefficient = (enableScalingLists) ? piQCoef   [uiBlkPos] : defaultQuantisationCoefficient;
+      const Double errorScale              = (enableScalingLists) ? pdErrScale[uiBlkPos] : defaultErrorScale;
+
+      const Int64  tmpLevel                = Int64(abs(plSrcCoeff[ uiBlkPos ])) * quantisationCoefficient;
+
+      const Intermediate_Int lLevelDouble  = (Intermediate_Int)min<Int64>(tmpLevel, MAX_INTERMEDIATE_INT - (Intermediate_Int(1) << (iQBits - 1)));
+
+#if ADAPTIVE_QP_SELECTION
+      if( m_bUseAdaptQpSelect )
+      {
+        piArlDstCoeff[uiBlkPos]   = (TCoeff)(( lLevelDouble + iAddC) >> iQBitsC );
+      }
+#endif
+      const UInt uiMaxAbsLevel  = std::min<UInt>(UInt(entropyCodingMaximum), UInt((lLevelDouble + (Intermediate_Int(1) << (iQBits - 1))) >> iQBits));
+
+      const Double dErr         = Double( lLevelDouble );
+      pdCostCoeff0[ iScanPos ]  = dErr * dErr * errorScale;
+      d64BlockUncodedCost      += pdCostCoeff0[ iScanPos ];
+      piDstCoeff[ uiBlkPos ]    = uiMaxAbsLevel;
+
+      if ( uiMaxAbsLevel > 0 && iLastScanPos < 0 )
+      {
+        iLastScanPos            = iScanPos;
+        uiCtxSet                = getContextSetIndex(compID, (iScanPos >> MLS_CG_SIZE), 0);
+        iCGLastScanPos          = iCGScanPos;
+      }
+
+      if ( iLastScanPos >= 0 )
+      {
+        //===== coefficient level estimation =====
+        UInt  uiLevel;
+        UInt  uiOneCtx         = (NUM_ONE_FLAG_CTX_PER_SET * uiCtxSet) + c1;
+        UInt  uiAbsCtx         = (NUM_ABS_FLAG_CTX_PER_SET * uiCtxSet) + c2;
+
+        if( iScanPos == iLastScanPos )
+        {
+          uiLevel              = xGetCodedLevel( pdCostCoeff[ iScanPos ], pdCostCoeff0[ iScanPos ], pdCostSig[ iScanPos ],
+                                                  lLevelDouble, uiMaxAbsLevel, significanceMapContextOffset, uiOneCtx, uiAbsCtx, uiGoRiceParam,
+                                                  c1Idx, c2Idx, iQBits, errorScale, 1, extendedPrecision, channelType
+                                                  );
+        }
+        else
+        {
+          UShort uiCtxSig      = significanceMapContextOffset + getSigCtxInc( patternSigCtx, codingParameters, iScanPos, uiLog2BlockWidth, uiLog2BlockHeight, channelType );
+
+          uiLevel              = xGetCodedLevel( pdCostCoeff[ iScanPos ], pdCostCoeff0[ iScanPos ], pdCostSig[ iScanPos ],
+                                                  lLevelDouble, uiMaxAbsLevel, uiCtxSig, uiOneCtx, uiAbsCtx, uiGoRiceParam,
+                                                  c1Idx, c2Idx, iQBits, errorScale, 0, extendedPrecision, channelType
+                                                  );
+
+          sigRateDelta[ uiBlkPos ] = m_pcEstBitsSbac->significantBits[ uiCtxSig ][ 1 ] - m_pcEstBitsSbac->significantBits[ uiCtxSig ][ 0 ];
+        }
+
+        deltaU[ uiBlkPos ]        = TCoeff((lLevelDouble - (Intermediate_Int(uiLevel) << iQBits)) >> (iQBits-8));
+
+        if( uiLevel > 0 )
+        {
+          Int rateNow = xGetICRate( uiLevel, uiOneCtx, uiAbsCtx, uiGoRiceParam, c1Idx, c2Idx, extendedPrecision, channelType );
+          rateIncUp   [ uiBlkPos ] = xGetICRate( uiLevel+1, uiOneCtx, uiAbsCtx, uiGoRiceParam, c1Idx, c2Idx, extendedPrecision, channelType ) - rateNow;
+          rateIncDown [ uiBlkPos ] = xGetICRate( uiLevel-1, uiOneCtx, uiAbsCtx, uiGoRiceParam, c1Idx, c2Idx, extendedPrecision, channelType ) - 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 = bUseGolombRiceParameterAdaptation ? (uiGoRiceParam + 1) : (std::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 % uiCGSize == 0 ) && ( iScanPos > 0 ) )
+        {
+          uiCtxSet          = getContextSetIndex(compID, ((iScanPos - 1) >> MLS_CG_SIZE), (c1 == 0)); //(iScanPos - 1) because we do this **before** entering the final group
+          c1                = 1;
+          c2                = 0;
+          c1Idx             = 0;
+          c2Idx             = 0;
+          uiGoRiceParam     = initialGolombRiceParameter;
+        }
+      }
+      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, codingParameters.widthInGroups, codingParameters.heightInGroups );
+          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, codingParameters.widthInGroups, codingParameters.heightInGroups );
+
+            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 = codingParameters.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 ) && isLuma(compID) && 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( rTu, channelType );
+    ui16CtxCbf  += getCBFContextOffset(compID);
+    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 = codingParameters.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     = codingParameters.scan[iScanPos];
+
+        if( piDstCoeff[ uiBlkPos ] )
+        {
+          UInt   uiPosY       = uiBlkPos >> uiLog2BlockWidth;
+          UInt   uiPosX       = uiBlkPos - ( uiPosY << uiLog2BlockWidth );
+
+          Double d64CostLast= codingParameters.scanType == SCAN_VER ? xGetRateLast( uiPosY, uiPosX, compID ) : xGetRateLast( uiPosX, uiPosY, compID );
+          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 = codingParameters.scan[ scanPos ];
+    TCoeff level = piDstCoeff[ blkPos ];
+    uiAbsSum += level;
+    piDstCoeff[ blkPos ] = ( plSrcCoeff[ blkPos ] < 0 ) ? -level : level;
+  }
+
+  //===== clean uncoded coefficients =====
+  for ( Int scanPos = iBestLastIdxP1; scanPos <= iLastScanPos; scanPos++ )
+  {
+    piDstCoeff[ codingParameters.scan[ scanPos ] ] = 0;
+  }
+
+
+  if( pcCU->getSlice()->getPPS()->getSignHideFlag() && uiAbsSum>=2)
+  {
+    const Double inverseQuantScale = Double(g_invQuantScales[cQP.rem]);
+    Int64 rdFactor = (Int64)(inverseQuantScale * inverseQuantScale * (1 << (2 * cQP.per))
+                             / m_dLambda / 16 / (1 << (2 * DISTORTION_PRECISION_ADJUSTMENT(g_bitDepth[channelType] - 8)))
+                             + 0.5);
+
+    Int lastCG = -1;
+    Int absSum = 0 ;
+    Int n ;
+
+    for( Int subSet = (uiWidth*uiHeight-1) >> MLS_CG_SIZE; subSet >= 0; subSet-- )
+    {
+      Int  subPos     = subSet << MLS_CG_SIZE;
+      Int  firstNZPosInCG=uiCGSize , lastNZPosInCG=-1 ;
+      absSum = 0 ;
+
+      for(n = uiCGSize-1; n >= 0; --n )
+      {
+        if( piDstCoeff[ codingParameters.scan[ n + subPos ]] )
+        {
+          lastNZPosInCG = n;
+          break;
+        }
+      }
+
+      for(n = 0; n <uiCGSize; n++ )
+      {
+        if( piDstCoeff[ codingParameters.scan[ n + subPos ]] )
+        {
+          firstNZPosInCG = n;
+          break;
+        }
+      }
+
+      for(n = firstNZPosInCG; n <=lastNZPosInCG; n++ )
+      {
+        absSum += Int(piDstCoeff[ codingParameters.scan[ n + subPos ]]);
+      }
+
+      if(lastNZPosInCG>=0 && lastCG==-1)
+      {
+        lastCG = 1;
+      }
+
+      if( lastNZPosInCG-firstNZPosInCG>=SBH_THRESHOLD )
+      {
+        UInt signbit = (piDstCoeff[codingParameters.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:uiCGSize-1) ; n >= 0; --n )
+          {
+            UInt uiBlkPos   = codingParameters.scan[ n + subPos ];
+            if(piDstCoeff[ uiBlkPos ] != 0 )
+            {
+              Int64 costUp   = rdFactor * ( - deltaU[uiBlkPos] ) + rateIncUp[uiBlkPos];
+              Int64 costDown = rdFactor * (   deltaU[uiBlkPos] ) + rateIncDown[uiBlkPos]
+                               -   ((abs(piDstCoeff[uiBlkPos]) == 1) ? sigRateDelta[uiBlkPos] : 0);
+
+              if(lastCG==1 && lastNZPosInCG==n && abs(piDstCoeff[uiBlkPos])==1)
+              {
+                costDown -= (4<<15);
+              }
+
+              if(costUp<costDown)
+              {
+                curCost = costUp;
+                curChange =  1;
+              }
+              else
+              {
+                curChange = -1;
+                if(n==firstNZPosInCG && abs(piDstCoeff[uiBlkPos])==1)
+                {
+                  curCost = MAX_INT64;
+                }
+                else
+                {
+                  curCost = costDown;
+                }
+              }
+            }
+            else
+            {
+              curCost = rdFactor * ( - (abs(deltaU[uiBlkPos])) ) + (1<<15) + rateIncUp[uiBlkPos] + sigRateDelta[uiBlkPos] ;
+              curChange = 1 ;
+
+              if(n<firstNZPosInCG)
+              {
+                UInt thissignbit = (plSrcCoeff[uiBlkPos]>=0?0:1);
+                if(thissignbit != signbit )
+                {
+                  curCost = MAX_INT64;
+                }
+              }
+            }
+
+            if( curCost<minCostInc)
+            {
+              minCostInc = curCost;
+              finalChange = curChange;
+              minPos = uiBlkPos;
+            }
+          }
+
+          if(piDstCoeff[minPos] == entropyCodingMaximum || piDstCoeff[minPos] == entropyCodingMinimum)
+          {
+            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 uiCGPosX column of current coefficient group
+ * \param uiCGPosY 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 uiCGPosX, UInt uiCGPosY, UInt widthInGroups, UInt heightInGroups )
+{
+  if ((widthInGroups <= 1) && (heightInGroups <= 1)) return 0;
+
+  const Bool rightAvailable = uiCGPosX < (widthInGroups  - 1);
+  const Bool belowAvailable = uiCGPosY < (heightInGroups - 1);
+
+  UInt sigRight = 0;
+  UInt sigLower = 0;
+
+  if (rightAvailable) sigRight = ((sigCoeffGroupFlag[ (uiCGPosY * widthInGroups) + uiCGPosX + 1 ] != 0) ? 1 : 0);
+  if (belowAvailable) sigLower = ((sigCoeffGroupFlag[ (uiCGPosY + 1) * widthInGroups + uiCGPosX ] != 0) ? 1 : 0);
+
+  return sigRight + (sigLower << 1);
+}
+
+
+/** Context derivation process of coeff_abs_significant_flag
+ * \param patternSigCtx pattern for current coefficient group
+ * \param codingParameters coding parmeters for the TU (includes the scan)
+ * \param scanPosition current position in scan order
+ * \param log2BlockWidth log2 width of the block
+ * \param log2BlockHeight log2 height of the block
+ * \param ChannelType channel type (CHANNEL_TYPE_LUMA/CHROMA)
+ * \returns ctxInc for current scan position
+ */
+Int TComTrQuant::getSigCtxInc    (       Int                        patternSigCtx,
+                                   const TUEntropyCodingParameters &codingParameters,
+                                   const Int                        scanPosition,
+                                   const Int                        log2BlockWidth,
+                                   const Int                        log2BlockHeight,
+                                   const ChannelType                chanType)
+{
+  if (codingParameters.firstSignificanceMapContext == significanceMapContextSetStart[chanType][CONTEXT_TYPE_SINGLE])
+  {
+    //single context mode
+    return significanceMapContextSetStart[chanType][CONTEXT_TYPE_SINGLE];
+  }
+
+  const UInt rasterPosition = codingParameters.scan[scanPosition];
+  const UInt posY           = rasterPosition >> log2BlockWidth;
+  const UInt posX           = rasterPosition - (posY << log2BlockWidth);
+
+  if ((posX + posY) == 0) return 0; //special case for the DC context variable
+
+  Int offset = MAX_INT;
+
+  if ((log2BlockWidth == 2) && (log2BlockHeight == 2)) //4x4
+  {
+    offset = ctxIndMap4x4[ (4 * posY) + posX ];
+  }
+  else
+  {
+    Int cnt = 0;
+
+    switch (patternSigCtx)
+    {
+      //------------------
+
+      case 0: //neither neighbouring group is significant
+        {
+          const Int posXinSubset     = posX & ((1 << MLS_CG_LOG2_WIDTH)  - 1);
+          const Int posYinSubset     = posY & ((1 << MLS_CG_LOG2_HEIGHT) - 1);
+          const Int posTotalInSubset = posXinSubset + posYinSubset;
+
+          //first N coefficients in scan order use 2; the next few use 1; the rest use 0.
+          const UInt context1Threshold = NEIGHBOURHOOD_00_CONTEXT_1_THRESHOLD_4x4;
+          const UInt context2Threshold = NEIGHBOURHOOD_00_CONTEXT_2_THRESHOLD_4x4;
+
+          cnt = (posTotalInSubset >= context1Threshold) ? 0 : ((posTotalInSubset >= context2Threshold) ? 1 : 2);
+        }
+        break;
+
+      //------------------
+
+      case 1: //right group is significant, below is not
+        {
+          const Int posYinSubset = posY & ((1 << MLS_CG_LOG2_HEIGHT) - 1);
+          const Int groupHeight  = 1 << MLS_CG_LOG2_HEIGHT;
+
+          cnt = (posYinSubset >= (groupHeight >> 1)) ? 0 : ((posYinSubset >= (groupHeight >> 2)) ? 1 : 2); //top quarter uses 2; second-from-top quarter uses 1; bottom half uses 0
+        }
+        break;
+
+      //------------------
+
+      case 2: //below group is significant, right is not
+        {
+          const Int posXinSubset = posX & ((1 << MLS_CG_LOG2_WIDTH)  - 1);
+          const Int groupWidth   = 1 << MLS_CG_LOG2_WIDTH;
+
+          cnt = (posXinSubset >= (groupWidth >> 1)) ? 0 : ((posXinSubset >= (groupWidth >> 2)) ? 1 : 2); //left quarter uses 2; second-from-left quarter uses 1; right half uses 0
+        }
+        break;
+
+      //------------------
+
+      case 3: //both neighbouring groups are significant
+        {
+          cnt = 2;
+        }
+        break;
+
+      //------------------
+
+      default:
+        std::cerr << "ERROR: Invalid patternSigCtx \"" << Int(patternSigCtx) << "\" in getSigCtxInc" << std::endl;
+        exit(1);
+        break;
+    }
+
+    //------------------------------------------------
+
+    const Bool notFirstGroup = ((posX >> MLS_CG_LOG2_WIDTH) + (posY >> MLS_CG_LOG2_HEIGHT)) > 0;
+
+    offset = (notFirstGroup ? notFirstGroupNeighbourhoodContextOffset[chanType] : 0) + cnt;
+  }
+
+  return codingParameters.firstSignificanceMapContext + offset;
+}
+
+
+/** 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,
+                                            Intermediate_Int lLevelDouble,
+                                            UInt             uiMaxAbsLevel,
+                                            UShort           ui16CtxNumSig,
+                                            UShort           ui16CtxNumOne,
+                                            UShort           ui16CtxNumAbs,
+                                            UShort           ui16AbsGoRice,
+                                            UInt             c1Idx,
+                                            UInt             c2Idx,
+                                            Int              iQBits,
+                                            Double           errorScale,
+                                            Bool             bLast,
+                                            Bool             useLimitedPrefixLength,
+                                            ChannelType      channelType
+                                            ) 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  - ( Intermediate_Int(uiAbsLevel) << iQBits ) );
+    Double dCurrCost    = dErr * dErr * errorScale + xGetICost( xGetICRate( uiAbsLevel, ui16CtxNumOne, ui16CtxNumAbs, ui16AbsGoRice, c1Idx, c2Idx, useLimitedPrefixLength, channelType ) );
+    dCurrCost          += dCurrCostSig;
+
+    if( dCurrCost < rd64CodedCost )
+    {
+      uiBestAbsLevel    = uiAbsLevel;
+      rd64CodedCost     = dCurrCost;
+      rd64CodedCostSig  = dCurrCostSig;
+    }
+  }
+
+  return uiBestAbsLevel;
+}
+
+/** Calculates the cost for specific absolute transform level
+ * \param uiAbsLevel scaled quantized level
+ * \param ui16CtxNumOne current ctxInc for coeff_abs_level_greater1 (1st bin of coeff_abs_level_minus1 in AVC)
+ * \param ui16CtxNumAbs current ctxInc for coeff_abs_level_greater2 (remaining bins of coeff_abs_level_minus1 in AVC)
+ * \param ui16AbsGoRice Rice parameter for coeff_abs_level_minus3
+ * \returns cost of given absolute transform level
+ */
+__inline Int TComTrQuant::xGetICRate         ( UInt                            uiAbsLevel,
+                                               UShort                          ui16CtxNumOne,
+                                               UShort                          ui16CtxNumAbs,
+                                               UShort                          ui16AbsGoRice,
+                                               UInt                            c1Idx,
+                                               UInt                            c2Idx,
+                                               Bool                            useLimitedPrefixLength,
+                                               ChannelType                     channelType
+                                               ) const
+{
+  Int  iRate      = Int(xGetIEPRate()); // cost of sign bit
+  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 if (useLimitedPrefixLength)
+    {
+      const UInt maximumPrefixLength = (32 - (COEF_REMAIN_BIN_REDUCTION + g_maxTrDynamicRange[channelType]));
+
+      UInt prefixLength = 0;
+      UInt suffix       = (symbol >> ui16AbsGoRice) - COEF_REMAIN_BIN_REDUCTION;
+
+      while ((prefixLength < maximumPrefixLength) && (suffix > ((2 << prefixLength) - 2)))
+      {
+        prefixLength++;
+      }
+
+      const UInt suffixLength = (prefixLength == maximumPrefixLength) ? (g_maxTrDynamicRange[channelType] - ui16AbsGoRice) : (prefixLength + 1/*separator*/);
+
+      iRate += (COEF_REMAIN_BIN_REDUCTION + prefixLength + suffixLength + ui16AbsGoRice) << 15;
+    }
+    else
+    {
+      length = ui16AbsGoRice;
+      symbol  = symbol - ( COEF_REMAIN_BIN_REDUCTION << ui16AbsGoRice);
+      while (symbol >= (1<<length))
+      {
+        symbol -=  (1<<(length++));
+      }
+      iRate += (COEF_REMAIN_BIN_REDUCTION+length+1-ui16AbsGoRice+length)<< 15;
+    }
+
+    if (c1Idx < C1FLAG_NUMBER)
+    {
+      iRate += m_pcEstBitsSbac->m_greaterOneBits[ ui16CtxNumOne ][ 1 ];
+
+      if (c2Idx < C2FLAG_NUMBER)
+      {
+        iRate += m_pcEstBitsSbac->m_levelAbsBits[ ui16CtxNumAbs ][ 1 ];
+      }
+    }
+  }
+  else if( uiAbsLevel == 1 )
+  {
+    iRate += m_pcEstBitsSbac->m_greaterOneBits[ ui16CtxNumOne ][ 0 ];
+  }
+  else if( uiAbsLevel == 2 )
+  {
+    iRate += m_pcEstBitsSbac->m_greaterOneBits[ ui16CtxNumOne ][ 1 ];
+    iRate += m_pcEstBitsSbac->m_levelAbsBits[ ui16CtxNumAbs ][ 0 ];
+  }
+  else
+  {
+    iRate = 0;
+  }
+
+  return  iRate;
+}
+
+__inline Double TComTrQuant::xGetRateSigCoeffGroup  ( UShort                    uiSignificanceCoeffGroup,
+                                                UShort                          ui16CtxNumSig ) const
+{
+  return xGetICost( m_pcEstBitsSbac->significantCoeffGroupBits[ ui16CtxNumSig ][ uiSignificanceCoeffGroup ] );
+}
+
+/** Calculates the cost of signaling the last significant coefficient in the block
+ * \param uiPosX X coordinate of the last significant coefficient
+ * \param uiPosY Y coordinate of the last significant coefficient
+ * \returns cost of last significant coefficient
+ */
+/*
+ * \param uiWidth width of the transform unit (TU)
+*/
+__inline Double TComTrQuant::xGetRateLast   ( const UInt                      uiPosX,
+                                              const UInt                      uiPosY,
+                                              const ComponentID               component  ) const
+{
+  UInt uiCtxX   = g_uiGroupIdx[uiPosX];
+  UInt uiCtxY   = g_uiGroupIdx[uiPosY];
+
+  Double uiCost = m_pcEstBitsSbac->lastXBits[toChannelType(component)][ uiCtxX ] + m_pcEstBitsSbac->lastYBits[toChannelType(component)][ 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,
+                                           const UInt   widthInGroups,
+                                           const UInt   heightInGroups)
+{
+  UInt sigRight = 0;
+  UInt sigLower = 0;
+
+  if (uiCGPosX < (widthInGroups  - 1)) sigRight = ((uiSigCoeffGroupFlag[ (uiCGPosY * widthInGroups) + uiCGPosX + 1 ] != 0) ? 1 : 0);
+  if (uiCGPosY < (heightInGroups - 1)) sigLower = ((uiSigCoeffGroupFlag[ (uiCGPosY + 1) * widthInGroups + uiCGPosX ] != 0) ? 1 : 0);
+
+  return ((sigRight + sigLower) != 0) ? 1 : 0;
+}
+
+
+/** set quantized matrix coefficient for encode
+ * \param scalingList quantaized matrix address
+ */
+Void TComTrQuant::setScalingList(TComScalingList *scalingList, const ChromaFormat format)
+{
+  const Int minimumQp = 0;
+  const Int maximumQp = SCALING_LIST_REM_NUM;
+
+  for(UInt size = 0; size < SCALING_LIST_SIZE_NUM; size++)
+  {
+    for(UInt list = 0; list < SCALING_LIST_NUM; list++)
+    {
+      for(Int qp = minimumQp; qp < maximumQp; qp++)
+      {
+        xSetScalingListEnc(scalingList,list,size,qp,format);
+        xSetScalingListDec(scalingList,list,size,qp,format);
+        setErrScaleCoeff(list,size,qp);
+      }
+    }
+  }
+}
+/** set quantized matrix coefficient for decode
+ * \param scalingList quantaized matrix address
+ */
+Void TComTrQuant::setScalingListDec(TComScalingList *scalingList, const ChromaFormat format)
+{
+  const Int minimumQp = 0;
+  const Int maximumQp = SCALING_LIST_REM_NUM;
+
+  for(UInt size = 0; size < SCALING_LIST_SIZE_NUM; size++)
+  {
+    for(UInt list = 0; list < SCALING_LIST_NUM; list++)
+    {
+      for(Int qp = minimumQp; qp < maximumQp; qp++)
+      {
+        xSetScalingListDec(scalingList,list,size,qp,format);
+      }
+    }
+  }
+}
+/** set error scale coefficients
+ * \param list List ID
+ * \param uiSize Size
+ * \param uiQP Quantization parameter
+ */
+Void TComTrQuant::setErrScaleCoeff(UInt list, UInt size, Int qp)
+{
+  const UInt uiLog2TrSize = g_aucConvertToBit[ g_scalingListSizeX[size] ] + 2;
+  const ChannelType channelType = ((list == 0) || (list == MAX_NUM_COMPONENT)) ? CHANNEL_TYPE_LUMA : CHANNEL_TYPE_CHROMA;
+
+  const Int iTransformShift = getTransformShift(channelType, 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 * (g_bitDepth[channelType] - 8)));
+  }
+
+  getErrScaleCoeffNoScalingList(list, size, qp) = dErrScale / g_quantScales[qp] / g_quantScales[qp] / (1 << DISTORTION_PRECISION_ADJUSTMENT(2 * (g_bitDepth[channelType] - 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, Int qp, const ChromaFormat format)
+{
+  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);
+
+  Int quantScales = g_quantScales[qp];
+
+  processScalingListEnc(coeff,
+                        quantcoeff,
+                        (quantScales << LOG2_SCALING_LIST_NEUTRAL_VALUE),
+                        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, Int qp, const ChromaFormat format)
+{
+  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);
+
+  Int invQuantScale = g_invQuantScales[qp];
+
+  processScalingListDec(coeff,
+                        dequantcoeff,
+                        invQuantScale,
+                        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(const ChromaFormat format)
+{
+  const Int minimumQp = 0;
+  const Int maximumQp = SCALING_LIST_REM_NUM;
+
+  for(UInt size = 0; size < SCALING_LIST_SIZE_NUM; size++)
+  {
+    for(UInt list = 0; list < SCALING_LIST_NUM; list++)
+    {
+      for(Int qp = minimumQp; qp < maximumQp; qp++)
+      {
+        xsetFlatScalingList(list,size,qp,format);
+        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, Int qp, const ChromaFormat format)
+{
+  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)
+{
+  for(UInt j=0;j<height;j++)
+  {
+    for(UInt i=0;i<width;i++)
+    {
+      quantcoeff[j*width + i] = quantScales / coeff[sizuNum * (j / ratio) + i / 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 qp = 0; qp < SCALING_LIST_REM_NUM; qp++)
+    {
+      for(UInt listId = 0; listId < SCALING_LIST_NUM; listId++)
+      {
+        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]];
+      } // listID loop
+    }
+  }
+}
+
+/** destroy quantization matrix array
+ */
+Void TComTrQuant::destroyScalingList()
+{
+  for(UInt sizeId = 0; sizeId < SCALING_LIST_SIZE_NUM; sizeId++)
+  {
+    for(UInt listId = 0; listId < SCALING_LIST_NUM; 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];
+      }
+    }
+  }
+}
+
+Void TComTrQuant::transformSkipQuantOneSample(TComTU &rTu, const ComponentID compID, const Pel resiDiff, TCoeff* pcCoeff, const UInt uiPos, const QpParam &cQP, const Bool bUseHalfRoundingPoint)
+{
+        TComDataCU    *pcCU                           = rTu.getCU();
+  const UInt           uiAbsPartIdx                   = rTu.GetAbsPartIdxTU();
+  const TComRectangle &rect                           = rTu.getRect(compID);
+  const UInt           uiWidth                        = rect.width;
+  const UInt           uiHeight                       = rect.height;
+  const Int            iTransformShift                = getTransformShift(toChannelType(compID), rTu.GetEquivalentLog2TrSize(compID));
+  const Int            scalingListType                = getScalingListType(pcCU->getPredictionMode(uiAbsPartIdx), compID);
+  const Bool           enableScalingLists             = getUseScalingList(uiWidth, uiHeight, true);
+  const Int            defaultQuantisationCoefficient = g_quantScales[cQP.rem];
+
+  assert( scalingListType < SCALING_LIST_NUM );
+  const Int *const piQuantCoeff = getQuantCoeff( scalingListType, cQP.rem, (rTu.GetEquivalentLog2TrSize(compID)-2) );
+
+
+  /* for 422 chroma blocks, the effective scaling applied during transformation is not a power of 2, hence it cannot be
+  * implemented as a bit-shift (the quantised result will be sqrt(2) * larger than required). Alternatively, adjust the
+  * uiLog2TrSize applied in iTransformShift, such that the result is 1/sqrt(2) the required result (i.e. smaller)
+  * Then a QP+3 (sqrt(2)) or QP-3 (1/sqrt(2)) method could be used to get the required result
+  */
+
+  const Int iQBits = QUANT_SHIFT + cQP.per + iTransformShift;
+  // QBits will be OK for any internal bit depth as the reduction in transform shift is balanced by an increase in Qp_per due to QpBDOffset
+
+  const Int iAdd = ( bUseHalfRoundingPoint ? 256 : (pcCU->getSlice()->getSliceType() == I_SLICE ? 171 : 85) ) << (iQBits - 9);
+
+  TCoeff transformedCoefficient;
+
+  // transform-skip
+  if (iTransformShift >= 0)
+  {
+    transformedCoefficient = resiDiff << iTransformShift;
+  }
+  else // for very high bit depths
+  {
+    const Int iTrShiftNeg  = -iTransformShift;
+    const Int offset       = 1 << (iTrShiftNeg - 1);
+    transformedCoefficient = ( resiDiff + offset ) >> iTrShiftNeg;
+  }
+
+  // quantization
+  const TCoeff iSign = (transformedCoefficient < 0 ? -1: 1);
+
+  const Int quantisationCoefficient = enableScalingLists ? piQuantCoeff[uiPos] : defaultQuantisationCoefficient;
+
+  const Int64 tmpLevel = (Int64)abs(transformedCoefficient) * quantisationCoefficient;
+
+  const TCoeff quantisedCoefficient = (TCoeff((tmpLevel + iAdd ) >> iQBits)) * iSign;
+
+  const TCoeff entropyCodingMinimum = -(1 << g_maxTrDynamicRange[toChannelType(compID)]);
+  const TCoeff entropyCodingMaximum =  (1 << g_maxTrDynamicRange[toChannelType(compID)]) - 1;
+  pcCoeff[ uiPos ] = Clip3<TCoeff>( entropyCodingMinimum, entropyCodingMaximum, quantisedCoefficient );
+}
+
+
+Void TComTrQuant::invTrSkipDeQuantOneSample( TComTU &rTu, ComponentID compID, TCoeff inSample, Pel &reconSample, const QpParam &cQP, UInt uiPos )
+{
+        TComDataCU    *pcCU               = rTu.getCU();
+  const UInt           uiAbsPartIdx       = rTu.GetAbsPartIdxTU();
+  const TComRectangle &rect               = rTu.getRect(compID);
+  const UInt           uiWidth            = rect.width;
+  const UInt           uiHeight           = rect.height;
+  const Int            QP_per             = cQP.per;
+  const Int            QP_rem             = cQP.rem;
+  const Int            iTransformShift    = getTransformShift(toChannelType(compID), rTu.GetEquivalentLog2TrSize(compID));
+  const Int            scalingListType    = getScalingListType(pcCU->getPredictionMode(uiAbsPartIdx), compID);
+  const Bool           enableScalingLists = getUseScalingList(uiWidth, uiHeight, true);
+  const UInt           uiLog2TrSize       = rTu.GetEquivalentLog2TrSize(compID);
+
+  assert( scalingListType < SCALING_LIST_NUM );
+
+  const Int rightShift = (IQUANT_SHIFT - (iTransformShift + QP_per)) + (enableScalingLists ? LOG2_SCALING_LIST_NEUTRAL_VALUE : 0);
+
+  const TCoeff transformMinimum = -(1 << g_maxTrDynamicRange[toChannelType(compID)]);
+  const TCoeff transformMaximum =  (1 << g_maxTrDynamicRange[toChannelType(compID)]) - 1;
+
+  // Dequantisation
+
+  TCoeff dequantisedSample;
+
+  if(enableScalingLists)
+  {
+    const UInt             dequantCoefBits     = 1 + IQUANT_SHIFT + SCALING_LIST_BITS;
+    const UInt             targetInputBitDepth = std::min<UInt>((g_maxTrDynamicRange[toChannelType(compID)] + 1), (((sizeof(Intermediate_Int) * 8) + rightShift) - dequantCoefBits));
+
+    const Intermediate_Int inputMinimum        = -(1 << (targetInputBitDepth - 1));
+    const Intermediate_Int inputMaximum        =  (1 << (targetInputBitDepth - 1)) - 1;
+
+    Int *piDequantCoef = getDequantCoeff(scalingListType,QP_rem,uiLog2TrSize-2);
+
+    if(rightShift > 0)
+    {
+      const Intermediate_Int iAdd      = 1 << (rightShift - 1);
+      const TCoeff           clipQCoef = TCoeff(Clip3<Intermediate_Int>(inputMinimum, inputMaximum, inSample));
+      const Intermediate_Int iCoeffQ   = ((Intermediate_Int(clipQCoef) * piDequantCoef[uiPos]) + iAdd ) >> rightShift;
+
+      dequantisedSample = TCoeff(Clip3<Intermediate_Int>(transformMinimum,transformMaximum,iCoeffQ));
+    }
+    else
+    {
+      const Int              leftShift = -rightShift;
+      const TCoeff           clipQCoef = TCoeff(Clip3<Intermediate_Int>(inputMinimum, inputMaximum, inSample));
+      const Intermediate_Int iCoeffQ   = (Intermediate_Int(clipQCoef) * piDequantCoef[uiPos]) << leftShift;
+
+      dequantisedSample = TCoeff(Clip3<Intermediate_Int>(transformMinimum,transformMaximum,iCoeffQ));
+    }
+  }
+  else
+  {
+    const Int scale     =  g_invQuantScales[QP_rem];
+    const Int scaleBits =     (IQUANT_SHIFT + 1)   ;
+
+    const UInt             targetInputBitDepth = std::min<UInt>((g_maxTrDynamicRange[toChannelType(compID)] + 1), (((sizeof(Intermediate_Int) * 8) + rightShift) - scaleBits));
+    const Intermediate_Int inputMinimum        = -(1 << (targetInputBitDepth - 1));
+    const Intermediate_Int inputMaximum        =  (1 << (targetInputBitDepth - 1)) - 1;
+
+    if (rightShift > 0)
+    {
+      const Intermediate_Int iAdd      = 1 << (rightShift - 1);
+      const TCoeff           clipQCoef = TCoeff(Clip3<Intermediate_Int>(inputMinimum, inputMaximum, inSample));
+      const Intermediate_Int iCoeffQ   = (Intermediate_Int(clipQCoef) * scale + iAdd) >> rightShift;
+
+      dequantisedSample = TCoeff(Clip3<Intermediate_Int>(transformMinimum,transformMaximum,iCoeffQ));
+    }
+    else
+    {
+      const Int              leftShift = -rightShift;
+      const TCoeff           clipQCoef = TCoeff(Clip3<Intermediate_Int>(inputMinimum, inputMaximum, inSample));
+      const Intermediate_Int iCoeffQ   = (Intermediate_Int(clipQCoef) * scale) << leftShift;
+
+      dequantisedSample = TCoeff(Clip3<Intermediate_Int>(transformMinimum,transformMaximum,iCoeffQ));
+    }
+  }
+
+  // Inverse transform-skip
+
+  if (iTransformShift >= 0)
+  {
+    const TCoeff offset = iTransformShift==0 ? 0 : (1 << (iTransformShift - 1));
+    reconSample =  Pel(( dequantisedSample + offset ) >> iTransformShift);
+  }
+  else //for very high bit depths
+  {
+    const Int iTrShiftNeg = -iTransformShift;
+    reconSample = Pel(dequantisedSample << iTrShiftNeg);
+  }
+}
+
+
+Void TComTrQuant::crossComponentPrediction(       TComTU      & rTu,
+                                            const ComponentID   compID,
+                                            const Pel         * piResiL,
+                                            const Pel         * piResiC,
+                                                  Pel         * piResiT,
+                                            const Int           width,
+                                            const Int           height,
+                                            const Int           strideL,
+                                            const Int           strideC,
+                                            const Int           strideT,
+                                            const Bool          reverse )
+{
+  const Pel *pResiL = piResiL;
+  const Pel *pResiC = piResiC;
+        Pel *pResiT = piResiT;
+
+  TComDataCU *pCU = rTu.getCU();
+  const Char alpha = pCU->getCrossComponentPredictionAlpha( rTu.GetAbsPartIdxTU( compID ), compID );
+  const Int diffBitDepth = pCU->getSlice()->getSPS()->getDifferentialLumaChromaBitDepth();
+
+  for( Int y = 0; y < height; y++ )
+  {
+    if (reverse)
+    {
+      for( Int x = 0; x < width; x++ )
+      {
+        pResiT[x] = pResiC[x] + (( alpha * rightShift( pResiL[x], diffBitDepth) ) >> 3);
+      }
+    }
+    else
+    {
+      for( Int x = 0; x < width; x++ )
+      {
+        pResiT[x] = pResiC[x] - (( alpha * rightShift(pResiL[x], diffBitDepth) ) >> 3);
+      }
+    }
+
+    pResiL += strideL;
+    pResiC += strideC;
+    pResiT += strideT;
+  }
+}
+
+//! \}
Index: /tags/SHM-9.0/source/Lib/TLibCommon/TComTrQuant.h
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibCommon/TComTrQuant.h	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibCommon/TComTrQuant.h	(revision 1088)
@@ -0,0 +1,328 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TComTrQuant.h
+    \brief    transform and quantization class (header)
+*/
+
+#ifndef __TCOMTRQUANT__
+#define __TCOMTRQUANT__
+
+#include "CommonDef.h"
+#include "TComYuv.h"
+#include "TComDataCU.h"
+#include "TComChromaFormat.h"
+#include "ContextTables.h"
+
+//! \ingroup TLibCommon
+//! \{
+
+// ====================================================================================================================
+// Constants
+// ====================================================================================================================
+
+#define QP_BITS                 15
+
+// ====================================================================================================================
+// Type definition
+// ====================================================================================================================
+
+typedef struct
+{
+  Int significantCoeffGroupBits[NUM_SIG_CG_FLAG_CTX][2 /*Flag = [0|1]*/];
+  Int significantBits[NUM_SIG_FLAG_CTX][2 /*Flag = [0|1]*/];
+  Int lastXBits[MAX_NUM_CHANNEL_TYPE][LAST_SIGNIFICANT_GROUPS];
+  Int lastYBits[MAX_NUM_CHANNEL_TYPE][LAST_SIGNIFICANT_GROUPS];
+  Int m_greaterOneBits[NUM_ONE_FLAG_CTX][2 /*Flag = [0|1]*/];
+  Int m_levelAbsBits[NUM_ABS_FLAG_CTX][2 /*Flag = [0|1]*/];
+
+  Int blockCbpBits[NUM_QT_CBF_CTX_SETS * NUM_QT_CBF_CTX_PER_SET][2 /*Flag = [0|1]*/];
+  Int blockRootCbpBits[4][2 /*Flag = [0|1]*/];
+
+  Int golombRiceAdaptationStatistics[RExt__GOLOMB_RICE_ADAPTATION_STATISTICS_SETS];
+} estBitsSbacStruct;
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// QP struct
+struct QpParam
+{
+  Int Qp;
+  Int per;
+  Int rem;
+
+  QpParam(const Int           qpy,
+          const ChannelType   chType,
+          const Int           qpBdOffset,
+          const Int           chromaQPOffset,
+          const ChromaFormat  chFmt );
+
+  QpParam(const TComDataCU   &cu, const ComponentID compID);
+
+}; // END STRUCT 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(       TComTU         & rTu,
+                     const ComponentID      compID,
+                           Pel           *  pcResidual,
+                     const UInt             uiStride,
+                           TCoeff        *  rpcCoeff,
+#if ADAPTIVE_QP_SELECTION
+                           TCoeff        * rpcArlCoeff,
+#endif
+                           TCoeff         & uiAbsSum,
+                     const QpParam        & cQP
+                    );
+
+
+  Void invTransformNxN(      TComTU       & rTu,
+                       const ComponentID    compID,
+                             Pel         *pcResidual,
+                       const UInt           uiStride,
+                             TCoeff      *  pcCoeff,
+                       const QpParam      & cQP
+                             DEBUG_STRING_FN_DECLAREP(psDebug));
+
+  Void invRecurTransformNxN ( const ComponentID compID, TComYuv *pResidual, TComTU &rTu );
+
+  Void rdpcmNxN   ( TComTU& rTu, const ComponentID compID, Pel* pcResidual, const UInt uiStride, const QpParam& cQP, TCoeff* pcCoeff, TCoeff &uiAbsSum, RDPCMMode& rdpcmMode );
+  Void invRdpcmNxN( TComTU& rTu, const ComponentID compID, Pel* pcResidual, const UInt uiStride );
+
+  Void applyForwardRDPCM( TComTU& rTu, const ComponentID compID, Pel* pcResidual, const UInt uiStride, const QpParam& cQP, TCoeff* pcCoeff, TCoeff &uiAbsSum, const RDPCMMode mode );
+
+  // Misc functions
+
+#if RDOQ_CHROMA_LAMBDA
+  Void setLambdas(const Double lambdas[MAX_NUM_COMPONENT]) { for (UInt component = 0; component < MAX_NUM_COMPONENT; component++) m_lambdas[component] = lambdas[component]; }
+  Void selectLambda(const ComponentID compIdx) { m_dLambda = m_lambdas[compIdx]; }
+#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 uiCGPosX, UInt uiCGPosY, UInt widthInGroups, UInt heightInGroups );
+
+  static Int      getSigCtxInc     ( Int                              patternSigCtx,
+                                     const TUEntropyCodingParameters &codingParameters,
+                                     const Int                        scanPosition,
+                                     const Int                        log2BlockWidth,
+                                     const Int                        log2BlockHeight,
+                                     const ChannelType                chanType
+                                    );
+
+  static UInt getSigCoeffGroupCtxInc  (const UInt*  uiSigCoeffGroupFlag,
+                                       const UInt   uiCGPosX,
+                                       const UInt   uiCGPosY,
+                                       const UInt   widthInGroups,
+                                       const UInt   heightInGroups);
+
+  Void initScalingList                      ();
+  Void destroyScalingList                   ();
+  Void setErrScaleCoeff    ( UInt list, UInt size, Int qp );
+  Double* getErrScaleCoeff              ( UInt list, UInt size, Int qp ) { return m_errScale             [size][list][qp]; };  //!< get Error Scale Coefficent
+  Double& getErrScaleCoeffNoScalingList ( UInt list, UInt size, Int qp ) { return m_errScaleNoScalingList[size][list][qp]; };  //!< get Error Scale Coefficent
+  Int* getQuantCoeff                    ( UInt list, Int qp, UInt size ) { return m_quantCoef            [size][list][qp]; };  //!< get Quant Coefficent
+  Int* getDequantCoeff                  ( UInt list, Int qp, UInt size ) { return m_dequantCoef          [size][list][qp]; };  //!< get DeQuant Coefficent
+  Void setUseScalingList   ( Bool bUseScalingList){ m_scalingListEnabledFlag = bUseScalingList; };
+  Bool getUseScalingList   (const UInt width, const UInt height, const Bool isTransformSkip){ return m_scalingListEnabledFlag && (!isTransformSkip || ((width == 4) && (height == 4))); };
+  Void setFlatScalingList  (const ChromaFormat format);
+  Void xsetFlatScalingList ( UInt list, UInt size, Int qp, const ChromaFormat format);
+  Void xSetScalingListEnc  ( TComScalingList *scalingList, UInt list, UInt size, Int qp, const ChromaFormat format);
+  Void xSetScalingListDec  ( TComScalingList *scalingList, UInt list, UInt size, Int qp, const ChromaFormat format);
+  Void setScalingList      ( TComScalingList *scalingList, const ChromaFormat format);
+  Void setScalingListDec   ( TComScalingList *scalingList, const ChromaFormat format);
+  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
+  Void transformSkipQuantOneSample(TComTU &rTu, const ComponentID compID, const Pel resiDiff, TCoeff* pcCoeff, const UInt uiPos, const QpParam &cQP, const Bool bUseHalfRoundingPoint);
+  Void invTrSkipDeQuantOneSample(TComTU &rTu, ComponentID compID, TCoeff pcCoeff, Pel &reconSample, const QpParam &cQP, UInt uiPos );
+
+protected:
+#if ADAPTIVE_QP_SELECTION
+  Int     m_qpDelta[MAX_QP+1];
+  Int     m_sliceNsamples[LEVEL_RANGE+1];
+  Double  m_sliceSumC[LEVEL_RANGE+1] ;
+#endif
+  TCoeff* m_plTempCoeff;
+
+//  QpParam  m_cQP; - removed - placed on the stack.
+#if RDOQ_CHROMA_LAMBDA
+  Double   m_lambdas[MAX_NUM_COMPONENT];
+#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
+  Double    m_errScaleNoScalingList[SCALING_LIST_SIZE_NUM][SCALING_LIST_NUM][SCALING_LIST_REM_NUM]; ///< array of quantization matrix coefficient 4x4
+
+private:
+  // forward Transform
+  Void xT   ( const ComponentID compID, Bool useDST, Pel* piBlkResi, UInt uiStride, TCoeff* psCoeff, Int iWidth, Int iHeight );
+
+  // skipping Transform
+  Void xTransformSkip ( Pel* piBlkResi, UInt uiStride, TCoeff* psCoeff, TComTU &rTu, const ComponentID component );
+
+  Void signBitHidingHDQ( const ComponentID compID, TCoeff* pQCoef, TCoeff* pCoef, TCoeff* deltaU, const TUEntropyCodingParameters &codingParameters );
+
+  // quantization
+  Void xQuant(       TComTU       &rTu,
+                     TCoeff      * pSrc,
+                     TCoeff      * pDes,
+#if ADAPTIVE_QP_SELECTION
+                     TCoeff      *pArlDes,
+#endif
+                     TCoeff       &uiAbsSum,
+               const ComponentID   compID,
+               const QpParam      &cQP );
+
+  // RDOQ functions
+
+  Void           xRateDistOptQuant (       TComTU       &rTu,
+                                           TCoeff      * plSrcCoeff,
+                                           TCoeff      * piDstCoeff,
+#if ADAPTIVE_QP_SELECTION
+                                           TCoeff      *piArlDstCoeff,
+#endif
+                                           TCoeff       &uiAbsSum,
+                                     const ComponentID   compID,
+                                     const QpParam      &cQP );
+
+__inline UInt              xGetCodedLevel  ( Double&          rd64CodedCost,
+                                             Double&          rd64CodedCost0,
+                                             Double&          rd64CodedCostSig,
+                                             Intermediate_Int lLevelDouble,
+                                             UInt             uiMaxAbsLevel,
+                                             UShort           ui16CtxNumSig,
+                                             UShort           ui16CtxNumOne,
+                                             UShort           ui16CtxNumAbs,
+                                             UShort           ui16AbsGoRice,
+                                             UInt             c1Idx,
+                                             UInt             c2Idx,
+                                             Int              iQBits,
+                                             Double           errorScale,
+                                             Bool             bLast,
+                                             Bool             useLimitedPrefixLength,
+                                             ChannelType      channelType
+                                             ) const;
+
+
+  __inline Int xGetICRate  ( UInt   uiAbsLevel,
+                             UShort ui16CtxNumOne,
+                             UShort ui16CtxNumAbs,
+                             UShort ui16AbsGoRice,
+                             UInt   c1Idx,
+                             UInt   c2Idx,
+                             Bool   useLimitedPrefixLength,
+                             ChannelType channelType
+                           ) const;
+
+  __inline Double xGetRateLast         ( const UInt uiPosX, const UInt uiPosY, const ComponentID component ) 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(       TComTU       &rTu,
+                 const TCoeff      * pSrc,
+                       TCoeff      * pDes,
+                 const ComponentID   compID,
+                 const QpParam      &cQP );
+
+  // inverse transform
+  Void xIT    ( const ComponentID compID, Bool useDST, TCoeff* plCoef, Pel* pResidual, UInt uiStride, Int iWidth, Int iHeight );
+
+  // inverse skipping transform
+  Void xITransformSkip ( TCoeff* plCoef, Pel* pResidual, UInt uiStride, TComTU &rTu, const ComponentID component );
+
+public:
+  static Void crossComponentPrediction(      TComTU      &rTu,
+                                       const ComponentID  compID,
+                                       const Pel         *piResiL,
+                                       const Pel         *piResiC,
+                                             Pel         *piResiT,
+                                       const Int          width,
+                                       const Int          height,
+                                       const Int          strideL,
+                                       const Int          strideC,
+                                       const Int          strideT,
+                                       const Bool         reverse);
+
+};// END CLASS DEFINITION TComTrQuant
+
+//! \}
+
+#endif // __TCOMTRQUANT__
Index: /tags/SHM-9.0/source/Lib/TLibCommon/TComUpsampleFilter.cpp
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibCommon/TComUpsampleFilter.cpp	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibCommon/TComUpsampleFilter.cpp	(revision 1088)
@@ -0,0 +1,731 @@
+#include "TypeDef.h"
+#if SVC_EXTENSION
+#include "TComUpsampleFilter.h"
+
+const Int TComUpsampleFilter::m_lumaFixedFilter[16][NTAPS_US_LUMA] =
+{
+  {  0, 0,   0, 64,  0,   0,  0,  0 },
+  {  0, 1,  -3, 63,  4,  -2,  1,  0 },
+  { -1, 2,  -5, 62,  8,  -3,  1,  0 },
+  { -1, 3,  -8, 60, 13,  -4,  1,  0 },
+  { -1, 4, -10, 58, 17,  -5,  1,  0 },
+  { -1, 4, -11, 52, 26,  -8,  3, -1 }, // <-> actual phase shift 1/3, used for spatial scalability x1.5
+  { -1, 3,  -9, 47, 31, -10,  4, -1 },
+  { -1, 4, -11, 45, 34, -10,  4, -1 },
+  { -1, 4, -11, 40, 40, -11,  4, -1 }, // <-> actual phase shift 1/2, equal to HEVC MC, used for spatial scalability x2
+  { -1, 4, -10, 34, 45, -11,  4, -1 },
+  { -1, 4, -10, 31, 47,  -9,  3, -1 },
+  { -1, 3,  -8, 26, 52, -11,  4, -1 }, // <-> actual phase shift 2/3, used for spatial scalability x1.5
+  {  0, 1,  -5, 17, 58, -10,  4, -1 },
+  {  0, 1,  -4, 13, 60,  -8,  3, -1 },
+  {  0, 1,  -3,  8, 62,  -5,  2, -1 },
+  {  0, 1,  -2,  4, 63,  -3,  1,  0 }
+};
+
+const Int TComUpsampleFilter::m_chromaFixedFilter[16][NTAPS_US_CHROMA] =
+{
+  {  0, 64,  0,  0 },
+  { -2, 62,  4,  0 },
+  { -2, 58, 10, -2 },
+  { -4, 56, 14, -2 },
+  { -4, 54, 16, -2 }, // <-> actual phase shift 1/4,equal to HEVC MC, used for spatial scalability x1.5 (only for accurate Chroma alignement)
+  { -6, 52, 20, -2 }, // <-> actual phase shift 1/3, used for spatial scalability x1.5
+  { -6, 46, 28, -4 }, // <-> actual phase shift 3/8,equal to HEVC MC, used for spatial scalability x2 (only for accurate Chroma alignement)
+  { -4, 42, 30, -4 },
+  { -4, 36, 36, -4 }, // <-> actual phase shift 1/2,equal to HEVC MC, used for spatial scalability x2
+  { -4, 30, 42, -4 }, // <-> actual phase shift 7/12, used for spatial scalability x1.5 (only for accurate Chroma alignement)
+  { -4, 28, 46, -6 },
+  { -2, 20, 52, -6 }, // <-> actual phase shift 2/3, used for spatial scalability x1.5
+  { -2, 16, 54, -4 },
+  { -2, 14, 56, -4 },
+  { -2, 10, 58, -2 }, // <-> actual phase shift 7/8,equal to HEVC MC, used for spatial scalability x2 (only for accurate Chroma alignement)
+  {  0,  4, 62, -2 }  // <-> actual phase shift 11/12, used for spatial scalability x1.5 (only for accurate Chroma alignement)
+};
+
+TComUpsampleFilter::TComUpsampleFilter(void)
+{
+}
+
+TComUpsampleFilter::~TComUpsampleFilter(void)
+{
+}
+
+#if O0215_PHASE_ALIGNMENT_REMOVAL
+Void TComUpsampleFilter::upsampleBasePic( TComSlice* currSlice, UInt refLayerIdc, TComPicYuv* pcUsPic, TComPicYuv* pcBasePic, TComPicYuv* pcTempPic )
+#else
+#if O0215_PHASE_ALIGNMENT
+#if O0194_JOINT_US_BITSHIFT
+Void TComUpsampleFilter::upsampleBasePic( TComSlice* currSlice, UInt refLayerIdc, TComPicYuv* pcUsPic, TComPicYuv* pcBasePic, TComPicYuv* pcTempPic, Bool phaseAlignFlag )
+#else
+Void TComUpsampleFilter::upsampleBasePic( UInt refLayerIdc, TComPicYuv* pcUsPic, TComPicYuv* pcBasePic, TComPicYuv* pcTempPic, const Window window, Bool phaseAlignFlag )
+#endif
+#else
+#if O0194_JOINT_US_BITSHIFT
+#if REF_REGION_OFFSET
+Void TComUpsampleFilter::upsampleBasePic( TComSlice* currSlice, UInt refLayerIdc, TComPicYuv* pcUsPic, TComPicYuv* pcBasePic, TComPicYuv* pcTempPic, const Window window, const Window altRefWindow )
+#else
+Void TComUpsampleFilter::upsampleBasePic( TComSlice* currSlice, UInt refLayerIdc, TComPicYuv* pcUsPic, TComPicYuv* pcBasePic, TComPicYuv* pcTempPic, const Window window )
+#endif
+#else
+Void TComUpsampleFilter::upsampleBasePic( UInt refLayerIdc, TComPicYuv* pcUsPic, TComPicYuv* pcBasePic, TComPicYuv* pcTempPic, const Window window )
+#endif
+#endif
+#endif
+{
+  assert ( NTAPS_US_LUMA == 8 );
+  assert ( NTAPS_US_CHROMA == 4 );
+
+  Int i, j;
+
+#if O0194_JOINT_US_BITSHIFT
+  UInt currLayerId = currSlice->getLayerId();
+  UInt refLayerId  = currSlice->getVPS()->getRefLayerId( currLayerId, refLayerIdc );
+#endif
+
+#if MOVE_SCALED_OFFSET_TO_PPS
+#if O0098_SCALED_REF_LAYER_ID
+  const Window &scalEL = currSlice->getPPS()->getScaledRefLayerWindowForLayer(refLayerId);
+#else
+  const Window &scalEL = currSlice->getPPS()->getScaledRefLayerWindow(refLayerIdc);
+#endif
+#if REF_REGION_OFFSET
+  const Window &windowRL = currSlice->getPPS()->getRefLayerWindowForLayer(refLayerId);
+#endif
+#else
+#if O0098_SCALED_REF_LAYER_ID
+  const Window &scalEL = currSlice->getSPS()->getScaledRefLayerWindowForLayer(refLayerId);
+#else
+  const Window &scalEL = currSlice->getSPS()->getScaledRefLayerWindow(refLayerIdc);
+#endif
+#endif
+
+  //========== Y component upsampling ===========
+  Int widthBL   = pcBasePic->getWidth (COMPONENT_Y);
+  Int heightBL  = pcBasePic->getHeight(COMPONENT_Y);
+  Int strideBL  = pcBasePic->getStride(COMPONENT_Y);
+
+  Int widthEL   = pcUsPic->getWidth (COMPONENT_Y) - scalEL.getWindowLeftOffset() - scalEL.getWindowRightOffset();
+  Int heightEL  = pcUsPic->getHeight(COMPONENT_Y) - scalEL.getWindowTopOffset()  - scalEL.getWindowBottomOffset();
+  Int strideEL  = pcUsPic->getStride(COMPONENT_Y);
+
+#if Q0200_CONFORMANCE_BL_SIZE
+  const Window &confBL = currSlice->getBaseColPic(refLayerIdc)->getConformanceWindow();
+#endif
+#if Q0200_CONFORMANCE_BL_SIZE || REF_REGION_OFFSET
+  Int chromaFormatIdc = currSlice->getBaseColPic(refLayerIdc)->getSlice(0)->getChromaFormatIdc();
+  Int xScal = TComSPS::getWinUnitX( chromaFormatIdc );
+  Int yScal = TComSPS::getWinUnitY( chromaFormatIdc );
+#endif
+#if R0209_GENERIC_PHASE
+  Bool phaseSetPresentFlag;
+  Int phaseHorLuma, phaseVerLuma, phaseHorChroma, phaseVerChroma;  
+  currSlice->getPPS()->getResamplingPhase( refLayerId, phaseSetPresentFlag, phaseHorLuma, phaseVerLuma, phaseHorChroma, phaseVerChroma );
+
+  if( !phaseSetPresentFlag )
+  {
+    Int refRegionHeight = heightBL - windowRL.getWindowTopOffset() - windowRL.getWindowBottomOffset();
+    phaseVerChroma = (4 * heightEL + (refRegionHeight >> 1)) / refRegionHeight - 4;
+  }
+#endif
+#if P0312_VERT_PHASE_ADJ
+  Bool vertPhasePositionEnableFlag = scalEL.getVertPhasePositionEnableFlag();
+  Bool vertPhasePositionFlag = currSlice->getVertPhasePositionFlag( refLayerIdc );
+  if( vertPhasePositionFlag )
+  {
+    assert( vertPhasePositionEnableFlag );
+  }
+#endif
+
+  Pel* piTempBufY = pcTempPic->getAddr(COMPONENT_Y);
+  Pel* piSrcBufY  = pcBasePic->getAddr(COMPONENT_Y);
+  Pel* piDstBufY  = pcUsPic->getAddr(COMPONENT_Y);
+
+  Pel* piSrcY;
+  Pel* piDstY;
+
+  Pel* piTempBufU = pcTempPic->getAddr(COMPONENT_Cb);
+  Pel* piSrcBufU  = pcBasePic->getAddr(COMPONENT_Cb);
+  Pel* piDstBufU  = pcUsPic->getAddr(COMPONENT_Cb);
+
+  Pel* piTempBufV = pcTempPic->getAddr(COMPONENT_Cr);
+  Pel* piSrcBufV  = pcBasePic->getAddr(COMPONENT_Cr);
+  Pel* piDstBufV  = pcUsPic->getAddr(COMPONENT_Cr);
+
+  Pel* piSrcU;
+  Pel* piDstU;
+  Pel* piSrcV;
+  Pel* piDstV;
+
+  Int scaleX = g_posScalingFactor[refLayerIdc][0];
+  Int scaleY = g_posScalingFactor[refLayerIdc][1];
+
+  // non-normative software optimization for certain simple resampling cases
+  if( scaleX == 65536 && scaleY == 65536 ) // ratio 1x
+  {
+    piSrcY = piSrcBufY;
+    piDstY = piDstBufY + scalEL.getWindowLeftOffset() + scalEL.getWindowTopOffset() * strideEL;
+
+#if O0194_JOINT_US_BITSHIFT
+    Int shift = g_bitDepthLayer[CHANNEL_TYPE_LUMA][currLayerId] - g_bitDepthLayer[CHANNEL_TYPE_LUMA][refLayerId];
+#if Q0048_CGS_3D_ASYMLUT
+    if( currSlice->getPPS()->getCGSFlag() )
+    {
+      shift = g_bitDepthLayer[CHANNEL_TYPE_LUMA][currLayerId] - currSlice->getPPS()->getCGSOutputBitDepthY();
+    }
+    assert( shift >= 0 );
+#endif
+#endif
+
+    for( i = 0; i < heightBL; i++ )
+    {
+#if O0194_JOINT_US_BITSHIFT
+      for( j = 0; j < widthBL; j++ )
+      {
+        piDstY[j] = piSrcY[j] << shift;
+      }
+#else
+      memcpy( piDstY, piSrcY, sizeof(Pel) * widthBL );
+#endif
+      piSrcY += strideBL;
+      piDstY += strideEL;
+    }
+
+    widthEL  >>= 1;
+    heightEL >>= 1;
+
+    widthBL  >>= 1;
+    heightBL >>= 1;
+
+    strideBL = pcBasePic->getStride( COMPONENT_Cb );
+    strideEL = pcUsPic->getStride( COMPONENT_Cb );
+
+    piSrcU = piSrcBufU;
+    piSrcV = piSrcBufV;
+
+    piDstU = piDstBufU + ( scalEL.getWindowLeftOffset() >> 1 ) + ( scalEL.getWindowTopOffset() >> 1 ) * strideEL;
+    piDstV = piDstBufV + ( scalEL.getWindowLeftOffset() >> 1 ) + ( scalEL.getWindowTopOffset() >> 1 ) * strideEL;
+
+#if O0194_JOINT_US_BITSHIFT
+    shift = g_bitDepthLayer[CHANNEL_TYPE_CHROMA][currLayerId] - g_bitDepthLayer[CHANNEL_TYPE_CHROMA][refLayerId];
+#if Q0048_CGS_3D_ASYMLUT
+    if( currSlice->getPPS()->getCGSFlag() )
+    {
+      shift = g_bitDepthLayer[CHANNEL_TYPE_CHROMA][currLayerId] - currSlice->getPPS()->getCGSOutputBitDepthC();
+    }
+#endif
+#endif
+
+    for( i = 0; i < heightBL; i++ )
+    {
+#if O0194_JOINT_US_BITSHIFT
+      for( j = 0; j < widthBL; j++ )
+      {
+        piDstU[j] = piSrcU[j] << shift;
+        piDstV[j] = piSrcV[j] << shift;
+      }
+#else
+      memcpy( piDstU, piSrcU, sizeof(Pel) * widthBL );
+      memcpy( piDstV, piSrcV, sizeof(Pel) * widthBL );
+#endif
+      piSrcU += strideBL;
+      piSrcV += strideBL;
+      piDstU += strideEL;
+      piDstV += strideEL;
+    }
+  }
+  else // general resampling process
+  {
+    Int refPos16 = 0;
+    Int phase    = 0;
+    Int refPos   = 0;
+    Int* coeff = m_chromaFilter[phase];
+    for ( i = 0; i < 16; i++)
+    {
+      memcpy(   m_lumaFilter[i],   m_lumaFixedFilter[i], sizeof(Int) * NTAPS_US_LUMA   );
+      memcpy( m_chromaFilter[i], m_chromaFixedFilter[i], sizeof(Int) * NTAPS_US_CHROMA );
+    }
+
+    assert ( widthEL >= widthBL );
+    assert ( heightEL >= heightBL );
+
+    pcBasePic->setBorderExtension(false);
+    pcBasePic->extendPicBorder(); // extend the border.
+
+    Int   shiftX = 16;
+    Int   shiftY = 16;
+
+#if R0209_GENERIC_PHASE
+    Int phaseX = phaseHorLuma;
+    Int phaseY = phaseVerLuma;
+    Int addX = ( ( phaseX * scaleX + 8 ) >> 4 ) -  (1 << ( shiftX - 5 ));
+    Int addY = ( ( phaseY * scaleY + 8 ) >> 4 ) -  (1 << ( shiftX - 5 ));
+#if REF_REGION_OFFSET
+    Int refOffsetX = windowRL.getWindowLeftOffset() << 4;
+    Int refOffsetY = windowRL.getWindowTopOffset()  << 4;
+#else
+#if Q0200_CONFORMANCE_BL_SIZE
+    Int refOffsetX = ( confBL.getWindowLeftOffset() * xScal ) << 4;
+    Int refOffsetY = ( confBL.getWindowTopOffset()  * yScal ) << 4;
+#endif
+#endif
+#else
+#if O0215_PHASE_ALIGNMENT //for Luma, if Phase 0, then both PhaseX  and PhaseY should be 0. If symmetric: both PhaseX and PhaseY should be 2
+    Int   phaseX = 2*phaseAlignFlag;
+#if P0312_VERT_PHASE_ADJ
+#if Q0120_PHASE_CALCULATION
+    Int   phaseY = 2*phaseAlignFlag;
+#else
+    Int   phaseY = vertPhasePositionEnableFlag ? ( vertPhasePositionFlag * 4 ) : ( 2 * phaseAlignFlag );
+#endif
+#else
+    Int   phaseY = 2*phaseAlignFlag;
+#endif
+#else
+    Int   phaseX = 0;
+#if P0312_VERT_PHASE_ADJ
+#if Q0120_PHASE_CALCULATION
+    Int   phaseY = 0;
+#else
+    Int   phaseY = (vertPhasePositionEnableFlag?(vertPhasePositionFlag *4):(0));
+#endif
+#else
+    Int   phaseY = 0;
+#endif
+#endif
+ 
+    Int   addX = ( ( phaseX * scaleX + 2 ) >> 2 ) + ( 1 << ( shiftX - 5 ) );
+    Int   addY = ( ( phaseY * scaleY + 2 ) >> 2 ) + ( 1 << ( shiftY - 5 ) );
+
+#if Q0120_PHASE_CALCULATION
+    Int   deltaX = (Int)phaseAlignFlag <<3;
+    Int   deltaY = (((Int)phaseAlignFlag <<3)>>(Int)vertPhasePositionEnableFlag) + ((Int)vertPhasePositionFlag<<3);
+#else
+    Int   deltaX = 4 * phaseX;
+    Int   deltaY = 4 * phaseY;
+#endif
+
+#if REF_REGION_OFFSET
+    Int refOffsetX = windowRL.getWindowLeftOffset() << 4;
+    Int refOffsetY = windowRL.getWindowTopOffset() << 4;
+#else
+#if Q0200_CONFORMANCE_BL_SIZE
+    deltaX -= ( confBL.getWindowLeftOffset() * xScal ) << 4;
+    deltaY -= ( confBL.getWindowTopOffset() * yScal ) << 4;
+#endif
+#endif
+#endif
+
+    Int shiftXM4 = shiftX - 4;
+    Int shiftYM4 = shiftY - 4;
+
+    widthEL  = pcUsPic->getWidth ( COMPONENT_Y );
+    heightEL = pcUsPic->getHeight( COMPONENT_Y );
+
+    widthBL  = pcBasePic->getWidth ( COMPONENT_Y );
+    heightBL = min<Int>( pcBasePic->getHeight( COMPONENT_Y ), heightEL );
+
+#if R0220_REMOVE_EL_CLIP
+    Int phaseXL = scalEL.getWindowLeftOffset();
+    Int phaseYL = scalEL.getWindowTopOffset();
+    Int rlClipL = -(NTAPS_US_LUMA>>1);
+    Int rlClipR = widthBL -1 + (NTAPS_US_LUMA>>1);
+    Int rlClipT = -(NTAPS_US_LUMA>>1);
+    Int rlClipB = heightBL - 1 + (NTAPS_US_LUMA>>1);
+#else
+    Int leftStartL = scalEL.getWindowLeftOffset();
+    Int rightEndL  = pcUsPic->getWidth() - scalEL.getWindowRightOffset();
+    Int topStartL  = scalEL.getWindowTopOffset();
+    Int bottomEndL = pcUsPic->getHeight() - scalEL.getWindowBottomOffset();
+    Int leftOffset = leftStartL > 0 ? leftStartL : 0;
+#endif
+#if O0194_JOINT_US_BITSHIFT
+    // g_bitDepthY was set to EL bit-depth, but shift1 should be calculated using BL bit-depth
+    Int shift1 = g_bitDepthLayer[CHANNEL_TYPE_LUMA][refLayerId] - 8;
+#if Q0048_CGS_3D_ASYMLUT
+    if( currSlice->getPPS()->getCGSFlag() )
+    {
+      shift1 = currSlice->getPPS()->getCGSOutputBitDepthY() - 8;
+    }
+#endif
+#else
+    Int shift1 = g_bitDepthY - 8;
+#endif
+
+    //========== horizontal upsampling ===========
+    for( i = 0; i < widthEL; i++ )
+    {
+#if R0220_REMOVE_EL_CLIP
+      Int x = i;
+#if R0209_GENERIC_PHASE
+      refPos16 = (((x - phaseXL)*scaleX - addX) >> shiftXM4) + refOffsetX;
+#else
+#if REF_REGION_OFFSET
+      refPos16 = (((x - phaseXL)*scaleX + addX) >> shiftXM4) - deltaX + refOffsetX;
+#else
+      refPos16 = (((x - phaseXL)*scaleX + addX) >> shiftXM4) - deltaX;
+#endif
+#endif
+#else
+      Int x = Clip3( leftStartL, rightEndL - 1, i );
+#if REF_REGION_OFFSET
+      refPos16 = (((x - leftStartL)*scaleX + addX) >> shiftXM4) - deltaX + refOffsetX;
+#else
+      refPos16 = (((x - leftStartL)*scaleX + addX) >> shiftXM4) - deltaX;
+#endif
+#endif
+      phase    = refPos16 & 15;
+      refPos   = refPos16 >> 4;
+#if R0220_REMOVE_EL_CLIP
+      refPos   = Clip3( rlClipL, rlClipR, refPos );
+#endif
+      coeff = m_lumaFilter[phase];
+
+      piSrcY = piSrcBufY + refPos -((NTAPS_US_LUMA>>1) - 1);
+      piDstY = piTempBufY + i;
+
+      for( j = 0; j < heightBL ; j++ )
+      {
+        *piDstY = sumLumaHor(piSrcY, coeff) >> shift1;
+        piSrcY += strideBL;
+        piDstY += strideEL;
+      }
+    }
+
+    //========== vertical upsampling ===========
+    pcTempPic->setBorderExtension(false);
+    pcTempPic->setHeight(heightBL);
+    pcTempPic->extendPicBorder   (); // extend the border.
+    pcTempPic->setHeight(heightEL);
+
+#if O0194_JOINT_US_BITSHIFT
+    Int nShift = 20 - g_bitDepthLayer[CHANNEL_TYPE_LUMA][currLayerId];
+#else
+    Int nShift = US_FILTER_PREC*2 - shift1;
+#endif
+    Int iOffset = 1 << (nShift - 1);
+
+    for( j = 0; j < pcTempPic->getHeight(COMPONENT_Y); j++ )
+    {
+#if R0220_REMOVE_EL_CLIP
+      Int y = j;
+#if R0209_GENERIC_PHASE
+      refPos16 = ((( y - phaseYL )*scaleY - addY) >> shiftYM4) + refOffsetY;
+#else
+#if REF_REGION_OFFSET
+      refPos16 = ((( y - phaseYL )*scaleY + addY) >> shiftYM4) - deltaY + refOffsetY;
+#else
+      refPos16 = ((( y - pahseYL )*scaleY + addY) >> shiftYM4) - deltaY;
+#endif
+#endif
+#else
+      Int y = Clip3(topStartL, bottomEndL - 1, j);
+#if REF_REGION_OFFSET
+      refPos16 = ((( y - topStartL )*scaleY + addY) >> shiftYM4) - deltaY + refOffsetY;
+#else
+      refPos16 = ((( y - topStartL )*scaleY + addY) >> shiftYM4) - deltaY;
+#endif
+#endif
+      phase    = refPos16 & 15;
+      refPos   = refPos16 >> 4;
+#if R0220_REMOVE_EL_CLIP
+      refPos = Clip3( rlClipT, rlClipB, refPos );
+#endif
+      coeff = m_lumaFilter[phase];
+
+      piSrcY = piTempBufY + (refPos -((NTAPS_US_LUMA>>1) - 1))*strideEL;
+      Pel* piDstY0 = piDstBufY + j * strideEL;
+
+#if R0220_REMOVE_EL_CLIP
+      piDstY = piDstY0;
+
+      for( i = pcTempPic->getWidth(COMPONENT_Y); i > 0; i-- )
+      {
+        *piDstY = Clip( (sumLumaVer(piSrcY, coeff, strideEL) + iOffset) >> (nShift), CHANNEL_TYPE_LUMA );
+        piSrcY++;
+        piDstY++;
+      }
+#else
+      piDstY = piDstY0 + leftOffset;
+      piSrcY += leftOffset;
+
+      for( i = min<Int>(rightEndL, pcTempPic->getWidth()) - max<Int>(0, leftStartL); i > 0; i-- )
+      {
+        *piDstY = Clip( (sumLumaVer(piSrcY, coeff, strideEL) + iOffset) >> (nShift), CHANNEL_TYPE_LUMA );
+        piSrcY++;
+        piDstY++;
+      }
+
+      for( i = rightEndL; i < pcTempPic->getWidth(); i++ )
+      {
+        *piDstY = piDstY0[rightEndL-1];
+        piDstY++;
+      }
+
+      piDstY = piDstY0;
+      for( i = 0; i < leftStartL; i++ )
+      {
+        *piDstY = piDstY0[leftStartL];
+        piDstY++;
+      }
+#endif
+    }
+
+    widthBL   = pcBasePic->getWidth (COMPONENT_Y);
+    heightBL  = pcBasePic->getHeight(COMPONENT_Y);
+    widthEL   = pcUsPic->getWidth (COMPONENT_Y) - scalEL.getWindowLeftOffset() - scalEL.getWindowRightOffset();
+    heightEL  = pcUsPic->getHeight(COMPONENT_Y) - scalEL.getWindowTopOffset()  - scalEL.getWindowBottomOffset();
+
+    //========== UV component upsampling ===========
+
+    widthEL  >>= 1;
+    heightEL >>= 1;
+
+    widthBL  >>= 1;
+    heightBL >>= 1;
+
+    strideBL  = pcBasePic->getStride( COMPONENT_Cb );
+    strideEL  = pcUsPic->getStride( COMPONENT_Cb );
+
+#if R0220_REMOVE_EL_CLIP
+    Int srlLOffsetC = scalEL.getWindowLeftOffset() >> 1;
+    Int srlTOffsetC = scalEL.getWindowTopOffset() >> 1;
+    rlClipL = -(NTAPS_US_CHROMA>>1);
+    rlClipR = widthBL -1 + (NTAPS_US_CHROMA>>1);
+    rlClipT = -(NTAPS_US_CHROMA>>1);
+    rlClipB = heightBL - 1 + (NTAPS_US_CHROMA>>1);
+#else
+    Int leftStartC = scalEL.getWindowLeftOffset() >> 1;
+    Int rightEndC  = (pcUsPic->getWidth() >> 1) - (scalEL.getWindowRightOffset() >> 1);
+    Int topStartC  = scalEL.getWindowTopOffset() >> 1;
+    Int bottomEndC = (pcUsPic->getHeight() >> 1) - (scalEL.getWindowBottomOffset() >> 1);
+    leftOffset = leftStartC > 0 ? leftStartC : 0;
+#endif
+    shiftX = 16;
+    shiftY = 16;
+
+#if R0209_GENERIC_PHASE
+    addX = ( ( phaseHorChroma * scaleX + 8 ) >> 4 ) -  (1 << ( shiftX - 5 ));
+    addY = ( ( phaseVerChroma * scaleY + 8 ) >> 4 ) -  (1 << ( shiftX - 5 ));
+    Int refOffsetXC = (windowRL.getWindowLeftOffset() / xScal) << 4;
+    Int refOffsetYC = (windowRL.getWindowTopOffset()  / yScal) << 4;
+#else
+#if O0215_PHASE_ALIGNMENT
+    Int phaseXC = phaseAlignFlag;
+#if P0312_VERT_PHASE_ADJ
+#if Q0120_PHASE_CALCULATION
+    Int phaseYC = phaseAlignFlag + 1;
+#else
+    Int phaseYC = vertPhasePositionEnableFlag ? ( vertPhasePositionFlag * 4 ) : ( phaseAlignFlag + 1 );
+#endif
+#else
+    Int phaseYC = phaseAlignFlag + 1;
+#endif
+#else
+    Int phaseXC = 0;
+#if P0312_VERT_PHASE_ADJ
+#if Q0120_PHASE_CALCULATION
+    Int phaseYC = 1;
+#else
+    Int phaseYC = vertPhasePositionEnableFlag ? (vertPhasePositionFlag * 4): 1;
+#endif
+#else
+    Int phaseYC = 1;
+#endif
+#endif
+    
+    addX       = ( ( phaseXC * scaleX + 2 ) >> 2 ) + ( 1 << ( shiftX - 5 ) );
+    addY       = ( ( phaseYC * scaleY + 2 ) >> 2 ) + ( 1 << ( shiftY - 5 ) );
+
+#if Q0120_PHASE_CALCULATION
+    deltaX     = (Int)phaseAlignFlag << 2;
+    deltaY     = ((( (Int)phaseAlignFlag +1)<<2)>>(Int)vertPhasePositionEnableFlag)+((Int)vertPhasePositionFlag<<3);
+#else
+    deltaX     = 4 * phaseXC;
+    deltaY     = 4 * phaseYC;
+#endif
+
+#if REF_REGION_OFFSET
+    Int refOffsetXC = (windowRL.getWindowLeftOffset() / xScal) << 4;
+    Int refOffsetYC  = (windowRL.getWindowTopOffset()  / yScal) << 4;
+#else
+#if Q0200_CONFORMANCE_BL_SIZE
+    deltaX -= ( ( confBL.getWindowLeftOffset() * xScal ) >> 1 ) << 4;
+    deltaY  -= ( ( confBL.getWindowTopOffset() * yScal ) >> 1 ) << 4;
+#endif
+#endif
+#endif
+
+    shiftXM4 = shiftX - 4;
+    shiftYM4 = shiftY - 4;
+
+    widthEL   = pcUsPic->getWidth (COMPONENT_Y) >> 1;
+    heightEL  = pcUsPic->getHeight(COMPONENT_Y) >> 1;
+
+    widthBL   = pcBasePic->getWidth (COMPONENT_Y) >> 1;
+    heightBL  = min<Int>( pcBasePic->getHeight(COMPONENT_Y) >> 1, heightEL );
+
+#if O0194_JOINT_US_BITSHIFT
+    // g_bitDepthC was set to EL bit-depth, but shift1 should be calculated using BL bit-depth
+    shift1 = g_bitDepthLayer[CHANNEL_TYPE_CHROMA][refLayerId] - 8;
+#if Q0048_CGS_3D_ASYMLUT
+    if( currSlice->getPPS()->getCGSFlag() )
+    {
+      shift1 = currSlice->getPPS()->getCGSOutputBitDepthC() - 8;
+    }
+#endif
+#else
+    shift1 = g_bitDepthC - 8;
+#endif
+
+    //========== horizontal upsampling ===========
+    for( i = 0; i < widthEL; i++ )
+    {
+#if R0220_REMOVE_EL_CLIP
+      Int x = i;
+#if R0209_GENERIC_PHASE
+      refPos16 = (((x - srlLOffsetC)*scaleX - addX) >> shiftXM4) + refOffsetXC;
+#else
+#if REF_REGION_OFFSET
+      refPos16 = (((x - srlLOffsetC)*scaleX + addX) >> shiftXM4) - deltaX + refOffsetXC;
+#else
+      refPos16 = (((x - srlLOffsetC)*scaleX + addX) >> shiftXM4) - deltaX;
+#endif
+#endif
+#else
+      Int x = Clip3(leftStartC, rightEndC - 1, i);
+#if REF_REGION_OFFSET
+      refPos16 = (((x - leftStartC)*scaleX + addX) >> shiftXM4) - deltaX + refOffsetXC;
+#else
+      refPos16 = (((x - leftStartC)*scaleX + addX) >> shiftXM4) - deltaX;
+#endif
+#endif
+      phase    = refPos16 & 15;
+      refPos   = refPos16 >> 4;
+#if R0220_REMOVE_EL_CLIP
+      refPos   = Clip3(rlClipL, rlClipR, refPos);
+#endif
+      coeff = m_chromaFilter[phase];
+
+      piSrcU = piSrcBufU + refPos -((NTAPS_US_CHROMA>>1) - 1);
+      piSrcV = piSrcBufV + refPos -((NTAPS_US_CHROMA>>1) - 1);
+      piDstU = piTempBufU + i;
+      piDstV = piTempBufV + i;
+
+      for( j = 0; j < heightBL ; j++ )
+      {
+        *piDstU = sumChromaHor(piSrcU, coeff) >> shift1;
+        *piDstV = sumChromaHor(piSrcV, coeff) >> shift1;
+
+        piSrcU += strideBL;
+        piSrcV += strideBL;
+        piDstU += strideEL;
+        piDstV += strideEL;
+      }
+    }
+
+    //========== vertical upsampling ===========
+    pcTempPic->setBorderExtension(false);
+    pcTempPic->setHeight(heightBL << 1);
+    pcTempPic->extendPicBorder   (); // extend the border.
+    pcTempPic->setHeight(heightEL << 1);
+
+#if O0194_JOINT_US_BITSHIFT
+    nShift = 20 - g_bitDepthLayer[CHANNEL_TYPE_CHROMA][currLayerId];
+#else
+    nShift = US_FILTER_PREC*2 - shift1;
+#endif
+    iOffset = 1 << (nShift - 1);
+
+    for( j = 0; j < pcTempPic->getHeight(COMPONENT_Y) >> 1; j++ )
+    {
+#if R0220_REMOVE_EL_CLIP
+      Int y = j;
+#if R0209_GENERIC_PHASE
+      refPos16 = (((y - srlTOffsetC)*scaleY - addY) >> shiftYM4) + refOffsetYC;
+#else
+#if REF_REGION_OFFSET
+      refPos16 = (((y - srlTOffsetC)*scaleY + addY) >> shiftYM4) - deltaY + refOffsetYC;
+#else
+      refPos16 = (((y - srlTOffsetC)*scaleY + addY) >> shiftYM4) - deltaY;
+#endif
+#endif
+#else
+      Int y = Clip3(topStartC, bottomEndC - 1, j);
+#if REF_REGION_OFFSET
+      refPos16 = (((y - topStartC)*scaleY + addY) >> shiftYM4) - deltaY + refOffsetYC;
+#else
+      refPos16 = (((y - topStartC)*scaleY + addY) >> shiftYM4) - deltaY;
+#endif
+#endif
+      phase    = refPos16 & 15;
+      refPos   = refPos16 >> 4;
+#if R0220_REMOVE_EL_CLIP
+      refPos = Clip3(rlClipT, rlClipB, refPos);
+#endif
+      coeff = m_chromaFilter[phase];
+
+      piSrcU = piTempBufU  + (refPos -((NTAPS_US_CHROMA>>1) - 1))*strideEL;
+      piSrcV = piTempBufV  + (refPos -((NTAPS_US_CHROMA>>1) - 1))*strideEL;
+
+      Pel* piDstU0 = piDstBufU + j*strideEL;
+      Pel* piDstV0 = piDstBufV + j*strideEL;
+
+#if R0220_REMOVE_EL_CLIP
+      piDstU = piDstU0;
+      piDstV = piDstV0;
+
+      for( i = pcTempPic->getWidth(COMPONENT_Y) >> 1; i > 0; i-- )
+      {
+        *piDstU = Clip( (sumChromaVer(piSrcU, coeff, strideEL) + iOffset) >> (nShift), CHANNEL_TYPE_CHROMA );
+        *piDstV = Clip( (sumChromaVer(piSrcV, coeff, strideEL) + iOffset) >> (nShift), CHANNEL_TYPE_CHROMA );
+        piSrcU++;
+        piSrcV++;
+        piDstU++;
+        piDstV++;
+      }
+#else
+      piDstU = piDstU0 + leftOffset;
+      piDstV = piDstV0 + leftOffset;
+      piSrcU += leftOffset;
+      piSrcV += leftOffset;
+
+      for( i = min<Int>(rightEndC, pcTempPic->getWidth() >> 1) - max<Int>(0, leftStartC); i > 0; i-- )
+      {
+        *piDstU = Clip( (sumChromaVer(piSrcU, coeff, strideEL) + iOffset) >> (nShift), CHANNEL_TYPE_CHROMA );
+        *piDstV = Clip( (sumChromaVer(piSrcV, coeff, strideEL) + iOffset) >> (nShift), CHANNEL_TYPE_CHROMA );
+        piSrcU++;
+        piSrcV++;
+        piDstU++;
+        piDstV++;
+      }
+
+      for( i = rightEndC; i < pcTempPic->getWidth(COMPONENT_Y) >> 1; i++ )
+      {
+        *piDstU = piDstU0[rightEndC-1];
+        *piDstV = piDstV0[rightEndC-1];
+        piDstU++;
+        piDstV++;
+      }
+
+      piDstU = piDstU0;
+      piDstV = piDstV0;
+      for( i = 0; i < leftStartC; i++ )
+      {
+        *piDstU = piDstU0[leftStartC];
+        *piDstV = piDstV0[leftStartC];
+        piDstU++;
+        piDstV++;
+      }
+#endif
+
+    }
+  }
+    pcUsPic->setBorderExtension(false);
+    pcUsPic->extendPicBorder   (); // extend the border.
+
+    //Reset the Border extension flag
+    pcUsPic->setBorderExtension(false);
+    pcTempPic->setBorderExtension(false);
+    pcBasePic->setBorderExtension(false);
+}
+#endif //SVC_EXTENSION
Index: /tags/SHM-9.0/source/Lib/TLibCommon/TComUpsampleFilter.h
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibCommon/TComUpsampleFilter.h	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibCommon/TComUpsampleFilter.h	(revision 1088)
@@ -0,0 +1,68 @@
+#ifndef __TCOMUPSAMPLEFILTER__
+#define __TCOMUPSAMPLEFILTER__
+
+#include "TComPic.h"
+#include "TComYuv.h"
+#include "TComDataCU.h"
+
+#define NTAPS_US_LUMA        8 ///< Number of taps for luma upsampling filter
+#define NTAPS_US_CHROMA      4 ///< Number of taps for chroma upsampling filter
+#define US_FILTER_PREC       6 ///< Log2 of sum of filter taps
+
+class TComUpsampleFilter
+{
+private:
+  static const Int m_lumaFixedFilter[16][NTAPS_US_LUMA];     ///< Luma filter taps for both 1.5x and 2x scalability
+  static const Int m_chromaFixedFilter[16][NTAPS_US_CHROMA]; ///< Chroma filter taps for 1.5x scalability
+
+  Int m_lumaFilter[16][NTAPS_US_LUMA];
+  Int m_chromaFilter[16][NTAPS_US_CHROMA];
+
+  static inline Int sumLumaHor( Pel* pel, Int* coeff )
+  {
+    return ( pel[0]*coeff[0] + pel[1]*coeff[1] + pel[2]*coeff[2] + pel[3]*coeff[3] + pel[4]*coeff[4] + pel[5]*coeff[5] + pel[6]*coeff[6] + pel[7]*coeff[7]);
+  }
+
+  static inline Int sumChromaHor( Pel* pel, Int* coeff )
+  {
+    return ( pel[0]*coeff[0] + pel[1]*coeff[1] + pel[2]*coeff[2] + pel[3]*coeff[3] );
+  }
+
+  static inline Int sumLumaVer( Pel* pel, Int* coeff, Int stride )
+  {
+    return ( pel[0]*coeff[0] + pel[stride]*coeff[1] + pel[2*stride]*coeff[2] + pel[3*stride]*coeff[3] + pel[4*stride]*coeff[4] + pel[5*stride]*coeff[5] + pel[6*stride]*coeff[6] + pel[7*stride]*coeff[7]);
+  }
+
+  static inline Int sumChromaVer( Pel* pel, Int* coeff, Int stride )
+  {
+    return ( pel[0]*coeff[0] + pel[stride]*coeff[1] + pel[2*stride]*coeff[2] + pel[3*stride]*coeff[3] );
+  }
+
+public:
+  TComUpsampleFilter(void);
+  ~TComUpsampleFilter(void);
+#if O0215_PHASE_ALIGNMENT_REMOVAL
+  Void upsampleBasePic( TComSlice* currSlice, UInt refLayerIdc, TComPicYuv* pcUsPic, TComPicYuv* pcBasePic, TComPicYuv* pcTempPic );
+#else
+#if O0215_PHASE_ALIGNMENT
+#if O0194_JOINT_US_BITSHIFT
+  Void upsampleBasePic( TComSlice* currSlice, UInt refLayerIdc, TComPicYuv* pcUsPic, TComPicYuv* pcBasePic, TComPicYuv* pcTempPic, Bool phaseAlignFlag );
+#else
+  Void upsampleBasePic( UInt refLayerIdc, TComPicYuv* pcUsPic, TComPicYuv* pcBasePic, TComPicYuv* pcTempPic, const Window window, Bool phaseAlignFlag );
+#endif
+#else
+#if O0194_JOINT_US_BITSHIFT
+#if REF_REGION_OFFSET
+  Void upsampleBasePic( TComSlice* currSlice, UInt refLayerIdc, TComPicYuv* pcUsPic, TComPicYuv* pcBasePic, TComPicYuv* pcTempPic, const Window window, const Window altRefWindow );
+#else
+  Void upsampleBasePic( TComSlice* currSlice, UInt refLayerIdc, TComPicYuv* pcUsPic, TComPicYuv* pcBasePic, TComPicYuv* pcTempPic, const Window window );
+#endif
+#else
+  Void upsampleBasePic( UInt refLayerIdc, TComPicYuv* pcUsPic, TComPicYuv* pcBasePic, TComPicYuv* pcTempPic, const Window window );
+#endif
+#endif
+#endif
+
+};
+
+#endif //__TCOMUPSAMPLEFILTER__
Index: /tags/SHM-9.0/source/Lib/TLibCommon/TComWeightPrediction.cpp
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibCommon/TComWeightPrediction.cpp	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibCommon/TComWeightPrediction.cpp	(revision 1088)
@@ -0,0 +1,376 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TComWeightPrediction.h
+    \brief    weighting prediction class (header)
+*/
+
+// Include files
+#include "TComSlice.h"
+#include "TComWeightPrediction.h"
+#include "TComInterpolationFilter.h"
+
+
+static inline Pel weightBidir( Int w0, Pel P0, Int w1, Pel P1, Int round, Int shift, Int offset, Int clipBD)
+{
+  return ClipBD( ( (w0*(P0 + IF_INTERNAL_OFFS) + w1*(P1 + IF_INTERNAL_OFFS) + round + (offset << (shift-1))) >> shift ), clipBD );
+}
+
+
+static inline Pel weightUnidir( Int w0, Pel P0, Int round, Int shift, Int offset, Int clipBD)
+{
+  return ClipBD( ( (w0*(P0 + IF_INTERNAL_OFFS) + round) >> shift ) + offset, clipBD );
+}
+
+// ====================================================================================================================
+// 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( const TComYuv              *pcYuvSrc0,
+                                        const TComYuv              *pcYuvSrc1,
+                                        const UInt                  iPartUnitIdx,
+                                        const UInt                  uiWidth,
+                                        const UInt                  uiHeight,
+                                        const WPScalingParam *const wp0,
+                                        const WPScalingParam *const wp1,
+                                              TComYuv        *const rpcYuvDst,
+                                        const Bool                  bRoundLuma )
+{
+
+  const Bool enableRounding[MAX_NUM_COMPONENT]={ bRoundLuma, true, true };
+
+  const UInt numValidComponent = pcYuvSrc0->getNumberValidComponents();
+
+  for(Int componentIndex=0; componentIndex<numValidComponent; componentIndex++)
+  {
+    const ComponentID compID=ComponentID(componentIndex);
+
+    const Pel* pSrc0       = pcYuvSrc0->getAddr( compID,  iPartUnitIdx );
+    const Pel* pSrc1       = pcYuvSrc1->getAddr( compID,  iPartUnitIdx );
+          Pel* pDst        = rpcYuvDst->getAddr( compID,  iPartUnitIdx );
+
+    // Luma : --------------------------------------------
+    const Int  w0          = wp0[compID].w;
+    const Int  offset      = wp0[compID].offset;
+    const Int  clipBD      = g_bitDepth[toChannelType(compID)];
+    const Int  shiftNum    = std::max<Int>(2, (IF_INTERNAL_PREC - clipBD));
+    const Int  shift       = wp0[compID].shift + shiftNum;
+    const Int  round       = (enableRounding[compID] && (shift > 0)) ? (1<<(shift-1)) : 0;
+    const Int  w1          = wp1[compID].w;
+    const UInt csx         = pcYuvSrc0->getComponentScaleX(compID);
+    const UInt csy         = pcYuvSrc0->getComponentScaleY(compID);
+    const Int  iHeight     = uiHeight>>csy;
+    const Int  iWidth      = uiWidth>>csx;
+
+    const UInt iSrc0Stride = pcYuvSrc0->getStride(compID);
+    const UInt iSrc1Stride = pcYuvSrc1->getStride(compID);
+    const UInt iDstStride  = rpcYuvDst->getStride(compID);
+
+    for ( Int y = iHeight-1; y >= 0; y-- )
+    {
+      // do it in batches of 4 (partial unroll)
+      Int x = iWidth-1;
+      for ( ; x >= 3; )
+      {
+        pDst[x] = weightBidir(w0,pSrc0[x], w1,pSrc1[x], round, shift, offset, clipBD); x--;
+        pDst[x] = weightBidir(w0,pSrc0[x], w1,pSrc1[x], round, shift, offset, clipBD); x--;
+        pDst[x] = weightBidir(w0,pSrc0[x], w1,pSrc1[x], round, shift, offset, clipBD); x--;
+        pDst[x] = weightBidir(w0,pSrc0[x], w1,pSrc1[x], round, shift, offset, clipBD); x--;
+      }
+      for( ; x >= 0; x-- )
+      {
+        pDst[x] = weightBidir(w0,pSrc0[x], w1,pSrc1[x], round, shift, offset, clipBD);
+      }
+
+      pSrc0 += iSrc0Stride;
+      pSrc1 += iSrc1Stride;
+      pDst  += iDstStride;
+    } // y loop
+  } // compID loop
+}
+
+
+/** 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( const TComYuv        *const pcYuvSrc0,
+                                         const UInt                  iPartUnitIdx,
+                                         const UInt                  uiWidth,
+                                         const UInt                  uiHeight,
+                                         const WPScalingParam *const wp0,
+                                               TComYuv        *const pcYuvDst )
+{
+  const UInt numValidComponent = pcYuvSrc0->getNumberValidComponents();
+
+  for(Int componentIndex=0; componentIndex<numValidComponent; componentIndex++)
+  {
+    const ComponentID compID=ComponentID(componentIndex);
+
+    const Pel* pSrc0       = pcYuvSrc0->getAddr( compID,  iPartUnitIdx );
+          Pel* pDst        = pcYuvDst->getAddr( compID,  iPartUnitIdx );
+
+    // Luma : --------------------------------------------
+    const Int  w0          = wp0[compID].w;
+    const Int  offset      = wp0[compID].offset;
+    const Int  clipBD      = g_bitDepth[toChannelType(compID)];
+    const Int  shiftNum    = std::max<Int>(2, (IF_INTERNAL_PREC - clipBD));
+    const Int  shift       = wp0[compID].shift + shiftNum;
+    const Int  round       = (shift > 0) ? (1<<(shift-1)) : 0;
+    const UInt iSrc0Stride = pcYuvSrc0->getStride(compID);
+    const UInt iDstStride  = pcYuvDst->getStride(compID);
+    const UInt csx         = pcYuvSrc0->getComponentScaleX(compID);
+    const UInt csy         = pcYuvSrc0->getComponentScaleY(compID);
+    const Int  iHeight     = uiHeight>>csy;
+    const Int  iWidth      = uiWidth>>csx;
+
+    for (Int y = iHeight-1; y >= 0; y-- )
+    {
+      Int x = iWidth-1;
+      for ( ; x >= 3; )
+      {
+        pDst[x] = weightUnidir(w0, pSrc0[x], round, shift, offset, clipBD); x--;
+        pDst[x] = weightUnidir(w0, pSrc0[x], round, shift, offset, clipBD); x--;
+        pDst[x] = weightUnidir(w0, pSrc0[x], round, shift, offset, clipBD); x--;
+        pDst[x] = weightUnidir(w0, pSrc0[x], round, shift, offset, clipBD); x--;
+      }
+      for( ; x >= 0; x--)
+      {
+        pDst[x] = weightUnidir(w0, pSrc0[x], round, shift, offset, clipBD);
+      }
+      pSrc0 += iSrc0Stride;
+      pDst  += 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 *const pcCU,
+                                         const Int               iRefIdx0,
+                                         const Int               iRefIdx1,
+                                               WPScalingParam  *&wp0,
+                                               WPScalingParam  *&wp1)
+{
+  assert(iRefIdx0 >= 0 || iRefIdx1 >= 0);
+
+        TComSlice *const pcSlice  = pcCU->getSlice();
+  const Bool             wpBiPred = pcCU->getSlice()->getPPS()->getWPBiPred();
+  const Bool             bBiDir   = (iRefIdx0>=0 && iRefIdx1>=0);
+  const 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;
+  }
+
+  const UInt numValidComponent                    = pcCU->getPic()->getNumberValidComponents();
+  const Bool bUseHighPrecisionPredictionWeighting = pcSlice->getSPS()->getUseHighPrecisionPredictionWeighting();
+
+  if ( bBiDir )
+  { // Bi-Dir case
+    for ( Int yuv=0 ; yuv<numValidComponent ; yuv++ )
+    {
+      const Int bitDepth            = g_bitDepth[toChannelType(ComponentID(yuv))];
+      const Int offsetScalingFactor = bUseHighPrecisionPredictionWeighting ? 1 : (1 << (bitDepth-8));
+
+      wp0[yuv].w      = wp0[yuv].iWeight;
+      wp1[yuv].w      = wp1[yuv].iWeight;
+      wp0[yuv].o      = wp0[yuv].iOffset * offsetScalingFactor;
+      wp1[yuv].o      = wp1[yuv].iOffset * offsetScalingFactor;
+      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
+    WPScalingParam *const pwp = (iRefIdx0>=0) ? wp0 : wp1 ;
+
+    for ( Int yuv=0 ; yuv<numValidComponent ; yuv++ )
+    {
+      const Int bitDepth            = g_bitDepth[toChannelType(ComponentID(yuv))];
+      const Int offsetScalingFactor = bUseHighPrecisionPredictionWeighting ? 1 : (1 << (bitDepth-8));
+
+      pwp[yuv].w      = pwp[yuv].iWeight;
+      pwp[yuv].offset = pwp[yuv].iOffset * offsetScalingFactor;
+      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 *const pcCU,
+                                                  const TComYuv    *const pcYuvSrc0,
+                                                  const TComYuv    *const pcYuvSrc1,
+                                                  const Int               iRefIdx0,
+                                                  const Int               iRefIdx1,
+                                                  const UInt              uiPartIdx,
+                                                  const Int               iWidth,
+                                                  const Int               iHeight,
+                                                        TComYuv          *rpcYuvDst )
+{
+  WPScalingParam  *pwp0;
+  WPScalingParam  *pwp1;
+
+  assert(pcCU->getSlice()->getPPS()->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* pcYuvPred
+ * \param iPartIdx
+ * \param iRefIdx
+ * \returns Void
+ */
+Void TComWeightPrediction::xWeightedPredictionUni(       TComDataCU *const pcCU,
+                                                   const TComYuv    *const pcYuvSrc,
+                                                   const UInt              uiPartAddr,
+                                                   const Int               iWidth,
+                                                   const Int               iHeight,
+                                                   const RefPicList        eRefPicList,
+                                                         TComYuv          *pcYuvPred,
+                                                   const Int               iRefIdx_input)
+{
+  WPScalingParam  *pwp, *pwpTmp;
+
+  Int iRefIdx=iRefIdx_input;
+  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, pcYuvPred );
+}
Index: /tags/SHM-9.0/source/Lib/TLibCommon/TComWeightPrediction.h
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibCommon/TComWeightPrediction.h	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibCommon/TComWeightPrediction.h	(revision 1088)
@@ -0,0 +1,101 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TComWeightPrediction.h
+    \brief    weighting prediction class (header)
+*/
+
+#ifndef __TCOMWEIGHTPREDICTION__
+#define __TCOMWEIGHTPREDICTION__
+
+
+// Include files
+#include "TComPic.h"
+#include "TComMotionInfo.h"
+#include "TComPattern.h"
+#include "TComTrQuant.h"
+#include "TComInterpolationFilter.h"
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+/// weighting prediction class
+class TComWeightPrediction
+{
+public:
+  TComWeightPrediction();
+
+  Void  getWpScaling(                 TComDataCU     *const pcCU,
+                                const Int                   iRefIdx0,
+                                const Int                   iRefIdx1,
+                                      WPScalingParam      *&wp0,
+                                      WPScalingParam      *&wp1);
+
+  Void addWeightBi(             const TComYuv              *pcYuvSrc0,
+                                const TComYuv              *pcYuvSrc1,
+                                const UInt                  iPartUnitIdx,
+                                const UInt                  uiWidth,
+                                const UInt                  uiHeight,
+                                const WPScalingParam *const wp0,
+                                const WPScalingParam *const wp1,
+                                      TComYuv        *const rpcYuvDst,
+                                const Bool                  bRoundLuma=true );
+
+  Void  addWeightUni(           const TComYuv        *const pcYuvSrc0,
+                                const UInt                  iPartUnitIdx,
+                                const UInt                  uiWidth,
+                                const UInt                  uiHeight,
+                                const WPScalingParam *const wp0,
+                                      TComYuv        *const rpcYuvDst );
+
+  Void  xWeightedPredictionUni(       TComDataCU     *const pcCU,
+                                const TComYuv        *const pcYuvSrc,
+                                const UInt                  uiPartAddr,
+                                const Int                   iWidth,
+                                const Int                   iHeight,
+                                const RefPicList            eRefPicList,
+                                      TComYuv              *pcYuvPred,
+                                const Int                   iRefIdx=-1 );
+
+  Void  xWeightedPredictionBi(        TComDataCU     *const pcCU,
+                                const TComYuv        *const pcYuvSrc0,
+                                const TComYuv        *const pcYuvSrc1,
+                                const Int                   iRefIdx0,
+                                const Int                   iRefIdx1,
+                                const UInt                  uiPartIdx,
+                                const Int                   iWidth,
+                                const Int                   iHeight,
+                                      TComYuv              *pcYuvDst );
+};
+
+#endif
Index: /tags/SHM-9.0/source/Lib/TLibCommon/TComYuv.cpp
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibCommon/TComYuv.cpp	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibCommon/TComYuv.cpp	(revision 1088)
@@ -0,0 +1,426 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TComYuv.cpp
+    \brief    general YUV buffer class
+    \todo     this should be merged with TComPicYuv
+*/
+
+#include <stdlib.h>
+#include <memory.h>
+#include <assert.h>
+#include <math.h>
+
+#include "CommonDef.h"
+#include "TComYuv.h"
+#include "TComInterpolationFilter.h"
+
+//! \ingroup TLibCommon
+//! \{
+
+TComYuv::TComYuv()
+{
+  for(Int comp=0; comp<MAX_NUM_COMPONENT; comp++)
+  {
+    m_apiBuf[comp] = NULL;
+  }
+}
+
+TComYuv::~TComYuv()
+{
+}
+
+Void TComYuv::create( UInt iWidth, UInt iHeight, ChromaFormat chromaFormatIDC )
+{
+  // set width and height
+  m_iWidth   = iWidth;
+  m_iHeight  = iHeight;
+  m_chromaFormatIDC = chromaFormatIDC;
+
+  for(Int ch=0; ch<MAX_NUM_COMPONENT; ch++)
+  {
+    // memory allocation
+    m_apiBuf[ch]  = (Pel*)xMalloc( Pel, getWidth(ComponentID(ch))*getHeight(ComponentID(ch)) );
+  }
+}
+
+Void TComYuv::destroy()
+{
+  // memory free
+  for(Int ch=0; ch<MAX_NUM_COMPONENT; ch++)
+  {
+    if (m_apiBuf[ch]!=NULL) { xFree( m_apiBuf[ch] ); m_apiBuf[ch] = NULL; }
+  }
+}
+
+Void TComYuv::clear()
+{
+  for(Int ch=0; ch<MAX_NUM_COMPONENT; ch++)
+  {
+    if (m_apiBuf[ch]!=NULL)
+      ::memset( m_apiBuf[ch], 0, ( getWidth(ComponentID(ch)) * getHeight(ComponentID(ch))  )*sizeof(Pel) );
+  }
+}
+
+
+
+
+Void TComYuv::copyToPicYuv   ( TComPicYuv* pcPicYuvDst, const UInt ctuRsAddr, const UInt uiAbsZorderIdx, const UInt uiPartDepth, const UInt uiPartIdx ) const
+{
+  for(Int ch=0; ch<getNumberValidComponents(); ch++)
+    copyToPicComponent  ( ComponentID(ch), pcPicYuvDst, ctuRsAddr, uiAbsZorderIdx, uiPartDepth, uiPartIdx );
+}
+
+Void TComYuv::copyToPicComponent  ( const ComponentID ch, TComPicYuv* pcPicYuvDst, const UInt ctuRsAddr, const UInt uiAbsZorderIdx, const UInt uiPartDepth, const UInt uiPartIdx ) const
+{
+  const Int iWidth  = getWidth(ch) >>uiPartDepth;
+  const Int iHeight = getHeight(ch)>>uiPartDepth;
+
+  const Pel* pSrc     = getAddr(ch, uiPartIdx, iWidth);
+        Pel* pDst     = pcPicYuvDst->getAddr ( ch, ctuRsAddr, uiAbsZorderIdx );
+
+  const UInt  iSrcStride  = getStride(ch);
+  const UInt  iDstStride  = pcPicYuvDst->getStride(ch);
+
+  for ( Int y = iHeight; y != 0; y-- )
+  {
+    ::memcpy( pDst, pSrc, sizeof(Pel)*iWidth);
+    pDst += iDstStride;
+    pSrc += iSrcStride;
+  }
+}
+
+
+
+
+Void TComYuv::copyFromPicYuv   ( const TComPicYuv* pcPicYuvSrc, const UInt ctuRsAddr, const UInt uiAbsZorderIdx )
+{
+  for(Int ch=0; ch<getNumberValidComponents(); ch++)
+    copyFromPicComponent  ( ComponentID(ch), pcPicYuvSrc, ctuRsAddr, uiAbsZorderIdx );
+}
+
+Void TComYuv::copyFromPicComponent  ( const ComponentID ch, const TComPicYuv* pcPicYuvSrc, const UInt ctuRsAddr, const UInt uiAbsZorderIdx )
+{
+        Pel* pDst     = getAddr(ch);
+  const Pel* pSrc     = pcPicYuvSrc->getAddr ( ch, ctuRsAddr, uiAbsZorderIdx );
+
+  const UInt iDstStride  = getStride(ch);
+  const UInt iSrcStride  = pcPicYuvSrc->getStride(ch);
+  const Int  iWidth=getWidth(ch);
+  const Int  iHeight=getHeight(ch);
+
+  for (Int y = iHeight; y != 0; y-- )
+  {
+    ::memcpy( pDst, pSrc, sizeof(Pel)*iWidth);
+    pDst += iDstStride;
+    pSrc += iSrcStride;
+  }
+}
+
+
+
+
+Void TComYuv::copyToPartYuv( TComYuv* pcYuvDst, const UInt uiDstPartIdx ) const
+{
+  for(Int ch=0; ch<getNumberValidComponents(); ch++)
+    copyToPartComponent  ( ComponentID(ch), pcYuvDst, uiDstPartIdx );
+}
+
+Void TComYuv::copyToPartComponent( const ComponentID ch, TComYuv* pcYuvDst, const UInt uiDstPartIdx ) const
+{
+  const Pel* pSrc     = getAddr(ch);
+        Pel* pDst     = pcYuvDst->getAddr( ch, uiDstPartIdx );
+
+  const UInt iSrcStride  = getStride(ch);
+  const UInt iDstStride  = pcYuvDst->getStride(ch);
+  const Int  iWidth=getWidth(ch);
+  const Int  iHeight=getHeight(ch);
+
+  for (Int y = iHeight; y != 0; y-- )
+  {
+    ::memcpy( pDst, pSrc, sizeof(Pel)*iWidth);
+    pDst += iDstStride;
+    pSrc += iSrcStride;
+  }
+}
+
+
+
+
+Void TComYuv::copyPartToYuv( TComYuv* pcYuvDst, const UInt uiSrcPartIdx ) const
+{
+  for(Int ch=0; ch<getNumberValidComponents(); ch++)
+    copyPartToComponent  ( ComponentID(ch), pcYuvDst, uiSrcPartIdx );
+}
+
+Void TComYuv::copyPartToComponent( const ComponentID ch, TComYuv* pcYuvDst, const UInt uiSrcPartIdx ) const
+{
+  const Pel* pSrc     = getAddr(ch, uiSrcPartIdx);
+        Pel* pDst     = pcYuvDst->getAddr(ch, 0 );
+
+  const UInt  iSrcStride  = getStride(ch);
+  const UInt  iDstStride  = pcYuvDst->getStride(ch);
+
+  const UInt uiHeight = pcYuvDst->getHeight(ch);
+  const UInt uiWidth = pcYuvDst->getWidth(ch);
+
+  for ( UInt y = uiHeight; y != 0; y-- )
+  {
+    ::memcpy( pDst, pSrc, sizeof(Pel)*uiWidth);
+    pDst += iDstStride;
+    pSrc += iSrcStride;
+  }
+}
+
+
+
+
+Void TComYuv::copyPartToPartYuv   ( TComYuv* pcYuvDst, const UInt uiPartIdx, const UInt iWidth, const UInt iHeight ) const
+{
+  for(Int ch=0; ch<getNumberValidComponents(); ch++)
+    copyPartToPartComponent   (ComponentID(ch), pcYuvDst, uiPartIdx, iWidth>>getComponentScaleX(ComponentID(ch)), iHeight>>getComponentScaleY(ComponentID(ch)) );
+}
+
+Void TComYuv::copyPartToPartComponent  ( const ComponentID ch, TComYuv* pcYuvDst, const UInt uiPartIdx, const UInt iWidthComponent, const UInt iHeightComponent ) const
+{
+  const Pel* pSrc =           getAddr(ch, uiPartIdx);
+        Pel* pDst = pcYuvDst->getAddr(ch, uiPartIdx);
+  if( pSrc == pDst )
+  {
+    //th not a good idea
+    //th best would be to fix the caller
+    return ;
+  }
+
+  const UInt  iSrcStride = getStride(ch);
+  const UInt  iDstStride = pcYuvDst->getStride(ch);
+  for ( UInt y = iHeightComponent; y != 0; y-- )
+  {
+    ::memcpy( pDst, pSrc, iWidthComponent * sizeof(Pel) );
+    pSrc += iSrcStride;
+    pDst += iDstStride;
+  }
+}
+
+
+
+
+Void TComYuv::copyPartToPartComponentMxN  ( const ComponentID ch, TComYuv* pcYuvDst, const TComRectangle &rect) const
+{
+  const Pel* pSrc =           getAddrPix( ch, rect.x0, rect.y0 );
+        Pel* pDst = pcYuvDst->getAddrPix( ch, rect.x0, rect.y0 );
+  if( pSrc == pDst )
+  {
+    //th not a good idea
+    //th best would be to fix the caller
+    return ;
+  }
+
+  const UInt  iSrcStride = getStride(ch);
+  const UInt  iDstStride = pcYuvDst->getStride(ch);
+  const UInt uiHeightComponent=rect.height;
+  const UInt uiWidthComponent=rect.width;
+  for ( UInt y = uiHeightComponent; y != 0; y-- )
+  {
+    ::memcpy( pDst, pSrc, uiWidthComponent * sizeof( Pel ) );
+    pSrc += iSrcStride;
+    pDst += iDstStride;
+  }
+}
+
+
+
+
+Void TComYuv::addClip( const TComYuv* pcYuvSrc0, const TComYuv* pcYuvSrc1, const UInt uiTrUnitIdx, const UInt uiPartSize )
+{
+  for(Int chan=0; chan<getNumberValidComponents(); chan++)
+  {
+    const ComponentID ch=ComponentID(chan);
+    const Int uiPartWidth =uiPartSize>>getComponentScaleX(ch);
+    const Int uiPartHeight=uiPartSize>>getComponentScaleY(ch);
+
+    const Pel* pSrc0 = pcYuvSrc0->getAddr(ch, uiTrUnitIdx, uiPartWidth );
+    const Pel* pSrc1 = pcYuvSrc1->getAddr(ch, uiTrUnitIdx, uiPartWidth );
+          Pel* pDst  = getAddr(ch, uiTrUnitIdx, uiPartWidth );
+
+    const UInt iSrc0Stride = pcYuvSrc0->getStride(ch);
+    const UInt iSrc1Stride = pcYuvSrc1->getStride(ch);
+    const UInt iDstStride  = getStride(ch);
+    const Int clipbd = g_bitDepth[toChannelType(ch)];
+#if O0043_BEST_EFFORT_DECODING
+    const Int bitDepthDelta = g_bitDepthInStream[toChannelType(ch)] - g_bitDepth[toChannelType(ch)];
+#endif
+
+    for ( Int y = uiPartHeight-1; y >= 0; y-- )
+    {
+      for ( Int x = uiPartWidth-1; x >= 0; x-- )
+      {
+#if O0043_BEST_EFFORT_DECODING
+        pDst[x] = Pel(ClipBD<Int>( Int(pSrc0[x]) + rightShiftEvenRounding<Pel>(pSrc1[x], bitDepthDelta), clipbd));
+#else
+        pDst[x] = Pel(ClipBD<Int>( Int(pSrc0[x]) + Int(pSrc1[x]), clipbd));
+#endif
+      }
+      pSrc0 += iSrc0Stride;
+      pSrc1 += iSrc1Stride;
+      pDst  += iDstStride;
+    }
+  }
+}
+
+
+
+
+Void TComYuv::subtract( const TComYuv* pcYuvSrc0, const TComYuv* pcYuvSrc1, const UInt uiTrUnitIdx, const UInt uiPartSize )
+{
+  for(Int chan=0; chan<getNumberValidComponents(); chan++)
+  {
+    const ComponentID ch=ComponentID(chan);
+    const Int uiPartWidth =uiPartSize>>getComponentScaleX(ch);
+    const Int uiPartHeight=uiPartSize>>getComponentScaleY(ch);
+
+    const Pel* pSrc0 = pcYuvSrc0->getAddr( ch, uiTrUnitIdx, uiPartWidth );
+    const Pel* pSrc1 = pcYuvSrc1->getAddr( ch, uiTrUnitIdx, uiPartWidth );
+          Pel* pDst  = getAddr( ch, uiTrUnitIdx, uiPartWidth );
+
+    const Int  iSrc0Stride = pcYuvSrc0->getStride(ch);
+    const Int  iSrc1Stride = pcYuvSrc1->getStride(ch);
+    const Int  iDstStride  = getStride(ch);
+
+    for (Int y = uiPartHeight-1; y >= 0; y-- )
+    {
+      for (Int x = uiPartWidth-1; x >= 0; x-- )
+      {
+        pDst[x] = pSrc0[x] - pSrc1[x];
+      }
+      pSrc0 += iSrc0Stride;
+      pSrc1 += iSrc1Stride;
+      pDst  += iDstStride;
+    }
+  }
+}
+
+
+
+
+Void TComYuv::addAvg( const TComYuv* pcYuvSrc0, const TComYuv* pcYuvSrc1, const UInt iPartUnitIdx, const UInt uiWidth, const UInt uiHeight )
+{
+  for(Int chan=0; chan<getNumberValidComponents(); chan++)
+  {
+    const ComponentID ch=ComponentID(chan);
+    const Pel* pSrc0  = pcYuvSrc0->getAddr( ch, iPartUnitIdx );
+    const Pel* pSrc1  = pcYuvSrc1->getAddr( ch, iPartUnitIdx );
+    Pel* pDst   = getAddr( ch, iPartUnitIdx );
+
+    const UInt  iSrc0Stride = pcYuvSrc0->getStride(ch);
+    const UInt  iSrc1Stride = pcYuvSrc1->getStride(ch);
+    const UInt  iDstStride  = getStride(ch);
+    const Int   clipbd      = g_bitDepth[toChannelType(ch)];
+    const Int   shiftNum    = std::max<Int>(2, (IF_INTERNAL_PREC - clipbd)) + 1;
+    const Int   offset      = ( 1 << ( shiftNum - 1 ) ) + 2 * IF_INTERNAL_OFFS;
+
+    const Int   iWidth      = uiWidth  >> getComponentScaleX(ch);
+    const Int   iHeight     = uiHeight >> getComponentScaleY(ch);
+
+    if (iWidth&1)
+    {
+      assert(0);
+      exit(-1);
+    }
+    else if (iWidth&2)
+    {
+      for ( Int y = 0; y < iHeight; y++ )
+      {
+        for (Int x=0 ; x < iWidth; x+=2 )
+        {
+          pDst[ x + 0 ] = ClipBD( rightShift(( pSrc0[ x + 0 ] + pSrc1[ x + 0 ] + offset ), shiftNum), clipbd );
+          pDst[ x + 1 ] = ClipBD( rightShift(( pSrc0[ x + 1 ] + pSrc1[ x + 1 ] + offset ), shiftNum), clipbd );
+        }
+        pSrc0 += iSrc0Stride;
+        pSrc1 += iSrc1Stride;
+        pDst  += iDstStride;
+      }
+    }
+    else
+    {
+      for ( Int y = 0; y < iHeight; y++ )
+      {
+        for (Int x=0 ; x < iWidth; x+=4 )
+        {
+          pDst[ x + 0 ] = ClipBD( rightShift(( pSrc0[ x + 0 ] + pSrc1[ x + 0 ] + offset ), shiftNum), clipbd );
+          pDst[ x + 1 ] = ClipBD( rightShift(( pSrc0[ x + 1 ] + pSrc1[ x + 1 ] + offset ), shiftNum), clipbd );
+          pDst[ x + 2 ] = ClipBD( rightShift(( pSrc0[ x + 2 ] + pSrc1[ x + 2 ] + offset ), shiftNum), clipbd );
+          pDst[ x + 3 ] = ClipBD( rightShift(( pSrc0[ x + 3 ] + pSrc1[ x + 3 ] + offset ), shiftNum), clipbd );
+        }
+        pSrc0 += iSrc0Stride;
+        pSrc1 += iSrc1Stride;
+        pDst  += iDstStride;
+      }
+    }
+  }
+}
+
+Void TComYuv::removeHighFreq( const TComYuv* pcYuvSrc, const UInt uiPartIdx, const UInt uiWidth, UInt const uiHeight )
+{
+  for(Int chan=0; chan<getNumberValidComponents(); chan++)
+  {
+    const ComponentID ch=ComponentID(chan);
+#if !DISABLING_CLIP_FOR_BIPREDME
+    const ChannelType chType=toChannelType(ch);
+#endif
+
+    const Pel* pSrc  = pcYuvSrc->getAddr(ch, uiPartIdx);
+    Pel* pDst  = getAddr(ch, uiPartIdx);
+
+    const Int iSrcStride = pcYuvSrc->getStride(ch);
+    const Int iDstStride = getStride(ch);
+    const Int iWidth  = uiWidth >>getComponentScaleX(ch);
+    const Int iHeight = uiHeight>>getComponentScaleY(ch);
+
+    for ( Int y = iHeight-1; y >= 0; y-- )
+    {
+      for ( Int x = iWidth-1; x >= 0; x-- )
+      {
+#if DISABLING_CLIP_FOR_BIPREDME
+        pDst[x ] = (2 * pDst[x]) - pSrc[x];
+#else
+        pDst[x ] = Clip((2 * pDst[x]) - pSrc[x], chType);
+#endif
+      }
+      pSrc += iSrcStride;
+      pDst += iDstStride;
+    }
+  }
+}
+
+//! \}
Index: /tags/SHM-9.0/source/Lib/TLibCommon/TComYuv.h
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibCommon/TComYuv.h	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibCommon/TComYuv.h	(revision 1088)
@@ -0,0 +1,207 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TComYuv.h
+    \brief    general YUV buffer class (header)
+    \todo     this should be merged with TComPicYuv \n
+              check usage of removeHighFreq function
+*/
+
+#ifndef __TCOMYUV__
+#define __TCOMYUV__
+#include <assert.h>
+#include "CommonDef.h"
+#include "TComPicYuv.h"
+#include "TComRectangle.h"
+
+//! \ingroup TLibCommon
+//! \{
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// general YUV buffer class
+class TComYuv
+{
+private:
+
+  // ------------------------------------------------------------------------------------------------------------------
+  //  YUV buffer
+  // ------------------------------------------------------------------------------------------------------------------
+
+  Pel*    m_apiBuf[MAX_NUM_COMPONENT];
+
+  // ------------------------------------------------------------------------------------------------------------------
+  //  Parameter for general YUV buffer usage
+  // ------------------------------------------------------------------------------------------------------------------
+
+  UInt     m_iWidth;
+  UInt     m_iHeight;
+  ChromaFormat m_chromaFormatIDC; ////< Chroma Format
+
+  // dims 16x16
+  // blkSize=4x4
+
+  // these functions assume a square CU, of size width*width, split into square TUs each of size blkSize*blkSize.
+  // iTransUnitIdx is the raster-scanned index of the sub-block (TU) in question.
+  // eg for a 16x16 CU, with 4x4 TUs:
+  //  0  1  2  3
+  //  4  5  6  7
+  //  8  9 10 11
+  // 12 13 14 15
+
+  // So, for iTransUnitIdx=14, 14*4 & 15 =8=X offset.
+  //                           14*4 / 16 =3=Y block offset
+  //                                      3*4*16 = Y offset within buffer
+
+
+public:
+
+               TComYuv                    ();
+  virtual     ~TComYuv                    ();
+
+  // ------------------------------------------------------------------------------------------------------------------
+  //  Memory management
+  // ------------------------------------------------------------------------------------------------------------------
+
+  Void         create                     ( const UInt iWidth, const UInt iHeight, const ChromaFormat chromaFormatIDC );  ///< 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, const UInt ctuRsAddr, const UInt uiAbsZorderIdx, const UInt uiPartDepth = 0, const UInt uiPartIdx = 0 ) const ;
+  Void         copyToPicComponent         ( const ComponentID id, TComPicYuv* pcPicYuvDst, const UInt iCtuRsAddr, const UInt uiAbsZorderIdx, const UInt uiPartDepth = 0, const UInt uiPartIdx = 0 ) const ;
+
+  //  Copy YUV buffer from picture buffer
+  Void         copyFromPicYuv             ( const TComPicYuv* pcPicYuvSrc, const  UInt ctuRsAddr, const UInt uiAbsZorderIdx );
+  Void         copyFromPicComponent       ( const ComponentID id, const TComPicYuv* pcPicYuvSrc, const UInt iCtuRsAddr, const UInt uiAbsZorderIdx );
+
+  //  Copy Small YUV buffer to the part of other Big YUV buffer
+  Void         copyToPartYuv              ( TComYuv*    pcYuvDst,    const UInt uiDstPartIdx ) const ;
+  Void         copyToPartComponent        ( const ComponentID id, TComYuv*    pcYuvDst,    const UInt uiDstPartIdx ) const ;
+
+  //  Copy the part of Big YUV buffer to other Small YUV buffer
+  Void         copyPartToYuv              ( TComYuv*    pcYuvDst,   const UInt uiSrcPartIdx ) const;
+  Void         copyPartToComponent        ( const ComponentID id, TComYuv*    pcYuvDst,    const UInt uiSrcPartIdx ) const;
+
+  //  Copy YUV partition buffer to other YUV partition buffer
+  Void         copyPartToPartYuv          ( TComYuv*    pcYuvDst, const UInt uiPartIdx, const UInt uiWidth, const UInt uiHeight ) const;
+  Void         copyPartToPartComponent    ( const ComponentID id, TComYuv*    pcYuvDst, const UInt uiPartIdx, const UInt uiWidthComponent, const UInt uiHeightComponent ) const;
+
+ // Copy YUV partition buffer to other YUV partition buffer for non-square blocks
+  Void         copyPartToPartComponentMxN ( const ComponentID id, TComYuv*    pcYuvDst, const TComRectangle &rect ) const;
+
+  // ------------------------------------------------------------------------------------------------------------------
+  //  Algebraic operation for YUV buffer
+  // ------------------------------------------------------------------------------------------------------------------
+
+  //  Clip(pcYuvSrc0 + pcYuvSrc1) -> m_apiBuf
+  Void         addClip                    ( const TComYuv* pcYuvSrc0, const TComYuv* pcYuvSrc1, const UInt uiTrUnitIdx, const UInt uiPartSize );
+
+  //  pcYuvSrc0 - pcYuvSrc1 -> m_apiBuf
+  Void         subtract                   ( const TComYuv* pcYuvSrc0, const TComYuv* pcYuvSrc1, const UInt uiTrUnitIdx, const UInt uiPartSize );
+
+  //  (pcYuvSrc0 + pcYuvSrc1)/2 for YUV partition
+  Void         addAvg                     ( const TComYuv* pcYuvSrc0, const TComYuv* pcYuvSrc1, const UInt iPartUnitIdx, const UInt iWidth, const UInt iHeight );
+
+  Void         removeHighFreq             ( const TComYuv* pcYuvSrc, const UInt uiPartIdx, const UInt uiWidth, const UInt uiHeight );
+
+  // ------------------------------------------------------------------------------------------------------------------
+  //  Access function for YUV buffer
+  // ------------------------------------------------------------------------------------------------------------------
+
+  //  Access starting position of YUV buffer
+  Pel*         getAddr                    (const ComponentID id)                    { return m_apiBuf[id]; }
+  const Pel*   getAddr                    (const ComponentID id) const              { return m_apiBuf[id]; }
+
+  //  Access starting position of YUV partition unit buffer
+  Pel*         getAddr                    (const ComponentID id, const UInt uiPartUnitIdx)
+                                              {
+                                                  Int blkX = g_auiRasterToPelX[ g_auiZscanToRaster[ uiPartUnitIdx ] ] >> getComponentScaleX(id);
+                                                  Int blkY = g_auiRasterToPelY[ g_auiZscanToRaster[ uiPartUnitIdx ] ] >> getComponentScaleY(id);
+                                                  assert((blkX<getWidth(id) && blkY<getHeight(id)));
+                                                  return m_apiBuf[id] + blkX + blkY * getStride(id);
+                                              }
+  const Pel*   getAddr                    (const ComponentID id, const UInt uiPartUnitIdx) const
+                                              {
+                                                  Int blkX = g_auiRasterToPelX[ g_auiZscanToRaster[ uiPartUnitIdx ] ] >> getComponentScaleX(id);
+                                                  Int blkY = g_auiRasterToPelY[ g_auiZscanToRaster[ uiPartUnitIdx ] ] >> getComponentScaleY(id);
+                                                  assert((blkX<getWidth(id) && blkY<getHeight(id)));
+                                                  return m_apiBuf[id] + blkX + blkY * getStride(id);
+                                              }
+
+  //  Access starting position of YUV transform unit buffer
+  Pel*         getAddr                    (const ComponentID id, const UInt iTransUnitIdx, const UInt iBlkSizeForComponent)
+                                              {
+                                                UInt width=getWidth(id);
+                                                Int blkX = ( iTransUnitIdx * iBlkSizeForComponent ) &  ( width - 1 );
+                                                Int blkY = ( iTransUnitIdx * iBlkSizeForComponent ) &~ ( width - 1 );
+                                                if (m_chromaFormatIDC==CHROMA_422 && id!=COMPONENT_Y) blkY<<=1;
+//                                                assert((blkX<getWidth(id) && blkY<getHeight(id)));
+                                                return m_apiBuf[id] + blkX + blkY * iBlkSizeForComponent;
+                                              }
+
+  const Pel*   getAddr                    (const ComponentID id, const UInt iTransUnitIdx, const UInt iBlkSizeForComponent) const
+                                              {
+                                                UInt width=getWidth(id);
+                                                Int blkX = ( iTransUnitIdx * iBlkSizeForComponent ) &  ( width - 1 );
+                                                Int blkY = ( iTransUnitIdx * iBlkSizeForComponent ) &~ ( width - 1 );
+                                                if (m_chromaFormatIDC==CHROMA_422 && id!=COMPONENT_Y) blkY<<=1;
+//                                                UInt w=getWidth(id), h=getHeight(id);
+//                                                assert((blkX<w && blkY<h));
+                                                return m_apiBuf[id] + blkX + blkY * iBlkSizeForComponent;
+                                              }
+
+  // Access starting position of YUV transform unit buffer by pix offset for square & non-square blocks
+  Pel*         getAddrPix                 (const ComponentID id, const UInt iPixX, const UInt iPixY )       { return m_apiBuf[id] + iPixY * getStride(id) + iPixX; }
+  const Pel*   getAddrPix                 (const ComponentID id, const UInt iPixX, const UInt iPixY ) const { return m_apiBuf[id] + iPixY * getStride(id) + iPixX; }
+
+  //  Get stride value of YUV buffer
+  UInt         getStride                  (const ComponentID id) const { return m_iWidth >> getComponentScaleX(id);   }
+  UInt         getHeight                  (const ComponentID id) const { return m_iHeight >> getComponentScaleY(id);  }
+  UInt         getWidth                   (const ComponentID id) const { return m_iWidth >> getComponentScaleX(id);   }
+  ChromaFormat getChromaFormat            ()                     const { return m_chromaFormatIDC; }
+  UInt         getNumberValidComponents   ()                     const { return ::getNumberValidComponents(m_chromaFormatIDC); }
+  UInt         getComponentScaleX         (const ComponentID id) const { return ::getComponentScaleX(id, m_chromaFormatIDC); }
+  UInt         getComponentScaleY         (const ComponentID id) const { return ::getComponentScaleY(id, m_chromaFormatIDC); }
+
+};// END CLASS DEFINITION TComYuv
+
+//! \}
+
+#endif // __TCOMYUV__
Index: /tags/SHM-9.0/source/Lib/TLibCommon/TypeDef.h
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibCommon/TypeDef.h	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibCommon/TypeDef.h	(revision 1088)
@@ -0,0 +1,1159 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TypeDef.h
+    \brief    Define basic types, new types and enumerations
+*/
+
+#ifndef __TYPEDEF__
+#define __TYPEDEF__
+
+#include <vector>
+
+#define SVC_EXTENSION                    1
+
+#if SVC_EXTENSION
+#define MAX_LAYERS                       8      ///< max number of layers the codec is supposed to handle
+#define O0215_PHASE_ALIGNMENT_REMOVAL    1
+#define CONFORMANCE_BITSTREAM_MODE       1      ///< In order to generate the metadata related to conformance bitstreams
+#define FIX_CONF_MODE                    1
+#define FIX_NON_OUTPUT_LAYER             1
+#define SIGNALLING_BITRATE_PICRATE_FIX   1      ///< Fix for signalling of bitrate and picture rate info in VPS VUI to be more aligned to JCTVC-R1008
+#define INFERENCE_POC_MSB_VAL_PRESENT    1      ///< JCTVC-Q0146 -- poc_msb_val_present_flag shall be equal to 0 when slice_header_extension_length is (inferred to be ) equal to 0
+#define CROSS_LAYER_BLA_FLAG_FIX         1      ///< Fix for earlier implementation mistake that omit the signalling of cross_layer_bla_flag
+#define NON_REF_NAL_TYPE_DISCARDABLE     1      ///< JCTVC-P0041 -- If discardable picture is a non-IRAP, it must be a non-referenced sub-layer picture
+#define VPS_AVC_BL_FLAG_REMOVAL          1      ///< remove avc_base_layer_flag and direct the function its offer to vps_base_layer_internal_flag and vps_base_layer_available_flag
+#define VPS_RESERVED_FLAGS               1      ///< vps_base_layer_internal_flag and vps_base_layer_available_flag
+#define VPS_VUI_VST_PARAMS               1      ///< JCTVC-R0227: Related to signalling of VST parameters of the base layer.
+#define VPS_VUI_OFFSET                   1      ///< N0085: Signal VPS VUI offset in the VPS extension 
+#define REMOVE_BSP_HRD_SEI               1      ///< R0010: Remove bitstream partition HRD SEI message.
+#define NESTING_SEI_EXTENSIBILITY        1      ///< R0221: Signalling the number of SEI messages in bitstream partition nesting SEI message
+#define POC_RESET_RESTRICTIONS           1      ///< Restrictions on semantics of POC reset-related syntax elements, including one item from R0223
+#define POC_RESET_VALUE_RESTRICTION      1      ///< R0223: Restriction on the value of full_poc_reset_flag
+#define OUTPUT_LAYER_SETS_CONFIG         1
+#define MOVE_ADDN_LS_SIGNALLING          1      ///< JCTVC-R0238: (Ed.) Move additional layer set signalling in VPS extn.
+#define PTL_SIGNALLING                   1      ///< Overall macro for all PTL-related signalling
+#if PTL_SIGNALLING
+#define LIST_OF_PTL                      1      ///< JCTVC-R0272: Signalling the PTL for the 0-th OLS
+#define NECESSARY_LAYER_FLAG             1      ////< Derivation of NecessaryLayerFlag
+#define PER_LAYER_PTL                    1      ///< Signal profile-tier-level information for each layer.
+#endif
+#define BSP_INIT_ARRIVAL_SEI             1      ///< JCTVC-R0231: Make signalling of vcl_initial_arrival_delay independent of NalHrdBpPresentFlag
+#define SUB_LAYERS_IN_LAYER_SET          1      ///< Move calculation of MaxSubLayerInLayerSets to a separate function
+#define VPS_VUI_BSP_HRD_PARAMS           1      ///< JCTVC-R0231: Define the VPS VUI BSP hrd_params() as a separate function, and apply changes adopted.
+#define O0137_MAX_LAYERID                1      ///< JCTVC-O0137, JCTVC-O0200, JCTVC-O0223: restrict nuh_layer_id and vps_max_layers_minus1
+
+#define R0226_CONSTRAINT_TMVP_SEI        1      ///< JCTVC-R0226, Modification to semantics in temporal motion vector prediction constraints SEI message
+#define R0226_SLICE_TMVP                 1      ///< JCTVC-R0226, Regarding slice_temporal_mvp_enabled_flag
+#define R0279_REP_FORMAT_INBL            1      ///< JCTVC-R0279, For any independent non-base layer the used representation format is the one that is signalled in the active SPS for the layer
+#define R0227_VUI_BSP_HRD_FLAG           1      ///< JCTVC-R0227, Conformance checking such that VPS VUI HRD only present if VPS timing info is signalled
+#define R0227_REP_FORMAT_CONSTRAINT      1      ///< JCTVC-R0227, Conformance checking such that representation format of a particular layer shall not be greater than the one defined in VPS for that layer
+#define R0227_BR_PR_ADD_LAYER_SET        1      ///< JCTVC-R0227, Signalling of bit-rate and picture rate for additional layer set
+#define R0042_PROFILE_INDICATION         1      ///< JCTVC-R0042, Profile indication for additional layer sets
+#define R0235_SMALLEST_LAYER_ID          1      ///< JCTVC-R0235, SmallestLayerId semantics 
+
+#define Q0108_TSA_STSA                   1      ///< JCTVC-Q0108, Remove cross-layer alignment constraints of TSA and STSA pictures, enable to have different prediction structures in different layers
+#define Q0177_SPS_TEMP_NESTING_FIX       1      ///< JCTVC-Q0177; Fix the inference value of sps_temporal_id_nesting_flag when it is not present
+#define Q0177_EOS_CHECKS                 1      ///< JCTVC-Q0177; Put checks on handling EOS
+#define Q0142_POC_LSB_NOT_PRESENT        1      ///< JCTVC-Q0142; Add constraint checking on the value of poc_reset_idc and poc_lsb_val
+#define Q0146_SSH_EXT_DATA_BIT           1      ///< JCTVC-Q0146; Bug-fix -- the SSH_EXT_DATA_BIT can have any value -- not required to be 1
+
+#define P0130_EOB                        1      ///< JCTVC-P0130, set layer Id of EOB NALU to be fixed to 0
+#define T_ID_EOB_BUG_FIX                 1      ///< Bug fix for the value of temporal id of EOB NALU. It must be set to 0
+#define P0307_REMOVE_VPS_VUI_OFFSET      1      ///< JCTVC-P0307, remove implementation related to VPS VUI offset signalling
+#define P0307_VPS_NON_VUI_EXTENSION      1      ///< JCTVC-P0307, implementation related to NON VUI VPS Extension signalling
+#define P0307_VPS_NON_VUI_EXT_UPDATE     1      ///< JCTVC-P0307, implementation related to NON VUI VPS Extension signalling
+
+#define DISCARDABLE_PIC_RPS              1      ///< JCTVC-P0130: Inter-layer RPS and temporal RPS should not contain picture with discardable_flag equal to 1
+#define VPS_EXTN_UEV_CODING              1      ///< JCTVC-P0306: Code some syntax elements as ue(v), and remove some syntax elements that duplicate behaviour
+#define CHANGE_NUMSUBDPB_IDX             1      ///< Change index of NumSubDpb from output layer set to layer set, to be more aligned with the Spec
+#define RESOLUTION_BASED_DPB             0      ///< JCTVC-Q0154 - remove sharing of sub-DPB across layers
+                                                ///< JCTVC-P0192: Assign layers to sub-DPBs based on the rep_format() signaled in the VPS
+#define ALIGNED_BUMPING                  1      ///< JCTVC-P0192: Align bumping of pictures in an AU
+#define FIX_ALIGN_BUMPING                1
+#define O0109_O0199_FLAGS_TO_VUI         1      ///< JCTVC-O0109, O0199: move single_layer_for_non_irap_flag and higher_layer_flag to vps_vui
+#define O0109_VIEW_ID_LEN                1      ///< JCTVC-O0109: view_id_len_minus1 to view_id_len, and add constraint (1<<view_id_len) is greater than or equal to NumViews
+
+#define P0048_REMOVE_PROFILE_REF         1      ///< JCTVC-P0048: remove profile_ref_minus1
+#if !P0048_REMOVE_PROFILE_REF
+#define O0109_PROF_REF_MINUS1            1      ///< JCTVC-O0109: constraint that profile_ref_minus1[i] shall be less than or equal to i
+#endif
+
+#define P0295_DEFAULT_OUT_LAYER_IDC      1      ///< JCTVC-P0295: modifify default_one_target_output_layer_idc to default_output_layer_idc
+#define O0109_DEFAULT_ONE_OUT_LAYER_IDC  1      ///< JCTVC-O0109: default_one_target_output_layer_flag to default_one_target_output_layer_idc
+#define O0109_MOVE_VPS_VUI_FLAG          1      ///< JCTVC-O0109: move vps_vui_present_flag before vps_vui_offset
+
+#define O0135_DEFAULT_ONE_OUT_SEMANTIC   1      ///< JCTVC-O0135: semantics change of default_one_target_output_layer_idc for auxiliary pictures
+
+#define O0164_MULTI_LAYER_HRD            1      ///< JCTVC-O0164: Multi-layer HRD operation
+#define Q0182_MULTI_LAYER_HRD_UPDATE     1      ///< JCTVC-Q0182: On bitstream partition buffering
+
+#define O0194_DIFFERENT_BITDEPTH_EL_BL   1      ///< JCTVC-O0194: Support for different bitdepth values for BL and EL, add required configuration parameters (and Some bugfixes when REPN_FORMAT_IN_VPS (JCTVC-N0092) is enabled)
+#if O0194_DIFFERENT_BITDEPTH_EL_BL
+#define O0194_JOINT_US_BITSHIFT          1      ///< JCTVC-O0194: Joint Upsampling and bit-shift
+#endif
+#define Q0048_CGS_3D_ASYMLUT             1      ///< JCTVC-Q0048: Colour gamut scalability with look-up table
+#if Q0048_CGS_3D_ASYMLUT
+#define CGS_GCC_NO_VECTORIZATION         1
+#define R0150_CGS_SIGNAL_CONSTRAINTS     1      ///< JCTVC-R0150: CGS signaling improvement and constraints
+#define R0151_CGS_3D_ASYMLUT_IMPROVE     1      ///< JCTVC-R0151: Non-uniform chroma partitioning and improved LUT coefficient coding
+#define R0164_CGS_LUT_BUGFIX             1      ///< JCTVC-R0164: Bug fix with LUT syntax
+#define R0164_CGS_LUT_BUGFIX_CHECK       0      ///< JCTVC-R0164: Add traces explicitly/non-explicitly encoded vertices and check if 3DLUT is correctly filled
+#define R0179_CGS_SIZE_8x1x1             1      ///< JCTVC-R0179: allow CGS LUT size to be 8x1x1 as well 
+#define R0300_CGS_RES_COEFF_CODING       1      ///< JCTVC-R0300: improved residual coefficient coding for R0151
+#define R0179_ENC_OPT_3DLUT_SIZE         0      ///< JCTVC-R0179: RD decision based LUT size selection 
+#endif
+#define O0194_WEIGHTED_PREDICTION_CGS    1      ///< JCTVC-O0194: Weighted prediction for colour gamut scalability
+#define POC_RESET_FLAG                   0      ///< JCTVC-N0244: POC reset flag for  layer pictures.
+#define POC_RESET_IDC                    1      ///< JCTVC-P0041: Include poc_reset_idc and related derivation - eventually will replace POC_RESET_FLAG
+#if POC_RESET_IDC
+#define POC_RESET_IDC_SIGNALLING         1      ///< JCTVC-P0041: Include signalling for poc_reset related syntax elements
+#define POC_RESET_IDC_ENCODER            1      ///< JCTVC-P0041: Include support of enabling POC reset at the encoder
+#define POC_RESET_IDC_DECODER            1      ///< JCTVC-P0041: Include support of enabling POC reset at the decoder
+#define ALIGN_IRAP_BUGFIX                1
+#define UNAVAILABLE_PIC_BUGFIX           1
+#endif
+#if INFERENCE_POC_MSB_VAL_PRESENT
+#define POC_MSB_VAL_PRESENT_FLAG_SEM     0      ///< JCTVC-Q0146: Inference of poc_msb_val_present_flag
+#else
+#define POC_MSB_VAL_PRESENT_FLAG_SEM     1      ///< JCTVC-Q0146: Inference of poc_msb_val_present_flag
+#endif
+#define POC_RESET_INFO_INFERENCE         1      ///< JCTVC-Q0146: Infer the value of poc_reset_info_present_flag when not present
+#define NO_OUTPUT_OF_PRIOR_PICS          1      ///< Use no_output_of_prior_pics_flag
+#define REPN_FORMAT_IN_VPS               1      ///< JCTVC-N0092: Signal represenation format (spatial resolution, bit depth, colour format) in the VPS
+#if REPN_FORMAT_IN_VPS
+#define REPN_FORMAT_CONTROL_FLAG         1      ///< JCTVC-O0179: Add control flag in representation format to control sending of chroma and bitdepth parameters
+#endif 
+#define RPL_INIT_N0316_N0082             1      ///< JCTVC-N0316, JCTVC-N0082: initial reference picture list construction 
+
+#define SCALINGLIST_INFERRING            1      ///< JCTVC-N0371: inter-layer scaling list
+#define O0142_CONDITIONAL_SPS_EXTENSION  1      ///< JCTVC-O0142: Conditional SPS extension
+#if POC_RESET_FLAG
+#define PREVTID0_POC_RESET               1      ///< JCTVC-O0117 Modification of the PicOrderCntVal of prevTid0Pic
+#define POC_RESET_RPS                    1      ///< JCTVC-O0117 Modification to the decoding process for rps
+#endif
+
+#define P0297_VPS_POC_LSB_ALIGNED_FLAG   1      ///< JCTVC-P0297: vps_poc_lsb_aligned_flag for cross-layer POC anchor picture derivation
+
+#define VPS_EXTN_MASK_AND_DIM_INFO       1      ///< Include avc_base_layer_flag, splitting_flag, scalability mask and dimension related info
+#if VPS_EXTN_MASK_AND_DIM_INFO
+#define MAX_VPS_NUM_SCALABILITY_TYPES    16
+#endif
+#define VPS_EXTN_OP_LAYER_SETS           1      ///< Include output layer sets in VPS extension
+#define VPS_EXTN_PROFILE_INFO            1      ///< Include profile information for layer sets in VPS extension
+#define VPS_EXTN_DIRECT_REF_LAYERS       1      ///< Include indication of direct dependency of layers in VPS extension
+#define M0040_ADAPTIVE_RESOLUTION_CHANGE 1
+#define R0071_IRAP_EOS_CROSS_LAYER_IMPACTS 1
+
+#define VPS_VUI_TILES_NOT_IN_USE__FLAG   1      ///< JCTVC-O0226: VPS VUI flag to indicate tile not in use
+#define VPS_VUI_WPP_NOT_IN_USE__FLAG     1      ///< JCTVC-O0226: VPS VUI flag to indicate tile not in use
+#define N0160_VUI_EXT_ILP_REF            1      ///< VUI extension inter-layer dependency offset signalling
+#if M0040_ADAPTIVE_RESOLUTION_CHANGE
+#define HIGHER_LAYER_IRAP_SKIP_FLAG      1      ///< JCTVC-O0199: Indication that higher layer IRAP picture uses skip blocks only
+#endif
+#define VPS_VUI_VIDEO_SIGNAL             1      ///< JCTVC-O0118 video signal information
+#if VPS_VUI_VIDEO_SIGNAL
+#define VPS_VUI_VIDEO_SIGNAL_MOVE        1      ///< JCTVC-P0076 Move video signal information syntax structure earlier in the VPS VUI
+#endif 
+#define P0182_VPS_VUI_PS_FLAG            1      ///< JCTVC-P0182, add base_layer_parameter_set_compatibility_flag
+
+#define P0125_REVERT_VPS_EXTN_OFFSET_TO_RESERVED        1   ///< JCTVC-P0125 -- Keep it as a reserved FFFF value --- The following two macros (VPS_EXTN_OFFSET & VPS_EXTN_OFFSET_CALC) will have no effect when this macro is set to 1.
+#define VPS_EXTN_OFFSET                  1      ///< implementation of vps_extension_offset syntax element
+#define VPS_EXTN_OFFSET_CALC             1      ///< Calculation of VPS extension offset
+#define SPS_PTL_FIX                      1      ///< remove profile_tier_level from enhancement layer SPS
+
+#define DERIVE_LAYER_ID_LIST_VARIABLES   1      ///< Derived variables based on the variables in VPS - for use in syntax table parsing
+#define FIX_LAYER_ID_INIT                1
+
+#define AVC_BASE                         1      ///< YUV BL reading for AVC base SVC
+
+#define REF_IDX_MFM                      1      ///< JCTVC-L0336: motion vector mapping of inter-layer reference picture
+#define MAX_ONE_RESAMPLING_DIRECT_LAYERS 1      ///< Allow maximum of one resampling process for direct reference layers
+#define MOTION_RESAMPLING_CONSTRAINT     1      ///< JCTVC-N0108: Allow maximum of one motion resampling process for direct reference layers, and use motion inter-layer prediction from the same layer as texture inter-layer prediction.
+#define EARLY_REF_PIC_MARKING            0      ///< Valencia meeting - remove early marking of inter-layer reference pictures
+                                                ///< Decoded picture marking of sub-layer non-reference pictures
+#define O0225_TID_BASED_IL_RPS_DERIV     1
+#define VPS_TSLAYERS                     1      ///< JCTVC-O0120 signal max temporal sub-layers for each layer
+#define TSLAYERS_IL_RPS                  1      ///< JCTVC-O0120 IL RPS based on max temporal sub-layers
+#define P0079_DERIVE_NUMACTIVE_REF_PICS  1      ///< JCTVC-P0079 Modification of derivation of variable NumActiveRefLayerPics
+#define Q0060_MAX_TID_REF_EQUAL_TO_ZERO  1      ///< JCTVC-Q0060 handling the case max_tid_il_ref_pics_plus1 is equal to 0.
+
+#define O0223_PICTURE_TYPES_ALIGN_FLAG   1      ///< a flag to indicatate whether picture types are aligned across layers.
+
+#define P0068_CROSS_LAYER_ALIGNED_IDR_ONLY_FOR_IRAP_FLAG   1  ///< a flag to indicatate whether picture types for IRAP are IDR across layers.
+
+#define IRAP_ALIGN_FLAG_IN_VPS_VUI       1      ///< Move IRAP align flag to VPS VUI 
+
+#define VIEW_ID_RELATED_SIGNALING        1      ///< Introduce syntax elements view_id and view_id_val
+#define N0065_LAYER_POC_ALIGNMENT        1
+#if !O0215_PHASE_ALIGNMENT_REMOVAL
+#define O0215_PHASE_ALIGNMENT            1      ///< JCTVC_O0215: signal a flag to specify phase alignment case, 0: zero-position-aligned, 1: central-position-aligned,
+#endif
+#define AUXILIARY_PICTURES               1      ///< JCTVC-O0041: auxiliary picture layers
+#define R0062_AUX_PSEUDO_MONOCHROME      1      ///> JCVVC-R0063: pseudo monochrome for auxiliary pictures
+
+#define O0062_POC_LSB_NOT_PRESENT_FLAG   1      ///< JCTVC-O0062: signal poc_lsb_not_present_flag for each layer in VPS extension
+#define SHM_FIX7                         1      ///< fix for SHVC WD ticket #7
+
+#define O0092_0094_DEPENDENCY_CONSTRAINT 1      ///< JCTVC-O0092: constraint on the layer_id of SPS/PPS
+#if O0092_0094_DEPENDENCY_CONSTRAINT
+#define MAX_REF_LAYERS                   7
+#endif
+#define O0096_REP_FORMAT_INDEX           1      ///< JCTVC-O0096: identify SPS rep_format() with an index into the lists of formats in VPS extension.
+#define O0096_DEFAULT_DEPENDENCY_TYPE    1      ///< JCTVC-O0096: specify default dependency type for all direct reference layers
+
+#define Q0195_REP_FORMAT_CLEANUP         1      ///< JCTVC-Q0195: restructureing of rep_format() signaling
+
+#define R0156_CONF_WINDOW_IN_REP_FORMAT  O0096_REP_FORMAT_INDEX ///< JCTVC-R0156: add conformance window cropping offsets to rep_format()
+
+#define RESAMPLING_CONSTRAINT_BUG_FIX    1
+#define O0098_SCALED_REF_LAYER_ID        1      ///< JCTVC-O0098: signal scaled reference id
+
+#define O0153_ALT_OUTPUT_LAYER_FLAG      1      ///< JCTVC-O0153: alt output layer flag
+#define P0300_ALT_OUTPUT_LAYER_FLAG      1      ///< JCTVC-P0300: alt output layer flag
+
+#define Q0165_OUTPUT_LAYER_SET           1      ///< JCTVC-Q0165: add a constraint to disallow an empty output layer set
+#define Q0165_NUM_ADD_OUTPUT_LAYER_SETS  1      ///< JCTVC-Q0165: signal num_add_olss and default_target_output_layer_idc when vps_num_layer_sets_minus1 is greater than 0
+
+#define Q0078_ADD_LAYER_SETS             1      ///< JCTVC-Q0078: additional layer sets and layer set config
+#if Q0078_ADD_LAYER_SETS
+#define MAX_NUM_ADD_LAYER_SETS           1023
+#endif
+#define MULTIPLE_PTL_SUPPORT             1      ///< Profile, tier and level signalling
+
+#define VPS_DPB_SIZE_TABLE               1      ///< JCTVC-O0217: DPB operations: signaling DPB-related parameters
+#if VPS_DPB_SIZE_TABLE 
+#define OUTPUT_LAYER_SET_INDEX           1      ///< JCTVC-O0217: DPB operations: Inference/input of output layer set index
+#if OUTPUT_LAYER_SET_INDEX
+#define USE_DPB_SIZE_TABLE               1      ///< JCTVC-O0217: DPB operations: Use signaled DPB-size table parameters in the decoder
+#endif
+#endif
+#define SPS_DPB_PARAMS                   1      ///< JCTVC-P0155 signaling & inferrence for sps dpb parameters for nuh_layer_id > 0
+#define DPB_PARAMS_MAXTLAYERS            1      ///< JCTVC-P0156 DPB parameters up to maximum temporal sub-layers in the layer set
+#define NUM_OL_FLAGS                     1      ///< JCTVC-P0156 output_layer_flag[ i ][ j ] is signalled for j equal to 0 to NumLayersInIdList[ lsIdx ] inclusive
+#define NO_CLRAS_OUTPUT_FLAG             1
+#define O0149_CROSS_LAYER_BLA_FLAG       1      ///< JCTVC-O0149: signal cross_layer_bla_flag in slice header
+
+#define P0138_USE_ALT_CPB_PARAMS_FLAG    1      ///< JCTVC-P0138: use_alt_cpb_params_flag syntax in buffering period SEI message extension
+#define P0166_MODIFIED_PPS_EXTENSION     1      ///< JCTVC-P0166: add pps_extension_type_flag
+#define BITRATE_PICRATE_SIGNALLING       1      ///< JCTVC-Q0102 Proposal 3 signal bitrate, picrate only up to the maximum temporal sub-layers in the corresponding layer set
+#define LAYER_DECPICBUFF_PARAM           1      ///< JCTVC-Q0102 Proposal 2 infer value from layer DPB param
+#define HRD_BPB                          1      ///< JCTVC-Q0101 Bitstream Partition Buffering Proposals
+#define DPB_CONSTRAINTS                  1      ///< JCTVC-Q0100 RPS DPB constraints
+#define DPB_INTERNAL_BL_SIG              1      ///< JCTVC-R0153: external base layer
+#define ALT_OPT_LAYER_FLAG               1      ///< JCTVC-R0154: proposal1 - alt_output_layer_flag[i] inference
+#define DEF_OPT_LAYER_IDC                1      ///< JCTVC-R0154: proposal2 - default_output_layer_idc and output_layer_flag[i][j]
+#define ISLICE_TYPE_NUMDIR               1      ///< JCTVC-R0155: Proposal 1 I slice_type
+#define OLS_IDX_CHK                      1      ///< JCTVC-R0155: Proposal 2 valid range for output_layer_set_idx_to_vps[i]
+#define R0340_RESAMPLING_MODIFICATION    1      ///< JCTVC-R0340: set of changes regarding resampling (as listed below)
+#if R0340_RESAMPLING_MODIFICATION
+#define MOVE_SCALED_OFFSET_TO_PPS        1      ///< JCTVC-R0013: move scaled reference layer offset from SPS to PPS
+#if MOVE_SCALED_OFFSET_TO_PPS
+#define REF_REGION_OFFSET                1      ///< JCTVC-Q0159/R0220: reference region offset
+#define R0209_GENERIC_PHASE              1      ///< JCTVC-R0209: resampling with generic phase
+#define R0220_REMOVE_EL_CLIP             1      ///< JCTVC-R0220: remove clip to scaled ref window in resampling process
+#define RESAMPLING_FIX                   1      ///< Resampling fix -- equal offset check and conformance check
+#endif
+#else
+#define Q0200_CONFORMANCE_BL_SIZE        1      ///< JCTVC-Q0200; use conformance picture size in re-sampling processs
+#define P0312_VERT_PHASE_ADJ             1      ///< JCTVC-P0312: vertical phase adjustment in re-sampling process (BoG report)
+#if P0312_VERT_PHASE_ADJ
+#define Q0120_PHASE_CALCULATION          1      ///< JCTVC-Q0120 phase offset derivation for combination of spatial scalibility and field coding.
+#endif
+#endif
+#define R0157_RESTRICT_PPSID_FOR_CGS_LUT 1      ///< JCTVC-R0157: when pps_pic_parameter_set_id greater than or equal to 8, colour_mapping_enabled_flag shall be equal to 0
+
+#define VPS_FIX_TO_MATCH_SPEC            1
+
+/// scalability types
+enum ScalabilityType
+{
+  VIEW_ORDER_INDEX  = 1,
+  SCALABILITY_ID    = 2,
+  AUX_ID            = 3,
+};
+
+enum AuxType
+{
+  AUX_ALPHA = 1,
+  AUX_DEPTH = 2,
+};
+
+/// normative encoder constraints --------
+#define MFM_ENCCONSTRAINT                1      ///< JCTVC-O0216: Encoder constraint for motion field mapping
+#define REF_IDX_ME_ZEROMV                1      ///< JCTVC-L0051: use zero motion for inter-layer reference picture (without fractional ME)
+
+/// encoder settings ---------------------
+#define FAST_INTRA_SHVC                  1      ///< JCTVC-M0115: reduction number of intra modes in the EL (encoder only)
+#if FAST_INTRA_SHVC
+#define NB_REMAIN_MODES                  2      ///< JCTVC-M0115: nb of remaining modes
+#endif
+#define RC_SHVC_HARMONIZATION            1      ///< JCTVC-M0037: rate control for SHVC
+#define JCTVC_M0259_LAMBDAREFINEMENT     1      ///< JCTVC-M0259: lambda refinement (encoder only optimization)
+#define ENCODER_FAST_MODE                1      ///< JCTVC-L0174: enable encoder fast mode. TestMethod 1 is enabled by setting to 1 and TestMethod 2 is enable by setting to 2. By default it is set to 1.
+#define LAYER_CTB                        0      ///< enable layer-specific CTB structure
+
+/// SEI messages -------------------------
+#define SUB_BITSTREAM_PROPERTY_SEI       1      ///< JCTVC-P0204: Sub-bitstream property SEI message
+#if SUB_BITSTREAM_PROPERTY_SEI
+#define MAX_SUB_STREAMS                  1024
+#endif
+#define LAYERS_NOT_PRESENT_SEI           1      ///< JCTVC-M0043: add layers not present SEI.
+#define N0383_IL_CONSTRAINED_TILE_SETS_SEI  1
+#define Q0189_TMVP_CONSTRAINTS           1      ///< JCTVC-Q0189: indicate constraints on TMVP
+#define Q0247_FRAME_FIELD_INFO           1      ///< JCTVC-Q0247: field_frame_info SEI message
+#define R0247_SEI_ACTIVE                 1      ///< JCTVC-R0247: active parameter sets SEI message
+#define Q0096_OVERLAY_SEI                1      ///< JCTVC-Q0096, JCTVC-Q0045: selectable overlays SEI message
+#if Q0096_OVERLAY_SEI 
+# define MAX_OVERLAYS                    16
+# define MAX_OVERLAY_ELEMENTS            256
+# define MAX_OVERLAY_STRING_BYTES        256
+#endif
+#define P0123_ALPHA_CHANNEL_SEI          1      ///< JCTVC-P0123: SEI message for alpha channel information
+
+#endif // SVC_EXTENSION
+#define Q0074_COLOUR_REMAPPING_SEI       1      ///< JCTVC-Q0074, JCTVC-R0344: SEI Colour Remapping Information
+
+//! \ingroup TLibCommon
+//! \{
+
+// ====================================================================================================================
+// Debugging
+// ====================================================================================================================
+
+// #define DEBUG_STRING                 // enable to print out final decision debug info at encoder and decoder
+// #define DEBUG_ENCODER_SEARCH_BINS    // enable to print out each bin as it is coded during encoder search
+// #define DEBUG_CABAC_BINS             // enable to print out each bin as it is coded during final encode and decode
+// #define DEBUG_INTRA_SEARCH_COSTS     // enable to print out the cost for each mode during encoder search
+// #define DEBUG_TRANSFORM_AND_QUANTISE // enable to print out each TU as it passes through the transform-quantise-dequantise-inverseTransform process
+
+#ifdef DEBUG_STRING
+  #define DEBUG_STRING_PASS_INTO(name) , name
+  #define DEBUG_STRING_PASS_INTO_OPTIONAL(name, exp) , (exp==0)?0:name
+  #define DEBUG_STRING_FN_DECLARE(name) , std::string &name
+  #define DEBUG_STRING_FN_DECLAREP(name) , std::string *name
+  #define DEBUG_STRING_NEW(name) std::string name;
+  #define DEBUG_STRING_OUTPUT(os, name) os << name;
+  #define DEBUG_STRING_APPEND(str1, str2) str1+=str2;
+  #define DEBUG_STRING_SWAP(str1, str2) str1.swap(str2);
+  #define DEBUG_STRING_CHANNEL_CONDITION(compID) (true)
+  #include <sstream>
+  #include <iomanip>
+#else
+  #define DEBUG_STRING_PASS_INTO(name)
+  #define DEBUG_STRING_PASS_INTO_OPTIONAL(name, exp)
+  #define DEBUG_STRING_FN_DECLARE(name)
+  #define DEBUG_STRING_FN_DECLAREP(name)
+  #define DEBUG_STRING_NEW(name)
+  #define DEBUG_STRING_OUTPUT(os, name)
+  #define DEBUG_STRING_APPEND(str1, str2)
+  #define DEBUG_STRING_SWAP(srt1, str2)
+  #define DEBUG_STRING_CHANNEL_CONDITION(compID)
+#endif
+
+
+// ====================================================================================================================
+// Tool Switches
+// ====================================================================================================================
+
+#define HARMONIZE_GOP_FIRST_FIELD_COUPLE                  1
+#define EFFICIENT_FIELD_IRAP                              1
+#define ALLOW_RECOVERY_POINT_AS_RAP                       1
+#define BUGFIX_INTRAPERIOD                                1
+
+#define SAO_ENCODE_ALLOW_USE_PREDEBLOCK                   1
+
+#define TILE_SIZE_CHECK                                   1
+
+#define MAX_NUM_PICS_IN_SOP                            1024
+
+#define MAX_NESTING_NUM_OPS                            1024
+#define MAX_NESTING_NUM_LAYER                            64
+
+#if NESTING_SEI_EXTENSIBILITY
+#define MAX_SEIS_IN_BSP_NESTING                          64
+#endif
+
+#if SVC_EXTENSION
+#define MAX_VPS_OP_LAYER_SETS_PLUS1          (MAX_LAYERS+1)
+#define MAX_VPS_LAYER_SETS_PLUS1                       1024
+#define MAX_VPS_OUTPUT_LAYER_SETS_PLUS1                1024
+#define MAX_VPS_LAYER_IDX_PLUS1                   MAX_LAYERS
+#else
+#define MAX_VPS_NUM_HRD_PARAMETERS                        1
+#define MAX_VPS_OP_SETS_PLUS1                          1024
+#define MAX_VPS_NUH_RESERVED_ZERO_LAYER_ID_PLUS1          1
+#endif
+
+#define MAXIMUM_INTRA_FILTERED_WIDTH                     16
+#define MAXIMUM_INTRA_FILTERED_HEIGHT                    16
+
+#define MAX_CPB_CNT                                      32 ///< Upper bound of (cpb_cnt_minus1 + 1)
+
+#if O0137_MAX_LAYERID
+#define MAX_NUM_LAYER_IDS                                63
+#else
+#define MAX_NUM_LAYER_IDS                                64
+#endif
+
+#define COEF_REMAIN_BIN_REDUCTION                         3 ///< indicates the level at which the VLC
+                                                            ///< transitions from Golomb-Rice to TU+EG(k)
+
+#define CU_DQP_TU_CMAX                                    5 ///< max number bins for truncated unary
+#define CU_DQP_EG_k                                       0 ///< expgolomb order
+
+#define SBH_THRESHOLD                                     4  ///< I0156: value of the fixed SBH controlling threshold
+
+#define DISABLING_CLIP_FOR_BIPREDME                       1  ///< Ticket #175
+
+#define C1FLAG_NUMBER                                     8 // maximum number of largerThan1 flag coded in one chunk :  16 in HM5
+#define C2FLAG_NUMBER                                     1 // maximum number of largerThan2 flag coded in one chunk:  16 in HM5
+
+#define SAO_ENCODING_CHOICE                               1  ///< I0184: picture early termination
+#if SAO_ENCODING_CHOICE
+#define SAO_ENCODING_RATE                                 0.75
+#define SAO_ENCODING_CHOICE_CHROMA                        1 ///< J0044: picture early termination Luma and Chroma are handled separately
+#if SAO_ENCODING_CHOICE_CHROMA
+#define SAO_ENCODING_RATE_CHROMA                          0.5
+#endif
+#endif
+
+#define MAX_NUM_SAO_OFFSETS                               4
+
+#define MAX_NUM_VPS                                      16
+#define MAX_NUM_SPS                                      16
+#define MAX_NUM_PPS                                      64
+
+#define RDOQ_CHROMA_LAMBDA                                1   ///< F386: weighting of chroma for RDOQ
+
+#define MIN_SCAN_POS_CROSS                                4
+
+#define FAST_BIT_EST                                      1   ///< G763: Table-based bit estimation for CABAC
+
+#define MLS_GRP_NUM                                      64     ///< G644 : Max number of coefficient groups, max(16, 64)
+#define MLS_CG_LOG2_WIDTH                                 2
+#define MLS_CG_LOG2_HEIGHT                                2
+#define MLS_CG_SIZE                                     (MLS_CG_LOG2_WIDTH + MLS_CG_LOG2_HEIGHT)  ///< G644 : Coefficient group size of 4x4
+
+#define ADAPTIVE_QP_SELECTION                             1      ///< G382: Adaptive reconstruction levels, non-normative part for adaptive QP selection
+#if ADAPTIVE_QP_SELECTION
+#define ARL_C_PRECISION                                   7      ///< G382: 7-bit arithmetic precision
+#define LEVEL_RANGE                                      30     ///< G382: max coefficient level in statistics collection
+#endif
+
+#define HHI_RQT_INTRA_SPEEDUP                             1           ///< tests one best mode with full rqt
+#define HHI_RQT_INTRA_SPEEDUP_MOD                         0           ///< tests two best modes with full rqt
+
+#if HHI_RQT_INTRA_SPEEDUP_MOD && !HHI_RQT_INTRA_SPEEDUP
+#error
+#endif
+
+#define VERBOSE_RATE 0 ///< Print additional rate information in encoder
+
+#define AMVP_DECIMATION_FACTOR                            4
+
+#define SCAN_SET_SIZE                                    16
+#define LOG2_SCAN_SET_SIZE                                4
+
+#define FAST_UDI_MAX_RDMODE_NUM                          35          ///< maximum number of RD comparison in fast-UDI estimation loop
+
+#define NUM_INTRA_MODE                                   36
+
+#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 INVALID_MODE_IDX                                 (NUM_INTRA_MODE+1)    // value used to indicate an invalid intra mode
+#define STOPCHROMASEARCH_MODE_IDX                        (INVALID_MODE_IDX+1)  // value used to signal the end of a chroma mode search
+
+#define MDCS_ANGLE_LIMIT                                  4         ///< (default 4) 0 = Horizontal/vertical only, 1 = Horizontal/vertical +/- 1, 2 = Horizontal/vertical +/- 2 etc...
+#define MDCS_MAXIMUM_WIDTH                                8         ///< (default 8) (measured in pixels) TUs with width greater than this can only use diagonal scan
+#define MDCS_MAXIMUM_HEIGHT                               8         ///< (default 8) (measured in pixels) TUs with height greater than this can only use diagonal scan
+
+#define FAST_UDI_USE_MPM 1
+
+#define RDO_WITHOUT_DQP_BITS                              0           ///< Disable counting dQP bits in RDO-based mode decision
+
+#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 AMP_SAD                                           1 ///< dedicated SAD functions for AMP
+#define AMP_ENC_SPEEDUP                                   1 ///< encoder only speed-up by AMP mode skipping
+#if AMP_ENC_SPEEDUP
+#define AMP_MRG                                           1 ///< encoder only force merge for AMP partition (no motion search for AMP)
+#endif
+
+#define CABAC_INIT_PRESENT_FLAG                           1
+
+#define LUMA_INTERPOLATION_FILTER_SUB_SAMPLE_POSITIONS    4
+#define CHROMA_INTERPOLATION_FILTER_SUB_SAMPLE_POSITIONS  8
+
+#define MAX_NUM_LONG_TERM_REF_PICS                       33
+
+#define DECODER_CHECK_SUBSTREAM_AND_SLICE_TRAILING_BYTES  1
+
+#define RD_TEST_SAO_DISABLE_AT_PICTURE_LEVEL              0 ///< 1 = tests whether SAO should be disabled at the picture level,  0 (default) = does not apply this additional test
+
+#define O0043_BEST_EFFORT_DECODING                        0 ///< 0 (default) = disable code related to best effort decoding, 1 = enable code relating to best effort decoding [ decode-side only ].
+
+// Cost mode support
+
+#define LOSSLESS_AND_MIXED_LOSSLESS_RD_COST_TEST_QP       0 ///< QP to use for lossless coding.
+#define LOSSLESS_AND_MIXED_LOSSLESS_RD_COST_TEST_QP_PRIME 4 ///< QP' to use for mixed_lossy_lossless coding.
+
+// Debug support
+
+#define ENVIRONMENT_VARIABLE_DEBUG_AND_TEST               0 ///< When enabled, allows control of debug modifications via environment variables
+
+#define PRINT_MACRO_VALUES                                1 ///< When enabled, the encoder prints out a list of the non-environment-variable controlled macros and their values on startup
+
+// TODO: rename this macro to DECODER_DEBUG_BIT_STATISTICS (may currently cause merge issues with other branches)
+// This can be enabled by the makefile
+#ifndef RExt__DECODER_DEBUG_BIT_STATISTICS
+#define RExt__DECODER_DEBUG_BIT_STATISTICS                                     0 ///< 0 (default) = decoder reports as normal, 1 = decoder produces bit usage statistics (will impact decoder run time by up to ~10%)
+#endif
+
+// This can be enabled by the makefile
+#ifndef RExt__HIGH_BIT_DEPTH_SUPPORT
+#define RExt__HIGH_BIT_DEPTH_SUPPORT                                           0 ///< 0 (default) use data type definitions for 8-10 bit video, 1 = use larger data types to allow for up to 16-bit video (originally developed as part of N0188)
+#endif
+
+#define RExt__GOLOMB_RICE_ADAPTATION_STATISTICS_SETS                           4
+#define RExt__GOLOMB_RICE_INCREMENT_DIVISOR                                    4
+
+#define RExt__PREDICTION_WEIGHTING_ANALYSIS_DC_PRECISION                       0 ///< Additional fixed bit precision used during encoder-side weighting prediction analysis. Currently only used when high_precision_prediction_weighting_flag is set, for backwards compatibility reasons.
+
+#define MAX_TIMECODE_SEI_SETS                                                  3 ///< Maximum number of time sets
+
+
+//------------------------------------------------
+// Derived macros
+//------------------------------------------------
+
+#if RExt__HIGH_BIT_DEPTH_SUPPORT
+#define FULL_NBIT                                                              1 ///< When enabled, use distortion measure derived from all bits of source data, otherwise discard (bitDepth - 8) least-significant bits of distortion
+#define RExt__HIGH_PRECISION_FORWARD_TRANSFORM                                 1 ///< 0 use original 6-bit transform matrices for both forward and inverse transform, 1 (default) = use original matrices for inverse transform and high precision matrices for forward transform
+#else
+#define FULL_NBIT                                                              0 ///< When enabled, use distortion measure derived from all bits of source data, otherwise discard (bitDepth - 8) least-significant bits of distortion
+#define RExt__HIGH_PRECISION_FORWARD_TRANSFORM                                 0 ///< 0 (default) use original 6-bit transform matrices for both forward and inverse transform, 1 = use original matrices for inverse transform and high precision matrices for forward transform
+#endif
+
+#if FULL_NBIT
+# define DISTORTION_PRECISION_ADJUSTMENT(x)  0
+#else
+# define DISTORTION_PRECISION_ADJUSTMENT(x) (x)
+#endif
+
+
+//------------------------------------------------
+// Error checks
+//------------------------------------------------
+
+#if ((RExt__HIGH_PRECISION_FORWARD_TRANSFORM != 0) && (RExt__HIGH_BIT_DEPTH_SUPPORT == 0))
+#error ERROR: cannot enable RExt__HIGH_PRECISION_FORWARD_TRANSFORM without RExt__HIGH_BIT_DEPTH_SUPPORT
+#endif
+
+// ====================================================================================================================
+// Basic type redefinition
+// ====================================================================================================================
+
+typedef       void                Void;
+typedef       bool                Bool;
+
+#ifdef __arm__
+typedef       signed char         Char;
+#else
+typedef       char                Char;
+#endif
+typedef       unsigned char       UChar;
+typedef       short               Short;
+typedef       unsigned short      UShort;
+typedef       int                 Int;
+typedef       unsigned int        UInt;
+typedef       double              Double;
+typedef       float               Float;
+
+
+// ====================================================================================================================
+// 64-bit integer type
+// ====================================================================================================================
+
+#ifdef _MSC_VER
+typedef       __int64             Int64;
+
+#if _MSC_VER <= 1200 // MS VC6
+typedef       __int64             UInt64;   // MS VC6 does not support unsigned __int64 to double conversion
+#else
+typedef       unsigned __int64    UInt64;
+#endif
+
+#else
+
+typedef       long long           Int64;
+typedef       unsigned long long  UInt64;
+
+#endif
+
+
+// ====================================================================================================================
+// Enumeration
+// ====================================================================================================================
+
+enum RDPCMMode
+{
+  RDPCM_OFF             = 0,
+  RDPCM_HOR             = 1,
+  RDPCM_VER             = 2,
+  NUMBER_OF_RDPCM_MODES = 3
+};
+
+enum RDPCMSignallingMode
+{
+  RDPCM_SIGNAL_IMPLICIT            = 0,
+  RDPCM_SIGNAL_EXPLICIT            = 1,
+  NUMBER_OF_RDPCM_SIGNALLING_MODES = 2
+};
+
+/// supported slice type
+enum SliceType
+{
+  B_SLICE               = 0,
+  P_SLICE               = 1,
+  I_SLICE               = 2,
+  NUMBER_OF_SLICE_TYPES = 3
+};
+
+/// chroma formats (according to semantics of chroma_format_idc)
+enum ChromaFormat
+{
+  CHROMA_400        = 0,
+  CHROMA_420        = 1,
+  CHROMA_422        = 2,
+  CHROMA_444        = 3,
+  NUM_CHROMA_FORMAT = 4
+};
+
+enum ChannelType
+{
+  CHANNEL_TYPE_LUMA    = 0,
+  CHANNEL_TYPE_CHROMA  = 1,
+  MAX_NUM_CHANNEL_TYPE = 2
+};
+
+enum ComponentID
+{
+  COMPONENT_Y       = 0,
+  COMPONENT_Cb      = 1,
+  COMPONENT_Cr      = 2,
+  MAX_NUM_COMPONENT = 3
+};
+
+enum InputColourSpaceConversion // defined in terms of conversion prior to input of encoder.
+{
+  IPCOLOURSPACE_UNCHANGED               = 0,
+  IPCOLOURSPACE_YCbCrtoYCrCb            = 1, // Mainly used for debug!
+  IPCOLOURSPACE_YCbCrtoYYY              = 2, // Mainly used for debug!
+  IPCOLOURSPACE_RGBtoGBR                = 3,
+  NUMBER_INPUT_COLOUR_SPACE_CONVERSIONS = 4
+};
+
+enum DeblockEdgeDir
+{
+  EDGE_VER     = 0,
+  EDGE_HOR     = 1,
+  NUM_EDGE_DIR = 2
+};
+
+/// supported partition shape
+enum PartSize
+{
+  SIZE_2Nx2N           = 0,           ///< symmetric motion partition,  2Nx2N
+  SIZE_2NxN            = 1,           ///< symmetric motion partition,  2Nx N
+  SIZE_Nx2N            = 2,           ///< symmetric motion partition,   Nx2N
+  SIZE_NxN             = 3,           ///< symmetric motion partition,   Nx N
+  SIZE_2NxnU           = 4,           ///< asymmetric motion partition, 2Nx( N/2) + 2Nx(3N/2)
+  SIZE_2NxnD           = 5,           ///< asymmetric motion partition, 2Nx(3N/2) + 2Nx( N/2)
+  SIZE_nLx2N           = 6,           ///< asymmetric motion partition, ( N/2)x2N + (3N/2)x2N
+  SIZE_nRx2N           = 7,           ///< asymmetric motion partition, (3N/2)x2N + ( N/2)x2N
+  NUMBER_OF_PART_SIZES = 8
+};
+
+/// supported prediction type
+enum PredMode
+{
+  MODE_INTER                 = 0,     ///< inter-prediction mode
+  MODE_INTRA                 = 1,     ///< intra-prediction mode
+  NUMBER_OF_PREDICTION_MODES = 2,
+};
+
+/// reference list index
+enum RefPicList
+{
+  REF_PIC_LIST_0               = 0,   ///< reference list 0
+  REF_PIC_LIST_1               = 1,   ///< reference list 1
+  NUM_REF_PIC_LIST_01          = 2,
+  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 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
+  DF_TOTAL_FUNCTIONS = 64
+#else
+  DF_SSE_FRAME       = 32,     ///< Frame-based SSE
+  DF_TOTAL_FUNCTIONS = 33
+#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
+};
+
+enum StoredResidualType
+{
+  RESIDUAL_RECONSTRUCTED          = 0,
+  RESIDUAL_ENCODER_SIDE           = 1,
+  NUMBER_OF_STORED_RESIDUAL_TYPES = 2
+};
+
+enum TransformDirection
+{
+  TRANSFORM_FORWARD              = 0,
+  TRANSFORM_INVERSE              = 1,
+  TRANSFORM_NUMBER_OF_DIRECTIONS = 2
+};
+
+/// supported ME search methods
+enum MESearchMethod
+{
+  FULL_SEARCH                = 0,     ///< Full search
+  DIAMOND                    = 1,     ///< Fast search
+  SELECTIVE                  = 2      ///< Selective search
+};
+
+/// coefficient scanning type used in ACS
+enum COEFF_SCAN_TYPE
+{
+  SCAN_DIAG = 0,        ///< up-right diagonal scan
+  SCAN_HOR  = 1,        ///< horizontal first scan
+  SCAN_VER  = 2,        ///< vertical first scan
+  SCAN_NUMBER_OF_TYPES = 3
+};
+
+enum COEFF_SCAN_GROUP_TYPE
+{
+  SCAN_UNGROUPED   = 0,
+  SCAN_GROUPED_4x4 = 1,
+  SCAN_NUMBER_OF_GROUP_TYPES = 2
+};
+
+enum SignificanceMapContextType
+{
+  CONTEXT_TYPE_4x4    = 0,
+  CONTEXT_TYPE_8x8    = 1,
+  CONTEXT_TYPE_NxN    = 2,
+  CONTEXT_TYPE_SINGLE = 3,
+  CONTEXT_NUMBER_OF_TYPES = 4
+};
+
+enum ScalingListMode
+{
+  SCALING_LIST_OFF,
+  SCALING_LIST_DEFAULT,
+  SCALING_LIST_FILE_READ
+};
+
+enum ScalingListSize
+{
+  SCALING_LIST_4x4 = 0,
+  SCALING_LIST_8x8,
+  SCALING_LIST_16x16,
+  SCALING_LIST_32x32,
+  SCALING_LIST_SIZE_NUM
+};
+
+// Slice / Slice segment encoding modes
+enum SliceConstraint
+{
+  NO_SLICES              = 0,          ///< don't use slices / slice segments
+  FIXED_NUMBER_OF_CTU    = 1,          ///< Limit maximum number of largest coding tree units in a slice / slice segments
+  FIXED_NUMBER_OF_BYTES  = 2,          ///< Limit maximum number of bytes in a slice / slice segment
+  FIXED_NUMBER_OF_TILES  = 3,          ///< slices / slice segments span an integer number of tiles
+};
+
+enum SAOMode //mode
+{
+  SAO_MODE_OFF = 0,
+  SAO_MODE_NEW,
+  SAO_MODE_MERGE,
+  NUM_SAO_MODES
+};
+
+enum SAOModeMergeTypes
+{
+  SAO_MERGE_LEFT =0,
+  SAO_MERGE_ABOVE,
+  NUM_SAO_MERGE_TYPES
+};
+
+
+enum SAOModeNewTypes
+{
+  SAO_TYPE_START_EO =0,
+  SAO_TYPE_EO_0 = SAO_TYPE_START_EO,
+  SAO_TYPE_EO_90,
+  SAO_TYPE_EO_135,
+  SAO_TYPE_EO_45,
+
+  SAO_TYPE_START_BO,
+  SAO_TYPE_BO = SAO_TYPE_START_BO,
+
+  NUM_SAO_NEW_TYPES
+};
+#define NUM_SAO_EO_TYPES_LOG2 2
+
+enum SAOEOClasses
+{
+  SAO_CLASS_EO_FULL_VALLEY = 0,
+  SAO_CLASS_EO_HALF_VALLEY = 1,
+  SAO_CLASS_EO_PLAIN       = 2,
+  SAO_CLASS_EO_HALF_PEAK   = 3,
+  SAO_CLASS_EO_FULL_PEAK   = 4,
+  NUM_SAO_EO_CLASSES,
+};
+
+#define NUM_SAO_BO_CLASSES_LOG2  5
+#define NUM_SAO_BO_CLASSES       (1<<NUM_SAO_BO_CLASSES_LOG2)
+
+namespace Profile
+{
+  enum Name
+  {
+    NONE = 0,
+    MAIN = 1,
+    MAIN10 = 2,
+    MAINSTILLPICTURE = 3,
+    MAINREXT = 4,
+    HIGHTHROUGHPUTREXT = 5,
+#if MULTIPLE_PTL_SUPPORT
+    MULTIVIEWMAIN = 6,
+    SCALABLEMAIN = 7,
+    SCALABLEMAIN10 = 8,
+#endif
+  };
+}
+
+namespace Level
+{
+  enum Tier
+  {
+    MAIN = 0,
+    HIGH = 1,
+  };
+
+  enum Name
+  {
+    // code = (level * 30)
+    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,
+    LEVEL8_5 = 255,
+  };
+}
+
+enum CostMode
+{
+  COST_STANDARD_LOSSY              = 0,
+  COST_SEQUENCE_LEVEL_LOSSLESS     = 1,
+  COST_LOSSLESS_CODING             = 2,
+  COST_MIXED_LOSSLESS_LOSSY_CODING = 3
+};
+
+enum SPSExtensionFlagIndex
+{
+  SPS_EXT__REXT           = 0,
+#if SVC_EXTENSION
+  SPS_EXT__MLAYER         = 1,
+#else
+//SPS_EXT__MVHEVC         = 1, //for use in future versions
+//SPS_EXT__SHVC           = 2, //for use in future versions
+#endif
+  NUM_SPS_EXTENSION_FLAGS = 8
+};
+
+enum PPSExtensionFlagIndex
+{
+  PPS_EXT__REXT           = 0,
+#if SVC_EXTENSION
+  PPS_EXT__MLAYER         = 1, // multilayer extension
+#else
+//PPS_EXT__MVHEVC         = 1, //for use in future versions
+//PPS_EXT__SHVC           = 2, //for use in future versions
+#endif
+  NUM_PPS_EXTENSION_FLAGS = 8
+};
+
+// ====================================================================================================================
+// Type definition
+// ====================================================================================================================
+
+#if RExt__HIGH_BIT_DEPTH_SUPPORT
+typedef       Int             Pel;               ///< pixel type
+typedef       Int64           TCoeff;            ///< transform coefficient
+typedef       Int             TMatrixCoeff;      ///< transform matrix coefficient
+typedef       Short           TFilterCoeff;      ///< filter coefficient
+typedef       Int64           Intermediate_Int;  ///< used as intermediate value in calculations
+typedef       UInt64          Intermediate_UInt; ///< used as intermediate value in calculations
+#else
+typedef       Short           Pel;               ///< pixel type
+typedef       Int             TCoeff;            ///< transform coefficient
+typedef       Short           TMatrixCoeff;      ///< transform matrix coefficient
+typedef       Short           TFilterCoeff;      ///< filter coefficient
+typedef       Int             Intermediate_Int;  ///< used as intermediate value in calculations
+typedef       UInt            Intermediate_UInt; ///< used as intermediate value in calculations
+#endif
+
+#if FULL_NBIT
+typedef       UInt64          Distortion;        ///< distortion measurement
+#else
+typedef       UInt            Distortion;        ///< distortion measurement
+#endif
+
+/// parameters for adaptive loop filter
+class TComPicSym;
+
+#define MAX_NUM_SAO_CLASSES  32  //(NUM_SAO_EO_GROUPS > NUM_SAO_BO_GROUPS)?NUM_SAO_EO_GROUPS:NUM_SAO_BO_GROUPS
+
+struct SAOOffset
+{
+  SAOMode modeIdc; // NEW, MERGE, OFF
+  Int typeIdc;     // union of SAOModeMergeTypes and SAOModeNewTypes, depending on modeIdc.
+  Int typeAuxInfo; // BO: starting band index
+  Int offset[MAX_NUM_SAO_CLASSES];
+
+  SAOOffset();
+  ~SAOOffset();
+  Void reset();
+
+  const SAOOffset& operator= (const SAOOffset& src);
+};
+
+struct SAOBlkParam
+{
+
+  SAOBlkParam();
+  ~SAOBlkParam();
+  Void reset();
+  const SAOBlkParam& operator= (const SAOBlkParam& src);
+  SAOOffset& operator[](Int compIdx){ return offsetParam[compIdx];}
+private:
+  SAOOffset offsetParam[MAX_NUM_COMPONENT];
+
+};
+
+
+/// parameters for deblocking filter
+typedef struct _LFCUParam
+{
+  Bool bInternalEdge;                     ///< indicates internal edge
+  Bool bLeftEdge;                         ///< indicates left edge
+  Bool bTopEdge;                          ///< indicates top edge
+} LFCUParam;
+
+
+
+//TU settings for entropy encoding
+struct TUEntropyCodingParameters
+{
+  const UInt            *scan;
+  const UInt            *scanCG;
+        COEFF_SCAN_TYPE  scanType;
+        UInt             widthInGroups;
+        UInt             heightInGroups;
+        UInt             firstSignificanceMapContext;
+};
+
+
+struct TComDigest
+{
+  std::vector<UChar> hash;
+
+  Bool operator==(const TComDigest &other) const
+  {
+    if (other.hash.size() != hash.size()) return false;
+    for(UInt i=0; i<UInt(hash.size()); i++)
+      if (other.hash[i] != hash[i]) return false;
+    return true;
+  }
+
+  Bool operator!=(const TComDigest &other) const
+  {
+    return !(*this == other);
+  }
+};
+
+struct TComSEITimeSet
+{
+  TComSEITimeSet() : clockTimeStampFlag(false),
+                     numUnitFieldBasedFlag(false),
+                     countingType(0),
+                     fullTimeStampFlag(false),
+                     discontinuityFlag(false),
+                     cntDroppedFlag(false),
+                     numberOfFrames(0),
+                     secondsValue(0),
+                     minutesValue(0),
+                     hoursValue(0),
+                     secondsFlag(false),
+                     minutesFlag(false),
+                     hoursFlag(false),
+                     timeOffsetLength(0),
+                     timeOffsetValue(0)
+  { }
+  Bool clockTimeStampFlag;
+  Bool numUnitFieldBasedFlag;
+  Int  countingType;
+  Bool fullTimeStampFlag;
+  Bool discontinuityFlag;
+  Bool cntDroppedFlag;
+  Int  numberOfFrames;
+  Int  secondsValue;
+  Int  minutesValue;
+  Int  hoursValue;
+  Bool secondsFlag;
+  Bool minutesFlag;
+  Bool hoursFlag;
+  Int  timeOffsetLength;
+  Int  timeOffsetValue;
+};
+
+struct TComSEIMasteringDisplay
+{
+  Bool      colourVolumeSEIEnabled;
+  UInt      maxLuminance;
+  UInt      minLuminance;
+  UShort    primaries[3][2];
+  UShort    whitePoint[2];
+};
+//! \}
+
+#endif
+
+
Index: /tags/SHM-9.0/source/Lib/TLibDecoder/AnnexBread.cpp
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibDecoder/AnnexBread.cpp	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibDecoder/AnnexBread.cpp	(revision 1088)
@@ -0,0 +1,199 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ \file     AnnexBread.cpp
+ \brief    reading functions for Annex B byte streams
+ */
+
+
+#include <stdint.h>
+#include <cassert>
+#include <vector>
+#include "AnnexBread.h"
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+#include "TLibCommon/TComCodingStatistics.h"
+#endif
+
+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.
+   */
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+  TComCodingStatistics::SStat &statBits=TComCodingStatistics::GetStatisticEP(STATS__NAL_UNIT_PACKING);
+#endif
+  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();
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+    statBits.bits+=8; statBits.count++;
+#endif
+    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();
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+    statBits.bits+=8; statBits.count++;
+#endif
+    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);
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+  statBits.bits+=24; statBits.count+=3;
+#endif
+  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 */
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+  TComCodingStatistics::SStat &bodyStats=TComCodingStatistics::GetStatisticEP(STATS__NAL_UNIT_TOTAL_BODY);
+#endif
+  while (bs.eofBeforeNBytes(24/8) || bs.peekBytes(24/8) > 2)
+  {
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+    uint8_t thebyte=bs.readByte();bodyStats.bits+=8;bodyStats.count++;
+    nalUnit.push_back(thebyte);
+#else
+    nalUnit.push_back(bs.readByte());
+#endif
+  }
+
+  /* 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();
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+    statBits.bits+=8; statBits.count++;
+#endif
+    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: /tags/SHM-9.0/source/Lib/TLibDecoder/AnnexBread.h
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibDecoder/AnnexBread.h	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibDecoder/AnnexBread.h	(revision 1088)
@@ -0,0 +1,195 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ \file     AnnexBread.h
+ \brief    reading functions for Annex B byte streams
+ */
+
+#pragma once
+
+#ifndef __ANNEXBREAD__
+#define __ANNEXBREAD__
+
+#include <stdint.h>
+#include <istream>
+#include <vector>
+
+#include "TLibCommon/TypeDef.h"
+
+//! \ingroup TLibDecoder
+//! \{
+
+class InputByteStream
+{
+public:
+  /**
+   * Create a bytestream reader that will extract bytes from
+   * istream.
+   *
+   * NB, it isn't safe to access istream while in use by a
+   * InputByteStream.
+   *
+   * Side-effects: the exception mask of istream is set to eofbit
+   */
+  InputByteStream(std::istream& istream)
+  : m_NumFutureBytes(0)
+  , m_FutureBytes(0)
+  , m_Input(istream)
+  {
+    istream.exceptions(std::istream::eofbit | std::istream::badbit);
+  }
+
+  /**
+   * Reset the internal state.  Must be called if input stream is
+   * modified externally to this class
+   */
+  Void reset()
+  {
+    m_NumFutureBytes = 0;
+    m_FutureBytes = 0;
+  }
+
+  /**
+   * returns true if an EOF will be encountered within the next
+   * n bytes.
+   */
+  Bool eofBeforeNBytes(UInt n)
+  {
+    assert(n <= 4);
+    if (m_NumFutureBytes >= n)
+      return false;
+
+    n -= m_NumFutureBytes;
+    try
+    {
+      for (UInt i = 0; i < n; i++)
+      {
+        m_FutureBytes = (m_FutureBytes << 8) | m_Input.get();
+        m_NumFutureBytes++;
+      }
+    }
+    catch (...)
+    {
+      return true;
+    }
+    return false;
+  }
+
+  /**
+   * return the next n bytes in the stream without advancing
+   * the stream pointer.
+   *
+   * Returns: an unsigned integer representing an n byte bigendian
+   * word.
+   *
+   * If an attempt is made to read past EOF, an n-byte word is
+   * returned, but the portion that required input bytes beyond EOF
+   * is undefined.
+   *
+   */
+  uint32_t peekBytes(UInt n)
+  {
+    eofBeforeNBytes(n);
+    return m_FutureBytes >> 8*(m_NumFutureBytes - n);
+  }
+
+  /**
+   * consume and return one byte from the input.
+   *
+   * If bytestream is already at EOF prior to a call to readByte(),
+   * an exception std::ios_base::failure is thrown.
+   */
+  uint8_t readByte()
+  {
+    if (!m_NumFutureBytes)
+    {
+      uint8_t byte = m_Input.get();
+      return byte;
+    }
+    m_NumFutureBytes--;
+    uint8_t wanted_byte = m_FutureBytes >> 8*m_NumFutureBytes;
+    m_FutureBytes &= ~(0xff << 8*m_NumFutureBytes);
+    return wanted_byte;
+  }
+
+  /**
+   * consume and return n bytes from the input.  n bytes from
+   * bytestream are interpreted as bigendian when assembling
+   * the return value.
+   */
+  uint32_t readBytes(UInt n)
+  {
+    uint32_t val = 0;
+    for (UInt i = 0; i < n; i++)
+      val = (val << 8) | readByte();
+    return val;
+  }
+
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+  UInt GetNumBufferedBytes() const { return m_NumFutureBytes; }
+#endif
+
+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);
+
+//! \}
+
+#endif
Index: /tags/SHM-9.0/source/Lib/TLibDecoder/NALread.cpp
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibDecoder/NALread.cpp	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibDecoder/NALread.cpp	(revision 1088)
@@ -0,0 +1,177 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ \file     NALread.cpp
+ \brief    reading funtionality for NAL units
+ */
+
+
+#include <vector>
+#include <algorithm>
+#include <ostream>
+
+#include "NALread.h"
+#include "TLibCommon/NAL.h"
+#include "TLibCommon/TComBitStream.h"
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+#include "TLibCommon/TComCodingStatistics.h"
+#endif
+
+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 RExt__DECODER_DEBUG_BIT_STATISTICS
+      TComCodingStatistics::IncrementStatisticEP(STATS__EMULATION_PREVENTION_3_BYTES, 8, 0);
+#endif
+      if (it_read == nalUnitBuf.end())
+      {
+        break;
+      }
+      assert(*it_read <= 0x03);
+    }
+    zeroCount = (*it_read == 0x00) ? zeroCount+1 : 0;
+    *it_write = *it_read;
+  }
+  assert(zeroCount == 0);
+
+  if (isVclNalUnit)
+  {
+    // Remove cabac_zero_word from payload if present
+    Int n = 0;
+
+    while (it_write[-1] == 0x00)
+    {
+      it_write--;
+      n++;
+    }
+
+    if (n > 0)
+    {
+      printf("\nDetected %d instances of cabac_zero_word\n", 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
+  nalu.m_reservedZero6Bits = bs.read(6);       // nuh_reserved_zero_6bits
+#if SVC_EXTENSION
+  nalu.m_layerId = nalu.m_reservedZero6Bits;
+#else
+  assert(nalu.m_reservedZero6Bits == 0);
+#endif
+  nalu.m_temporalId = bs.read(3) - 1;             // nuh_temporal_id_plus1
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+  TComCodingStatistics::IncrementStatisticEP(STATS__NAL_UNIT_HEADER_BITS, 1+6+6+3, 0);
+#endif
+
+  if ( nalu.m_temporalId )
+  {
+#if !Q0108_TSA_STSA
+    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_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); 
+#endif
+  }
+  else
+  {
+#if !Q0108_TSA_STSA
+    assert( nalu.m_nalUnitType != NAL_UNIT_CODED_SLICE_TSA_R
+         && nalu.m_nalUnitType != NAL_UNIT_CODED_SLICE_TSA_N
+         && nalu.m_nalUnitType != NAL_UNIT_CODED_SLICE_STSA_R
+         && nalu.m_nalUnitType != NAL_UNIT_CODED_SLICE_STSA_N );
+#else
+    assert( nalu.m_nalUnitType != NAL_UNIT_CODED_SLICE_TSA_R
+         && nalu.m_nalUnitType != NAL_UNIT_CODED_SLICE_TSA_N
+         );
+#endif
+  }
+}
+/**
+ * create a NALunit structure with given header values and storage for
+ * a bitstream
+ */
+Void read(InputNALUnit& nalu, vector<uint8_t>& nalUnitBuf)
+{
+  /* perform anti-emulation prevention */
+  TComInputBitstream *pcBitstream = new TComInputBitstream(NULL);
+  convertPayloadToRBSP(nalUnitBuf, pcBitstream, (nalUnitBuf[0] & 64) == 0);
+
+  nalu.m_Bitstream = new TComInputBitstream(&nalUnitBuf);
+  nalu.m_Bitstream->setEmulationPreventionByteLocation(pcBitstream->getEmulationPreventionByteLocation());
+  delete pcBitstream;
+  readNalUnitHeader(nalu);
+}
+//! \}
Index: /tags/SHM-9.0/source/Lib/TLibDecoder/NALread.h
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibDecoder/NALread.h	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibDecoder/NALread.h	(revision 1088)
@@ -0,0 +1,67 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ \file     NALread.h
+ \brief    reading funtionality for NAL units
+ */
+
+#pragma once
+
+#ifndef __NALREAD__
+#define __NALREAD__
+
+#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);
+
+//! \}
+
+#endif
Index: /tags/SHM-9.0/source/Lib/TLibDecoder/SEIread.cpp
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibDecoder/SEIread.cpp	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibDecoder/SEIread.cpp	(revision 1088)
@@ -0,0 +1,2062 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ \file     SEIread.cpp
+ \brief    reading funtionality 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"
+#include "TLibCommon/TComPicYuv.h"
+#include <iomanip>
+
+
+//! \ingroup TLibDecoder
+//! \{
+
+
+#if ENC_DEC_TRACE
+Void  xTraceSEIHeader()
+{
+  fprintf( g_hTrace, "=========== SEI message ===========\n");
+}
+
+Void  xTraceSEIMessageType(SEI::PayloadType payloadType)
+{
+  fprintf( g_hTrace, "=========== %s SEI message ===========\n", SEI::getSEIMessageString(payloadType));
+}
+#endif
+
+Void SEIReader::sei_read_code(std::ostream *pOS, UInt uiLength, UInt& ruiCode, const Char *pSymbolName)
+{
+  READ_CODE(uiLength, ruiCode, pSymbolName);
+  if (pOS)      (*pOS) << "  " << std::setw(55) << pSymbolName << ": " << ruiCode << "\n";
+}
+
+Void SEIReader::sei_read_uvlc(std::ostream *pOS, UInt& ruiCode, const Char *pSymbolName)
+{
+  READ_UVLC(ruiCode, pSymbolName);
+  if (pOS)      (*pOS) << "  " << std::setw(55) << pSymbolName << ": " << ruiCode << "\n";
+}
+
+Void SEIReader::sei_read_svlc(std::ostream *pOS, Int& ruiCode, const Char *pSymbolName)
+{
+  READ_SVLC(ruiCode, pSymbolName);
+  if (pOS)      (*pOS) << "  " << std::setw(55) << pSymbolName << ": " << ruiCode << "\n";
+}
+
+Void SEIReader::sei_read_flag(std::ostream *pOS, UInt& ruiCode, const Char *pSymbolName)
+{
+  READ_FLAG(ruiCode, pSymbolName);
+  if (pOS)      (*pOS) << "  " << std::setw(55) << pSymbolName << ": " << (ruiCode?1:0) << "\n";
+}
+
+static inline Void output_sei_message_header(SEI &sei, std::ostream *pDecodedMessageOutputStream, UInt payloadSize)
+{
+  if (pDecodedMessageOutputStream)
+  {
+    std::string seiMessageHdr(SEI::getSEIMessageString(sei.payloadType())); seiMessageHdr+=" SEI message";
+    (*pDecodedMessageOutputStream) << std::setfill('-') << std::setw(seiMessageHdr.size()) << "-" << std::setfill(' ') << "\n" << seiMessageHdr << "\n";
+  }
+}
+
+#undef READ_CODE
+#undef READ_SVLC
+#undef READ_UVLC
+#undef READ_FLAG
+
+
+/**
+ * unmarshal a single SEI message from bitstream bs
+ */
+#if LAYERS_NOT_PRESENT_SEI
+Void SEIReader::parseSEImessage(TComInputBitstream* bs, SEIMessages& seis, const NalUnitType nalUnitType, TComVPS *vps, TComSPS *sps, std::ostream *pDecodedMessageOutputStream)
+#else
+Void SEIReader::parseSEImessage(TComInputBitstream* bs, SEIMessages& seis, const NalUnitType nalUnitType, TComSPS *sps, std::ostream *pDecodedMessageOutputStream)
+#endif
+{
+  setBitstream(bs);
+
+  assert(!m_pcBitstream->getNumBitsUntilByteAligned());
+  do
+  {
+#if LAYERS_NOT_PRESENT_SEI
+    xReadSEImessage(seis, nalUnitType, vps, sps, pDecodedMessageOutputStream);
+#else
+    xReadSEImessage(seis, nalUnitType, sps, pDecodedMessageOutputStream);
+#endif
+    /* 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;
+  sei_read_code(NULL, 8, rbspTrailingBits, "rbsp_trailing_bits");
+  assert(rbspTrailingBits == 0x80);
+}
+
+#if O0164_MULTI_LAYER_HRD
+#if LAYERS_NOT_PRESENT_SEI
+Void SEIReader::xReadSEImessage(SEIMessages& seis, const NalUnitType nalUnitType, TComVPS *vps, TComSPS *sps, std::ostream *pDecodedMessageOutputStream, const SEIScalableNesting *nestingSei, const SEIBspNesting *bspNestingSei)
+#else
+Void SEIReader::xReadSEImessage(SEIMessages& seis, const NalUnitType nalUnitType, TComSPS *sps, std::ostream *pDecodedMessageOutputStream, const SEIScalableNesting *nestingSei)
+#endif
+#else
+#if LAYERS_NOT_PRESENT_SEI
+Void SEIReader::xReadSEImessage(SEIMessages& seis, const NalUnitType nalUnitType, TComVPS *vps, TComSPS *sps, std::ostream *pDecodedMessageOutputStream)
+#else
+Void SEIReader::xReadSEImessage(SEIMessages& seis, const NalUnitType nalUnitType, TComSPS *sps, std::ostream *pDecodedMessageOutputStream)
+#endif
+#endif
+{
+#if ENC_DEC_TRACE
+  xTraceSEIHeader();
+#endif
+  Int payloadType = 0;
+  UInt val = 0;
+
+  do
+  {
+    sei_read_code(NULL, 8, val, "payload_type");
+    payloadType += val;
+  } while (val==0xFF);
+
+  UInt payloadSize = 0;
+  do
+  {
+    sei_read_code(NULL, 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, pDecodedMessageOutputStream);
+      break;
+    case SEI::ACTIVE_PARAMETER_SETS:
+      sei = new SEIActiveParameterSets;
+      xParseSEIActiveParameterSets((SEIActiveParameterSets&) *sei, payloadSize, pDecodedMessageOutputStream);
+      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;
+#if VPS_VUI_BSP_HRD_PARAMS
+        xParseSEIDecodingUnitInfo((SEIDecodingUnitInfo&) *sei, payloadSize, sps, nestingSei, bspNestingSei, vps, pDecodedMessageOutputStream);
+#else        
+        xParseSEIDecodingUnitInfo((SEIDecodingUnitInfo&) *sei, payloadSize, sps, pDecodedMessageOutputStream);
+#endif
+      }
+      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;
+#if VPS_VUI_BSP_HRD_PARAMS
+        xParseSEIBufferingPeriod((SEIBufferingPeriod&) *sei, payloadSize, sps, nestingSei, bspNestingSei, vps, pDecodedMessageOutputStream);
+#else
+        xParseSEIBufferingPeriod((SEIBufferingPeriod&) *sei, payloadSize, sps, pDecodedMessageOutputStream);
+#endif
+      }
+      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;
+#if VPS_VUI_BSP_HRD_PARAMS
+        xParseSEIPictureTiming((SEIPictureTiming&)*sei, payloadSize, sps, nestingSei, bspNestingSei, vps, pDecodedMessageOutputStream);
+#else
+        xParseSEIPictureTiming((SEIPictureTiming&)*sei, payloadSize, sps, pDecodedMessageOutputStream);
+#endif
+      }
+      break;
+    case SEI::RECOVERY_POINT:
+      sei = new SEIRecoveryPoint;
+      xParseSEIRecoveryPoint((SEIRecoveryPoint&) *sei, payloadSize, pDecodedMessageOutputStream);
+      break;
+    case SEI::FRAME_PACKING:
+      sei = new SEIFramePacking;
+      xParseSEIFramePacking((SEIFramePacking&) *sei, payloadSize, pDecodedMessageOutputStream);
+      break;
+    case SEI::SEGM_RECT_FRAME_PACKING:
+      sei = new SEISegmentedRectFramePacking;
+      xParseSEISegmentedRectFramePacking((SEISegmentedRectFramePacking&) *sei, payloadSize, pDecodedMessageOutputStream);
+      break;
+    case SEI::DISPLAY_ORIENTATION:
+      sei = new SEIDisplayOrientation;
+      xParseSEIDisplayOrientation((SEIDisplayOrientation&) *sei, payloadSize, pDecodedMessageOutputStream);
+      break;
+    case SEI::TEMPORAL_LEVEL0_INDEX:
+      sei = new SEITemporalLevel0Index;
+      xParseSEITemporalLevel0Index((SEITemporalLevel0Index&) *sei, payloadSize, pDecodedMessageOutputStream);
+      break;
+    case SEI::REGION_REFRESH_INFO:
+      sei = new SEIGradualDecodingRefreshInfo;
+      xParseSEIRegionRefreshInfo((SEIGradualDecodingRefreshInfo&) *sei, payloadSize, pDecodedMessageOutputStream);
+      break;
+    case SEI::NO_DISPLAY:
+      sei = new SEINoDisplay;
+      xParseSEINoDisplay((SEINoDisplay&) *sei, payloadSize, pDecodedMessageOutputStream);
+      break;
+    case SEI::TONE_MAPPING_INFO:
+      sei = new SEIToneMappingInfo;
+      xParseSEIToneMappingInfo((SEIToneMappingInfo&) *sei, payloadSize, pDecodedMessageOutputStream);
+      break;
+    case SEI::SOP_DESCRIPTION:
+      sei = new SEISOPDescription;
+      xParseSEISOPDescription((SEISOPDescription&) *sei, payloadSize, pDecodedMessageOutputStream);
+      break;
+    case SEI::SCALABLE_NESTING:
+      sei = new SEIScalableNesting;
+#if LAYERS_NOT_PRESENT_SEI
+      xParseSEIScalableNesting((SEIScalableNesting&) *sei, nalUnitType, payloadSize, vps, sps, pDecodedMessageOutputStream);
+#else
+      xParseSEIScalableNesting((SEIScalableNesting&) *sei, nalUnitType, payloadSize, sps, pDecodedMessageOutputStream);
+#endif
+      break;
+    case SEI::TEMP_MOTION_CONSTRAINED_TILE_SETS:
+      sei = new SEITempMotionConstrainedTileSets;
+      xParseSEITempMotionConstraintsTileSets((SEITempMotionConstrainedTileSets&) *sei, payloadSize, pDecodedMessageOutputStream);
+      break;
+    case SEI::TIME_CODE:
+      sei = new SEITimeCode;
+      xParseSEITimeCode((SEITimeCode&) *sei, payloadSize, pDecodedMessageOutputStream);
+      break;
+    case SEI::CHROMA_SAMPLING_FILTER_HINT:
+      sei = new SEIChromaSamplingFilterHint;
+      xParseSEIChromaSamplingFilterHint((SEIChromaSamplingFilterHint&) *sei, payloadSize/*, sps*/, pDecodedMessageOutputStream);
+      //}
+      break;
+    case SEI::KNEE_FUNCTION_INFO:
+      sei = new SEIKneeFunctionInfo;
+      xParseSEIKneeFunctionInfo((SEIKneeFunctionInfo&) *sei, payloadSize, pDecodedMessageOutputStream);
+      break;
+    case SEI::MASTERING_DISPLAY_COLOUR_VOLUME:
+      sei = new SEIMasteringDisplayColourVolume;
+      xParseSEIMasteringDisplayColourVolume((SEIMasteringDisplayColourVolume&) *sei, payloadSize, pDecodedMessageOutputStream);
+      break;
+#if Q0074_COLOUR_REMAPPING_SEI
+    case SEI::COLOUR_REMAPPING_INFO:
+      sei = new SEIColourRemappingInfo;
+      xParseSEIColourRemappingInfo((SEIColourRemappingInfo&) *sei, payloadSize, pDecodedMessageOutputStream);
+      break;
+#endif
+#if SVC_EXTENSION
+#if LAYERS_NOT_PRESENT_SEI
+    case SEI::LAYERS_NOT_PRESENT:
+      if (!vps)
+      {
+        printf ("Warning: Found Layers not present SEI message, but no active VPS is available. Ignoring.");
+      }
+      else
+      {
+        sei = new SEILayersNotPresent;
+        xParseSEILayersNotPresent((SEILayersNotPresent&) *sei, payloadSize, vps, pDecodedMessageOutputStream);
+      }
+      break;
+#endif
+#if N0383_IL_CONSTRAINED_TILE_SETS_SEI
+    case SEI::INTER_LAYER_CONSTRAINED_TILE_SETS:
+      sei = new SEIInterLayerConstrainedTileSets;
+      xParseSEIInterLayerConstrainedTileSets((SEIInterLayerConstrainedTileSets&) *sei, payloadSize, pDecodedMessageOutputStream);
+      break;
+#endif
+#if SUB_BITSTREAM_PROPERTY_SEI
+   case SEI::SUB_BITSTREAM_PROPERTY:
+     sei = new SEISubBitstreamProperty;
+#if OLS_IDX_CHK
+     xParseSEISubBitstreamProperty((SEISubBitstreamProperty&) *sei, vps, pDecodedMessageOutputStream);
+#else
+     xParseSEISubBitstreamProperty((SEISubBitstreamProperty&) *sei, pDecodedMessageOutputStream);
+#endif
+     break;
+#endif
+#if O0164_MULTI_LAYER_HRD
+   case SEI::BSP_NESTING:
+     sei = new SEIBspNesting;
+#if LAYERS_NOT_PRESENT_SEI
+     xParseSEIBspNesting((SEIBspNesting&) *sei, nalUnitType, vps, sps, *nestingSei, pDecodedMessageOutputStream);
+#else
+     xParseSEIBspNesting((SEIBspNesting&) *sei, nalUnitType, sps, *nestingSei, pDecodedMessageOutputStream);
+#endif
+     break;
+   case SEI::BSP_INITIAL_ARRIVAL_TIME:
+     sei = new SEIBspInitialArrivalTime;
+     xParseSEIBspInitialArrivalTime((SEIBspInitialArrivalTime&) *sei, vps, sps, *nestingSei, *bspNestingSei, pDecodedMessageOutputStream);
+     break;
+#if !REMOVE_BSP_HRD_SEI
+   case SEI::BSP_HRD:
+     sei = new SEIBspHrd;
+     xParseSEIBspHrd((SEIBspHrd&) *sei, sps, *nestingSei, pDecodedMessageOutputStream);
+     break;
+#endif
+#endif
+#if Q0078_ADD_LAYER_SETS
+   case SEI::OUTPUT_LAYER_SET_NESTING:
+     sei = new SEIOutputLayerSetNesting;
+#if LAYERS_NOT_PRESENT_SEI
+     xParseSEIOutputLayerSetNesting((SEIOutputLayerSetNesting&)*sei, nalUnitType, vps, sps, pDecodedMessageOutputStream);
+#else
+     xParseSEIOutputLayerSetNesting((SEIOutputLayerSetNesting&)*sei, nalUnitType, sps, pDecodedMessageOutputStream);
+#endif
+     break;
+   case SEI::VPS_REWRITING:
+     sei = new SEIVPSRewriting;
+     xParseSEIVPSRewriting((SEIVPSRewriting&)*sei, pDecodedMessageOutputStream);
+     break;
+#endif
+#if Q0189_TMVP_CONSTRAINTS
+   case SEI::TMVP_CONSTRAINTS:
+     sei =  new SEITMVPConstrains;
+     xParseSEITMVPConstraints((SEITMVPConstrains&) *sei, payloadSize, pDecodedMessageOutputStream);
+     break;
+#endif
+#if Q0247_FRAME_FIELD_INFO
+   case SEI::FRAME_FIELD_INFO:
+     sei =  new SEIFrameFieldInfo;
+     xParseSEIFrameFieldInfo    ((SEIFrameFieldInfo&) *sei, payloadSize, pDecodedMessageOutputStream);
+     break;
+#endif
+#if P0123_ALPHA_CHANNEL_SEI
+   case SEI::ALPHA_CHANNEL_INFO:
+     sei = new SEIAlphaChannelInfo;
+     xParseSEIAlphaChannelInfo((SEIAlphaChannelInfo &) *sei, payloadSize, pDecodedMessageOutputStream);
+     break;
+#endif
+#if Q0096_OVERLAY_SEI
+   case SEI::OVERLAY_INFO:
+     sei = new SEIOverlayInfo;
+     xParseSEIOverlayInfo((SEIOverlayInfo&) *sei, payloadSize, pDecodedMessageOutputStream);
+     break;
+#endif
+#endif //SVC_EXTENSION
+   default:
+     for (UInt i = 0; i < payloadSize; i++)
+     {
+       UInt seiByte;
+       sei_read_code (NULL, 8, seiByte, "unknown prefix SEI payload byte");
+     }
+     printf ("Unknown prefix SEI message (payloadType = %d) was found!\n", payloadType);
+     if (pDecodedMessageOutputStream)
+     {
+       (*pDecodedMessageOutputStream) << "Unknown prefix SEI message (payloadType = " << payloadType << ") was found!\n";
+     }
+     break;
+    }
+  }
+  else
+  {
+    switch (payloadType)
+    {
+      case SEI::USER_DATA_UNREGISTERED:
+        sei = new SEIuserDataUnregistered;
+        xParseSEIuserDataUnregistered((SEIuserDataUnregistered&) *sei, payloadSize, pDecodedMessageOutputStream);
+        break;
+      case SEI::DECODED_PICTURE_HASH:
+        sei = new SEIDecodedPictureHash;
+        xParseSEIDecodedPictureHash((SEIDecodedPictureHash&) *sei, payloadSize, pDecodedMessageOutputStream);
+        break;
+      default:
+        for (UInt i = 0; i < payloadSize; i++)
+        {
+          UInt seiByte;
+          sei_read_code( NULL, 8, seiByte, "unknown suffix SEI payload byte");
+        }
+        printf ("Unknown suffix SEI message (payloadType = %d) was found!\n", payloadType);
+        if (pDecodedMessageOutputStream)
+        {
+          (*pDecodedMessageOutputStream) << "Unknown suffix SEI message (payloadType = " << payloadType << ") was found!\n";
+        }
+        break;
+    }
+  }
+
+  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;
+      sei_read_code ( pDecodedMessageOutputStream, 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;
+      sei_read_flag ( 0, reservedPayloadExtensionData, "reserved_payload_extension_data");
+    }
+
+    UInt dummy;
+    sei_read_flag( 0, dummy, "payload_bit_equal_to_one"); payloadBitsRemaining--;
+    while (payloadBitsRemaining)
+    {
+      sei_read_flag( 0, dummy, "payload_bit_equal_to_zero"); payloadBitsRemaining--;
+    }
+  }
+
+  /* restore primary bitstream for sei_message */
+  getBitstream()->deleteFifo();
+  delete getBitstream();
+  setBitstream(bs);
+}
+
+/**
+ * parse bitstream bs and unpack a user_data_unregistered SEI message
+ * of payloasSize bytes into sei.
+ */
+
+Void SEIReader::xParseSEIuserDataUnregistered(SEIuserDataUnregistered &sei, UInt payloadSize, std::ostream *pDecodedMessageOutputStream)
+{
+  assert(payloadSize >= ISO_IEC_11578_LEN);
+  UInt val;
+  output_sei_message_header(sei, pDecodedMessageOutputStream, payloadSize);
+
+  for (UInt i = 0; i < ISO_IEC_11578_LEN; i++)
+  {
+    sei_read_code( pDecodedMessageOutputStream, 8, val, "uuid_iso_iec_11578");
+    sei.uuid_iso_iec_11578[i] = val;
+  }
+
+  sei.userDataLength = payloadSize - ISO_IEC_11578_LEN;
+  if (!sei.userDataLength)
+  {
+    sei.userData = 0;
+    return;
+  }
+
+  sei.userData = new UChar[sei.userDataLength];
+  for (UInt i = 0; i < sei.userDataLength; i++)
+  {
+    sei_read_code( pDecodedMessageOutputStream, 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, std::ostream *pDecodedMessageOutputStream)
+{
+  UInt bytesRead = 0;
+  output_sei_message_header(sei, pDecodedMessageOutputStream, payloadSize);
+
+  UInt val;
+  sei_read_code( pDecodedMessageOutputStream, 8, val, "hash_type");
+  sei.method = static_cast<SEIDecodedPictureHash::Method>(val); bytesRead++;
+
+  const Char *traceString="\0";
+  switch (sei.method)
+  {
+    case SEIDecodedPictureHash::MD5: traceString="picture_md5"; break;
+    case SEIDecodedPictureHash::CRC: traceString="picture_crc"; break;
+    case SEIDecodedPictureHash::CHECKSUM: traceString="picture_checksum"; break;
+    default: assert(false); break;
+  }
+
+  if (pDecodedMessageOutputStream) (*pDecodedMessageOutputStream) << "  " << std::setw(55) << traceString << ": " << std::hex << std::setfill('0');
+
+  sei.m_digest.hash.clear();
+  for(;bytesRead < payloadSize; bytesRead++)
+  {
+    sei_read_code( NULL, 8, val, traceString);
+    sei.m_digest.hash.push_back((UChar)val);
+    if (pDecodedMessageOutputStream) (*pDecodedMessageOutputStream) << std::setw(2) << val;
+  }
+
+  if (pDecodedMessageOutputStream) (*pDecodedMessageOutputStream) << std::dec << std::setfill(' ') << "\n";
+}
+
+Void SEIReader::xParseSEIActiveParameterSets(SEIActiveParameterSets& sei, UInt payloadSize, std::ostream *pDecodedMessageOutputStream)
+{
+  UInt val; 
+  output_sei_message_header(sei, pDecodedMessageOutputStream, payloadSize);
+
+  sei_read_code( pDecodedMessageOutputStream, 4, val, "active_video_parameter_set_id");   sei.activeVPSId = val;
+  sei_read_flag( pDecodedMessageOutputStream,    val, "self_contained_cvs_flag");         sei.m_selfContainedCvsFlag     = (val != 0);
+  sei_read_flag( pDecodedMessageOutputStream,    val, "no_parameter_set_update_flag");    sei.m_noParameterSetUpdateFlag = (val != 0);
+  sei_read_uvlc( pDecodedMessageOutputStream,    val, "num_sps_ids_minus1");              sei.numSpsIdsMinus1 = val;
+
+  sei.activeSeqParameterSetId.resize(sei.numSpsIdsMinus1 + 1);
+#if R0247_SEI_ACTIVE
+  sei.layerSpsIdx.resize(sei.numSpsIdsMinus1 + 1);
+#endif
+  for (Int i=0; i < (sei.numSpsIdsMinus1 + 1); i++)
+  {
+    sei_read_uvlc( pDecodedMessageOutputStream, val, "active_seq_parameter_set_id[i]");    sei.activeSeqParameterSetId[i] = val;
+  }
+#if R0247_SEI_ACTIVE
+  for (Int i=1; i < (sei.numSpsIdsMinus1 + 1); i++)
+  {
+    sei_read_uvlc( pDecodedMessageOutputStream, val, "layer_sps_idx"); sei.layerSpsIdx[i] = val; 
+  }
+#endif  
+}
+
+#if VPS_VUI_BSP_HRD_PARAMS
+Void SEIReader::xParseSEIDecodingUnitInfo(SEIDecodingUnitInfo& sei, UInt payloadSize, TComSPS *sps, const SEIScalableNesting* nestingSei, const SEIBspNesting* bspNestingSei, TComVPS *vps,std::ostream *pDecodedMessageOutputStream)
+#else
+Void SEIReader::xParseSEIDecodingUnitInfo(SEIDecodingUnitInfo& sei, UInt payloadSize, TComSPS *sps, std::ostream *pDecodedMessageOutputStream)
+#endif
+{
+  UInt val;
+  output_sei_message_header(sei, pDecodedMessageOutputStream, payloadSize);
+  sei_read_uvlc( pDecodedMessageOutputStream, val, "decoding_unit_idx");
+  sei.m_decodingUnitIdx = val;
+
+#if VPS_VUI_BSP_HRD_PARAMS
+  TComHRD *hrd;
+  if( bspNestingSei )   // If DU info SEI contained inside a BSP nesting SEI message
+  {
+    assert( nestingSei );
+    Int psIdx = bspNestingSei->m_seiPartitioningSchemeIdx;
+    Int seiOlsIdx = bspNestingSei->m_seiOlsIdx;
+    Int maxTemporalId = nestingSei->m_nestingMaxTemporalIdPlus1[0] - 1;
+    Int maxValues = vps->getNumBspSchedulesMinus1(seiOlsIdx, psIdx, maxTemporalId) + 1;
+    std::vector<Int> hrdIdx(maxValues, 0);
+    std::vector<TComHRD *> hrdVec;
+    std::vector<Int> syntaxElemLen(maxValues, 0);
+    for(Int i = 0; i < maxValues; i++)
+    {
+      hrdIdx[i] = vps->getBspHrdIdx( seiOlsIdx, psIdx, maxTemporalId, i, bspNestingSei->m_bspIdx);
+      hrdVec.push_back(vps->getBspHrd(hrdIdx[i]));
+    
+      syntaxElemLen[i] = hrdVec[i]->getInitialCpbRemovalDelayLengthMinus1() + 1;
+      if ( !(hrdVec[i]->getNalHrdParametersPresentFlag() || hrdVec[i]->getVclHrdParametersPresentFlag()) )
+      {
+        assert( syntaxElemLen[i] == 24 ); // Default of value init_cpb_removal_delay_length_minus1 is 23
+      }
+      if( i > 0 )
+      {
+        assert( hrdVec[i]->getSubPicCpbParamsPresentFlag()    == hrdVec[i-1]->getSubPicCpbParamsPresentFlag() );
+        assert( hrdVec[i]->getSubPicCpbParamsInPicTimingSEIFlag()   == hrdVec[i-1]->getSubPicCpbParamsInPicTimingSEIFlag() );
+        assert( hrdVec[i]->getDpbOutputDelayDuLengthMinus1()  == hrdVec[i-1]->getDpbOutputDelayDuLengthMinus1() );
+        // To be done: Check CpbDpbDelaysPresentFlag
+      }
+    }
+    hrd = hrdVec[0];
+  }
+  else
+  {
+    TComVUI *vui = sps->getVuiParameters();
+    hrd = vui->getHrdParameters();
+  }
+
+  if(hrd->getSubPicCpbParamsInPicTimingSEIFlag())
+  {
+    sei_read_code( pDecodedMessageOutputStream, ( hrd->getDuCpbRemovalDelayLengthMinus1() + 1 ), val, "du_spt_cpb_removal_delay_increment");
+    sei.m_duSptCpbRemovalDelay = val;
+  }
+  else
+  {
+    sei.m_duSptCpbRemovalDelay = 0;
+  }
+  sei_read_flag( pDecodedMessageOutputStream, val, "dpb_output_du_delay_present_flag"); sei.m_dpbOutputDuDelayPresentFlag = (val != 0);
+  if(sei.m_dpbOutputDuDelayPresentFlag)
+  {
+    sei_read_code( pDecodedMessageOutputStream, hrd->getDpbOutputDelayDuLengthMinus1() + 1, val, "pic_spt_dpb_output_du_delay");
+    sei.m_picSptDpbOutputDuDelay = val;
+  }
+#else
+  TComVUI *vui = sps->getVuiParameters();  
+
+  if(vui->getHrdParameters()->getSubPicCpbParamsInPicTimingSEIFlag())
+  {
+    sei_read_code( pDecodedMessageOutputStream, ( vui->getHrdParameters()->getDuCpbRemovalDelayLengthMinus1() + 1 ), val, "du_spt_cpb_removal_delay_increment");
+    sei.m_duSptCpbRemovalDelay = val;
+  }
+  else
+  {
+    sei.m_duSptCpbRemovalDelay = 0;
+  }
+  sei_read_flag( pDecodedMessageOutputStream, val, "dpb_output_du_delay_present_flag"); sei.m_dpbOutputDuDelayPresentFlag = (val != 0);
+  if(sei.m_dpbOutputDuDelayPresentFlag)
+  {
+    sei_read_code( pDecodedMessageOutputStream, vui->getHrdParameters()->getDpbOutputDelayDuLengthMinus1() + 1, val, "pic_spt_dpb_output_du_delay");
+    sei.m_picSptDpbOutputDuDelay = val;
+  }
+#endif
+}
+
+#if VPS_VUI_BSP_HRD_PARAMS
+Void SEIReader::xParseSEIBufferingPeriod(SEIBufferingPeriod& sei, UInt payloadSize, TComSPS *sps, const SEIScalableNesting* nestingSei, const SEIBspNesting* bspNestingSei, TComVPS *vps, std::ostream *pDecodedMessageOutputStream)
+#else
+Void SEIReader::xParseSEIBufferingPeriod(SEIBufferingPeriod& sei, UInt payloadSize, TComSPS *sps, std::ostream *pDecodedMessageOutputStream)
+#endif
+{
+  Int i, nalOrVcl;
+  UInt code;
+
+#if VPS_VUI_BSP_HRD_PARAMS
+  TComHRD *pHRD;
+  if( bspNestingSei )   // If BP SEI contained inside a BSP nesting SEI message
+  {
+    assert( nestingSei );
+    Int psIdx = bspNestingSei->m_seiPartitioningSchemeIdx;
+    Int seiOlsIdx = bspNestingSei->m_seiOlsIdx;
+    Int maxTemporalId = nestingSei->m_nestingMaxTemporalIdPlus1[0] - 1;
+    Int maxValues = vps->getNumBspSchedulesMinus1(seiOlsIdx, psIdx, maxTemporalId) + 1;
+    std::vector<Int> hrdIdx(maxValues, 0);
+    std::vector<TComHRD *> hrdVec;
+    std::vector<Int> syntaxElemLen(maxValues, 0);
+    for(i = 0; i < maxValues; i++)
+    {
+      hrdIdx[i] = vps->getBspHrdIdx( seiOlsIdx, psIdx, maxTemporalId, i, bspNestingSei->m_bspIdx);
+      hrdVec.push_back(vps->getBspHrd(hrdIdx[i]));
+    
+      syntaxElemLen[i] = hrdVec[i]->getInitialCpbRemovalDelayLengthMinus1() + 1;
+      if ( !(hrdVec[i]->getNalHrdParametersPresentFlag() || hrdVec[i]->getVclHrdParametersPresentFlag()) )
+      {
+        assert( syntaxElemLen[i] == 24 ); // Default of value init_cpb_removal_delay_length_minus1 is 23
+      }
+      if( i > 0 )
+      {
+        assert( hrdVec[i]->getCpbRemovalDelayLengthMinus1()   == hrdVec[i-1]->getCpbRemovalDelayLengthMinus1() );
+        assert( hrdVec[i]->getDpbOutputDelayDuLengthMinus1()  == hrdVec[i-1]->getDpbOutputDelayDuLengthMinus1() );
+        assert( hrdVec[i]->getSubPicCpbParamsPresentFlag()    == hrdVec[i-1]->getSubPicCpbParamsPresentFlag() );
+      }
+    }
+    pHRD = hrdVec[i];
+  }
+  else
+  {
+    TComVUI *vui = sps->getVuiParameters();
+    pHRD = vui->getHrdParameters();
+  }
+  // To be done: When contained in an BSP HRD SEI message, the hrd structure is to be chosen differently.
+#else
+  TComVUI *pVUI = sps->getVuiParameters();
+  TComHRD *pHRD = pVUI->getHrdParameters();
+#endif
+
+  output_sei_message_header(sei, pDecodedMessageOutputStream, payloadSize);
+
+  sei_read_uvlc( pDecodedMessageOutputStream, code, "bp_seq_parameter_set_id" );                         sei.m_bpSeqParameterSetId     = code;
+  if( !pHRD->getSubPicCpbParamsPresentFlag() )
+  {
+    sei_read_flag( pDecodedMessageOutputStream, code, "irap_cpb_params_present_flag" );                   sei.m_rapCpbParamsPresentFlag = code;
+  }
+  if( sei.m_rapCpbParamsPresentFlag )
+  {
+    sei_read_code( pDecodedMessageOutputStream, pHRD->getCpbRemovalDelayLengthMinus1() + 1, code, "cpb_delay_offset" );      sei.m_cpbDelayOffset = code;
+    sei_read_code( pDecodedMessageOutputStream, pHRD->getDpbOutputDelayLengthMinus1()  + 1, code, "dpb_delay_offset" );      sei.m_dpbDelayOffset = code;
+  }
+
+  //read splicing flag and cpb_removal_delay_delta
+  sei_read_flag( pDecodedMessageOutputStream, code, "concatenation_flag");
+  sei.m_concatenationFlag = code;
+  sei_read_code( pDecodedMessageOutputStream, ( pHRD->getCpbRemovalDelayLengthMinus1() + 1 ), code, "au_cpb_removal_delay_delta_minus1" );
+  sei.m_auCpbRemovalDelayDelta = code + 1;
+
+  for( nalOrVcl = 0; nalOrVcl < 2; nalOrVcl ++ )
+  {
+    if( ( ( nalOrVcl == 0 ) && ( pHRD->getNalHrdParametersPresentFlag() ) ) ||
+        ( ( nalOrVcl == 1 ) && ( pHRD->getVclHrdParametersPresentFlag() ) ) )
+    {
+      for( i = 0; i < ( pHRD->getCpbCntMinus1( 0 ) + 1 ); i ++ )
+      {
+        sei_read_code( pDecodedMessageOutputStream, ( pHRD->getInitialCpbRemovalDelayLengthMinus1() + 1 ) , code, nalOrVcl?"vcl_initial_cpb_removal_delay":"nal_initial_cpb_removal_delay" );
+        sei.m_initialCpbRemovalDelay[i][nalOrVcl] = code;
+        sei_read_code( pDecodedMessageOutputStream, ( pHRD->getInitialCpbRemovalDelayLengthMinus1() + 1 ) , code, nalOrVcl?"vcl_initial_cpb_removal_offset":"vcl_initial_cpb_removal_offset" );
+        sei.m_initialCpbRemovalDelayOffset[i][nalOrVcl] = code;
+        if( pHRD->getSubPicCpbParamsPresentFlag() || sei.m_rapCpbParamsPresentFlag )
+        {
+          sei_read_code( pDecodedMessageOutputStream, ( pHRD->getInitialCpbRemovalDelayLengthMinus1() + 1 ) , code, nalOrVcl?"vcl_initial_alt_cpb_removal_delay":"vcl_initial_alt_cpb_removal_delay" );
+          sei.m_initialAltCpbRemovalDelay[i][nalOrVcl] = code;
+          sei_read_code( pDecodedMessageOutputStream, ( pHRD->getInitialCpbRemovalDelayLengthMinus1() + 1 ) , code, nalOrVcl?"vcl_initial_alt_cpb_removal_offset":"vcl_initial_alt_cpb_removal_offset" );
+          sei.m_initialAltCpbRemovalDelayOffset[i][nalOrVcl] = code;
+        }
+      }
+    }
+  }
+
+#if P0138_USE_ALT_CPB_PARAMS_FLAG
+  sei.m_useAltCpbParamsFlag = false;
+  sei.m_useAltCpbParamsFlagPresent = false;
+  if (xPayloadExtensionPresent())
+  {
+    sei_read_flag( pDecodedMessageOutputStream, code, "use_alt_cpb_params_flag");
+    sei.m_useAltCpbParamsFlag = code;
+    sei.m_useAltCpbParamsFlagPresent = true;
+  }
+#endif
+}
+
+#if VPS_VUI_BSP_HRD_PARAMS
+Void SEIReader::xParseSEIPictureTiming(SEIPictureTiming& sei, UInt payloadSize, TComSPS *sps, const SEIScalableNesting* nestingSei, const SEIBspNesting* bspNestingSei, TComVPS *vps, std::ostream *pDecodedMessageOutputStream)
+#else
+Void SEIReader::xParseSEIPictureTiming(SEIPictureTiming& sei, UInt payloadSize, TComSPS *sps, std::ostream *pDecodedMessageOutputStream)
+#endif
+{
+  Int i;
+  UInt code;
+
+#if VPS_VUI_BSP_HRD_PARAMS
+  TComHRD *hrd;    
+  TComVUI *vui = sps->getVuiParameters(); 
+  if( bspNestingSei )   // If BP SEI contained inside a BSP nesting SEI message
+  {
+    assert( nestingSei );
+    Int psIdx = bspNestingSei->m_seiPartitioningSchemeIdx;
+    Int seiOlsIdx = bspNestingSei->m_seiOlsIdx;
+    Int maxTemporalId = nestingSei->m_nestingMaxTemporalIdPlus1[0] - 1;
+    Int maxValues = vps->getNumBspSchedulesMinus1(seiOlsIdx, psIdx, maxTemporalId) + 1;
+    std::vector<Int> hrdIdx(maxValues, 0);
+    std::vector<TComHRD *> hrdVec;
+    std::vector<Int> syntaxElemLen(maxValues, 0);
+    for(i = 0; i < maxValues; i++)
+    {
+      hrdIdx[i] = vps->getBspHrdIdx( seiOlsIdx, psIdx, maxTemporalId, i, bspNestingSei->m_bspIdx);
+      hrdVec.push_back(vps->getBspHrd(hrdIdx[i]));
+    
+      syntaxElemLen[i] = hrdVec[i]->getInitialCpbRemovalDelayLengthMinus1() + 1;
+      if ( !(hrdVec[i]->getNalHrdParametersPresentFlag() || hrdVec[i]->getVclHrdParametersPresentFlag()) )
+      {
+        assert( syntaxElemLen[i] == 24 ); // Default of value init_cpb_removal_delay_length_minus1 is 23
+      }
+      if( i > 0 )
+      {
+        assert( hrdVec[i]->getSubPicCpbParamsPresentFlag()    == hrdVec[i-1]->getSubPicCpbParamsPresentFlag() );
+        assert( hrdVec[i]->getSubPicCpbParamsInPicTimingSEIFlag()   == hrdVec[i-1]->getSubPicCpbParamsInPicTimingSEIFlag() );
+        assert( hrdVec[i]->getCpbRemovalDelayLengthMinus1()  == hrdVec[i-1]->getCpbRemovalDelayLengthMinus1() );
+        assert( hrdVec[i]->getDpbOutputDelayLengthMinus1()  == hrdVec[i-1]->getDpbOutputDelayLengthMinus1() );
+        assert( hrdVec[i]->getDpbOutputDelayDuLengthMinus1()  == hrdVec[i-1]->getDpbOutputDelayDuLengthMinus1() );
+        assert( hrdVec[i]->getDuCpbRemovalDelayLengthMinus1()  == hrdVec[i-1]->getDuCpbRemovalDelayLengthMinus1() );
+        // To be done: Check CpbDpbDelaysPresentFlag
+      }
+    }
+    hrd = hrdVec[0];
+  }
+  else
+  {
+    hrd = vui->getHrdParameters();
+  }
+  // To be done: When contained in an BSP HRD SEI message, the hrd structure is to be chosen differently.
+#else
+  TComVUI *vui = sps->getVuiParameters();
+  TComHRD *hrd = vui->getHrdParameters();
+#endif
+  output_sei_message_header(sei, pDecodedMessageOutputStream, payloadSize);
+
+  if( vui->getFrameFieldInfoPresentFlag() )
+  {
+    sei_read_code( pDecodedMessageOutputStream, 4, code, "pic_struct" );             sei.m_picStruct            = code;
+    sei_read_code( pDecodedMessageOutputStream, 2, code, "source_scan_type" );       sei.m_sourceScanType       = code;
+    sei_read_flag( pDecodedMessageOutputStream,    code, "duplicate_flag" );         sei.m_duplicateFlag        = (code == 1);
+  }
+
+  if( hrd->getCpbDpbDelaysPresentFlag())
+  {
+    sei_read_code( pDecodedMessageOutputStream, ( hrd->getCpbRemovalDelayLengthMinus1() + 1 ), code, "au_cpb_removal_delay_minus1" );
+    sei.m_auCpbRemovalDelay = code + 1;
+    sei_read_code( pDecodedMessageOutputStream, ( hrd->getDpbOutputDelayLengthMinus1() + 1 ), code, "pic_dpb_output_delay" );
+    sei.m_picDpbOutputDelay = code;
+
+    if(hrd->getSubPicCpbParamsPresentFlag())
+    {
+      sei_read_code( pDecodedMessageOutputStream, hrd->getDpbOutputDelayDuLengthMinus1()+1, code, "pic_dpb_output_du_delay" );
+      sei.m_picDpbOutputDuDelay = code;
+    }
+
+    if( hrd->getSubPicCpbParamsPresentFlag() && hrd->getSubPicCpbParamsInPicTimingSEIFlag() )
+    {
+      sei_read_uvlc( pDecodedMessageOutputStream, code, "num_decoding_units_minus1");
+      sei.m_numDecodingUnitsMinus1 = code;
+      sei_read_flag( pDecodedMessageOutputStream, code, "du_common_cpb_removal_delay_flag" );
+      sei.m_duCommonCpbRemovalDelayFlag = code;
+      if( sei.m_duCommonCpbRemovalDelayFlag )
+      {
+        sei_read_code( pDecodedMessageOutputStream, ( hrd->getDuCpbRemovalDelayLengthMinus1() + 1 ), code, "du_common_cpb_removal_delay_increment_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 ++ )
+      {
+        sei_read_uvlc( pDecodedMessageOutputStream, code, "num_nalus_in_du_minus1[i]");
+        sei.m_numNalusInDuMinus1[ i ] = code;
+        if( ( !sei.m_duCommonCpbRemovalDelayFlag ) && ( i < sei.m_numDecodingUnitsMinus1 ) )
+        {
+          sei_read_code( pDecodedMessageOutputStream, ( hrd->getDuCpbRemovalDelayLengthMinus1() + 1 ), code, "du_cpb_removal_delay_minus1[i]" );
+          sei.m_duCpbRemovalDelayMinus1[ i ] = code;
+        }
+      }
+    }
+  }
+}
+
+Void SEIReader::xParseSEIRecoveryPoint(SEIRecoveryPoint& sei, UInt payloadSize, std::ostream *pDecodedMessageOutputStream)
+{
+  Int  iCode;
+  UInt uiCode;
+  output_sei_message_header(sei, pDecodedMessageOutputStream, payloadSize);
+
+  sei_read_svlc( pDecodedMessageOutputStream, iCode,  "recovery_poc_cnt" );      sei.m_recoveryPocCnt     = iCode;
+  sei_read_flag( pDecodedMessageOutputStream, uiCode, "exact_matching_flag" );   sei.m_exactMatchingFlag  = uiCode;
+  sei_read_flag( pDecodedMessageOutputStream, uiCode, "broken_link_flag" );      sei.m_brokenLinkFlag     = uiCode;
+}
+
+Void SEIReader::xParseSEIFramePacking(SEIFramePacking& sei, UInt payloadSize, std::ostream *pDecodedMessageOutputStream)
+{
+  UInt val;
+  output_sei_message_header(sei, pDecodedMessageOutputStream, payloadSize);
+
+  sei_read_uvlc( pDecodedMessageOutputStream, val, "frame_packing_arrangement_id" );                 sei.m_arrangementId = val;
+  sei_read_flag( pDecodedMessageOutputStream, val, "frame_packing_arrangement_cancel_flag" );        sei.m_arrangementCancelFlag = val;
+
+  if ( !sei.m_arrangementCancelFlag )
+  {
+    sei_read_code( pDecodedMessageOutputStream, 7, val, "frame_packing_arrangement_type" );          sei.m_arrangementType = val;
+    assert((sei.m_arrangementType > 2) && (sei.m_arrangementType < 6) );
+
+    sei_read_flag( pDecodedMessageOutputStream, val, "quincunx_sampling_flag" );                     sei.m_quincunxSamplingFlag = val;
+
+    sei_read_code( pDecodedMessageOutputStream, 6, val, "content_interpretation_type" );             sei.m_contentInterpretationType = val;
+    sei_read_flag( pDecodedMessageOutputStream, val, "spatial_flipping_flag" );                      sei.m_spatialFlippingFlag = val;
+    sei_read_flag( pDecodedMessageOutputStream, val, "frame0_flipped_flag" );                        sei.m_frame0FlippedFlag = val;
+    sei_read_flag( pDecodedMessageOutputStream, val, "field_views_flag" );                           sei.m_fieldViewsFlag = val;
+    sei_read_flag( pDecodedMessageOutputStream, val, "current_frame_is_frame0_flag" );               sei.m_currentFrameIsFrame0Flag = val;
+    sei_read_flag( pDecodedMessageOutputStream, val, "frame0_self_contained_flag" );                 sei.m_frame0SelfContainedFlag = val;
+    sei_read_flag( pDecodedMessageOutputStream, val, "frame1_self_contained_flag" );                 sei.m_frame1SelfContainedFlag = val;
+
+    if ( sei.m_quincunxSamplingFlag == 0 && sei.m_arrangementType != 5)
+    {
+      sei_read_code( pDecodedMessageOutputStream, 4, val, "frame0_grid_position_x" );                sei.m_frame0GridPositionX = val;
+      sei_read_code( pDecodedMessageOutputStream, 4, val, "frame0_grid_position_y" );                sei.m_frame0GridPositionY = val;
+      sei_read_code( pDecodedMessageOutputStream, 4, val, "frame1_grid_position_x" );                sei.m_frame1GridPositionX = val;
+      sei_read_code( pDecodedMessageOutputStream, 4, val, "frame1_grid_position_y" );                sei.m_frame1GridPositionY = val;
+    }
+
+    sei_read_code( pDecodedMessageOutputStream, 8, val, "frame_packing_arrangement_reserved_byte" );   sei.m_arrangementReservedByte = val;
+    sei_read_flag( pDecodedMessageOutputStream, val,  "frame_packing_arrangement_persistence_flag" );  sei.m_arrangementPersistenceFlag = (val != 0);
+  }
+  sei_read_flag( pDecodedMessageOutputStream, val, "upsampled_aspect_ratio_flag" );                  sei.m_upsampledAspectRatio = val;
+}
+
+Void SEIReader::xParseSEISegmentedRectFramePacking(SEISegmentedRectFramePacking& sei, UInt payloadSize, std::ostream *pDecodedMessageOutputStream)
+{
+  UInt val;
+  output_sei_message_header(sei, pDecodedMessageOutputStream, payloadSize);
+  sei_read_flag( pDecodedMessageOutputStream, val,       "segmented_rect_frame_packing_arrangement_cancel_flag" );       sei.m_arrangementCancelFlag            = val;
+  if( !sei.m_arrangementCancelFlag )
+  {
+    sei_read_code( pDecodedMessageOutputStream, 2, val, "segmented_rect_content_interpretation_type" );                sei.m_contentInterpretationType = val;
+    sei_read_flag( pDecodedMessageOutputStream, val,     "segmented_rect_frame_packing_arrangement_persistence" );                              sei.m_arrangementPersistenceFlag               = val;
+  }
+}
+
+Void SEIReader::xParseSEIDisplayOrientation(SEIDisplayOrientation& sei, UInt payloadSize, std::ostream *pDecodedMessageOutputStream)
+{
+  UInt val;
+  output_sei_message_header(sei, pDecodedMessageOutputStream, payloadSize);
+  sei_read_flag( pDecodedMessageOutputStream, val,       "display_orientation_cancel_flag" );       sei.cancelFlag            = val;
+  if( !sei.cancelFlag )
+  {
+    sei_read_flag( pDecodedMessageOutputStream, val,     "hor_flip" );                              sei.horFlip               = val;
+    sei_read_flag( pDecodedMessageOutputStream, val,     "ver_flip" );                              sei.verFlip               = val;
+    sei_read_code( pDecodedMessageOutputStream, 16, val, "anticlockwise_rotation" );                sei.anticlockwiseRotation = val;
+    sei_read_flag( pDecodedMessageOutputStream, val,     "display_orientation_persistence_flag" );  sei.persistenceFlag       = val;
+  }
+}
+
+Void SEIReader::xParseSEITemporalLevel0Index(SEITemporalLevel0Index& sei, UInt payloadSize, std::ostream *pDecodedMessageOutputStream)
+{
+  UInt val;
+  output_sei_message_header(sei, pDecodedMessageOutputStream, payloadSize);
+  sei_read_code( pDecodedMessageOutputStream, 8, val, "temporal_sub_layer_zero_idx" );  sei.tl0Idx = val;
+  sei_read_code( pDecodedMessageOutputStream, 8, val, "irap_pic_id" );  sei.rapIdx = val;
+}
+
+Void SEIReader::xParseSEIRegionRefreshInfo(SEIGradualDecodingRefreshInfo& sei, UInt payloadSize, std::ostream *pDecodedMessageOutputStream)
+{
+  UInt val;
+  output_sei_message_header(sei, pDecodedMessageOutputStream, payloadSize);
+  sei_read_flag( pDecodedMessageOutputStream, val, "refreshed_region_flag" ); sei.m_gdrForegroundFlag = val ? 1 : 0;
+}
+
+Void SEIReader::xParseSEINoDisplay(SEINoDisplay& sei, UInt payloadSize, std::ostream *pDecodedMessageOutputStream)
+{
+  output_sei_message_header(sei, pDecodedMessageOutputStream, payloadSize);
+  sei.m_noDisplay = true;
+}
+
+Void SEIReader::xParseSEIToneMappingInfo(SEIToneMappingInfo& sei, UInt payloadSize, std::ostream *pDecodedMessageOutputStream)
+{
+  Int i;
+  UInt val;
+  output_sei_message_header(sei, pDecodedMessageOutputStream, payloadSize);
+  sei_read_uvlc( pDecodedMessageOutputStream, val, "tone_map_id" );                         sei.m_toneMapId = val;
+  sei_read_flag( pDecodedMessageOutputStream, val, "tone_map_cancel_flag" );                sei.m_toneMapCancelFlag = val;
+
+  if ( !sei.m_toneMapCancelFlag )
+  {
+    sei_read_flag( pDecodedMessageOutputStream, val, "tone_map_persistence_flag" );         sei.m_toneMapPersistenceFlag = val;
+    sei_read_code( pDecodedMessageOutputStream, 8, val, "coded_data_bit_depth" );           sei.m_codedDataBitDepth = val;
+    sei_read_code( pDecodedMessageOutputStream, 8, val, "target_bit_depth" );               sei.m_targetBitDepth = val;
+    sei_read_uvlc( pDecodedMessageOutputStream, val, "tone_map_model_id" );                 sei.m_modelId = val;
+    switch(sei.m_modelId)
+    {
+    case 0:
+      {
+        sei_read_code( pDecodedMessageOutputStream, 32, val, "min_value" );                 sei.m_minValue = val;
+        sei_read_code( pDecodedMessageOutputStream, 32, val, "max_value" );                 sei.m_maxValue = val;
+        break;
+      }
+    case 1:
+      {
+        sei_read_code( pDecodedMessageOutputStream, 32, val, "sigmoid_midpoint" );          sei.m_sigmoidMidpoint = val;
+        sei_read_code( pDecodedMessageOutputStream, 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++)
+        {
+          sei_read_code( pDecodedMessageOutputStream, ((( sei.m_codedDataBitDepth + 7 ) >> 3 ) << 3), val, "start_of_coded_interval[i]" );
+          sei.m_startOfCodedInterval[i] = val;
+        }
+        sei.m_startOfCodedInterval[num] = 1u << sei.m_codedDataBitDepth;
+        break;
+      }
+    case 3:
+      {
+        sei_read_code( pDecodedMessageOutputStream, 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++ )
+        {
+          sei_read_code( pDecodedMessageOutputStream, ((( sei.m_codedDataBitDepth + 7 ) >> 3 ) << 3), val, "coded_pivot_value[i]" );
+          sei.m_codedPivotValue[i] = val;
+          sei_read_code( pDecodedMessageOutputStream, ((( sei.m_targetBitDepth + 7 ) >> 3 ) << 3),    val, "target_pivot_value[i]" );
+          sei.m_targetPivotValue[i] = val;
+        }
+        break;
+      }
+    case 4:
+      {
+        sei_read_code( pDecodedMessageOutputStream, 8, val, "camera_iso_speed_idc" );                     sei.m_cameraIsoSpeedIdc = val;
+        if( sei.m_cameraIsoSpeedIdc == 255) //Extended_ISO
+        {
+          sei_read_code( pDecodedMessageOutputStream, 32,   val,   "camera_iso_speed_value" );            sei.m_cameraIsoSpeedValue = val;
+        }
+        sei_read_code( pDecodedMessageOutputStream, 8, val, "exposure_index_idc" );                       sei.m_exposureIndexIdc = val;
+        if( sei.m_exposureIndexIdc == 255) //Extended_ISO
+        {
+          sei_read_code( pDecodedMessageOutputStream, 32,   val,   "exposure_index_value" );              sei.m_exposureIndexValue = val;
+        }
+        sei_read_flag( pDecodedMessageOutputStream, val, "exposure_compensation_value_sign_flag" );       sei.m_exposureCompensationValueSignFlag = val;
+        sei_read_code( pDecodedMessageOutputStream, 16, val, "exposure_compensation_value_numerator" );   sei.m_exposureCompensationValueNumerator = val;
+        sei_read_code( pDecodedMessageOutputStream, 16, val, "exposure_compensation_value_denom_idc" );   sei.m_exposureCompensationValueDenomIdc = val;
+        sei_read_code( pDecodedMessageOutputStream, 32, val, "ref_screen_luminance_white" );              sei.m_refScreenLuminanceWhite = val;
+        sei_read_code( pDecodedMessageOutputStream, 32, val, "extended_range_white_level" );              sei.m_extendedRangeWhiteLevel = val;
+        sei_read_code( pDecodedMessageOutputStream, 16, val, "nominal_black_level_code_value" );          sei.m_nominalBlackLevelLumaCodeValue = val;
+        sei_read_code( pDecodedMessageOutputStream, 16, val, "nominal_white_level_code_value" );          sei.m_nominalWhiteLevelLumaCodeValue= val;
+        sei_read_code( pDecodedMessageOutputStream, 16, val, "extended_white_level_code_value" );         sei.m_extendedWhiteLevelLumaCodeValue = val;
+        break;
+      }
+    default:
+      {
+        assert(!"Undefined SEIToneMapModelId");
+        break;
+      }
+    }//switch model id
+  }// if(!sei.m_toneMapCancelFlag)
+}
+
+Void SEIReader::xParseSEISOPDescription(SEISOPDescription &sei, UInt payloadSize, std::ostream *pDecodedMessageOutputStream)
+{
+  Int iCode;
+  UInt uiCode;
+  output_sei_message_header(sei, pDecodedMessageOutputStream, payloadSize);
+
+  sei_read_uvlc( pDecodedMessageOutputStream, uiCode,           "sop_seq_parameter_set_id"            ); sei.m_sopSeqParameterSetId = uiCode;
+  sei_read_uvlc( pDecodedMessageOutputStream, uiCode,           "num_pics_in_sop_minus1"              ); sei.m_numPicsInSopMinus1 = uiCode;
+  for (UInt i = 0; i <= sei.m_numPicsInSopMinus1; i++)
+  {
+    sei_read_code( pDecodedMessageOutputStream, 6, uiCode,                     "sop_vcl_nut[i]" );  sei.m_sopDescVclNaluType[i] = uiCode;
+    sei_read_code( pDecodedMessageOutputStream, 3, sei.m_sopDescTemporalId[i], "sop_temporal_id[i]"   );  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)
+    {
+      sei_read_uvlc( pDecodedMessageOutputStream, sei.m_sopDescStRpsIdx[i],    "sop_short_term_rps_idx[i]"    ); sei.m_sopDescStRpsIdx[i] = uiCode;
+    }
+    if (i > 0)
+    {
+      sei_read_svlc( pDecodedMessageOutputStream, iCode,                       "sop_poc_delta[i]"     ); sei.m_sopDescPocDelta[i] = iCode;
+    }
+  }
+}
+
+#if LAYERS_NOT_PRESENT_SEI
+Void SEIReader::xParseSEIScalableNesting(SEIScalableNesting& sei, const NalUnitType nalUnitType, UInt payloadSize, TComVPS *vps, TComSPS *sps, std::ostream *pDecodedMessageOutputStream)
+#else
+Void SEIReader::xParseSEIScalableNesting(SEIScalableNesting& sei, const NalUnitType nalUnitType, UInt payloadSize, TComSPS *sps, std::ostream *pDecodedMessageOutputStream)
+#endif
+{
+  UInt uiCode;
+  SEIMessages seis;
+  output_sei_message_header(sei, pDecodedMessageOutputStream, payloadSize);
+
+  sei_read_flag( pDecodedMessageOutputStream, uiCode,            "bitstream_subset_flag"         ); sei.m_bitStreamSubsetFlag = uiCode;
+  sei_read_flag( pDecodedMessageOutputStream, uiCode,            "nesting_op_flag"               ); sei.m_nestingOpFlag = uiCode;
+  if (sei.m_nestingOpFlag)
+  {
+    sei_read_flag( pDecodedMessageOutputStream, uiCode,            "default_op_flag"               ); sei.m_defaultOpFlag = uiCode;
+    sei_read_uvlc( pDecodedMessageOutputStream, uiCode,            "nesting_num_ops_minus1"        ); sei.m_nestingNumOpsMinus1 = uiCode;
+    for (UInt i = sei.m_defaultOpFlag; i <= sei.m_nestingNumOpsMinus1; i++)
+    {
+      sei_read_code( pDecodedMessageOutputStream, 3,        uiCode,  "nesting_max_temporal_id_plus1[i]"   ); sei.m_nestingMaxTemporalIdPlus1[i] = uiCode;
+      sei_read_uvlc( pDecodedMessageOutputStream, uiCode,            "nesting_op_idx[i]"                  ); sei.m_nestingOpIdx[i] = uiCode;
+    }
+  }
+  else
+  {
+    sei_read_flag( pDecodedMessageOutputStream, uiCode,            "all_layers_flag"               ); sei.m_allLayersFlag       = uiCode;
+    if (!sei.m_allLayersFlag)
+    {
+      sei_read_code( pDecodedMessageOutputStream, 3,        uiCode,  "nesting_no_op_max_temporal_id_plus1"  ); sei.m_nestingNoOpMaxTemporalIdPlus1 = uiCode;
+      sei_read_uvlc( pDecodedMessageOutputStream, uiCode,            "nesting_num_layers_minus1"            ); sei.m_nestingNumLayersMinus1        = uiCode;
+      for (UInt i = 0; i <= sei.m_nestingNumLayersMinus1; i++)
+      {
+        sei_read_code( pDecodedMessageOutputStream, 6,           uiCode,     "nesting_layer_id[i]"      ); sei.m_nestingLayerId[i]   = uiCode;
+      }
+    }
+  }
+
+  // byte alignment
+  while ( m_pcBitstream->getNumBitsRead() % 8 != 0 )
+  {
+    UInt code;
+    sei_read_flag( pDecodedMessageOutputStream, code, "nesting_zero_bit" );
+  }
+
+  sei.m_callerOwnsSEIs = false;
+
+  // read nested SEI messages
+  do {
+#if O0164_MULTI_LAYER_HRD
+#if LAYERS_NOT_PRESENT_SEI
+    xReadSEImessage(sei.m_nestedSEIs, nalUnitType, vps, sps, pDecodedMessageOutputStream, &sei);
+#else
+    xReadSEImessage(sei.m_nestedSEIs, nalUnitType, sps, pDecodedMessageOutputStream, &sei);
+#endif
+#else
+#if LAYERS_NOT_PRESENT_SEI
+    xReadSEImessage(sei.m_nestedSEIs, nalUnitType, vps, sps, pDecodedMessageOutputStream);
+#else
+    xReadSEImessage(sei.m_nestedSEIs, nalUnitType, sps, pDecodedMessageOutputStream);
+#endif
+#endif
+  } while (m_pcBitstream->getNumBitsLeft() > 8);
+
+  if (pDecodedMessageOutputStream) (*pDecodedMessageOutputStream) << "End of scalable nesting SEI message\n";
+}
+
+Void SEIReader::xParseSEITempMotionConstraintsTileSets(SEITempMotionConstrainedTileSets& sei, UInt payloadSize, std::ostream *pDecodedMessageOutputStream)
+{
+  UInt code;
+  output_sei_message_header(sei, pDecodedMessageOutputStream, payloadSize);
+  sei_read_flag( pDecodedMessageOutputStream, code, "mc_all_tiles_exact_sample_value_match_flag");  sei.m_mc_all_tiles_exact_sample_value_match_flag = (code != 0);
+  sei_read_flag( pDecodedMessageOutputStream, code, "each_tile_one_tile_set_flag");                 sei.m_each_tile_one_tile_set_flag                = (code != 0);
+
+  if(!sei.m_each_tile_one_tile_set_flag)
+  {
+    sei_read_flag( pDecodedMessageOutputStream, code, "limited_tile_set_display_flag");  sei.m_limited_tile_set_display_flag = (code != 0);
+    sei_read_uvlc( pDecodedMessageOutputStream, code, "num_sets_in_message_minus1");     sei.setNumberOfTileSets(code + 1);
+
+    if(sei.getNumberOfTileSets() != 0)
+    {
+      for(Int i = 0; i < sei.getNumberOfTileSets(); i++)
+      {
+        sei_read_uvlc( pDecodedMessageOutputStream, code, "mcts_id");  sei.tileSetData(i).m_mcts_id = code;
+
+        if(sei.m_limited_tile_set_display_flag)
+        {
+          sei_read_flag( pDecodedMessageOutputStream, code, "display_tile_set_flag");  sei.tileSetData(i).m_display_tile_set_flag = (code != 1);
+        }
+
+        sei_read_uvlc( pDecodedMessageOutputStream, code, "num_tile_rects_in_set_minus1");  sei.tileSetData(i).setNumberOfTileRects(code + 1);
+
+        for(Int j=0; j<sei.tileSetData(i).getNumberOfTileRects(); j++)
+        {
+          sei_read_uvlc( pDecodedMessageOutputStream, code, "top_left_tile_index");      sei.tileSetData(i).topLeftTileIndex(j)     = code;
+          sei_read_uvlc( pDecodedMessageOutputStream, code, "bottom_right_tile_index");  sei.tileSetData(i).bottomRightTileIndex(j) = code;
+        }
+
+        if(!sei.m_mc_all_tiles_exact_sample_value_match_flag)
+        {
+          sei_read_flag( pDecodedMessageOutputStream, code, "exact_sample_value_match_flag");   sei.tileSetData(i).m_exact_sample_value_match_flag    = (code != 0);
+        }
+        sei_read_flag( pDecodedMessageOutputStream, code, "mcts_tier_level_idc_present_flag");  sei.tileSetData(i).m_mcts_tier_level_idc_present_flag = (code != 0);
+
+        if(sei.tileSetData(i).m_mcts_tier_level_idc_present_flag)
+        {
+          sei_read_flag( pDecodedMessageOutputStream, code,    "mcts_tier_flag"); sei.tileSetData(i).m_mcts_tier_flag = (code != 0);
+          sei_read_code( pDecodedMessageOutputStream, 8, code, "mcts_level_idc"); sei.tileSetData(i).m_mcts_level_idc =  code;
+        }
+      }
+    }
+  }
+  else
+  {
+    sei_read_flag( pDecodedMessageOutputStream, code, "max_mcs_tier_level_idc_present_flag");  sei.m_max_mcs_tier_level_idc_present_flag = code;
+    if(sei.m_max_mcs_tier_level_idc_present_flag)
+    {
+      sei_read_flag( pDecodedMessageOutputStream, code, "max_mcts_tier_flag");  sei.m_max_mcts_tier_flag = code;
+      sei_read_code( pDecodedMessageOutputStream, 8, code, "max_mcts_level_idc"); sei.m_max_mcts_level_idc = code;
+    }
+  }
+}
+
+Void SEIReader::xParseSEITimeCode(SEITimeCode& sei, UInt payloadSize, std::ostream *pDecodedMessageOutputStream)
+{
+  UInt code;
+  output_sei_message_header(sei, pDecodedMessageOutputStream, payloadSize);
+  sei_read_code( pDecodedMessageOutputStream, 2, code, "num_clock_ts"); sei.numClockTs = code;
+  for(Int i = 0; i < sei.numClockTs; i++)
+  {
+    TComSEITimeSet currentTimeSet;
+    sei_read_flag( pDecodedMessageOutputStream, code, "clock_time_stamp_flag[i]"); currentTimeSet.clockTimeStampFlag = code;
+    if(currentTimeSet.clockTimeStampFlag)
+    {
+      sei_read_flag( pDecodedMessageOutputStream, code, "nuit_field_based_flag"); currentTimeSet.numUnitFieldBasedFlag = code;
+      sei_read_code( pDecodedMessageOutputStream, 5, code, "counting_type"); currentTimeSet.countingType = code;
+      sei_read_flag( pDecodedMessageOutputStream, code, "full_timestamp_flag"); currentTimeSet.fullTimeStampFlag = code;
+      sei_read_flag( pDecodedMessageOutputStream, code, "discontinuity_flag"); currentTimeSet.discontinuityFlag = code;
+      sei_read_flag( pDecodedMessageOutputStream, code, "cnt_dropped_flag"); currentTimeSet.cntDroppedFlag = code;
+      sei_read_code( pDecodedMessageOutputStream, 9, code, "n_frames"); currentTimeSet.numberOfFrames = code;
+      if(currentTimeSet.fullTimeStampFlag)
+      {
+        sei_read_code( pDecodedMessageOutputStream, 6, code, "seconds_value"); currentTimeSet.secondsValue = code;
+        sei_read_code( pDecodedMessageOutputStream, 6, code, "minutes_value"); currentTimeSet.minutesValue = code;
+        sei_read_code( pDecodedMessageOutputStream, 5, code, "hours_value"); currentTimeSet.hoursValue = code;
+      }
+      else
+      {
+        sei_read_flag( pDecodedMessageOutputStream, code, "seconds_flag"); currentTimeSet.secondsFlag = code;
+        if(currentTimeSet.secondsFlag)
+        {
+          sei_read_code( pDecodedMessageOutputStream, 6, code, "seconds_value"); currentTimeSet.secondsValue = code;
+          sei_read_flag( pDecodedMessageOutputStream, code, "minutes_flag"); currentTimeSet.minutesFlag = code;
+          if(currentTimeSet.minutesFlag)
+          {
+            sei_read_code( pDecodedMessageOutputStream, 6, code, "minutes_value"); currentTimeSet.minutesValue = code;
+            sei_read_flag( pDecodedMessageOutputStream, code, "hours_flag"); currentTimeSet.hoursFlag = code;
+            if(currentTimeSet.hoursFlag)
+              sei_read_code( pDecodedMessageOutputStream, 5, code, "hours_value"); currentTimeSet.hoursValue = code;
+          }
+        }
+      }
+      sei_read_code( pDecodedMessageOutputStream, 5, code, "time_offset_length"); currentTimeSet.timeOffsetLength = code;
+      if(currentTimeSet.timeOffsetLength > 0)
+      {
+        sei_read_code( pDecodedMessageOutputStream, currentTimeSet.timeOffsetLength, code, "time_offset_value");
+        if((code & (1 << (currentTimeSet.timeOffsetLength-1))) == 0)
+        {
+          currentTimeSet.timeOffsetValue = code;
+        }
+        else
+        {
+          code &= (1<< (currentTimeSet.timeOffsetLength-1)) - 1;
+          currentTimeSet.timeOffsetValue = ~code + 1;
+        }
+      }
+    }
+    sei.timeSetArray[i] = currentTimeSet;
+  }
+}
+
+Void SEIReader::xParseSEIChromaSamplingFilterHint(SEIChromaSamplingFilterHint& sei, UInt payloadSize/*, TComSPS* sps*/, std::ostream *pDecodedMessageOutputStream)
+{
+  UInt uiCode;
+  output_sei_message_header(sei, pDecodedMessageOutputStream, payloadSize);
+
+  sei_read_code( pDecodedMessageOutputStream, 8, uiCode, "ver_chroma_filter_idc"); sei.m_verChromaFilterIdc = uiCode;
+  sei_read_code( pDecodedMessageOutputStream, 8, uiCode, "hor_chroma_filter_idc"); sei.m_horChromaFilterIdc = uiCode;
+  sei_read_flag( pDecodedMessageOutputStream, uiCode, "ver_filtering_process_flag"); sei.m_verFilteringProcessFlag = uiCode;
+  if(sei.m_verChromaFilterIdc == 1 || sei.m_horChromaFilterIdc == 1)
+  {
+    sei_read_uvlc( pDecodedMessageOutputStream, uiCode, "target_format_idc"); sei.m_targetFormatIdc = uiCode;
+    if(sei.m_verChromaFilterIdc == 1)
+    {
+      sei_read_uvlc( pDecodedMessageOutputStream, uiCode, "num_vertical_filters"); sei.m_numVerticalFilters = uiCode;
+      if(sei.m_numVerticalFilters > 0)
+      {
+        sei.m_verTapLengthMinus1 = (Int*)malloc(sei.m_numVerticalFilters * sizeof(Int));
+        sei.m_verFilterCoeff = (Int**)malloc(sei.m_numVerticalFilters * sizeof(Int*));
+        for(Int i = 0; i < sei.m_numVerticalFilters; i ++)
+        {
+          sei_read_uvlc( pDecodedMessageOutputStream, uiCode, "ver_tap_length_minus_1"); sei.m_verTapLengthMinus1[i] = uiCode;
+          sei.m_verFilterCoeff[i] = (Int*)malloc(sei.m_verTapLengthMinus1[i] * sizeof(Int));
+          for(Int j = 0; j < sei.m_verTapLengthMinus1[i]; j ++)
+          {
+            sei_read_svlc( pDecodedMessageOutputStream, sei.m_verFilterCoeff[i][j], "ver_filter_coeff");
+          }
+        }
+      }
+    }
+    if(sei.m_horChromaFilterIdc == 1)
+    {
+      sei_read_uvlc( pDecodedMessageOutputStream, uiCode, "num_horizontal_filters"); sei.m_numHorizontalFilters = uiCode;
+      if(sei.m_numHorizontalFilters  > 0)
+      {
+        sei.m_horTapLengthMinus1 = (Int*)malloc(sei.m_numHorizontalFilters * sizeof(Int));
+        sei.m_horFilterCoeff = (Int**)malloc(sei.m_numHorizontalFilters * sizeof(Int*));
+        for(Int i = 0; i < sei.m_numHorizontalFilters; i ++)
+        {
+          sei_read_uvlc( pDecodedMessageOutputStream, uiCode, "hor_tap_length_minus_1"); sei.m_horTapLengthMinus1[i] = uiCode;
+          sei.m_horFilterCoeff[i] = (Int*)malloc(sei.m_horTapLengthMinus1[i] * sizeof(Int));
+          for(Int j = 0; j < sei.m_horTapLengthMinus1[i]; j ++)
+          {
+            sei_read_svlc( pDecodedMessageOutputStream, sei.m_horFilterCoeff[i][j], "hor_filter_coeff");
+          }
+        }
+      }
+    }
+  }
+}
+
+Void SEIReader::xParseSEIKneeFunctionInfo(SEIKneeFunctionInfo& sei, UInt payloadSize, std::ostream *pDecodedMessageOutputStream)
+{
+  Int i;
+  UInt val;
+  output_sei_message_header(sei, pDecodedMessageOutputStream, payloadSize);
+
+  sei_read_uvlc( pDecodedMessageOutputStream, val, "knee_function_id" );                   sei.m_kneeId = val;
+  sei_read_flag( pDecodedMessageOutputStream, val, "knee_function_cancel_flag" );          sei.m_kneeCancelFlag = val;
+  if ( !sei.m_kneeCancelFlag )
+  {
+    sei_read_flag( pDecodedMessageOutputStream, val, "knee_function_persistence_flag" );   sei.m_kneePersistenceFlag = val;
+    sei_read_code( pDecodedMessageOutputStream, 32, val, "input_d_range" );                sei.m_kneeInputDrange = val;
+    sei_read_code( pDecodedMessageOutputStream, 32, val, "input_disp_luminance" );         sei.m_kneeInputDispLuminance = val;
+    sei_read_code( pDecodedMessageOutputStream, 32, val, "output_d_range" );               sei.m_kneeOutputDrange = val;
+    sei_read_code( pDecodedMessageOutputStream, 32, val, "output_disp_luminance" );        sei.m_kneeOutputDispLuminance = val;
+    sei_read_uvlc( pDecodedMessageOutputStream, val, "num_knee_points_minus1" );           sei.m_kneeNumKneePointsMinus1 = val;
+    assert( sei.m_kneeNumKneePointsMinus1 > 0 );
+    sei.m_kneeInputKneePoint.resize(sei.m_kneeNumKneePointsMinus1+1);
+    sei.m_kneeOutputKneePoint.resize(sei.m_kneeNumKneePointsMinus1+1);
+    for(i = 0; i <= sei.m_kneeNumKneePointsMinus1; i++ )
+    {
+      sei_read_code( pDecodedMessageOutputStream, 10, val, "input_knee_point" );           sei.m_kneeInputKneePoint[i] = val;
+      sei_read_code( pDecodedMessageOutputStream, 10, val, "output_knee_point" );          sei.m_kneeOutputKneePoint[i] = val;
+    }
+  }
+}
+
+Void SEIReader::xParseSEIMasteringDisplayColourVolume(SEIMasteringDisplayColourVolume& sei, UInt payloadSize, std::ostream *pDecodedMessageOutputStream)
+{
+  UInt code;
+  output_sei_message_header(sei, pDecodedMessageOutputStream, payloadSize);
+
+  sei_read_code( pDecodedMessageOutputStream, 16, code, "display_primaries_x[0]" ); sei.values.primaries[0][0] = code;
+  sei_read_code( pDecodedMessageOutputStream, 16, code, "display_primaries_y[0]" ); sei.values.primaries[0][1] = code;
+
+  sei_read_code( pDecodedMessageOutputStream, 16, code, "display_primaries_x[1]" ); sei.values.primaries[1][0] = code;
+  sei_read_code( pDecodedMessageOutputStream, 16, code, "display_primaries_y[1]" ); sei.values.primaries[1][1] = code;
+
+  sei_read_code( pDecodedMessageOutputStream, 16, code, "display_primaries_x[2]" ); sei.values.primaries[2][0] = code;
+  sei_read_code( pDecodedMessageOutputStream, 16, code, "display_primaries_y[2]" ); sei.values.primaries[2][1] = code;
+
+
+  sei_read_code( pDecodedMessageOutputStream, 16, code, "white_point_x" ); sei.values.whitePoint[0] = code;
+  sei_read_code( pDecodedMessageOutputStream, 16, code, "white_point_y" ); sei.values.whitePoint[1] = code;
+
+  sei_read_code( pDecodedMessageOutputStream, 32, code, "max_display_mastering_luminance" ); sei.values.maxLuminance = code;
+  sei_read_code( pDecodedMessageOutputStream, 32, code, "min_display_mastering_luminance" ); sei.values.minLuminance = code;
+}
+
+#if Q0074_COLOUR_REMAPPING_SEI
+Void SEIReader::xParseSEIColourRemappingInfo(SEIColourRemappingInfo& sei, UInt /*payloadSize*/, std::ostream *pDecodedMessageOutputStream)
+{
+  UInt  uiVal;
+  Int   iVal;
+
+  sei_read_uvlc( pDecodedMessageOutputStream, uiVal, "colour_remap_id" );          sei.m_colourRemapId = uiVal;
+  sei_read_flag( pDecodedMessageOutputStream, uiVal, "colour_remap_cancel_flag" ); sei.m_colourRemapCancelFlag = uiVal;
+  if( !sei.m_colourRemapCancelFlag ) 
+  {
+    sei_read_flag( pDecodedMessageOutputStream, uiVal, "colour_remap_persistence_flag" );                sei.m_colourRemapPersistenceFlag = uiVal;
+    sei_read_flag( pDecodedMessageOutputStream, uiVal, "colour_remap_video_signal_info_present_flag" );  sei.m_colourRemapVideoSignalInfoPresentFlag = uiVal;
+    if ( sei.m_colourRemapVideoSignalInfoPresentFlag )
+    {
+      sei_read_flag( pDecodedMessageOutputStream, uiVal,    "colour_remap_full_range_flag" );           sei.m_colourRemapFullRangeFlag = uiVal;
+      sei_read_code( pDecodedMessageOutputStream, 8, uiVal, "colour_remap_primaries" );                 sei.m_colourRemapPrimaries = uiVal;
+      sei_read_code( pDecodedMessageOutputStream, 8, uiVal, "colour_remap_transfer_function" );         sei.m_colourRemapTransferFunction = uiVal;
+      sei_read_code( pDecodedMessageOutputStream, 8, uiVal, "colour_remap_matrix_coefficients" );       sei.m_colourRemapMatrixCoefficients = uiVal;
+    }
+    sei_read_code( pDecodedMessageOutputStream, 8, uiVal, "colour_remap_input_bit_depth" ); sei.m_colourRemapInputBitDepth = uiVal;
+    sei_read_code( pDecodedMessageOutputStream, 8, uiVal, "colour_remap_bit_depth" ); sei.m_colourRemapBitDepth = uiVal;
+  
+    for( Int c=0 ; c<3 ; c++ )
+    {
+      sei_read_code( pDecodedMessageOutputStream, 8, uiVal, "pre_lut_num_val_minus1[c]" ); sei.m_preLutNumValMinus1[c] = (uiVal==0) ? 1 : uiVal;
+      sei.m_preLutCodedValue[c].resize(sei.m_preLutNumValMinus1[c]+1);
+      sei.m_preLutTargetValue[c].resize(sei.m_preLutNumValMinus1[c]+1);
+      if( uiVal> 0 )
+        for ( Int i=0 ; i<=sei.m_preLutNumValMinus1[c] ; i++ )
+        {
+          sei_read_code( pDecodedMessageOutputStream, (( sei.m_colourRemapInputBitDepth   + 7 ) >> 3 ) << 3, uiVal, "pre_lut_coded_value[c][i]" );  sei.m_preLutCodedValue[c][i]  = uiVal;
+          sei_read_code( pDecodedMessageOutputStream, (( sei.m_colourRemapBitDepth + 7 ) >> 3 ) << 3, uiVal, "pre_lut_target_value[c][i]" ); sei.m_preLutTargetValue[c][i] = uiVal;
+        }
+      else // pre_lut_num_val_minus1[c] == 0
+      {
+        sei.m_preLutCodedValue[c][0]  = 0;
+        sei.m_preLutTargetValue[c][0] = 0;
+        sei.m_preLutCodedValue[c][1]  = (1 << sei.m_colourRemapInputBitDepth) - 1 ;
+        sei.m_preLutTargetValue[c][1] = (1 << sei.m_colourRemapBitDepth) - 1 ;
+      }
+    }
+
+    sei_read_flag( pDecodedMessageOutputStream, uiVal,      "colour_remap_matrix_present_flag" ); sei.m_colourRemapMatrixPresentFlag = uiVal;
+    if( sei.m_colourRemapMatrixPresentFlag )
+    {
+      sei_read_code( pDecodedMessageOutputStream, 4, uiVal, "log2_matrix_denom" ); sei.m_log2MatrixDenom = uiVal;
+      for ( Int c=0 ; c<3 ; c++ )
+        for ( Int i=0 ; i<3 ; i++ )
+        {
+          sei_read_svlc( pDecodedMessageOutputStream, iVal, "colour_remap_coeffs[c][i]" ); sei.m_colourRemapCoeffs[c][i] = iVal;
+        }
+    }
+    else // setting default matrix (I3)
+    {
+      sei.m_log2MatrixDenom = 0;
+      for ( Int c=0 ; c<3 ; c++ )
+        for ( Int i=0 ; i<3 ; i++ )
+          sei.m_colourRemapCoeffs[c][i] = (c==i) ? 1 : 0;
+    }
+    for( Int c=0 ; c<3 ; c++ )
+    {
+      sei_read_code( pDecodedMessageOutputStream, 8, uiVal, "post_lut_num_val_minus1[c]" ); sei.m_postLutNumValMinus1[c] = (uiVal==0) ? 1 : uiVal;
+      sei.m_postLutCodedValue[c].resize(sei.m_postLutNumValMinus1[c]+1);
+      sei.m_postLutTargetValue[c].resize(sei.m_postLutNumValMinus1[c]+1);
+      if( uiVal > 0 )
+        for ( Int i=0 ; i<=sei.m_postLutNumValMinus1[c] ; i++ )
+        {
+          sei_read_code( pDecodedMessageOutputStream, (( sei.m_colourRemapBitDepth + 7 ) >> 3 ) << 3, uiVal, "post_lut_coded_value[c][i]" );  sei.m_postLutCodedValue[c][i] = uiVal;
+          sei_read_code( pDecodedMessageOutputStream, (( sei.m_colourRemapBitDepth + 7 ) >> 3 ) << 3, uiVal, "post_lut_target_value[c][i]" ); sei.m_postLutTargetValue[c][i] = uiVal;
+        }
+      else
+      {
+        sei.m_postLutCodedValue[c][0]  = 0;
+        sei.m_postLutTargetValue[c][0] = 0;
+        sei.m_postLutTargetValue[c][1] = (1 << sei.m_colourRemapBitDepth) - 1;
+        sei.m_postLutCodedValue[c][1]  = (1 << sei.m_colourRemapBitDepth) - 1;
+      }
+    }
+  }
+}
+#endif
+
+
+#if SVC_EXTENSION
+#if LAYERS_NOT_PRESENT_SEI
+Void SEIReader::xParseSEILayersNotPresent(SEILayersNotPresent &sei, UInt payloadSize, TComVPS *vps, std::ostream *pDecodedMessageOutputStream)
+{
+  UInt uiCode;
+  UInt i = 0;
+
+  sei_read_uvlc( pDecodedMessageOutputStream, uiCode,           "lp_sei_active_vps_id" ); sei.m_activeVpsId = uiCode;
+  assert(vps->getVPSId() == sei.m_activeVpsId);
+  sei.m_vpsMaxLayers = vps->getMaxLayers();
+  for (; i < sei.m_vpsMaxLayers; i++)
+  {
+    sei_read_flag( pDecodedMessageOutputStream, uiCode,         "layer_not_present_flag"   ); sei.m_layerNotPresentFlag[i] = uiCode ? true : false;
+  }
+  for (; i < MAX_LAYERS; i++)
+  {
+    sei.m_layerNotPresentFlag[i] = false;
+  }
+}
+#endif
+
+#if N0383_IL_CONSTRAINED_TILE_SETS_SEI
+Void SEIReader::xParseSEIInterLayerConstrainedTileSets (SEIInterLayerConstrainedTileSets &sei, UInt payloadSize, std::ostream *pDecodedMessageOutputStream)
+{
+  UInt uiCode;
+
+  sei_read_flag( pDecodedMessageOutputStream, uiCode, "il_all_tiles_exact_sample_value_match_flag"   ); sei.m_ilAllTilesExactSampleValueMatchFlag = uiCode;
+  sei_read_flag( pDecodedMessageOutputStream, uiCode, "il_one_tile_per_tile_set_flag"                ); sei.m_ilOneTilePerTileSetFlag = uiCode;
+  if( !sei.m_ilOneTilePerTileSetFlag )
+  {
+    sei_read_uvlc( pDecodedMessageOutputStream, uiCode, "il_num_sets_in_message_minus1"                ); sei.m_ilNumSetsInMessageMinus1 = uiCode;
+    if( sei.m_ilNumSetsInMessageMinus1 )
+    {
+      sei_read_flag( pDecodedMessageOutputStream, uiCode, "skipped_tile_set_present_flag"                ); sei.m_skippedTileSetPresentFlag = uiCode;
+    }
+    else
+    {
+      sei.m_skippedTileSetPresentFlag = false;
+    }
+    UInt numSignificantSets = sei.m_ilNumSetsInMessageMinus1 - (sei.m_skippedTileSetPresentFlag ? 1 : 0) + 1;
+    for( UInt i = 0; i < numSignificantSets; i++ )
+    {
+      sei_read_uvlc( pDecodedMessageOutputStream, uiCode, "ilcts_id"                                     ); sei.m_ilctsId[i] = uiCode;
+      sei_read_uvlc( pDecodedMessageOutputStream, uiCode, "il_num_tile_rects_in_set_minus1"              ) ;sei.m_ilNumTileRectsInSetMinus1[i] = uiCode;
+      for( UInt j = 0; j <= sei.m_ilNumTileRectsInSetMinus1[i]; j++ )
+      {
+        sei_read_uvlc( pDecodedMessageOutputStream, uiCode, "il_top_left_tile_index"                       ); sei.m_ilTopLeftTileIndex[i][j] = uiCode;
+        sei_read_uvlc( pDecodedMessageOutputStream, uiCode, "il_bottom_right_tile_index"                   ); sei.m_ilBottomRightTileIndex[i][j] = uiCode;
+      }
+      sei_read_code( pDecodedMessageOutputStream, 2, uiCode, "ilc_idc"                                   ); sei.m_ilcIdc[i] = uiCode;
+      if( sei.m_ilAllTilesExactSampleValueMatchFlag )
+      {
+        sei_read_flag( pDecodedMessageOutputStream, uiCode, "il_exact_sample_value_match_flag"             ); sei.m_ilExactSampleValueMatchFlag[i] = uiCode;
+      }
+    }
+  }
+  else
+  {
+    sei_read_code( pDecodedMessageOutputStream, 2, uiCode, "all_tiles_ilc_idc"                         ); sei.m_allTilesIlcIdc = uiCode;
+  }
+}
+#endif
+
+#if SUB_BITSTREAM_PROPERTY_SEI
+#if OLS_IDX_CHK
+Void SEIReader::xParseSEISubBitstreamProperty(SEISubBitstreamProperty &sei, TComVPS *vps, std::ostream *pDecodedMessageOutputStream)
+#else
+Void SEIReader::xParseSEISubBitstreamProperty(SEISubBitstreamProperty &sei, std::ostream *pDecodedMessageOutputStream)
+#endif
+{
+  UInt uiCode;
+  sei_read_code( pDecodedMessageOutputStream, 4, uiCode, "active_vps_id" );                      sei.m_activeVpsId = uiCode;
+  sei_read_uvlc( pDecodedMessageOutputStream,    uiCode, "num_additional_sub_streams_minus1" );  sei.m_numAdditionalSubStreams = uiCode + 1;
+
+  for( Int i = 0; i < sei.m_numAdditionalSubStreams; i++ )
+  {
+    sei_read_code( pDecodedMessageOutputStream,  2, uiCode, "sub_bitstream_mode[i]"           ); sei.m_subBitstreamMode[i] = uiCode;
+    sei_read_uvlc( pDecodedMessageOutputStream,     uiCode, "output_layer_set_idx_to_vps[i]"  );
+#if OLS_IDX_CHK
+      // The value of output_layer_set_idx_to_vps[ i ]  shall be in the range of 0 to NumOutputLayerSets − 1, inclusive.
+      assert(uiCode > 0 && uiCode <= vps->getNumOutputLayerSets()-1);
+#endif
+      sei.m_outputLayerSetIdxToVps[i] = uiCode;
+    sei_read_code( pDecodedMessageOutputStream,  3, uiCode, "highest_sub_layer_id[i]"         ); sei.m_highestSublayerId[i] = uiCode;
+    sei_read_code( pDecodedMessageOutputStream, 16, uiCode, "avg_bit_rate[i]"                 ); sei.m_avgBitRate[i] = uiCode;
+    sei_read_code( pDecodedMessageOutputStream, 16, uiCode, "max_bit_rate[i]"                 ); sei.m_maxBitRate[i] = uiCode;
+  }  
+}
+#endif
+
+#if O0164_MULTI_LAYER_HRD
+#if LAYERS_NOT_PRESENT_SEI
+Void SEIReader::xParseSEIBspNesting(SEIBspNesting &sei, const NalUnitType nalUnitType, TComVPS *vps, TComSPS *sps, const SEIScalableNesting &nestingSei, std::ostream *pDecodedMessageOutputStream)
+#else
+Void SEIReader::xParseSEIBspNesting(SEIBspNesting &sei, const NalUnitType nalUnitType, TComSPS *sps, const SEIScalableNesting &nestingSei, std::ostream *pDecodedMessageOutputStream)
+#endif
+{
+  UInt uiCode;
+  sei_read_uvlc( pDecodedMessageOutputStream, uiCode, "bsp_idx" ); sei.m_bspIdx = uiCode;
+
+  // byte alignment
+  while ( m_pcBitstream->getNumBitsRead() % 8 != 0 )
+  {
+    UInt code;
+    sei_read_flag( pDecodedMessageOutputStream, code, "bsp_nesting_zero_bit" );
+  }
+
+  sei.m_callerOwnsSEIs = false;
+
+  // read nested SEI messages
+#if NESTING_SEI_EXTENSIBILITY
+  Int numSeiMessages = 0;
+  sei_read_uvlc( pDecodedMessageOutputStream, uiCode, "num_seis_in_bsp_minus1" );  assert( uiCode <= MAX_SEIS_IN_BSP_NESTING );
+  numSeiMessages = uiCode;
+  for(Int i = 0; i < numSeiMessages; i++)
+  {
+    xReadSEImessage(sei.m_nestedSEIs, nalUnitType, vps, sps, pDecodedMessageOutputStream, &nestingSei, &sei);
+  }
+#else
+  do {
+#if LAYERS_NOT_PRESENT_SEI
+    xReadSEImessage(sei.m_nestedSEIs, nalUnitType, vps, sps, pDecodedMessageOutputStream, &nestingSei, &sei);
+#else
+    xReadSEImessage(sei.m_nestedSEIs, nalUnitType, sps, pDecodedMessageOutputStream, &nestingSei);
+#endif
+  } while (m_pcBitstream->getNumBitsLeft() > 8);
+#endif
+}
+
+Void SEIReader::xParseSEIBspInitialArrivalTime(SEIBspInitialArrivalTime &sei, TComVPS *vps, TComSPS *sps, const SEIScalableNesting &nestingSei, const SEIBspNesting &bspNestingSei, std::ostream *pDecodedMessageOutputStream)
+{
+  assert(vps->getVpsVuiPresentFlag());
+
+#if VPS_VUI_BSP_HRD_PARAMS
+  UInt uiCode;
+  Int psIdx         = bspNestingSei.m_seiPartitioningSchemeIdx;
+  Int seiOlsIdx     = bspNestingSei.m_seiOlsIdx;
+  Int maxTemporalId = nestingSei.m_nestingMaxTemporalIdPlus1[0];
+  Int maxValues     = vps->getNumBspSchedulesMinus1(seiOlsIdx, psIdx, maxTemporalId) + 1;
+  std::vector<Int> hrdIdx(0, maxValues);
+  std::vector<TComHRD *> hrdVec;
+  std::vector<Int> syntaxElemLen;
+  for(Int i = 0; i < maxValues; i++)
+  {
+    hrdIdx[i] = vps->getBspHrdIdx( seiOlsIdx, psIdx, maxTemporalId, i, bspNestingSei.m_bspIdx);
+    hrdVec[i] = vps->getBspHrd(hrdIdx[i]);
+    
+    syntaxElemLen[i] = hrdVec[i]->getInitialCpbRemovalDelayLengthMinus1() + 1;
+    if ( !(hrdVec[i]->getNalHrdParametersPresentFlag() || hrdVec[i]->getVclHrdParametersPresentFlag()) )
+    {
+      assert( syntaxElemLen[i] == 24 ); // Default value of init_cpb_removal_delay_length_minus1 is 23
+    }
+    if( i > 0 )
+    {
+      assert( hrdVec[i]->getNalHrdParametersPresentFlag() == hrdVec[i-1]->getNalHrdParametersPresentFlag() );
+      assert( hrdVec[i]->getVclHrdParametersPresentFlag() == hrdVec[i-1]->getVclHrdParametersPresentFlag() );
+    }
+  }
+  if (hrdVec[0]->getNalHrdParametersPresentFlag())
+  {
+    for(UInt i = 0; i < maxValues; i++)
+    {
+      sei_read_code( pDecodedMessageOutputStream, syntaxElemLen[i], uiCode, "nal_initial_arrival_delay[i]" ); sei.m_nalInitialArrivalDelay[i] = uiCode;
+    }
+  }
+  if( hrdVec[0]->getVclHrdParametersPresentFlag() )
+  {
+    for(UInt i = 0; i < maxValues; i++)
+    {
+      sei_read_code( pDecodedMessageOutputStream, syntaxElemLen[i], uiCode, "vcl_initial_arrival_delay[i]" ); sei.m_vclInitialArrivalDelay[i] = uiCode;
+    }
+  }
+#else
+  UInt schedCombCnt = vps->getNumBspSchedCombinations(nestingSei.m_nestingOpIdx[0]);
+  UInt len;
+  UInt hrdIdx;
+  UInt uiCode;
+
+  if (schedCombCnt > 0)
+  {
+    hrdIdx = vps->getBspCombHrdIdx(nestingSei.m_nestingOpIdx[0], 0, bspNestingSei.m_bspIdx);
+  }
+  else
+  {
+    hrdIdx = 0;
+  }
+
+  TComHRD *hrd = vps->getBspHrd(hrdIdx);
+
+  if (hrd->getNalHrdParametersPresentFlag() || hrd->getVclHrdParametersPresentFlag())
+  {
+    len = hrd->getInitialCpbRemovalDelayLengthMinus1() + 1;
+  }
+  else
+  {
+    len = 23 + 1;
+  }
+
+  if (hrd->getNalHrdParametersPresentFlag())
+  {
+    for(UInt i = 0; i < schedCombCnt; i++)
+    {
+      sei_read_code( pDecodedMessageOutputStream, len, uiCode, "nal_initial_arrival_delay" ); sei.m_nalInitialArrivalDelay[i] = uiCode;
+    }
+  }
+#if BSP_INIT_ARRIVAL_SEI
+  if( hrd->getVclHrdParametersPresentFlag() )
+#else
+  else
+#endif
+  {
+    for(UInt i = 0; i < schedCombCnt; i++)
+    {
+      sei_read_code( pDecodedMessageOutputStream, len, uiCode, "vcl_initial_arrival_delay" ); sei.m_vclInitialArrivalDelay[i] = uiCode;
+    }
+  }
+#endif
+}
+
+#if !REMOVE_BSP_HRD_SEI
+Void SEIReader::xParseSEIBspHrd(SEIBspHrd &sei, TComSPS *sps, const SEIScalableNesting &nestingSei, std::ostream *pDecodedMessageOutputStream)
+{
+  UInt uiCode;
+  sei_read_uvlc( pDecodedMessageOutputStream, uiCode, "sei_num_bsp_hrd_parameters_minus1" ); sei.m_seiNumBspHrdParametersMinus1 = uiCode;
+  for (UInt i = 0; i <= sei.m_seiNumBspHrdParametersMinus1; i++)
+  {
+    if (i > 0)
+    {
+      sei_read_flag( pDecodedMessageOutputStream, uiCode, "sei_bsp_cprms_present_flag" ); sei.m_seiBspCprmsPresentFlag[i] = uiCode;
+    }
+    xParseHrdParameters(sei.hrd, i==0 ? 1 : sei.m_seiBspCprmsPresentFlag[i], nestingSei.m_nestingMaxTemporalIdPlus1[0]-1);
+  }
+  for (UInt h = 0; h <= nestingSei.m_nestingNumOpsMinus1; h++)
+  {
+    UInt lsIdx = nestingSei.m_nestingOpIdx[h];
+    sei_read_uvlc( pDecodedMessageOutputStream, uiCode, "num_sei_bitstream_partitions_minus1[i]"); sei.m_seiNumBitstreamPartitionsMinus1[lsIdx] = uiCode;
+#if HRD_BPB
+    Int chkPart=0;
+#endif
+    UInt i;
+    for(i = 0; i <= sei.m_seiNumBitstreamPartitionsMinus1[lsIdx]; i++)
+    {
+#if HRD_BPB
+      UInt nl=0; UInt j;
+      for(j = 0; j < sei.m_vpsMaxLayers; j++)
+      {
+        if (sei.m_layerIdIncludedFlag[lsIdx][j])
+        {
+          nl++;
+        }
+      }
+      for (j = 0; j < nl; j++)
+      {
+#else
+      for (UInt j = 0; j < sei.m_vpsMaxLayers; j++)
+      {
+        if (sei.m_layerIdIncludedFlag[lsIdx][j])
+        {
+#endif
+          sei_read_flag( pDecodedMessageOutputStream, uiCode, "sei_layer_in_bsp_flag[lsIdx][i][j]" ); sei.m_seiLayerInBspFlag[lsIdx][i][j] = uiCode;
+        }
+#if !HRD_BPB
+      }
+#endif
+#if HRD_BPB
+      chkPart+=sei.m_seiLayerInBspFlag[lsIdx][i][j];
+#endif
+    }
+#if HRD_BPB
+    assert(chkPart<=1);
+#endif
+#if HRD_BPB
+    if(sei.m_seiNumBitstreamPartitionsMinus1[lsIdx]==0)
+    {
+      Int chkPartition1=0; Int chkPartition2=0;
+      for (UInt j = 0; j < sei.m_vpsMaxLayers; j++)
+      {
+        if( sei.m_layerIdIncludedFlag[lsIdx][j] )
+        {
+          chkPartition1+=sei.m_seiLayerInBspFlag[lsIdx][0][j];
+          chkPartition2++;
+        }
+      }
+      assert(chkPartition1!=chkPartition2);
+    }
+#endif
+      
+    sei_read_uvlc( pDecodedMessageOutputStream, uiCode, "sei_num_bsp_sched_combinations_minus1[i]"); sei.m_seiNumBspSchedCombinationsMinus1[lsIdx] = uiCode;
+    for (i = 0; i <= sei.m_seiNumBspSchedCombinationsMinus1[lsIdx]; i++)
+    {
+      for (UInt j = 0; j <= sei.m_seiNumBitstreamPartitionsMinus1[lsIdx]; j++)
+      {
+        sei_read_uvlc( pDecodedMessageOutputStream, uiCode, "sei_bsp_comb_hrd_idx[lsIdx][i][j]"); sei.m_seiBspCombHrdIdx[lsIdx][i][j] = uiCode;
+#if HRD_BPB
+        assert(uiCode <= sei.m_seiNumBspHrdParametersMinus1);
+#endif
+        sei_read_uvlc( pDecodedMessageOutputStream, uiCode, "sei_bsp_comb_sched_idx[lsIdx][i][j]"); sei.m_seiBspCombScheddx[lsIdx][i][j] = uiCode;
+#if HRD_BPB
+        assert(uiCode <= sei.hrd->getCpbCntMinus1( sps->getMaxTLayers()-1 ));
+#endif
+
+      }
+    }
+  }
+}
+#endif
+
+Void SEIReader::xParseHrdParameters(TComHRD *hrd, Bool commonInfPresentFlag, UInt maxNumSubLayersMinus1, std::ostream *pDecodedMessageOutputStream)
+{
+  UInt  uiCode;
+  if( commonInfPresentFlag )
+  {
+    sei_read_flag( pDecodedMessageOutputStream, uiCode, "nal_hrd_parameters_present_flag" );           hrd->setNalHrdParametersPresentFlag( uiCode == 1 ? true : false );
+    sei_read_flag( pDecodedMessageOutputStream, uiCode, "vcl_hrd_parameters_present_flag" );           hrd->setVclHrdParametersPresentFlag( uiCode == 1 ? true : false );
+    if( hrd->getNalHrdParametersPresentFlag() || hrd->getVclHrdParametersPresentFlag() )
+    {
+      sei_read_flag( pDecodedMessageOutputStream, uiCode, "sub_pic_cpb_params_present_flag" );         hrd->setSubPicCpbParamsPresentFlag( uiCode == 1 ? true : false );
+      if( hrd->getSubPicCpbParamsPresentFlag() )
+      {
+        sei_read_code( pDecodedMessageOutputStream, 8, uiCode, "tick_divisor_minus2" );                hrd->setTickDivisorMinus2( uiCode );
+        sei_read_code( pDecodedMessageOutputStream, 5, uiCode, "du_cpb_removal_delay_length_minus1" ); hrd->setDuCpbRemovalDelayLengthMinus1( uiCode );
+        sei_read_flag( pDecodedMessageOutputStream, uiCode, "sub_pic_cpb_params_in_pic_timing_sei_flag" ); hrd->setSubPicCpbParamsInPicTimingSEIFlag( uiCode == 1 ? true : false );
+        sei_read_code( pDecodedMessageOutputStream, 5, uiCode, "dpb_output_delay_du_length_minus1"  ); hrd->setDpbOutputDelayDuLengthMinus1( uiCode );
+      }
+      sei_read_code( pDecodedMessageOutputStream, 4, uiCode, "bit_rate_scale" );                       hrd->setBitRateScale( uiCode );
+      sei_read_code( pDecodedMessageOutputStream, 4, uiCode, "cpb_size_scale" );                       hrd->setCpbSizeScale( uiCode );
+      if( hrd->getSubPicCpbParamsPresentFlag() )
+      {
+        sei_read_code( pDecodedMessageOutputStream, 4, uiCode, "cpb_size_du_scale" );                  hrd->setDuCpbSizeScale( uiCode );
+      }
+      sei_read_code( pDecodedMessageOutputStream, 5, uiCode, "initial_cpb_removal_delay_length_minus1" ); hrd->setInitialCpbRemovalDelayLengthMinus1( uiCode );
+      sei_read_code( pDecodedMessageOutputStream, 5, uiCode, "au_cpb_removal_delay_length_minus1" );      hrd->setCpbRemovalDelayLengthMinus1( uiCode );
+      sei_read_code( pDecodedMessageOutputStream, 5, uiCode, "dpb_output_delay_length_minus1" );       hrd->setDpbOutputDelayLengthMinus1( uiCode );
+    }
+  }
+  Int i, j, nalOrVcl;
+  for( i = 0; i <= maxNumSubLayersMinus1; i ++ )
+  {
+    sei_read_flag( pDecodedMessageOutputStream, uiCode, "fixed_pic_rate_general_flag" );                     hrd->setFixedPicRateFlag( i, uiCode == 1 ? true : false  );
+    if( !hrd->getFixedPicRateFlag( i ) )
+    {
+       sei_read_flag( pDecodedMessageOutputStream, 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 ) )
+    {
+      sei_read_uvlc( pDecodedMessageOutputStream, uiCode, "elemental_duration_in_tc_minus1" );             hrd->setPicDurationInTcMinus1( i, uiCode );
+    }
+    else
+    {
+      sei_read_flag( pDecodedMessageOutputStream, uiCode, "low_delay_hrd_flag" );                      hrd->setLowDelayHrdFlag( i, uiCode == 1 ? true : false  );
+    }
+    if (!hrd->getLowDelayHrdFlag( i ))
+    {
+      sei_read_uvlc( pDecodedMessageOutputStream, 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 ++ )
+        {
+          sei_read_uvlc( pDecodedMessageOutputStream, uiCode, "bit_rate_value_minus1" );             hrd->setBitRateValueMinus1( i, j, nalOrVcl, uiCode );
+          sei_read_uvlc( pDecodedMessageOutputStream, uiCode, "cpb_size_value_minus1" );             hrd->setCpbSizeValueMinus1( i, j, nalOrVcl, uiCode );
+          if( hrd->getSubPicCpbParamsPresentFlag() )
+          {
+            sei_read_uvlc( pDecodedMessageOutputStream, uiCode, "cpb_size_du_value_minus1" );       hrd->setDuCpbSizeValueMinus1( i, j, nalOrVcl, uiCode );
+            sei_read_uvlc( pDecodedMessageOutputStream, uiCode, "bit_rate_du_value_minus1" );       hrd->setDuBitRateValueMinus1( i, j, nalOrVcl, uiCode );
+          }
+           sei_read_flag( pDecodedMessageOutputStream, uiCode, "cbr_flag" );                          hrd->setCbrFlag( i, j, nalOrVcl, uiCode == 1 ? true : false  );
+        }
+      }
+    }
+  }
+}
+#endif
+
+#if Q0078_ADD_LAYER_SETS
+
+#if LAYERS_NOT_PRESENT_SEI
+Void SEIReader::xParseSEIOutputLayerSetNesting(SEIOutputLayerSetNesting& sei, const NalUnitType nalUnitType, TComVPS *vps, TComSPS *sps, std::ostream *pDecodedMessageOutputStream)
+#else
+Void SEIReader::xParseSEIOutputLayerSetNesting(SEIOutputLayerSetNesting& sei, const NalUnitType nalUnitType, TComSPS *sps, std::ostream *pDecodedMessageOutputStream)
+#endif
+{
+  UInt uiCode;
+  SEIMessages seis;
+
+  sei_read_flag( pDecodedMessageOutputStream, uiCode, "ols_flag"); sei.m_olsFlag = uiCode;
+  sei_read_uvlc( pDecodedMessageOutputStream, uiCode, "num_ols_indices_minus1"); sei.m_numOlsIndicesMinus1 = uiCode;
+
+  for (Int i = 0; i <= sei.m_numOlsIndicesMinus1; i++)
+  {
+    sei_read_uvlc( pDecodedMessageOutputStream, uiCode, "ols_idx[i]"); sei.m_olsIdx[i] = uiCode;
+  }
+
+  // byte alignment
+  while (m_pcBitstream->getNumBitsRead() % 8 != 0)
+  {
+    UInt code;
+    sei_read_flag( pDecodedMessageOutputStream, code, "ols_nesting_zero_bit");
+  }
+
+  sei.m_callerOwnsSEIs = false;
+
+  // read nested SEI messages
+  do {
+#if O0164_MULTI_LAYER_HRD
+#if LAYERS_NOT_PRESENT_SEI
+    xReadSEImessage(sei.m_nestedSEIs, nalUnitType, vps, sps, pDecodedMessageOutputStream);
+#else
+    xReadSEImessage(sei.m_nestedSEIs, nalUnitType, sps, pDecodedMessageOutputStream);
+#endif
+#else
+#if LAYERS_NOT_PRESENT_SEI
+    xReadSEImessage(sei.m_nestedSEIs, nalUnitType, vps, sps, pDecodedMessageOutputStream);
+#else
+    xReadSEImessage(sei.m_nestedSEIs, nalUnitType, sps, pDecodedMessageOutputStream);
+#endif
+#endif
+  } while (m_pcBitstream->getNumBitsLeft() > 8);
+
+}
+
+Void SEIReader::xParseSEIVPSRewriting(SEIVPSRewriting &sei, std::ostream *pDecodedMessageOutputStream )
+{
+}
+
+#endif
+
+#if P0123_ALPHA_CHANNEL_SEI
+void SEIReader::xParseSEIAlphaChannelInfo(SEIAlphaChannelInfo &sei, UInt payloadSize, std::ostream *pDecodedMessageOutputStream)
+{
+  UInt value;
+  sei_read_flag(pDecodedMessageOutputStream, value, "alpha_channel_cancel_flag"); sei.m_alphaChannelCancelFlag = value;
+  if(!sei.m_alphaChannelCancelFlag)
+  {
+    sei_read_code(pDecodedMessageOutputStream, 3, value, "alpha_channel_use_idc");          sei.m_alphaChannelUseIdc = value;
+    sei_read_code(pDecodedMessageOutputStream, 3, value, "alpha_channel_bit_depth_minus8"); sei.m_alphaChannelBitDepthMinus8 = value;
+    sei_read_code(pDecodedMessageOutputStream, sei.m_alphaChannelBitDepthMinus8 + 9, value, "alpha_transparent_value"); sei.m_alphaTransparentValue = value;
+    sei_read_code(pDecodedMessageOutputStream, sei.m_alphaChannelBitDepthMinus8 + 9, value, "alpha_opaque_value"); sei.m_alphaOpaqueValue = value;
+    sei_read_flag(pDecodedMessageOutputStream, value, "alpha_channel_incr_flag");        sei.m_alphaChannelIncrFlag = value;
+    sei_read_flag(pDecodedMessageOutputStream, value, "alpha_channel_clip_flag");        sei.m_alphaChannelClipFlag = value;
+    if(sei.m_alphaChannelClipFlag)
+    {
+      sei_read_flag(pDecodedMessageOutputStream, value, "alpha_channel_clip_type_flag"); sei.m_alphaChannelClipTypeFlag = value;
+    }
+  }  
+}
+#endif
+
+#if Q0096_OVERLAY_SEI
+Void SEIReader::xParseSEIOverlayInfo(SEIOverlayInfo& sei, UInt /*payloadSize*/, std::ostream *pDecodedMessageOutputStream)
+{
+  Int i, j;
+  UInt val;
+  sei_read_flag( pDecodedMessageOutputStream, val, "overlay_info_cancel_flag" );                 sei.m_overlayInfoCancelFlag = val;
+  if ( !sei.m_overlayInfoCancelFlag )
+  {
+    sei_read_uvlc( pDecodedMessageOutputStream, val, "overlay_content_aux_id_minus128" );            sei.m_overlayContentAuxIdMinus128 = val;
+    sei_read_uvlc( pDecodedMessageOutputStream, val, "overlay_label_aux_id_minus128" );              sei.m_overlayLabelAuxIdMinus128 = val;
+    sei_read_uvlc( pDecodedMessageOutputStream, val, "overlay_alpha_aux_id_minus128" );              sei.m_overlayAlphaAuxIdMinus128 = val;
+    sei_read_uvlc( pDecodedMessageOutputStream, val, "overlay_element_label_value_length_minus8" );  sei.m_overlayElementLabelValueLengthMinus8 = val;
+    sei_read_uvlc( pDecodedMessageOutputStream, val, "num_overlays_minus1" );                        sei.m_numOverlaysMinus1 = val;
+
+    assert( sei.m_numOverlaysMinus1 < MAX_OVERLAYS );
+    sei.m_overlayIdx.resize( sei.m_numOverlaysMinus1+1 );
+    sei.m_languageOverlayPresentFlag.resize( sei.m_numOverlaysMinus1+1 );
+    sei.m_overlayContentLayerId.resize( sei.m_numOverlaysMinus1+1 );
+    sei.m_overlayLabelPresentFlag.resize( sei.m_numOverlaysMinus1+1 );
+    sei.m_overlayLabelLayerId.resize( sei.m_numOverlaysMinus1+1 );
+    sei.m_overlayAlphaPresentFlag.resize( sei.m_numOverlaysMinus1+1 );
+    sei.m_overlayAlphaLayerId.resize( sei.m_numOverlaysMinus1+1 );
+    sei.m_numOverlayElementsMinus1.resize( sei.m_numOverlaysMinus1+1 );
+    sei.m_overlayElementLabelMin.resize( sei.m_numOverlaysMinus1+1 );
+    sei.m_overlayElementLabelMax.resize( sei.m_numOverlaysMinus1+1 );
+    for ( i=0 ; i<=sei.m_numOverlaysMinus1 ; i++ )
+    {
+      sei_read_uvlc( pDecodedMessageOutputStream, val, "overlay_idx" );                      sei.m_overlayIdx[i] = val;
+      sei_read_flag( pDecodedMessageOutputStream, val, "language_overlay_present_flag" );    sei.m_languageOverlayPresentFlag[i] = val;
+      sei_read_code( pDecodedMessageOutputStream, 6, val, "overlay_content_layer_id");       sei.m_overlayContentLayerId[i] = val;
+      sei_read_flag( pDecodedMessageOutputStream, val, "overlay_label_present_flag" );       sei.m_overlayLabelPresentFlag[i] = val;
+      if ( sei.m_overlayLabelPresentFlag[i] )
+      {
+        sei_read_code( pDecodedMessageOutputStream, 6, val, "overlay_label_layer_id");     sei.m_overlayLabelLayerId[i] = val;
+      }
+      sei_read_flag( pDecodedMessageOutputStream, val, "overlay_alpha_present_flag" );       sei.m_overlayAlphaPresentFlag[i] = val;
+      if ( sei.m_overlayAlphaPresentFlag[i] )
+      {
+        sei_read_code( pDecodedMessageOutputStream, 6, val, "overlay_alpha_layer_id");     sei.m_overlayAlphaLayerId[i] = val;
+      }
+      if ( sei.m_overlayLabelPresentFlag[i] )
+      {
+        sei_read_uvlc( pDecodedMessageOutputStream, val, "num_overlay_elements_minus1");   sei.m_numOverlayElementsMinus1[i] = val;
+        assert( sei.m_numOverlayElementsMinus1[i] < MAX_OVERLAY_ELEMENTS );
+        sei.m_overlayElementLabelMin[i].resize( sei.m_numOverlayElementsMinus1[i]+1 );
+        sei.m_overlayElementLabelMax[i].resize( sei.m_numOverlayElementsMinus1[i]+1 );
+        for ( j=0 ; j<=sei.m_numOverlayElementsMinus1[i] ; j++ )
+        {
+          sei_read_code( pDecodedMessageOutputStream, sei.m_overlayElementLabelValueLengthMinus8 + 8, val, "overlay_element_label_min"); sei.m_overlayElementLabelMin[i][j] = val;
+          sei_read_code( pDecodedMessageOutputStream, sei.m_overlayElementLabelValueLengthMinus8 + 8, val, "overlay_element_label_max"); sei.m_overlayElementLabelMax[i][j] = val;
+        }      
+      }
+      else
+      {
+        sei.m_numOverlayElementsMinus1[i] = 0;
+      }
+    }
+
+    // byte alignment
+    while ( m_pcBitstream->getNumBitsRead() % 8 != 0 )
+    {
+      sei_read_flag( pDecodedMessageOutputStream, val, "overlay_zero_bit" );
+      assert( val==0 );
+    }
+
+    UChar* sval = new UChar[MAX_OVERLAY_STRING_BYTES];
+    UInt slen;    
+    sei.m_overlayLanguage.resize( sei.m_numOverlaysMinus1+1, NULL );
+    sei.m_overlayLanguageLength.resize( sei.m_numOverlaysMinus1+1 );
+    sei.m_overlayName.resize( sei.m_numOverlaysMinus1+1, NULL );
+    sei.m_overlayNameLength.resize( sei.m_numOverlaysMinus1+1 );
+    sei.m_overlayElementName.resize( sei.m_numOverlaysMinus1+1 );
+    sei.m_overlayElementNameLength.resize( sei.m_numOverlaysMinus1+1 );
+    for ( i=0 ; i<=sei.m_numOverlaysMinus1 ; i++ )
+    {
+      if ( sei.m_languageOverlayPresentFlag[i] )
+      {
+        READ_STRING( MAX_OVERLAY_STRING_BYTES, sval, slen, "overlay_language" );
+        sei.m_overlayLanguage[i] = new UChar[slen];
+        memcpy(sei.m_overlayLanguage[i], sval, slen);
+        sei.m_overlayLanguageLength[i] = slen;
+      }
+      READ_STRING( MAX_OVERLAY_STRING_BYTES, sval, slen, "overlay_name" );
+      sei.m_overlayName[i] = new UChar[slen];
+      memcpy(sei.m_overlayName[i], sval, slen);
+      sei.m_overlayNameLength[i] = slen;
+      if ( sei.m_overlayLabelPresentFlag[i] )
+      {
+        sei.m_overlayElementName[i].resize( sei.m_numOverlayElementsMinus1[i]+1, NULL );
+        sei.m_overlayElementNameLength[i].resize( sei.m_numOverlayElementsMinus1[i]+1 );
+        for ( j=0 ; j<=sei.m_numOverlayElementsMinus1[i] ; j++)
+        {
+          READ_STRING( MAX_OVERLAY_STRING_BYTES, sval, slen, "overlay_element_name" );
+          sei.m_overlayElementName[i][j] = new UChar[slen];
+          memcpy(sei.m_overlayElementName[i][j], sval, slen);
+          sei.m_overlayElementNameLength[i][j] = slen;
+        }
+      }
+    }
+    sei_read_flag( pDecodedMessageOutputStream, val, "overlay_info_persistence_flag" );        sei.m_overlayInfoPersistenceFlag = val;
+  }  
+}
+#endif
+
+#if P0138_USE_ALT_CPB_PARAMS_FLAG
+/**
+ * Check if SEI message contains payload extension
+ */
+Bool SEIReader::xPayloadExtensionPresent()
+{
+  Int payloadBitsRemaining = getBitstream()->getNumBitsLeft();
+  Bool payloadExtensionPresent = false;
+
+  if (payloadBitsRemaining > 8)
+  {
+    payloadExtensionPresent = true;
+  }
+  else
+  {
+    Int finalBits = getBitstream()->peekBits(payloadBitsRemaining);
+    while (payloadBitsRemaining && (finalBits & 1) == 0)
+    {
+      payloadBitsRemaining--;
+      finalBits >>= 1;
+    }
+    payloadBitsRemaining--;
+    if (payloadBitsRemaining > 0)
+    {
+      payloadExtensionPresent = true;
+    }
+  }
+
+  return payloadExtensionPresent;
+}
+#endif
+
+#if Q0189_TMVP_CONSTRAINTS 
+Void SEIReader::xParseSEITMVPConstraints   (SEITMVPConstrains& sei, UInt payloadSize, std::ostream *pDecodedMessageOutputStream)
+{
+  UInt uiCode;
+  sei_read_uvlc( pDecodedMessageOutputStream, uiCode,           "prev_pics_not_used_flag"              ); sei.prev_pics_not_used_flag = uiCode;
+  sei_read_uvlc( pDecodedMessageOutputStream, uiCode,           "no_intra_layer_col_pic_flag"          ); sei.no_intra_layer_col_pic_flag = uiCode;
+}
+#endif
+
+#if Q0247_FRAME_FIELD_INFO
+Void SEIReader::xParseSEIFrameFieldInfo    (SEIFrameFieldInfo& sei, UInt payloadSize, std::ostream *pDecodedMessageOutputStream)
+{
+  UInt code;
+  sei_read_code( pDecodedMessageOutputStream, 4, code, "ffinfo_pic_struct"       );       sei.m_ffinfo_picStruct      = code;
+  sei_read_code( pDecodedMessageOutputStream, 2, code, "ffinfo_source_scan_type" );       sei.m_ffinfo_sourceScanType = code;
+  sei_read_flag( pDecodedMessageOutputStream,    code, "ffinfo_duplicate_flag"   );       sei.m_ffinfo_duplicateFlag  = ( code == 1 ? true : false );
+}
+#endif
+
+
+#endif //SVC_EXTENSION
+
+//! \}
Index: /tags/SHM-9.0/source/Lib/TLibDecoder/SEIread.h
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibDecoder/SEIread.h	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibDecoder/SEIread.h	(revision 1088)
@@ -0,0 +1,170 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ \file     SEIread.h
+ \brief    reading funtionality for SEI messages
+ */
+
+#ifndef __SEIREAD__
+#define __SEIREAD__
+
+#if _MSC_VER > 1000
+#pragma once
+#endif // _MSC_VER > 1000
+
+//! \ingroup TLibDecoder
+//! \{
+
+#include "TLibCommon/SEI.h"
+class TComInputBitstream;
+
+
+class SEIReader: public SyntaxElementParser
+{
+public:
+  SEIReader() {};
+  virtual ~SEIReader() {};
+#if LAYERS_NOT_PRESENT_SEI
+  Void parseSEImessage(TComInputBitstream* bs, SEIMessages& seis, const NalUnitType nalUnitType, TComVPS *vps, TComSPS *sps, std::ostream *pDecodedMessageOutputStream);
+#else
+  Void parseSEImessage(TComInputBitstream* bs, SEIMessages& seis, const NalUnitType nalUnitType, TComSPS *sps, std::ostream *pDecodedMessageOutputStream);
+#endif
+protected:
+#if O0164_MULTI_LAYER_HRD
+#if LAYERS_NOT_PRESENT_SEI
+  Void xReadSEImessage                        (SEIMessages& seis, const NalUnitType nalUnitType, TComVPS *vps, TComSPS *sps, std::ostream *pDecodedMessageOutputStream, const SEIScalableNesting *nestingSei=NULL, const SEIBspNesting *bspNestingSei=NULL);
+#else
+  Void xReadSEImessage                        (SEIMessages& seis, const NalUnitType nalUnitType, TComSPS *sps, , std::ostream *pDecodedMessageOutputStream, const SEIScalableNesting *nestingSei=NULL);
+#endif
+#else
+#if LAYERS_NOT_PRESENT_SEI
+  Void xReadSEImessage                        (SEIMessages& seis, const NalUnitType nalUnitType, TComVPS *vps, TComSPS *sps, std::ostream *pDecodedMessageOutputStream);
+#else
+  Void xReadSEImessage                        (SEIMessages& seis, const NalUnitType nalUnitType, TComSPS *sps, std::ostream *pDecodedMessageOutputStream);
+#endif
+#endif
+  Void xParseSEIuserDataUnregistered          (SEIuserDataUnregistered &sei,          UInt payloadSize,               std::ostream *pDecodedMessageOutputStream);
+  Void xParseSEIActiveParameterSets           (SEIActiveParameterSets  &sei,          UInt payloadSize,               std::ostream *pDecodedMessageOutputStream);
+  Void xParseSEIDecodedPictureHash            (SEIDecodedPictureHash& sei,            UInt payloadSize,               std::ostream *pDecodedMessageOutputStream);
+#if VPS_VUI_BSP_HRD_PARAMS
+  Void xParseSEIDecodingUnitInfo              (SEIDecodingUnitInfo& sei,              UInt payloadSize, TComSPS *sps, const SEIScalableNesting* nestingSei, const SEIBspNesting* bspNestingSei, TComVPS *vps, std::ostream *pDecodedMessageOutputStream);
+  Void xParseSEIBufferingPeriod               (SEIBufferingPeriod& sei,               UInt payloadSize, TComSPS *sps, const SEIScalableNesting* nestingSei, const SEIBspNesting* bspNestingSei, TComVPS *vps, std::ostream *pDecodedMessageOutputStream);
+  Void xParseSEIPictureTiming                 (SEIPictureTiming& sei,                 UInt payloadSize, TComSPS *sps, const SEIScalableNesting* nestingSei, const SEIBspNesting* bspNestingSei, TComVPS *vps, std::ostream *pDecodedMessageOutputStream);
+#else
+  Void xParseSEIDecodingUnitInfo              (SEIDecodingUnitInfo& sei,              UInt payloadSize, TComSPS *sps, std::ostream *pDecodedMessageOutputStream);
+  Void xParseSEIBufferingPeriod               (SEIBufferingPeriod& sei,               UInt payloadSize, TComSPS *sps, std::ostream *pDecodedMessageOutputStream);
+  Void xParseSEIPictureTiming                 (SEIPictureTiming& sei,                 UInt payloadSize, TComSPS *sps, std::ostream *pDecodedMessageOutputStream);
+#endif
+  Void xParseSEIRecoveryPoint                 (SEIRecoveryPoint& sei,                 UInt payloadSize,               std::ostream *pDecodedMessageOutputStream);
+  Void xParseSEIFramePacking                  (SEIFramePacking& sei,                  UInt payloadSize,               std::ostream *pDecodedMessageOutputStream);
+  Void xParseSEISegmentedRectFramePacking     (SEISegmentedRectFramePacking& sei,     UInt payloadSize,               std::ostream *pDecodedMessageOutputStream);
+  Void xParseSEIDisplayOrientation            (SEIDisplayOrientation &sei,            UInt payloadSize,               std::ostream *pDecodedMessageOutputStream);
+  Void xParseSEITemporalLevel0Index           (SEITemporalLevel0Index &sei,           UInt payloadSize,               std::ostream *pDecodedMessageOutputStream);
+  Void xParseSEIRegionRefreshInfo             (SEIGradualDecodingRefreshInfo &sei,    UInt payloadSize,               std::ostream *pDecodedMessageOutputStream);
+  Void xParseSEINoDisplay                     (SEINoDisplay &sei,                     UInt payloadSize,               std::ostream *pDecodedMessageOutputStream);
+  Void xParseSEIToneMappingInfo               (SEIToneMappingInfo& sei,               UInt payloadSize,               std::ostream *pDecodedMessageOutputStream);
+  Void xParseSEISOPDescription                (SEISOPDescription &sei,                UInt payloadSize,               std::ostream *pDecodedMessageOutputStream);
+#if !LAYERS_NOT_PRESENT_SEI
+  Void xParseSEIScalableNesting               (SEIScalableNesting& sei, const NalUnitType nalUnitType, UInt payloadSize, TComSPS *sps, std::ostream *pDecodedMessageOutputStream);
+#endif
+  Void xParseSEITempMotionConstraintsTileSets (SEITempMotionConstrainedTileSets& sei, UInt payloadSize,               std::ostream *pDecodedMessageOutputStream);
+  Void xParseSEITimeCode                      (SEITimeCode& sei,                      UInt payloadSize,               std::ostream *pDecodedMessageOutputStream);
+  Void xParseSEIChromaSamplingFilterHint      (SEIChromaSamplingFilterHint& sei,      UInt payloadSize/*,TComSPS* */, std::ostream *pDecodedMessageOutputStream);
+  Void xParseSEIKneeFunctionInfo              (SEIKneeFunctionInfo& sei,              UInt payloadSize,               std::ostream *pDecodedMessageOutputStream);
+  Void xParseSEIMasteringDisplayColourVolume  (SEIMasteringDisplayColourVolume& sei,  UInt payloadSize,               std::ostream *pDecodedMessageOutputStream);
+
+  Void sei_read_code(std::ostream *pOS, UInt uiLength, UInt& ruiCode, const Char *pSymbolName);
+  Void sei_read_uvlc(std::ostream *pOS,                UInt& ruiCode, const Char *pSymbolName);
+  Void sei_read_svlc(std::ostream *pOS,                Int&  ruiCode, const Char *pSymbolName);
+  Void sei_read_flag(std::ostream *pOS,                UInt& ruiCode, const Char *pSymbolName);
+
+#if Q0074_COLOUR_REMAPPING_SEI
+  Void xParseSEIColourRemappingInfo           (SEIColourRemappingInfo& sei, UInt payloadSize, std::ostream *pDecodedMessageOutputStream);
+#endif
+#if N0383_IL_CONSTRAINED_TILE_SETS_SEI
+  Void xParseSEIInterLayerConstrainedTileSets (SEIInterLayerConstrainedTileSets &sei, UInt payloadSize, std::ostream *pDecodedMessageOutputStream);
+#endif
+#if SUB_BITSTREAM_PROPERTY_SEI
+#if OLS_IDX_CHK
+Void   xParseSEISubBitstreamProperty          (SEISubBitstreamProperty &sei, TComVPS *vps, std::ostream *pDecodedMessageOutputStream);
+#else
+Void   xParseSEISubBitstreamProperty          (SEISubBitstreamProperty &sei, std::ostream *pDecodedMessageOutputStream);
+#endif
+#endif
+#if LAYERS_NOT_PRESENT_SEI
+  Void xParseSEILayersNotPresent              (SEILayersNotPresent &sei, UInt payloadSize, TComVPS *vps ,std::ostream *pDecodedMessageOutputStream);
+  Void xParseSEIScalableNesting               (SEIScalableNesting& sei, const NalUnitType nalUnitType, UInt payloadSize, TComVPS *vps, TComSPS *sps, std::ostream *pDecodedMessageOutputStream);
+#endif
+#if O0164_MULTI_LAYER_HRD
+#if LAYERS_NOT_PRESENT_SEI
+  Void xParseSEIBspNesting                    (SEIBspNesting &sei, const NalUnitType nalUnitType, TComVPS *vps, TComSPS *sps, const SEIScalableNesting &nestingSei, std::ostream *pDecodedMessageOutputStream);
+#else
+  Void xParseSEIBspNesting                    (SEIBspNesting &sei, const NalUnitType nalUnitType, TComSPS *sps, const SEIScalableNesting &nestingSei ,std::ostream *pDecodedMessageOutputStream);
+#endif
+  Void xParseSEIBspInitialArrivalTime         (SEIBspInitialArrivalTime &sei, TComVPS *vps, TComSPS *sps, const SEIScalableNesting &nestingSei, const SEIBspNesting &bspNestingSei, std::ostream *pDecodedMessageOutputStream);
+#if !REMOVE_BSP_HRD_SEI
+  Void xParseSEIBspHrd(SEIBspHrd &sei, TComSPS *sps, const SEIScalableNesting &nestingSei, std::ostream *pDecodedMessageOutputStream);
+#endif
+  Void xParseHrdParameters                    (TComHRD *hrd, Bool commonInfPresentFlag, UInt maxNumSubLayersMinus1, std::ostream *pDecodedMessageOutputStream);
+#endif
+#if Q0078_ADD_LAYER_SETS
+#if LAYERS_NOT_PRESENT_SEI
+  Void xParseSEIOutputLayerSetNesting         (SEIOutputLayerSetNesting& sei, const NalUnitType nalUnitType, TComVPS *vps, TComSPS *sps, std::ostream *pDecodedMessageOutputStream);
+#else
+  Void xParseSEIOutputLayerSetNesting         (SEIOutputLayerSetNesting& sei, const NalUnitType nalUnitType, TComSPS *sps, std::ostream *pDecodedMessageOutputStream);
+#endif
+  Void xParseSEIVPSRewriting                  (SEIVPSRewriting &sei, std::ostream *pDecodedMessageOutputStream);
+#endif
+
+#if Q0189_TMVP_CONSTRAINTS 
+  Void xParseSEITMVPConstraints               (SEITMVPConstrains& sei, UInt payloadSize, std::ostream *pDecodedMessageOutputStream);
+#endif
+#if Q0247_FRAME_FIELD_INFO
+  Void xParseSEIFrameFieldInfo                (SEIFrameFieldInfo& sei, UInt payloadSize, std::ostream *pDecodedMessageOutputStream);
+#endif
+#if P0123_ALPHA_CHANNEL_SEI
+  Void xParseSEIAlphaChannelInfo              (SEIAlphaChannelInfo& sei, UInt payloadSize, std::ostream *pDecodedMessageOutputStream);
+#endif
+#if Q0096_OVERLAY_SEI
+  Void xParseSEIOverlayInfo                   (SEIOverlayInfo& sei, UInt payloadSize, std::ostream *pDecodedMessageOutputStream);
+#endif
+#if P0138_USE_ALT_CPB_PARAMS_FLAG
+  Bool xPayloadExtensionPresent       ();
+#endif
+};
+
+
+//! \}
+
+#endif
Index: /tags/SHM-9.0/source/Lib/TLibDecoder/SyntaxElementParser.cpp
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibDecoder/SyntaxElementParser.cpp	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibDecoder/SyntaxElementParser.cpp	(revision 1088)
@@ -0,0 +1,253 @@
+/* The copyright in this software is being made available under the BSD
+* License, included below. This software may be subject to other third party
+* and contributor rights, including patent rights, and no such rights are
+* granted under this license.
+*
+* Copyright (c) 2010-2014, ITU/ISO/IEC
+* All rights reserved.
+*
+* Redistribution and use in source and binary forms, with or without
+* modification, are permitted provided that the following conditions are met:
+*
+*  * Redistributions of source code must retain the above copyright notice,
+*    this list of conditions and the following disclaimer.
+*  * Redistributions in binary form must reproduce the above copyright notice,
+*    this list of conditions and the following disclaimer in the documentation
+*    and/or other materials provided with the distribution.
+*  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+*    be used to endorse or promote products derived from this software without
+*    specific prior written permission.
+*
+* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+* THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+/** \file     SyntaxElementParser.cpp
+    \brief    Parsing functionality high level syntax
+*/
+
+//! \ingroup TLibDecoder
+//! \{
+
+#include "TLibCommon/CommonDef.h"
+#include "TLibCommon/TComRom.h"
+#include "TLibCommon/TComBitStream.h"
+#include "SyntaxElementParser.h"
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+#include "TLibCommon/TComCodingStatistics.h"
+#endif
+
+#if ENC_DEC_TRACE
+
+Void  SyntaxElementParser::xReadCodeTr           (UInt length, UInt& rValue, const Char *pSymbolName)
+{
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+  xReadCode (length, rValue, pSymbolName);
+#else
+  xReadCode (length, rValue);
+#endif
+  fprintf( g_hTrace, "%8lld  ", g_nSymbolCounter++ );
+  if (length < 10)
+  {
+    fprintf( g_hTrace, "%-50s u(%d)  : %u\n", pSymbolName, length, rValue );
+  }
+  else
+  {
+    fprintf( g_hTrace, "%-50s u(%d) : %u\n", pSymbolName, length, rValue ); 
+  }
+  fflush ( g_hTrace );
+}
+
+Void  SyntaxElementParser::xReadUvlcTr           (UInt& rValue, const Char *pSymbolName)
+{
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+  xReadUvlc (rValue, pSymbolName);
+#else
+  xReadUvlc (rValue);
+#endif
+  fprintf( g_hTrace, "%8lld  ", g_nSymbolCounter++ );
+  fprintf( g_hTrace, "%-50s ue(v) : %u\n", pSymbolName, rValue );
+  fflush ( g_hTrace );
+}
+
+Void  SyntaxElementParser::xReadSvlcTr           (Int& rValue, const Char *pSymbolName)
+{
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+  xReadSvlc (rValue, pSymbolName);
+#else
+  xReadSvlc (rValue);
+#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)
+{
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+  xReadFlag (rValue, pSymbolName);
+#else
+  xReadFlag (rValue);
+#endif
+  fprintf( g_hTrace, "%8lld  ", g_nSymbolCounter++ );
+  fprintf( g_hTrace, "%-50s u(1)  : %d\n", pSymbolName, rValue );
+  fflush ( g_hTrace );
+}
+
+#if Q0096_OVERLAY_SEI
+Void  SyntaxElementParser::xReadStringTr        (UInt buSize, UChar *pValue, UInt& rLength, const Char *pSymbolName)
+{
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+  xReadString(buSize, pValue, rLength, pSymbolName);
+#else
+  xReadString(buSize, pValue, rLength);
+#endif
+  fprintf( g_hTrace, "%8lld  ", g_nSymbolCounter++ );
+  fprintf( g_hTrace, "%-50s st(v=%d)  : %s\n", pSymbolName, rLength, pValue );
+  fflush ( g_hTrace );
+}
+#endif
+
+#endif
+
+
+// ====================================================================================================================
+// Protected member functions
+// ====================================================================================================================
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+Void SyntaxElementParser::xReadCode (UInt uiLength, UInt& ruiCode, const Char *pSymbolName)
+#else
+Void SyntaxElementParser::xReadCode (UInt uiLength, UInt& ruiCode)
+#endif
+{
+  assert ( uiLength > 0 );
+  m_pcBitstream->read (uiLength, ruiCode);
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+  TComCodingStatistics::IncrementStatisticEP(pSymbolName, uiLength, ruiCode);
+#endif
+}
+
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+Void SyntaxElementParser::xReadUvlc( UInt& ruiVal, const Char *pSymbolName)
+#else
+Void SyntaxElementParser::xReadUvlc( UInt& ruiVal)
+#endif
+{
+  UInt uiVal = 0;
+  UInt uiCode = 0;
+  UInt uiLength;
+  m_pcBitstream->read( 1, uiCode );
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+  UInt totalLen=1;
+#endif
+
+  if( 0 == uiCode )
+  {
+    uiLength = 0;
+
+    while( ! ( uiCode & 1 ))
+    {
+      m_pcBitstream->read( 1, uiCode );
+      uiLength++;
+    }
+
+    m_pcBitstream->read( uiLength, uiVal );
+
+    uiVal += (1 << uiLength)-1;
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+    totalLen+=uiLength+uiLength;
+#endif
+  }
+
+  ruiVal = uiVal;
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+  TComCodingStatistics::IncrementStatisticEP(pSymbolName, Int(totalLen), ruiVal);
+#endif
+}
+
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+Void SyntaxElementParser::xReadSvlc( Int& riVal, const Char *pSymbolName)
+#else
+Void SyntaxElementParser::xReadSvlc( Int& riVal)
+#endif
+{
+  UInt uiBits = 0;
+  m_pcBitstream->read( 1, uiBits );
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+  UInt totalLen=1;
+#endif
+  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);
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+    totalLen+=uiLength+uiLength;
+#endif
+  }
+  else
+  {
+    riVal = 0;
+  }
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+  TComCodingStatistics::IncrementStatisticEP(pSymbolName, Int(totalLen), riVal);
+#endif
+}
+
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+Void SyntaxElementParser::xReadFlag (UInt& ruiCode, const Char *pSymbolName)
+#else
+Void SyntaxElementParser::xReadFlag (UInt& ruiCode)
+#endif
+{
+  m_pcBitstream->read( 1, ruiCode );
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+  TComCodingStatistics::IncrementStatisticEP(pSymbolName, 1, Int(ruiCode));
+#endif
+}
+
+#if Q0096_OVERLAY_SEI
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+Void SyntaxElementParser::xReadString (UInt bufSize, UChar *pVal, UInt& rLength, const Char *pSymbolName)
+#else
+Void  SyntaxElementParser::xReadString (UInt bufSize, UChar *pVal, UInt& rLength)
+#endif
+{
+  assert( m_pcBitstream->getNumBitsRead() % 8 == 0 ); //always start reading at a byte-aligned position
+  assert ( bufSize > 1 ); //last byte always used for null-termination
+  UInt val;
+  UInt i;
+  for (i=0 ; i<bufSize ; ++i ) 
+  {
+    m_pcBitstream->readByte( val );
+    pVal[i] = val;
+    if ( val == 0)
+    {
+      break;
+    }
+  }
+  rLength = i;
+  assert( pVal[rLength] == 0 );
+}
+#endif
+
+//! \}
+
Index: /tags/SHM-9.0/source/Lib/TLibDecoder/SyntaxElementParser.h
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibDecoder/SyntaxElementParser.h	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibDecoder/SyntaxElementParser.h	(revision 1088)
@@ -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-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     SyntaxElementParser.h
+    \brief    Parsing functionality high level syntax
+*/
+
+#ifndef __SYNTAXELEMENTPARSER__
+#define __SYNTAXELEMENTPARSER__
+
+#if _MSC_VER > 1000
+#pragma once
+#endif // _MSC_VER > 1000
+
+#include "TLibCommon/TComRom.h"
+
+#if ENC_DEC_TRACE
+
+#define READ_CODE(length, code, name)     xReadCodeTr ( length, code, name )
+#define READ_UVLC(        code, name)     xReadUvlcTr (         code, name )
+#define READ_SVLC(        code, name)     xReadSvlcTr (         code, name )
+#define READ_FLAG(        code, name)     xReadFlagTr (         code, name )
+#if Q0096_OVERLAY_SEI
+#define READ_STRING(bufSize, code, length, name)   xReadStringTr ( bufSize, code, length, name )
+#endif
+
+#else
+
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+
+#define READ_CODE(length, code, name)     xReadCode ( length, code, name )
+#define READ_UVLC(        code, name)     xReadUvlc (         code, name )
+#define READ_SVLC(        code, name)     xReadSvlc (         code, name )
+#define READ_FLAG(        code, name)     xReadFlag (         code, name )
+#if Q0096_OVERLAY_SEI
+#define READ_STRING(bufSize, code, length, name)   xReadString ( bufSize, code, length, name )
+#endif
+
+#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 )
+#if Q0096_OVERLAY_SEI
+#define READ_STRING(bufSize, code, length, name)   xReadString ( bufSize, code, length )
+#endif
+#endif
+
+#endif
+
+//! \ingroup TLibDecoder
+//! \{
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+class SyntaxElementParser
+{
+protected:
+  TComInputBitstream*   m_pcBitstream;
+
+  SyntaxElementParser()
+  : m_pcBitstream (NULL)
+  {};
+  virtual ~SyntaxElementParser() {};
+
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+  Void  xReadCode    ( UInt   length, UInt& val, const Char *pSymbolName );
+  Void  xReadUvlc    ( UInt&  val, const Char *pSymbolName );
+  Void  xReadSvlc    ( Int&   val, const Char *pSymbolName );
+  Void  xReadFlag    ( UInt&  val, const Char *pSymbolName );
+#if Q0096_OVERLAY_SEI
+  Void  xReadString  (UInt bufSize, UChar *pValue, UInt& rLength, const Char *pSymbolName);
+#endif
+#else
+  Void  xReadCode    ( UInt   length, UInt& val );
+  Void  xReadUvlc    ( UInt&  val );
+  Void  xReadSvlc    ( Int&   val );
+  Void  xReadFlag    ( UInt&  val );
+#if Q0096_OVERLAY_SEI
+  Void  xReadString  (UInt bufSize, UChar *val, UInt& length);
+#endif
+#endif
+#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);
+#if Q0096_OVERLAY_SEI
+  Void  xReadStringTr(UInt bufSize, UChar *pValue, UInt& rLength, const Char *pSymbolName);
+#endif
+#endif
+public:
+  Void  setBitstream ( TComInputBitstream* p )   { m_pcBitstream = p; }
+  TComInputBitstream* getBitstream() { return m_pcBitstream; }
+};
+
+//! \}
+
+#endif // !defined(__SYNTAXELEMENTPARSER__)
+
Index: /tags/SHM-9.0/source/Lib/TLibDecoder/TDecBinCoder.h
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibDecoder/TDecBinCoder.h	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibDecoder/TDecBinCoder.h	(revision 1088)
@@ -0,0 +1,86 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TDecBinCoder.h
+    \brief    binary entropy decoder interface
+*/
+
+#ifndef __TDECBINCODER__
+#define __TDECBINCODER__
+
+#include "TLibCommon/ContextModel.h"
+#include "TLibCommon/TComBitStream.h"
+
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+class TComCodingStatisticsClassType;
+#endif
+
+//! \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;
+
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+  virtual Void  decodeBin         ( UInt& ruiBin, ContextModel& rcCtxModel, const class TComCodingStatisticsClassType &whichStat )  = 0;
+  virtual Void  decodeBinEP       ( UInt& ruiBin                          , const class TComCodingStatisticsClassType &whichStat )  = 0;
+  virtual Void  decodeBinsEP      ( UInt& ruiBins, Int numBins            , const class TComCodingStatisticsClassType &whichStat )  = 0;
+#else
+  virtual Void  decodeBin         ( UInt& ruiBin, ContextModel& rcCtxModel )  = 0;
+  virtual Void  decodeBinEP       ( UInt& ruiBin                           )  = 0;
+  virtual Void  decodeBinsEP      ( UInt& ruiBins, Int numBins             )  = 0;
+#endif
+
+  virtual Void  align             ()                                          = 0;
+
+  virtual Void  decodeBinTrm      ( UInt& ruiBin                           )  = 0;
+
+  virtual Void  xReadPCMCode      ( UInt uiLength, UInt& ruiCode)             = 0;
+
+  virtual ~TDecBinIf() {}
+
+  virtual Void  copyState         ( const TDecBinIf* pcTDecBinIf )            = 0;
+  virtual TDecBinCABAC*   getTDecBinCABAC   ()             { return 0; }
+  virtual const TDecBinCABAC*   getTDecBinCABAC   () const { return 0; }
+};
+
+//! \}
+
+#endif
Index: /tags/SHM-9.0/source/Lib/TLibDecoder/TDecBinCoderCABAC.cpp
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibDecoder/TDecBinCoderCABAC.cpp	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibDecoder/TDecBinCoderCABAC.cpp	(revision 1088)
@@ -0,0 +1,378 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TDecBinCoderCABAC.cpp
+    \brief    binary entropy decoder of CABAC
+*/
+
+#include "TDecBinCoderCABAC.h"
+#include "TLibCommon/Debug.h"
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+#include "TLibCommon/TComCodingStatistics.h"
+#endif
+
+//! \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 );
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+  TComCodingStatistics::UpdateCABACStat(STATS__CABAC_INITIALISATION, 512, 510, 0);
+#endif
+  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( const TDecBinIf* pcTDecBinIf )
+{
+  const TDecBinCABAC* pcTDecBinCABAC = pcTDecBinIf->getTDecBinCABAC();
+  m_uiRange   = pcTDecBinCABAC->m_uiRange;
+  m_uiValue   = pcTDecBinCABAC->m_uiValue;
+  m_bitsNeeded= pcTDecBinCABAC->m_bitsNeeded;
+}
+
+
+
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+Void TDecBinCABAC::decodeBin( UInt& ruiBin, ContextModel &rcCtxModel, const TComCodingStatisticsClassType &whichStat )
+#else
+Void TDecBinCABAC::decodeBin( UInt& ruiBin, ContextModel &rcCtxModel )
+#endif
+{
+#ifdef DEBUG_CABAC_BINS
+  const UInt startingRange = m_uiRange;
+#endif
+
+  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();
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+    TComCodingStatistics::UpdateCABACStat(whichStat, m_uiRange+uiLPS, m_uiRange, Int(ruiBin));
+#endif
+    rcCtxModel.updateMPS();
+
+    if ( scaledRange < ( 256 << 7 ) )
+    {
+      m_uiRange = scaledRange >> 6;
+      m_uiValue += m_uiValue;
+
+      if ( ++m_bitsNeeded == 0 )
+      {
+        m_bitsNeeded = -8;
+        m_uiValue += m_pcTComBitstream->readByte();
+      }
+    }
+  }
+  else
+  {
+    // LPS path
+    ruiBin      = 1 - rcCtxModel.getMps();
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+    TComCodingStatistics::UpdateCABACStat(whichStat, m_uiRange+uiLPS, uiLPS, Int(ruiBin));
+#endif
+    Int numBits = TComCABACTables::sm_aucRenormTable[ uiLPS >> 3 ];
+    m_uiValue   = ( m_uiValue - scaledRange ) << numBits;
+    m_uiRange   = uiLPS << numBits;
+    rcCtxModel.updateLPS();
+
+    m_bitsNeeded += numBits;
+
+    if ( m_bitsNeeded >= 0 )
+    {
+      m_uiValue += m_pcTComBitstream->readByte() << m_bitsNeeded;
+      m_bitsNeeded -= 8;
+    }
+  }
+
+#ifdef DEBUG_CABAC_BINS
+  if ((g_debugCounter + debugCabacBinWindow) >= debugCabacBinTargetLine)
+    std::cout << g_debugCounter << ": coding bin value " << ruiBin << ", range = [" << startingRange << "->" << m_uiRange << "]\n";
+
+  if (g_debugCounter >= debugCabacBinTargetLine)
+  {
+    Char breakPointThis;
+    breakPointThis = 7;
+  }
+  if (g_debugCounter >= (debugCabacBinTargetLine + debugCabacBinWindow)) exit(0);
+  g_debugCounter++;
+#endif
+}
+
+
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+Void TDecBinCABAC::decodeBinEP( UInt& ruiBin, const TComCodingStatisticsClassType &whichStat )
+#else
+Void TDecBinCABAC::decodeBinEP( UInt& ruiBin )
+#endif
+{
+  if (m_uiRange == 256)
+  {
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+    decodeAlignedBinsEP(ruiBin, 1, whichStat);
+#else
+    decodeAlignedBinsEP(ruiBin, 1);
+#endif
+    return;
+  }
+
+  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;
+  }
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+  TComCodingStatistics::IncrementStatisticEP(whichStat, 1, Int(ruiBin));
+#endif
+}
+
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+Void TDecBinCABAC::decodeBinsEP( UInt& ruiBin, Int numBins, const TComCodingStatisticsClassType &whichStat )
+#else
+Void TDecBinCABAC::decodeBinsEP( UInt& ruiBin, Int numBins )
+#endif
+{
+  if (m_uiRange == 256)
+  {
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+    decodeAlignedBinsEP(ruiBin, numBins, whichStat);
+#else
+    decodeAlignedBinsEP(ruiBin, numBins);
+#endif
+    return;
+  }
+
+  UInt bins = 0;
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+  Int origNumBins=numBins;
+#endif
+  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;
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+  TComCodingStatistics::IncrementStatisticEP(whichStat, origNumBins, Int(ruiBin));
+#endif
+}
+
+Void TDecBinCABAC::align()
+{
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+  TComCodingStatistics::UpdateCABACStat(STATS__CABAC_EP_BIT_ALIGNMENT, m_uiRange, 256, 0);
+#endif
+  m_uiRange = 256;
+}
+
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+Void TDecBinCABAC::decodeAlignedBinsEP( UInt& ruiBins, Int numBins, const class TComCodingStatisticsClassType &whichStat )
+#else
+Void TDecBinCABAC::decodeAlignedBinsEP( UInt& ruiBins, Int numBins )
+#endif
+{
+  Int binsRemaining = numBins;
+  ruiBins = 0;
+
+  assert(m_uiRange == 256); //aligned decode only works when range = 256
+
+  while (binsRemaining > 0)
+  {
+    const UInt binsToRead = std::min<UInt>(binsRemaining, 8); //read bytes if able to take advantage of the system's byte-read function
+    const UInt binMask    = (1 << binsToRead) - 1;
+
+    //The MSB of m_uiValue is known to be 0 because range is 256. Therefore:
+    // > The comparison against the symbol range of 128 is simply a test on the next-most-significant bit
+    // > "Subtracting" the symbol range if the decoded bin is 1 simply involves clearing that bit.
+    //
+    //As a result, the required bins are simply the <binsToRead> next-most-significant bits of m_uiValue
+    //(m_uiValue is stored MSB-aligned in a 16-bit buffer - hence the shift of 15)
+    //
+    //   m_uiValue = |0|V|V|V|V|V|V|V|V|B|B|B|B|B|B|B|        (V = usable bit, B = potential buffered bit (buffer refills when m_bitsNeeded >= 0))
+    //
+    const UInt newBins = (m_uiValue >> (15 - binsToRead)) & binMask;
+
+    ruiBins   = (ruiBins   << binsToRead) | newBins;
+    m_uiValue = (m_uiValue << binsToRead) & 0x7FFF;
+
+    binsRemaining -= binsToRead;
+    m_bitsNeeded  += binsToRead;
+
+    if (m_bitsNeeded >= 0)
+    {
+      m_uiValue    |= m_pcTComBitstream->readByte() << m_bitsNeeded;
+      m_bitsNeeded -= 8;
+    }
+  }
+
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+  TComCodingStatistics::IncrementStatisticEP(whichStat, numBins, Int(ruiBins));
+#endif
+}
+
+Void
+TDecBinCABAC::decodeBinTrm( UInt& ruiBin )
+{
+  m_uiRange -= 2;
+  UInt scaledRange = m_uiRange << 7;
+  if( m_uiValue >= scaledRange )
+  {
+    ruiBin = 1;
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+    TComCodingStatistics::UpdateCABACStat(STATS__CABAC_TRM_BITS, m_uiRange+2, 2, ruiBin);
+    TComCodingStatistics::IncrementStatisticEP(STATS__BYTE_ALIGNMENT_BITS, -m_bitsNeeded, 0);
+#endif
+  }
+  else
+  {
+    ruiBin = 0;
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+    TComCodingStatistics::UpdateCABACStat(STATS__CABAC_TRM_BITS, m_uiRange+2, m_uiRange, ruiBin);
+#endif
+    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);
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+  TComCodingStatistics::IncrementStatisticEP(STATS__CABAC_PCM_CODE_BITS, uiLength, ruiCode);
+#endif
+}
+//! \}
Index: /tags/SHM-9.0/source/Lib/TLibDecoder/TDecBinCoderCABAC.h
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibDecoder/TDecBinCoderCABAC.h	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibDecoder/TDecBinCoderCABAC.h	(revision 1088)
@@ -0,0 +1,91 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TDecBinCoderCABAC.h
+    \brief    binary entropy decoder of CABAC
+*/
+
+#ifndef __TDECBINCODERCABAC__
+#define __TDECBINCODERCABAC__
+
+#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            ();
+
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+  Void  decodeBin          ( UInt& ruiBin, ContextModel& rcCtxModel, const class TComCodingStatisticsClassType &whichStat );
+  Void  decodeBinEP        ( UInt& ruiBin                          , const class TComCodingStatisticsClassType &whichStat );
+  Void  decodeBinsEP       ( UInt& ruiBin, Int numBins             , const class TComCodingStatisticsClassType &whichStat );
+  Void  decodeAlignedBinsEP( UInt& ruiBins, Int numBins            , const class TComCodingStatisticsClassType &whichStat );
+#else
+  Void  decodeBin         ( UInt& ruiBin, ContextModel& rcCtxModel );
+  Void  decodeBinEP       ( UInt& ruiBin                           );
+  Void  decodeBinsEP      ( UInt& ruiBin, Int numBins              );
+  Void  decodeAlignedBinsEP( UInt& ruiBins, Int numBins             );
+#endif
+
+  Void  align             ();
+
+  Void  decodeBinTrm      ( UInt& ruiBin                           );
+
+  Void  xReadPCMCode      ( UInt uiLength, UInt& ruiCode );
+
+  Void  copyState         ( const TDecBinIf* pcTDecBinIf );
+  TDecBinCABAC* getTDecBinCABAC()             { return this; }
+  const TDecBinCABAC* getTDecBinCABAC() const { return this; }
+
+private:
+  TComInputBitstream* m_pcTComBitstream;
+  UInt                m_uiRange;
+  UInt                m_uiValue;
+  Int                 m_bitsNeeded;
+};
+
+//! \}
+
+#endif
+
Index: /tags/SHM-9.0/source/Lib/TLibDecoder/TDecCAVLC.cpp
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibDecoder/TDecCAVLC.cpp	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibDecoder/TDecCAVLC.cpp	(revision 1088)
@@ -0,0 +1,4806 @@
+/* The copyright in this software is being made available under the BSD
+* License, included below. This software may be subject to other third party
+* and contributor rights, including patent rights, and no such rights are
+* granted under this license.
+*
+* Copyright (c) 2010-2014, ITU/ISO/IEC
+* All rights reserved.
+*
+* Redistribution and use in source and binary forms, with or without
+* modification, are permitted provided that the following conditions are met:
+*
+*  * Redistributions of source code must retain the above copyright notice,
+*    this list of conditions and the following disclaimer.
+*  * Redistributions in binary form must reproduce the above copyright notice,
+*    this list of conditions and the following disclaimer in the documentation
+*    and/or other materials provided with the distribution.
+*  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+*    be used to endorse or promote products derived from this software without
+*    specific prior written permission.
+*
+* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+* THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+/** \file     TDecCAVLC.cpp
+\brief    CAVLC decoder class
+*/
+
+#include "TDecCAVLC.h"
+#include "SEIread.h"
+#include "TDecSlice.h"
+#include "TLibCommon/TComChromaFormat.h"
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+#include "TLibCommon/TComCodingStatistics.h"
+#endif
+#if Q0048_CGS_3D_ASYMLUT
+#include "../TLibCommon/TCom3DAsymLUT.h"
+#endif
+
+//! \ingroup TLibDecoder
+//! \{
+
+#if ENC_DEC_TRACE
+
+Void  xTraceSPSHeader (TComSPS *pSPS)
+{
+  fprintf( g_hTrace, "=========== Sequence Parameter Set ID: %d ===========\n", pSPS->getSPSId() );
+}
+
+Void  xTracePPSHeader (TComPPS *pPPS)
+{
+  fprintf( g_hTrace, "=========== Picture Parameter Set ID: %d ===========\n", pPPS->getPPSId() );
+}
+
+Void  xTraceSliceHeader (TComSlice *pSlice)
+{
+  fprintf( g_hTrace, "=========== Slice ===========\n");
+}
+
+#endif
+
+// ====================================================================================================================
+// Constructor / destructor / create / destroy
+// ====================================================================================================================
+
+TDecCavlc::TDecCavlc()
+{
+}
+
+TDecCavlc::~TDecCavlc()
+{
+
+}
+
+// ====================================================================================================================
+// Public member functions
+// ====================================================================================================================
+
+Void TDecCavlc::parseShortTermRefPicSet( TComSPS* sps, TComReferencePictureSet* rps, Int idx )
+{
+  UInt code;
+  UInt interRPSPred;
+  if (idx > 0)
+  {
+    READ_FLAG(interRPSPred, "inter_ref_pic_set_prediction_flag");  rps->setInterRPSPrediction(interRPSPred);
+  }
+  else
+  {
+    interRPSPred = false;
+    rps->setInterRPSPrediction(false);
+  }
+
+  if (interRPSPred)
+  {
+    UInt bit;
+    if(idx == sps->getRPSList()->getNumberOfReferencePictureSets())
+    {
+      READ_UVLC(code, "delta_idx_minus1" ); // delta index of the Reference Picture Set used for prediction minus 1
+    }
+    else
+    {
+      code = 0;
+    }
+    assert(code <= idx-1); // delta_idx_minus1 shall not be larger than idx-1, otherwise we will predict from a negative row position that does not exist. When idx equals 0 there is no legal value and interRPSPred must be zero. See J0185-r2
+    Int rIdx =  idx - 1 - code;
+    assert (rIdx <= idx-1 && rIdx >= 0); // Made assert tighter; if rIdx = idx then prediction is done from itself. rIdx must belong to range 0, idx-1, inclusive, see J0185-r2
+    TComReferencePictureSet*   rpsRef = sps->getRPSList()->getReferencePictureSet(rIdx);
+    Int k = 0, k0 = 0, k1 = 0;
+    READ_CODE(1, bit, "delta_rps_sign"); // delta_RPS_sign
+    READ_UVLC(code, "abs_delta_rps_minus1");  // absolute delta RPS minus 1
+    Int deltaRPS = (1 - 2 * bit) * (code + 1); // delta_RPS
+    for(Int j=0 ; j <= rpsRef->getNumberOfPictures(); j++)
+    {
+      READ_CODE(1, bit, "used_by_curr_pic_flag" ); //first bit is "1" if Idc is 1
+      Int refIdc = bit;
+      if (refIdc == 0)
+      {
+        READ_CODE(1, bit, "use_delta_flag" ); //second bit is "1" if Idc is 2, "0" otherwise.
+        refIdc = bit<<1; //second bit is "1" if refIdc is 2, "0" if refIdc = 0.
+      }
+      if (refIdc == 1 || refIdc == 2)
+      {
+        Int deltaPOC = deltaRPS + ((j < rpsRef->getNumberOfPictures())? rpsRef->getDeltaPOC(j) : 0);
+        rps->setDeltaPOC(k, deltaPOC);
+        rps->setUsed(k, (refIdc == 1));
+
+        if (deltaPOC < 0)
+        {
+          k0++;
+        }
+        else
+        {
+          k1++;
+        }
+        k++;
+      }
+      rps->setRefIdc(j,refIdc);
+    }
+    rps->setNumRefIdc(rpsRef->getNumberOfPictures()+1);
+    rps->setNumberOfPictures(k);
+    rps->setNumberOfNegativePictures(k0);
+    rps->setNumberOfPositivePictures(k1);
+    rps->sortDeltaPOC();
+  }
+  else
+  {
+    READ_UVLC(code, "num_negative_pics");           rps->setNumberOfNegativePictures(code);
+    READ_UVLC(code, "num_positive_pics");           rps->setNumberOfPositivePictures(code);
+    Int prev = 0;
+    Int poc;
+    for(Int j=0 ; j < rps->getNumberOfNegativePictures(); j++)
+    {
+      READ_UVLC(code, "delta_poc_s0_minus1");
+      poc = prev-code-1;
+      prev = poc;
+      rps->setDeltaPOC(j,poc);
+      READ_FLAG(code, "used_by_curr_pic_s0_flag");  rps->setUsed(j,code);
+    }
+    prev = 0;
+    for(Int j=rps->getNumberOfNegativePictures(); j < rps->getNumberOfNegativePictures()+rps->getNumberOfPositivePictures(); j++)
+    {
+      READ_UVLC(code, "delta_poc_s1_minus1");
+      poc = prev+code+1;
+      prev = poc;
+      rps->setDeltaPOC(j,poc);
+      READ_FLAG(code, "used_by_curr_pic_s1_flag");  rps->setUsed(j,code);
+    }
+    rps->setNumberOfPictures(rps->getNumberOfNegativePictures()+rps->getNumberOfPositivePictures());
+  }
+#if PRINT_RPS_INFO
+  rps->printDeltaPOC();
+#endif
+}
+
+#if Q0048_CGS_3D_ASYMLUT
+Void TDecCavlc::parsePPS(TComPPS* pcPPS, TCom3DAsymLUT * pc3DAsymLUT, Int nLayerID)
+#else
+Void TDecCavlc::parsePPS(TComPPS* pcPPS)
+#endif
+
+{
+#if ENC_DEC_TRACE
+  xTracePPSHeader (pcPPS);
+#endif
+  UInt  uiCode;
+
+  Int   iCode;
+
+  READ_UVLC( uiCode, "pps_pic_parameter_set_id");
+  assert(uiCode <= 63);
+  pcPPS->setPPSId (uiCode);
+
+  READ_UVLC( uiCode, "pps_seq_parameter_set_id");
+  assert(uiCode <= 15);
+  pcPPS->setSPSId (uiCode);
+
+  READ_FLAG( uiCode, "dependent_slice_segments_enabled_flag"    );    pcPPS->setDependentSliceSegmentsEnabledFlag   ( uiCode == 1 );
+
+  READ_FLAG( uiCode, "output_flag_present_flag" );                    pcPPS->setOutputFlagPresentFlag( uiCode==1 );
+
+  READ_CODE(3, uiCode, "num_extra_slice_header_bits");                pcPPS->setNumExtraSliceHeaderBits(uiCode);
+
+  READ_FLAG ( uiCode, "sign_data_hiding_flag" ); pcPPS->setSignHideFlag( uiCode );
+
+  READ_FLAG( uiCode,   "cabac_init_present_flag" );            pcPPS->setCabacInitPresentFlag( uiCode ? true : false );
+
+  READ_UVLC(uiCode, "num_ref_idx_l0_default_active_minus1");
+  assert(uiCode <= 14);
+  pcPPS->setNumRefIdxL0DefaultActive(uiCode+1);
+
+  READ_UVLC(uiCode, "num_ref_idx_l1_default_active_minus1");
+  assert(uiCode <= 14);
+  pcPPS->setNumRefIdxL1DefaultActive(uiCode+1);
+
+  READ_SVLC(iCode, "init_qp_minus26" );                            pcPPS->setPicInitQPMinus26(iCode);
+  READ_FLAG( uiCode, "constrained_intra_pred_flag" );              pcPPS->setConstrainedIntraPred( uiCode ? true : false );
+  READ_FLAG( uiCode, "transform_skip_enabled_flag" );
+  pcPPS->setUseTransformSkip ( uiCode ? true : false );
+
+  READ_FLAG( uiCode, "cu_qp_delta_enabled_flag" );            pcPPS->setUseDQP( uiCode ? true : false );
+  if( pcPPS->getUseDQP() )
+  {
+    READ_UVLC( uiCode, "diff_cu_qp_delta_depth" );
+    pcPPS->setMaxCuDQPDepth( uiCode );
+  }
+  else
+  {
+    pcPPS->setMaxCuDQPDepth( 0 );
+  }
+  READ_SVLC( iCode, "pps_cb_qp_offset");
+  pcPPS->setQpOffset(COMPONENT_Cb, iCode);
+  assert( pcPPS->getQpOffset(COMPONENT_Cb) >= -12 );
+  assert( pcPPS->getQpOffset(COMPONENT_Cb) <=  12 );
+
+  READ_SVLC( iCode, "pps_cr_qp_offset");
+  pcPPS->setQpOffset(COMPONENT_Cr, iCode);
+  assert( pcPPS->getQpOffset(COMPONENT_Cr) >= -12 );
+  assert( pcPPS->getQpOffset(COMPONENT_Cr) <=  12 );
+
+  assert(MAX_NUM_COMPONENT<=3);
+
+  READ_FLAG( uiCode, "pps_slice_chroma_qp_offsets_present_flag" );
+  pcPPS->setSliceChromaQpFlag( uiCode ? true : false );
+
+  READ_FLAG( uiCode, "weighted_pred_flag" );          // Use of Weighting Prediction (P_SLICE)
+  pcPPS->setUseWP( uiCode==1 );
+  READ_FLAG( uiCode, "weighted_bipred_flag" );         // Use of Bi-Directional Weighting Prediction (B_SLICE)
+  pcPPS->setWPBiPred( uiCode==1 );
+
+  READ_FLAG( uiCode, "transquant_bypass_enable_flag");
+  pcPPS->setTransquantBypassEnableFlag(uiCode ? true : false);
+  READ_FLAG( uiCode, "tiles_enabled_flag"               );    pcPPS->setTilesEnabledFlag            ( uiCode == 1 );
+  READ_FLAG( uiCode, "entropy_coding_sync_enabled_flag" );    pcPPS->setEntropyCodingSyncEnabledFlag( uiCode == 1 );
+
+  if( pcPPS->getTilesEnabledFlag() )
+  {
+    READ_UVLC ( uiCode, "num_tile_columns_minus1" );                pcPPS->setNumTileColumnsMinus1( uiCode );  
+    READ_UVLC ( uiCode, "num_tile_rows_minus1" );                   pcPPS->setNumTileRowsMinus1( uiCode );  
+    READ_FLAG ( uiCode, "uniform_spacing_flag" );                   pcPPS->setTileUniformSpacingFlag( uiCode == 1 );
+
+    const UInt tileColumnsMinus1 = pcPPS->getNumTileColumnsMinus1();
+    const UInt tileRowsMinus1    = pcPPS->getNumTileRowsMinus1();
+ 
+    if ( !pcPPS->getTileUniformSpacingFlag())
+    {
+      if (tileColumnsMinus1 > 0)
+      {
+        std::vector<Int> columnWidth(tileColumnsMinus1);
+        for(UInt i = 0; i < tileColumnsMinus1; i++)
+        { 
+          READ_UVLC( uiCode, "column_width_minus1" );  
+          columnWidth[i] = uiCode+1;
+        }
+        pcPPS->setTileColumnWidth(columnWidth);
+      }
+
+      if (tileRowsMinus1 > 0)
+      {
+        std::vector<Int> rowHeight (tileRowsMinus1);
+        for(UInt i = 0; i < tileRowsMinus1; i++)
+        {
+          READ_UVLC( uiCode, "row_height_minus1" );
+          rowHeight[i] = uiCode + 1;
+        }
+        pcPPS->setTileRowHeight(rowHeight);
+      }
+    }
+
+    if ((tileColumnsMinus1 + tileRowsMinus1) != 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_present_flag");
+
+#if SVC_EXTENSION
+  pcPPS->setExtensionFlag( uiCode ? true : false );
+  if( pcPPS->getExtensionFlag() )
+#else
+  if (uiCode)
+#endif
+  {
+    Bool pps_extension_flags[NUM_PPS_EXTENSION_FLAGS];
+    for(Int i=0; i<NUM_PPS_EXTENSION_FLAGS; i++)
+    {
+      READ_FLAG( uiCode, "pps_extension_flag[]" );
+      pps_extension_flags[i] = uiCode!=0;
+    }
+
+    Bool bSkipTrailingExtensionBits=false;
+    for(Int i=0; i<NUM_PPS_EXTENSION_FLAGS; i++) // loop used so that the order is determined by the enum.
+    {
+      if (pps_extension_flags[i])
+      {
+        switch (PPSExtensionFlagIndex(i))
+        {
+          case PPS_EXT__REXT:
+            assert(!bSkipTrailingExtensionBits);
+
+            if (pcPPS->getUseTransformSkip())
+            {
+              READ_UVLC( uiCode, "log2_transform_skip_max_size_minus2");
+              pcPPS->setTransformSkipLog2MaxSize(uiCode+2);
+            }
+
+            READ_FLAG( uiCode, "cross_component_prediction_flag");
+            pcPPS->setUseCrossComponentPrediction(uiCode != 0);
+
+            READ_FLAG( uiCode, "chroma_qp_adjustment_enabled_flag");
+            if (uiCode == 0)
+            {
+              pcPPS->clearChromaQpAdjTable();
+              pcPPS->setMaxCuChromaQpAdjDepth(0);
+            }
+            else
+            {
+              READ_UVLC(uiCode, "diff_cu_chroma_qp_adjustment_depth"); pcPPS->setMaxCuChromaQpAdjDepth(uiCode);
+              UInt tableSizeMinus1 = 0;
+              READ_UVLC(tableSizeMinus1, "chroma_qp_adjustment_table_size_minus1");
+              /* skip zero index */
+              for (Int chromaQpAdjustmentIndex = 1; chromaQpAdjustmentIndex <= (tableSizeMinus1 + 1); chromaQpAdjustmentIndex++)
+              {
+                Int cbOffset;
+                Int crOffset;
+                READ_SVLC(cbOffset, "cb_qp_adjustnemt[i]");
+                READ_SVLC(crOffset, "cr_qp_adjustnemt[i]");
+                pcPPS->setChromaQpAdjTableAt(chromaQpAdjustmentIndex, cbOffset, crOffset);
+              }
+              assert(pcPPS->getChromaQpAdjTableSize() == tableSizeMinus1 + 1);
+            }
+
+            READ_UVLC( uiCode, "sao_luma_bit_shift");
+            pcPPS->setSaoOffsetBitShift(CHANNEL_TYPE_LUMA, uiCode);
+            READ_UVLC( uiCode, "sao_chroma_bit_shift");
+            pcPPS->setSaoOffsetBitShift(CHANNEL_TYPE_CHROMA, uiCode);
+            break;
+
+#if SVC_EXTENSION
+          case PPS_EXT__MLAYER:
+            READ_FLAG( uiCode, "poc_reset_info_present_flag" );
+            pcPPS->setPocResetInfoPresentFlag(uiCode ? true : false);
+
+#if SCALINGLIST_INFERRING
+            READ_FLAG( uiCode, "pps_infer_scaling_list_flag" );
+            pcPPS->setInferScalingListFlag( uiCode );
+
+            if( pcPPS->getInferScalingListFlag() )
+            {
+              READ_CODE( 6, uiCode, "pps_scaling_list_ref_layer_id" ); 
+              pcPPS->setScalingListRefLayerId( uiCode );
+              // The value of pps_scaling_list_ref_layer_id shall be in the range of 0 to 62, inclusive
+              assert( pcPPS->getScalingListRefLayerId() <= 62 );
+              pcPPS->setScalingListPresentFlag( false );
+            }
+#endif
+
+#if REF_REGION_OFFSET
+            READ_UVLC( uiCode,      "num_ref_loc_offsets" ); pcPPS->setNumRefLayerLocationOffsets(uiCode);
+            for(Int k = 0; k < pcPPS->getNumRefLayerLocationOffsets(); k++)
+            {
+              READ_CODE( 6, uiCode,  "ref_loc_offset_layer_id" );  pcPPS->setRefLocationOffsetLayerId( k, uiCode );
+              READ_FLAG( uiCode, "scaled_ref_layer_offset_present_flag" );   pcPPS->setScaledRefLayerOffsetPresentFlag( k, uiCode );
+              if (uiCode)
+              {
+                Window& scaledWindow = pcPPS->getScaledRefLayerWindow(k);
+                READ_SVLC( iCode, "scaled_ref_layer_left_offset" );    scaledWindow.setWindowLeftOffset  (iCode << 1);
+                READ_SVLC( iCode, "scaled_ref_layer_top_offset" );     scaledWindow.setWindowTopOffset   (iCode << 1);
+                READ_SVLC( iCode, "scaled_ref_layer_right_offset" );   scaledWindow.setWindowRightOffset (iCode << 1);
+                READ_SVLC( iCode, "scaled_ref_layer_bottom_offset" );  scaledWindow.setWindowBottomOffset(iCode << 1);
+#if P0312_VERT_PHASE_ADJ
+                READ_FLAG( uiCode, "vert_phase_position_enable_flag" ); scaledWindow.setVertPhasePositionEnableFlag(uiCode);  pcPPS->setVertPhasePositionEnableFlag( pcPPS->getScaledRefLayerId(i), uiCode);
+#endif
+              }
+              READ_FLAG( uiCode, "ref_region_offset_present_flag" );   pcPPS->setRefRegionOffsetPresentFlag( k, uiCode );
+              if (uiCode)
+              {
+                Window& refWindow = pcPPS->getRefLayerWindow(k);
+                READ_SVLC( iCode, "ref_region_left_offset" );    refWindow.setWindowLeftOffset  (iCode << 1);
+                READ_SVLC( iCode, "ref_region_top_offset" );     refWindow.setWindowTopOffset   (iCode << 1);
+                READ_SVLC( iCode, "ref_region_right_offset" );   refWindow.setWindowRightOffset (iCode << 1);
+                READ_SVLC( iCode, "ref_region_bottom_offset" );  refWindow.setWindowBottomOffset(iCode << 1);
+              }
+#if R0209_GENERIC_PHASE
+              READ_FLAG( uiCode, "resample_phase_set_present_flag" );   pcPPS->setResamplePhaseSetPresentFlag( k, uiCode );
+              if (uiCode)
+              {
+                READ_UVLC( uiCode, "phase_hor_luma" );    pcPPS->setPhaseHorLuma ( k, uiCode );
+                READ_UVLC( uiCode, "phase_ver_luma" );    pcPPS->setPhaseVerLuma ( k, uiCode );
+                READ_UVLC( uiCode, "phase_hor_chroma_plus8" );  pcPPS->setPhaseHorChroma (k, uiCode - 8);
+                READ_UVLC( uiCode, "phase_ver_chroma_plus8" );  pcPPS->setPhaseVerChroma (k, uiCode - 8);
+              }
+#endif
+            }
+#else
+#if MOVE_SCALED_OFFSET_TO_PPS
+            READ_UVLC( uiCode,      "num_scaled_ref_layer_offsets" ); pcPPS->setNumScaledRefLayerOffsets(uiCode);
+            for(Int k = 0; k < pcPPS->getNumScaledRefLayerOffsets(); k++)
+            {
+              Window& scaledWindow = pcPPS->getScaledRefLayerWindow(k);
+#if O0098_SCALED_REF_LAYER_ID
+              READ_CODE( 6,  uiCode,  "scaled_ref_layer_id" );       pcPPS->setScaledRefLayerId( k, uiCode );
+#endif
+              READ_SVLC( iCode, "scaled_ref_layer_left_offset" );    scaledWindow.setWindowLeftOffset  (iCode << 1);
+              READ_SVLC( iCode, "scaled_ref_layer_top_offset" );     scaledWindow.setWindowTopOffset   (iCode << 1);
+              READ_SVLC( iCode, "scaled_ref_layer_right_offset" );   scaledWindow.setWindowRightOffset (iCode << 1);
+              READ_SVLC( iCode, "scaled_ref_layer_bottom_offset" );  scaledWindow.setWindowBottomOffset(iCode << 1);
+#if P0312_VERT_PHASE_ADJ
+              READ_FLAG( uiCode, "vert_phase_position_enable_flag" ); scaledWindow.setVertPhasePositionEnableFlag(uiCode);  pcPPS->setVertPhasePositionEnableFlag( pcPPS->getScaledRefLayerId(k), uiCode);
+#endif
+            }
+#endif
+#endif
+#if Q0048_CGS_3D_ASYMLUT
+            READ_FLAG( uiCode , "colour_mapping_enabled_flag" ); 
+            pcPPS->setCGSFlag( uiCode );
+            if( pcPPS->getCGSFlag() )
+            {
+#if R0157_RESTRICT_PPSID_FOR_CGS_LUT
+              // when pps_pic_parameter_set_id greater than or equal to 8, colour_mapping_enabled_flag shall be equal to 0
+              assert( pcPPS->getPPSId() < 8 );
+#endif
+              xParse3DAsymLUT( pc3DAsymLUT );
+              pcPPS->setCGSOutputBitDepthY( pc3DAsymLUT->getOutputBitDepthY() );
+              pcPPS->setCGSOutputBitDepthC( pc3DAsymLUT->getOutputBitDepthC() );
+            }
+#endif
+            break;
+#endif
+          default:
+            bSkipTrailingExtensionBits=true;
+            break;
+        }
+      }
+    }
+    if (bSkipTrailingExtensionBits)
+    {
+      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 SVC_EXTENSION
+  if( pcSPS->getLayerId() > 0 )
+  {
+    assert( timingInfo->getTimingInfoPresentFlag() == false );
+  }
+#endif
+  if(timingInfo->getTimingInfoPresentFlag())
+  {
+    READ_CODE( 32, uiCode, "vui_num_units_in_tick");                timingInfo->setNumUnitsInTick             (uiCode);
+    READ_CODE( 32, uiCode, "vui_time_scale");                       timingInfo->setTimeScale                  (uiCode);
+    READ_FLAG(     uiCode, "vui_poc_proportional_to_timing_flag");  timingInfo->setPocProportionalToTimingFlag(uiCode ? true : false);
+    if(timingInfo->getPocProportionalToTimingFlag())
+    {
+      READ_UVLC(   uiCode, "vui_num_ticks_poc_diff_one_minus1");    timingInfo->setNumTicksPocDiffOneMinus1   (uiCode);
+    }
+
+    READ_FLAG(     uiCode, "hrd_parameters_present_flag");              pcVUI->setHrdParametersPresentFlag(uiCode);
+    if( pcVUI->getHrdParametersPresentFlag() )
+    {
+      parseHrdParameters( pcVUI->getHrdParameters(), 1, pcSPS->getMaxTLayers() - 1 );
+    }
+  }
+
+  READ_FLAG(     uiCode, "bitstream_restriction_flag");               pcVUI->setBitstreamRestrictionFlag(uiCode);
+  if (pcVUI->getBitstreamRestrictionFlag())
+  {
+    READ_FLAG(   uiCode, "tiles_fixed_structure_flag");               pcVUI->setTilesFixedStructureFlag(uiCode);
+    READ_FLAG(   uiCode, "motion_vectors_over_pic_boundaries_flag");  pcVUI->setMotionVectorsOverPicBoundariesFlag(uiCode);
+    READ_FLAG(   uiCode, "restricted_ref_pic_lists_flag");            pcVUI->setRestrictedRefPicListsFlag(uiCode);
+    READ_UVLC( uiCode, "min_spatial_segmentation_idc");            pcVUI->setMinSpatialSegmentationIdc(uiCode);
+    assert(uiCode < 4096);
+    READ_UVLC(   uiCode, "max_bytes_per_pic_denom" );                 pcVUI->setMaxBytesPerPicDenom(uiCode);
+    READ_UVLC(   uiCode, "max_bits_per_mincu_denom" );                pcVUI->setMaxBitsPerMinCuDenom(uiCode);
+    READ_UVLC(   uiCode, "log2_max_mv_length_horizontal" );           pcVUI->setLog2MaxMvLengthHorizontal(uiCode);
+    READ_UVLC(   uiCode, "log2_max_mv_length_vertical" );             pcVUI->setLog2MaxMvLengthVertical(uiCode);
+  }
+}
+
+Void TDecCavlc::parseHrdParameters(TComHRD *hrd, Bool commonInfPresentFlag, UInt maxNumSubLayersMinus1)
+{
+  UInt  uiCode;
+  if( commonInfPresentFlag )
+  {
+    READ_FLAG( uiCode, "nal_hrd_parameters_present_flag" );           hrd->setNalHrdParametersPresentFlag( uiCode == 1 ? true : false );
+    READ_FLAG( uiCode, "vcl_hrd_parameters_present_flag" );           hrd->setVclHrdParametersPresentFlag( uiCode == 1 ? true : false );
+    if( hrd->getNalHrdParametersPresentFlag() || hrd->getVclHrdParametersPresentFlag() )
+    {
+      READ_FLAG( uiCode, "sub_pic_cpb_params_present_flag" );         hrd->setSubPicCpbParamsPresentFlag( uiCode == 1 ? true : false );
+      if( hrd->getSubPicCpbParamsPresentFlag() )
+      {
+        READ_CODE( 8, uiCode, "tick_divisor_minus2" );                hrd->setTickDivisorMinus2( uiCode );
+        READ_CODE( 5, uiCode, "du_cpb_removal_delay_length_minus1" ); hrd->setDuCpbRemovalDelayLengthMinus1( uiCode );
+        READ_FLAG( uiCode, "sub_pic_cpb_params_in_pic_timing_sei_flag" ); hrd->setSubPicCpbParamsInPicTimingSEIFlag( uiCode == 1 ? true : false );
+        READ_CODE( 5, uiCode, "dpb_output_delay_du_length_minus1"  ); hrd->setDpbOutputDelayDuLengthMinus1( uiCode );
+      }
+      READ_CODE( 4, uiCode, "bit_rate_scale" );                       hrd->setBitRateScale( uiCode );
+      READ_CODE( 4, uiCode, "cpb_size_scale" );                       hrd->setCpbSizeScale( uiCode );
+      if( hrd->getSubPicCpbParamsPresentFlag() )
+      {
+        READ_CODE( 4, uiCode, "cpb_size_du_scale" );                  hrd->setDuCpbSizeScale( uiCode );
+      }
+      READ_CODE( 5, uiCode, "initial_cpb_removal_delay_length_minus1" ); hrd->setInitialCpbRemovalDelayLengthMinus1( uiCode );
+      READ_CODE( 5, uiCode, "au_cpb_removal_delay_length_minus1" );      hrd->setCpbRemovalDelayLengthMinus1( uiCode );
+      READ_CODE( 5, uiCode, "dpb_output_delay_length_minus1" );       hrd->setDpbOutputDelayLengthMinus1( uiCode );
+    }
+#if VPS_VUI_BSP_HRD_PARAMS
+    else
+    {
+      hrd->setInitialCpbRemovalDelayLengthMinus1( 23 );
+      // Add inferred values for other syntax elements here.
+    }
+#endif
+  }
+  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  );
+        }
+      }
+    }
+  }
+}
+
+Void TDecCavlc::parseSPS(TComSPS* pcSPS)
+{
+#if ENC_DEC_TRACE
+  xTraceSPSHeader (pcSPS);
+#endif
+
+  UInt  uiCode;
+  READ_CODE( 4,  uiCode, "sps_video_parameter_set_id");          pcSPS->setVPSId        ( uiCode );
+
+#if SVC_EXTENSION
+  UInt uiTmp = 0;
+  
+  if(pcSPS->getLayerId() == 0)
+  {
+#endif
+  READ_CODE( 3,  uiCode, "sps_max_sub_layers_minus1" );          pcSPS->setMaxTLayers   ( uiCode+1 );
+  assert(uiCode <= 6);
+#if SVC_EXTENSION
+  }
+  else
+  {
+    READ_CODE( 3,  uiCode, "sps_ext_or_max_sub_layers_minus1" );     uiTmp = uiCode;
+
+    if( uiTmp != 7 )
+    {
+      pcSPS->setMaxTLayers(uiTmp + 1);
+    }
+  }
+
+  pcSPS->setMultiLayerExtSpsFlag( pcSPS->getLayerId() != 0 && uiTmp == 7 );
+
+  if( !pcSPS->getMultiLayerExtSpsFlag() )
+  {
+#endif
+  READ_FLAG( uiCode, "sps_temporal_id_nesting_flag" );           pcSPS->setTemporalIdNestingFlag ( uiCode > 0 ? true : false );
+  parsePTL(pcSPS->getPTL(), 1, pcSPS->getMaxTLayers() - 1);
+#if SVC_EXTENSION
+  }
+#else
+  if ( pcSPS->getMaxTLayers() == 1 )
+  {
+    // sps_temporal_id_nesting_flag must be 1 when sps_max_sub_layers_minus1 is 0
+    assert( uiCode == 1 );
+  }
+#endif
+
+  READ_UVLC(     uiCode, "sps_seq_parameter_set_id" );           pcSPS->setSPSId( uiCode );
+  assert(uiCode <= 15);
+
+#if SVC_EXTENSION
+  if( pcSPS->getMultiLayerExtSpsFlag() )
+  {
+    READ_FLAG( uiCode, "update_rep_format_flag" );
+    pcSPS->setUpdateRepFormatFlag( uiCode ? true : false );
+    
+    if( pcSPS->getUpdateRepFormatFlag() )
+    {
+      READ_CODE(8, uiCode, "sps_rep_format_idx");
+      pcSPS->setUpdateRepFormatIndex(uiCode);
+    }
+  }
+  else
+  {
+    pcSPS->setUpdateRepFormatFlag( false );
+#endif
+  READ_UVLC(     uiCode, "chroma_format_idc" );                  pcSPS->setChromaFormatIdc( ChromaFormat(uiCode) );
+  assert(uiCode <= 3);
+
+  if( pcSPS->getChromaFormatIdc() == CHROMA_444 )
+  {
+    READ_FLAG(     uiCode, "separate_colour_plane_flag");        assert(uiCode == 0);
+  }
+
+  READ_UVLC (    uiCode, "pic_width_in_luma_samples" );          pcSPS->setPicWidthInLumaSamples ( uiCode    );
+  READ_UVLC (    uiCode, "pic_height_in_luma_samples" );         pcSPS->setPicHeightInLumaSamples( uiCode    );
+  READ_FLAG(     uiCode, "conformance_window_flag");
+  if (uiCode != 0)
+  {
+    Window &conf = pcSPS->getConformanceWindow();
+#if REPN_FORMAT_IN_VPS
+    READ_UVLC(   uiCode, "conf_win_left_offset" );               conf.setWindowLeftOffset  ( uiCode );
+    READ_UVLC(   uiCode, "conf_win_right_offset" );              conf.setWindowRightOffset ( uiCode );
+    READ_UVLC(   uiCode, "conf_win_top_offset" );                conf.setWindowTopOffset   ( uiCode );
+    READ_UVLC(   uiCode, "conf_win_bottom_offset" );             conf.setWindowBottomOffset( uiCode );
+#else
+    READ_UVLC(   uiCode, "conf_win_left_offset" );               conf.setWindowLeftOffset  ( uiCode * TComSPS::getWinUnitX( pcSPS->getChromaFormatIdc() ) );
+    READ_UVLC(   uiCode, "conf_win_right_offset" );              conf.setWindowRightOffset ( uiCode * TComSPS::getWinUnitX( pcSPS->getChromaFormatIdc() ) );
+    READ_UVLC(   uiCode, "conf_win_top_offset" );                conf.setWindowTopOffset   ( uiCode * TComSPS::getWinUnitY( pcSPS->getChromaFormatIdc() ) );
+    READ_UVLC(   uiCode, "conf_win_bottom_offset" );             conf.setWindowBottomOffset( uiCode * TComSPS::getWinUnitY( pcSPS->getChromaFormatIdc() ) );
+#endif
+  }
+
+  READ_UVLC(     uiCode, "bit_depth_luma_minus8" );
+#if O0043_BEST_EFFORT_DECODING
+  const UInt forceDecodeBitDepth = pcSPS->getForceDecodeBitDepth();
+  g_bitDepthInStream[CHANNEL_TYPE_LUMA] = 8 + uiCode;
+  if (forceDecodeBitDepth != 0)
+  {
+    uiCode = forceDecodeBitDepth - 8;
+  }
+#endif
+  assert(uiCode <= 8);
+
+  pcSPS->setBitDepth(CHANNEL_TYPE_LUMA, 8 + uiCode);
+#if O0043_BEST_EFFORT_DECODING
+  pcSPS->setQpBDOffset(CHANNEL_TYPE_LUMA, (Int) (6*(g_bitDepthInStream[CHANNEL_TYPE_LUMA]-8)) );
+#else
+  pcSPS->setQpBDOffset(CHANNEL_TYPE_LUMA, (Int) (6*uiCode) );
+#endif
+
+  READ_UVLC( uiCode,    "bit_depth_chroma_minus8" );
+#if O0043_BEST_EFFORT_DECODING
+  g_bitDepthInStream[CHANNEL_TYPE_CHROMA] = 8 + uiCode;
+  if (forceDecodeBitDepth != 0)
+  {
+    uiCode = forceDecodeBitDepth - 8;
+  }
+#endif
+  assert(uiCode <= 8);
+  pcSPS->setBitDepth(CHANNEL_TYPE_CHROMA, 8 + uiCode);
+#if O0043_BEST_EFFORT_DECODING
+  pcSPS->setQpBDOffset(CHANNEL_TYPE_CHROMA,  (Int) (6*(g_bitDepthInStream[CHANNEL_TYPE_CHROMA]-8)) );
+#else
+  pcSPS->setQpBDOffset(CHANNEL_TYPE_CHROMA,  (Int) (6*uiCode) );
+#endif
+
+#if SVC_EXTENSION
+  }
+#endif
+
+
+  READ_UVLC( uiCode,    "log2_max_pic_order_cnt_lsb_minus4" );   pcSPS->setBitsForPOC( 4 + uiCode );
+  assert(uiCode <= 12);
+
+#if SVC_EXTENSION
+  if( !pcSPS->getMultiLayerExtSpsFlag() )  
+  {
+#endif
+  UInt subLayerOrderingInfoPresentFlag;
+  READ_FLAG(subLayerOrderingInfoPresentFlag, "sps_sub_layer_ordering_info_present_flag");
+
+  for(UInt i=0; i <= pcSPS->getMaxTLayers()-1; i++)
+  {
+    READ_UVLC ( uiCode, "sps_max_dec_pic_buffering_minus1[i]");
+    pcSPS->setMaxDecPicBuffering( uiCode + 1, i);
+    READ_UVLC ( uiCode, "sps_num_reorder_pics[i]" );
+    pcSPS->setNumReorderPics(uiCode, i);
+    READ_UVLC ( uiCode, "sps_max_latency_increase_plus1[i]");
+    pcSPS->setMaxLatencyIncrease( uiCode, i );
+
+    if (!subLayerOrderingInfoPresentFlag)
+    {
+      for (i++; i <= pcSPS->getMaxTLayers()-1; i++)
+      {
+        pcSPS->setMaxDecPicBuffering(pcSPS->getMaxDecPicBuffering(0), i);
+        pcSPS->setNumReorderPics(pcSPS->getNumReorderPics(0), i);
+        pcSPS->setMaxLatencyIncrease(pcSPS->getMaxLatencyIncrease(0), i);
+      }
+      break;
+    }
+
+#if SVC_EXTENSION
+    if( i > 0 )
+    {
+      // When i is greater than 0, sps_max_dec_pic_buffering_minus1[ i ] shall be greater than or equal to sps_max_dec_pic_buffering_minus1[ i - 1 ]. 
+      assert( pcSPS->getMaxDecPicBuffering(i) >= pcSPS->getMaxDecPicBuffering(i-1) );
+    }
+#endif
+
+  }
+#if SVC_EXTENSION
+  }
+#endif
+  READ_UVLC( uiCode, "log2_min_coding_block_size_minus3" );
+  Int log2MinCUSize = uiCode + 3;
+  pcSPS->setLog2MinCodingBlockSize(log2MinCUSize);
+  READ_UVLC( uiCode, "log2_diff_max_min_coding_block_size" );
+  pcSPS->setLog2DiffMaxMinCodingBlockSize(uiCode);
+  
+  if (pcSPS->getPTL()->getGeneralPTL()->getLevelIdc() >= Level::LEVEL5)
+  {
+    assert(log2MinCUSize + pcSPS->getLog2DiffMaxMinCodingBlockSize() >= 5);
+  }
+  
+  Int maxCUDepthDelta = uiCode;
+  pcSPS->setMaxCUWidth  ( 1<<(log2MinCUSize + maxCUDepthDelta) );
+  pcSPS->setMaxCUHeight ( 1<<(log2MinCUSize + maxCUDepthDelta) );
+  READ_UVLC( uiCode, "log2_min_transform_block_size_minus2" );   pcSPS->setQuadtreeTULog2MinSize( uiCode + 2 );
+
+  READ_UVLC( uiCode, "log2_diff_max_min_transform_block_size" ); pcSPS->setQuadtreeTULog2MaxSize( uiCode + pcSPS->getQuadtreeTULog2MinSize() );
+  pcSPS->setMaxTrSize( 1<<(uiCode + pcSPS->getQuadtreeTULog2MinSize()) );
+
+  READ_UVLC( uiCode, "max_transform_hierarchy_depth_inter" );    pcSPS->setQuadtreeTUMaxDepthInter( uiCode+1 );
+  READ_UVLC( uiCode, "max_transform_hierarchy_depth_intra" );    pcSPS->setQuadtreeTUMaxDepthIntra( uiCode+1 );
+
+  Int addCuDepth = max (0, log2MinCUSize - (Int)pcSPS->getQuadtreeTULog2MinSize() );
+  pcSPS->setMaxCUDepth( maxCUDepthDelta + addCuDepth  + getMaxCUDepthOffset(pcSPS->getChromaFormatIdc(), pcSPS->getQuadtreeTULog2MinSize()) );
+
+  READ_FLAG( uiCode, "scaling_list_enabled_flag" );                 pcSPS->setScalingListFlag ( uiCode );
+  if(pcSPS->getScalingListFlag())
+  {
+#if SVC_EXTENSION
+    if( pcSPS->getMultiLayerExtSpsFlag() )
+    {
+      READ_FLAG( uiCode, "sps_infer_scaling_list_flag" ); pcSPS->setInferScalingListFlag( uiCode );
+    }
+
+    if( pcSPS->getInferScalingListFlag() )
+    {
+      READ_CODE( 6, uiCode, "sps_scaling_list_ref_layer_id" ); pcSPS->setScalingListRefLayerId( uiCode );
+
+      // The value of sps_scaling_list_ref_layer_id shall be in the range of 0 to 62, inclusive
+      assert( pcSPS->getScalingListRefLayerId() <= 62 );
+
+      pcSPS->setScalingListPresentFlag( false );
+    }
+    else
+    {
+#endif
+    READ_FLAG( uiCode, "sps_scaling_list_data_present_flag" );                 pcSPS->setScalingListPresentFlag ( uiCode );
+    if(pcSPS->getScalingListPresentFlag ())
+    {
+      parseScalingList( pcSPS->getScalingList() );
+    }
+#if SVC_EXTENSION
+    }
+#endif
+  }
+  READ_FLAG( uiCode, "amp_enabled_flag" );                          pcSPS->setUseAMP( uiCode );
+  READ_FLAG( uiCode, "sample_adaptive_offset_enabled_flag" );       pcSPS->setUseSAO ( uiCode ? true : false );
+
+  READ_FLAG( uiCode, "pcm_enabled_flag" ); pcSPS->setUsePCM( uiCode ? true : false );
+  if( pcSPS->getUsePCM() )
+  {
+    READ_CODE( 4, uiCode, "pcm_sample_bit_depth_luma_minus1" );          pcSPS->setPCMBitDepth    ( CHANNEL_TYPE_LUMA, 1 + uiCode );
+    READ_CODE( 4, uiCode, "pcm_sample_bit_depth_chroma_minus1" );        pcSPS->setPCMBitDepth    ( CHANNEL_TYPE_CHROMA, 1 + uiCode );
+    READ_UVLC( uiCode, "log2_min_pcm_luma_coding_block_size_minus3" );   pcSPS->setPCMLog2MinSize (uiCode+3);
+    READ_UVLC( uiCode, "log2_diff_max_min_pcm_luma_coding_block_size" ); pcSPS->setPCMLog2MaxSize ( uiCode+pcSPS->getPCMLog2MinSize() );
+    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_present_flag");
+
+#if SVC_EXTENSION
+  pcSPS->setExtensionFlag( uiCode ? true : false );
+
+  if( pcSPS->getExtensionFlag() )
+#else
+  if (uiCode)
+#endif
+  {
+    Bool sps_extension_flags[NUM_SPS_EXTENSION_FLAGS];
+    for(Int i=0; i<NUM_SPS_EXTENSION_FLAGS; i++)
+    {
+      READ_FLAG( uiCode, "sps_extension_flag[]" );
+      sps_extension_flags[i] = uiCode!=0;
+    }
+
+    Bool bSkipTrailingExtensionBits=false;
+    for(Int i=0; i<NUM_SPS_EXTENSION_FLAGS; i++) // loop used so that the order is determined by the enum.
+    {
+      if (sps_extension_flags[i])
+      {
+        switch (SPSExtensionFlagIndex(i))
+        {
+          case SPS_EXT__REXT:
+            assert(!bSkipTrailingExtensionBits);
+
+            READ_FLAG( uiCode, "transform_skip_rotation_enabled_flag");     pcSPS->setUseResidualRotation                    (uiCode != 0);
+            READ_FLAG( uiCode, "transform_skip_context_enabled_flag");      pcSPS->setUseSingleSignificanceMapContext        (uiCode != 0);
+            READ_FLAG( uiCode, "residual_dpcm_implicit_enabled_flag");      pcSPS->setUseResidualDPCM(RDPCM_SIGNAL_IMPLICIT, (uiCode != 0));
+            READ_FLAG( uiCode, "residual_dpcm_explicit_enabled_flag");      pcSPS->setUseResidualDPCM(RDPCM_SIGNAL_EXPLICIT, (uiCode != 0));
+            READ_FLAG( uiCode, "extended_precision_processing_flag");       pcSPS->setUseExtendedPrecision                   (uiCode != 0);
+            READ_FLAG( uiCode, "intra_smoothing_disabled_flag");            pcSPS->setDisableIntraReferenceSmoothing         (uiCode != 0);
+            READ_FLAG( uiCode, "high_precision_prediction_weighting_flag"); pcSPS->setUseHighPrecisionPredictionWeighting    (uiCode != 0);
+            READ_FLAG( uiCode, "golomb_rice_parameter_adaptation_flag");    pcSPS->setUseGolombRiceParameterAdaptation       (uiCode != 0);
+            READ_FLAG( uiCode, "cabac_bypass_alignment_enabled_flag");      pcSPS->setAlignCABACBeforeBypass                 (uiCode != 0);
+            break;
+#if SVC_EXTENSION
+          case SPS_EXT__MLAYER:
+            parseSPSExtension( pcSPS );
+            break;
+#endif
+          default:
+            bSkipTrailingExtensionBits=true;
+            break;
+        }
+      }
+    }
+    if (bSkipTrailingExtensionBits)
+    {
+      while ( xMoreRbspData() )
+      {
+        READ_FLAG( uiCode, "sps_extension_data_flag");
+      }
+    }
+  }
+}
+
+Void TDecCavlc::parseVPS(TComVPS* pcVPS)
+{
+  UInt  uiCode;
+
+  READ_CODE( 4,  uiCode,  "vps_video_parameter_set_id" );         pcVPS->setVPSId( uiCode );
+#if VPS_RESERVED_FLAGS
+  READ_FLAG( uiCode, "vps_base_layer_internal_flag");             pcVPS->setBaseLayerInternalFlag( uiCode ? true : false );
+  READ_FLAG( uiCode, "vps_base_layer_available_flag");            pcVPS->setBaseLayerAvailableFlag( uiCode ? true : false );
+#if VPS_AVC_BL_FLAG_REMOVAL
+  pcVPS->setNonHEVCBaseLayerFlag( (pcVPS->getBaseLayerAvailableFlag() && !pcVPS->getBaseLayerInternalFlag()) ? true : false);
+#endif
+#else
+  READ_CODE( 2,  uiCode,  "vps_reserved_three_2bits" );           assert(uiCode == 3);
+#endif
+#if SVC_EXTENSION
+#if O0137_MAX_LAYERID
+  READ_CODE( 6,  uiCode,  "vps_max_layers_minus1" );              pcVPS->setMaxLayers( min( 62u, uiCode) + 1 );
+#else
+  READ_CODE( 6,  uiCode,  "vps_max_layers_minus1" );              pcVPS->setMaxLayers( uiCode + 1 );
+#endif
+  assert( pcVPS->getBaseLayerInternalFlag() || pcVPS->getMaxLayers() > 1 );
+#else
+  READ_CODE( 6,  uiCode,  "vps_reserved_zero_6bits" );            assert(uiCode == 0);
+#endif
+  READ_CODE( 3,  uiCode,  "vps_max_sub_layers_minus1" );          pcVPS->setMaxTLayers( uiCode + 1 );    assert(uiCode+1 <= MAX_TLAYER);
+  READ_FLAG(     uiCode,  "vps_temporal_id_nesting_flag" );       pcVPS->setTemporalNestingFlag( uiCode ? true:false );
+  assert (pcVPS->getMaxTLayers()>1||pcVPS->getTemporalNestingFlag());
+#if !P0125_REVERT_VPS_EXTN_OFFSET_TO_RESERVED
+#if VPS_EXTN_OFFSET
+  READ_CODE( 16, uiCode,  "vps_extension_offset" );               pcVPS->setExtensionOffset( uiCode );
+#else
+  READ_CODE( 16, uiCode,  "vps_reserved_ffff_16bits" );           assert(uiCode == 0xffff);
+#endif
+#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;
+    }
+  }
+
+#if SVC_EXTENSION
+  assert( pcVPS->getNumHrdParameters() < MAX_VPS_LAYER_SETS_PLUS1 );
+  assert( pcVPS->getMaxLayerId()       < MAX_NUM_LAYER_IDS );
+  READ_CODE( 6, uiCode, "vps_max_layer_id" );           pcVPS->setMaxLayerId( uiCode );
+#if Q0078_ADD_LAYER_SETS
+  READ_UVLC(uiCode, "vps_num_layer_sets_minus1");  pcVPS->setVpsNumLayerSetsMinus1(uiCode);
+  pcVPS->setNumLayerSets(pcVPS->getVpsNumLayerSetsMinus1() + 1);
+  for (UInt opsIdx = 1; opsIdx <= pcVPS->getVpsNumLayerSetsMinus1(); opsIdx++)
+#else
+  READ_UVLC(    uiCode, "vps_num_layer_sets_minus1" );  pcVPS->setNumLayerSets( uiCode + 1 );
+  for( UInt opsIdx = 1; opsIdx <= ( pcVPS->getNumLayerSets() - 1 ); opsIdx ++ )
+#endif
+  {
+    // Operation point set
+    for( UInt i = 0; i <= pcVPS->getMaxLayerId(); i ++ )
+#else
+  assert( pcVPS->getNumHrdParameters() < MAX_VPS_OP_SETS_PLUS1 );
+  assert( pcVPS->getMaxNuhReservedZeroLayerId() < MAX_VPS_NUH_RESERVED_ZERO_LAYER_ID_PLUS1 );
+  READ_CODE( 6, uiCode, "vps_max_nuh_reserved_zero_layer_id" );   pcVPS->setMaxNuhReservedZeroLayerId( uiCode );
+  READ_UVLC(    uiCode, "vps_max_op_sets_minus1" );               pcVPS->setMaxOpSets( uiCode + 1 );
+  for( UInt opsIdx = 1; opsIdx <= ( pcVPS->getMaxOpSets() - 1 ); opsIdx ++ )
+  {
+    // Operation point set
+    for( UInt i = 0; i <= pcVPS->getMaxNuhReservedZeroLayerId(); i ++ )
+#endif
+    {
+      READ_FLAG( uiCode, "layer_id_included_flag[opsIdx][i]" );   pcVPS->setLayerIdIncludedFlag( uiCode == 1 ? true : false, opsIdx, i );
+    }
+  }
+#if DERIVE_LAYER_ID_LIST_VARIABLES
+  pcVPS->deriveLayerIdListVariables();
+#endif
+  TimingInfo *timingInfo = pcVPS->getTimingInfo();
+  READ_FLAG(       uiCode, "vps_timing_info_present_flag");         timingInfo->setTimingInfoPresentFlag      (uiCode ? true : false);
+  if(timingInfo->getTimingInfoPresentFlag())
+  {
+    READ_CODE( 32, uiCode, "vps_num_units_in_tick");                timingInfo->setNumUnitsInTick             (uiCode);
+    READ_CODE( 32, uiCode, "vps_time_scale");                       timingInfo->setTimeScale                  (uiCode);
+    READ_FLAG(     uiCode, "vps_poc_proportional_to_timing_flag");  timingInfo->setPocProportionalToTimingFlag(uiCode ? true : false);
+    if(timingInfo->getPocProportionalToTimingFlag())
+    {
+      READ_UVLC(   uiCode, "vps_num_ticks_poc_diff_one_minus1");    timingInfo->setNumTicksPocDiffOneMinus1   (uiCode);
+    }
+
+    READ_UVLC( uiCode, "vps_num_hrd_parameters" );                  pcVPS->setNumHrdParameters( uiCode );
+
+    if( pcVPS->getNumHrdParameters() > 0 )
+    {
+      pcVPS->createHrdParamBuffer();
+    }
+    for( UInt i = 0; i < pcVPS->getNumHrdParameters(); i ++ )
+    {
+      READ_UVLC( uiCode, "hrd_op_set_idx" );                       pcVPS->setHrdOpSetIdx( uiCode, i );
+      if( i > 0 )
+      {
+        READ_FLAG( uiCode, "cprms_present_flag[i]" );               pcVPS->setCprmsPresentFlag( uiCode == 1 ? true : false, i );
+      }
+      else
+      {
+        pcVPS->setCprmsPresentFlag( true, i );
+      }
+
+      parseHrdParameters(pcVPS->getHrdParameters(i), pcVPS->getCprmsPresentFlag( i ), pcVPS->getMaxTLayers() - 1);
+    }
+  }
+
+#if SVC_EXTENSION
+  READ_FLAG( uiCode,  "vps_extension_flag" );      pcVPS->setVpsExtensionFlag( uiCode ? true : false );
+
+  // When MaxLayersMinus1 is greater than 0, vps_extension_flag shall be equal to 1.
+  if( pcVPS->getMaxLayers() > 1 )
+  {
+    assert( pcVPS->getVpsExtensionFlag() == true );
+  }
+
+  if( pcVPS->getVpsExtensionFlag()  )
+  {
+    while ( m_pcBitstream->getNumBitsRead() % 8 != 0 )
+    {
+      READ_FLAG( uiCode, "vps_extension_alignment_bit_equal_to_one"); assert(uiCode == 1);
+    }
+    parseVPSExtension(pcVPS);
+    READ_FLAG( uiCode, "vps_entension2_flag" );
+    if(uiCode)
+    {
+      while ( xMoreRbspData() )
+      {
+        READ_FLAG( uiCode, "vps_extension_data_flag");
+      }
+    }
+  }
+  else
+  {
+    // set default parameters when syntax elements are not present
+    defaultVPSExtension(pcVPS);    
+  }
+#else
+  READ_FLAG( uiCode,  "vps_extension_flag" );
+  if (uiCode)
+  {
+    while ( xMoreRbspData() )
+    {
+      READ_FLAG( uiCode, "vps_extension_data_flag");
+    }
+  }
+#endif
+
+  return;
+}
+
+Void TDecCavlc::parseSliceHeader (TComSlice* pcSlice, ParameterSetManagerDecoder *parameterSetManager)
+{
+  UInt  uiCode;
+  Int   iCode;
+
+#if ENC_DEC_TRACE
+  xTraceSliceHeader(pcSlice);
+#endif
+  TComPPS* pps = NULL;
+  TComSPS* sps = NULL;
+
+  UInt firstSliceSegmentInPic;
+  READ_FLAG( firstSliceSegmentInPic, "first_slice_segment_in_pic_flag" );
+  if( pcSlice->getRapPicFlag())
+  {
+    READ_FLAG( uiCode, "no_output_of_prior_pics_flag" );  //ignored -- updated already
+    pcSlice->setNoOutputPriorPicsFlag(uiCode ? true : false);
+  }
+  READ_UVLC (    uiCode, "slice_pic_parameter_set_id" );  pcSlice->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);
+  pcSlice->setSPS(sps);
+  pcSlice->setPPS(pps);
+
+  const ChromaFormat chFmt = sps->getChromaFormatIdc();
+  const UInt numValidComp=getNumberValidComponents(chFmt);
+  const Bool bChroma=(chFmt!=CHROMA_400);
+
+  if( pps->getDependentSliceSegmentsEnabledFlag() && ( !firstSliceSegmentInPic ))
+  {
+    READ_FLAG( uiCode, "dependent_slice_segment_flag" );       pcSlice->setDependentSliceSegmentFlag(uiCode ? true : false);
+  }
+  else
+  {
+    pcSlice->setDependentSliceSegmentFlag(false);
+  }
+#if REPN_FORMAT_IN_VPS
+  Int numCTUs = ((pcSlice->getPicWidthInLumaSamples()+sps->getMaxCUWidth()-1)/sps->getMaxCUWidth())*((pcSlice->getPicHeightInLumaSamples()+sps->getMaxCUHeight()-1)/sps->getMaxCUHeight());
+#else
+  Int numCTUs = ((sps->getPicWidthInLumaSamples()+sps->getMaxCUWidth()-1)/sps->getMaxCUWidth())*((sps->getPicHeightInLumaSamples()+sps->getMaxCUHeight()-1)/sps->getMaxCUHeight());
+#endif  
+  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)
+  pcSlice->setSliceSegmentCurStartCtuTsAddr( sliceSegmentAddress );// this is actually a Raster-Scan (RS) address, but we do not have the RS->TS conversion table defined yet.
+  pcSlice->setSliceSegmentCurEndCtuTsAddr(numCTUs);                // Set end as the last CTU of the picture.
+
+  if (!pcSlice->getDependentSliceSegmentFlag())
+  {
+    pcSlice->setSliceCurStartCtuTsAddr(sliceSegmentAddress); // this is actually a Raster-Scan (RS) address, but we do not have the RS->TS conversion table defined yet.
+    pcSlice->setSliceCurEndCtuTsAddr(numCTUs);
+  }
+
+#if Q0142_POC_LSB_NOT_PRESENT
+#if SHM_FIX7
+  Int iPOClsb = 0;
+#endif
+#endif
+
+  if(!pcSlice->getDependentSliceSegmentFlag())
+  {
+#if SVC_EXTENSION
+#if POC_RESET_FLAG
+    Int iBits = 0;
+    if(pcSlice->getPPS()->getNumExtraSliceHeaderBits() > iBits)
+    {
+      READ_FLAG(uiCode, "poc_reset_flag");      pcSlice->setPocResetFlag( uiCode ? true : false );
+      iBits++;
+    }
+    if(pcSlice->getPPS()->getNumExtraSliceHeaderBits() > iBits)
+    {
+#if DISCARDABLE_PIC_RPS
+      READ_FLAG(uiCode, "discardable_flag"); pcSlice->setDiscardableFlag( uiCode ? true : false );
+#else
+      READ_FLAG(uiCode, "discardable_flag"); // ignored
+#endif
+      iBits++;
+    }
+#if O0149_CROSS_LAYER_BLA_FLAG
+    if(pcSlice->getPPS()->getNumExtraSliceHeaderBits() > iBits)
+    {
+      READ_FLAG(uiCode, "cross_layer_bla_flag");  pcSlice->setCrossLayerBLAFlag( uiCode ? true : false );
+      iBits++;
+    }
+#endif
+    for (; iBits < pcSlice->getPPS()->getNumExtraSliceHeaderBits(); iBits++)
+    {
+      READ_FLAG(uiCode, "slice_reserved_undetermined_flag[]"); // ignored
+    }
+#else
+#if CROSS_LAYER_BLA_FLAG_FIX
+    Int iBits = 0;
+    if(pcSlice->getPPS()->getNumExtraSliceHeaderBits() > iBits)
+#else
+    if(pcSlice->getPPS()->getNumExtraSliceHeaderBits()>0)
+#endif
+    {
+      READ_FLAG(uiCode, "discardable_flag"); // ignored
+#if NON_REF_NAL_TYPE_DISCARDABLE
+      pcSlice->setDiscardableFlag( uiCode ? true : false );
+      if (uiCode)
+      {
+        assert(pcSlice->getNalUnitType() != NAL_UNIT_CODED_SLICE_TRAIL_R &&
+          pcSlice->getNalUnitType() != NAL_UNIT_CODED_SLICE_TSA_R &&
+          pcSlice->getNalUnitType() != NAL_UNIT_CODED_SLICE_STSA_R &&
+          pcSlice->getNalUnitType() != NAL_UNIT_CODED_SLICE_RADL_R &&
+          pcSlice->getNalUnitType() != NAL_UNIT_CODED_SLICE_RASL_R);
+      }
+#endif
+#if CROSS_LAYER_BLA_FLAG_FIX
+      iBits++;
+#endif
+    }
+#if CROSS_LAYER_BLA_FLAG_FIX
+    if(pcSlice->getPPS()->getNumExtraSliceHeaderBits() > iBits)
+    {
+      READ_FLAG(uiCode, "cross_layer_bla_flag");  pcSlice->setCrossLayerBLAFlag( uiCode ? true : false );
+      iBits++;
+    }
+    for ( ; iBits < pcSlice->getPPS()->getNumExtraSliceHeaderBits(); iBits++)
+#else
+    for (Int i = 1; i < pcSlice->getPPS()->getNumExtraSliceHeaderBits(); i++)
+#endif
+    {
+      READ_FLAG(uiCode, "slice_reserved_undetermined_flag[]"); // ignored
+    }
+#endif
+#else //SVC_EXTENSION
+    for (Int i = 0; i < pcSlice->getPPS()->getNumExtraSliceHeaderBits(); i++)
+    {
+      READ_FLAG(uiCode, "slice_reserved_undetermined_flag[]"); // ignored
+    }
+#endif //SVC_EXTENSION
+
+    READ_UVLC (    uiCode, "slice_type" );            pcSlice->setSliceType((SliceType)uiCode);
+    if( pps->getOutputFlagPresentFlag() )
+    {
+      READ_FLAG( uiCode, "pic_output_flag" );    pcSlice->setPicOutputFlag( uiCode ? true : false );
+    }
+    else
+    {
+      pcSlice->setPicOutputFlag( true );
+    }
+
+    if( pcSlice->getIdrPicFlag() )
+    {
+      pcSlice->setPOC(0);
+      TComReferencePictureSet* rps = pcSlice->getLocalRPS();
+      rps->setNumberOfNegativePictures(0);
+      rps->setNumberOfPositivePictures(0);
+      rps->setNumberOfLongtermPictures(0);
+      rps->setNumberOfPictures(0);
+      pcSlice->setRPS(rps);
+    }
+#if N0065_LAYER_POC_ALIGNMENT
+#if O0062_POC_LSB_NOT_PRESENT_FLAG
+    if( ( pcSlice->getLayerId() > 0 && !pcSlice->getVPS()->getPocLsbNotPresentFlag( pcSlice->getVPS()->getLayerIdxInVps(pcSlice->getLayerId())) ) || !pcSlice->getIdrPicFlag() )
+#else
+    if( pcSlice->getLayerId() > 0 || !pcSlice->getIdrPicFlag() )
+#endif
+#else
+    else
+#endif
+    {
+      READ_CODE(sps->getBitsForPOC(), uiCode, "pic_order_cnt_lsb");
+#if POC_RESET_IDC_DECODER
+      pcSlice->setPicOrderCntLsb( uiCode );
+#endif
+#if SVC_EXTENSION
+      iPOClsb = uiCode;
+#else
+      Int iPOClsb = uiCode;
+#endif
+      Int iPrevPOC = pcSlice->getPrevTid0POC();
+      Int iMaxPOClsb = 1<< sps->getBitsForPOC();
+      Int iPrevPOClsb = iPrevPOC & (iMaxPOClsb - 1);
+      Int iPrevPOCmsb = iPrevPOC-iPrevPOClsb;
+      Int iPOCmsb;
+      if( ( iPOClsb  <  iPrevPOClsb ) && ( ( iPrevPOClsb - iPOClsb )  >=  ( iMaxPOClsb / 2 ) ) )
+      {
+        iPOCmsb = iPrevPOCmsb + iMaxPOClsb;
+      }
+      else if( (iPOClsb  >  iPrevPOClsb )  && ( (iPOClsb - iPrevPOClsb )  >  ( iMaxPOClsb / 2 ) ) )
+      {
+        iPOCmsb = iPrevPOCmsb - iMaxPOClsb;
+      }
+      else
+      {
+        iPOCmsb = iPrevPOCmsb;
+      }
+      if ( pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_LP
+        || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_RADL
+        || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_N_LP )
+      {
+        // For BLA picture types, POCmsb is set to 0.
+        iPOCmsb = 0;
+      }
+      pcSlice->setPOC              (iPOCmsb+iPOClsb);
+
+#if N0065_LAYER_POC_ALIGNMENT
+    }
+#if POC_RESET_IDC_DECODER
+    else
+    {
+      pcSlice->setPicOrderCntLsb( 0 );
+    }
+#endif
+    if( !pcSlice->getIdrPicFlag() )
+    {
+#endif
+      TComReferencePictureSet* rps;
+      rps = pcSlice->getLocalRPS();
+      pcSlice->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) < pcSlice->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 (pcSlice->getSPS()->getNumLongTermRefPicSPS() > 0)
+        {
+          READ_UVLC( uiCode, "num_long_term_sps");
+          numLtrpInSPS = uiCode;
+          numOfLtrp += numLtrpInSPS;
+          rps->setNumberOfLongtermPictures(numOfLtrp);
+        }
+        Int bitsForLtrpInSPS = 0;
+        while (pcSlice->getSPS()->getNumLongTermRefPicSPS() > (1 << bitsForLtrpInSPS))
+        {
+          bitsForLtrpInSPS++;
+        }
+        READ_UVLC( uiCode, "num_long_term_pics");             rps->setNumberOfLongtermPictures(uiCode);
+        numOfLtrp += uiCode;
+        rps->setNumberOfLongtermPictures(numOfLtrp);
+        Int maxPicOrderCntLSB = 1 << pcSlice->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=pcSlice->getSPS()->getUsedByCurrPicLtSPSFlag(uiCode);
+
+            pocLsbLt = pcSlice->getSPS()->getLtRefPicPocLsbSps(uiCode);
+            rps->setUsed(j,usedByCurrFromSPS);
+          }
+          else
+          {
+            READ_CODE(pcSlice->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 = pcSlice->getPOC() - deltaPocMSBCycleLT * maxPicOrderCntLSB
+                                        - iPOClsb + pocLsbLt;
+            rps->setPOC     (j, pocLTCurr);
+            rps->setDeltaPOC(j, - pcSlice->getPOC() + pocLTCurr);
+            rps->setCheckLTMSBPresent(j,true);
+          }
+          else
+          {
+            rps->setPOC     (j, pocLsbLt);
+            rps->setDeltaPOC(j, - pcSlice->getPOC() + pocLsbLt);
+            rps->setCheckLTMSBPresent(j,false);
+
+            // reset deltaPocMSBCycleLT for first LTRP from slice header if MSB not present
+            if( j == offset+(numOfLtrp-numLtrpInSPS)-1 )
+            {
+              deltaPocMSBCycleLT = 0;
+            }
+          }
+          prevDeltaMSB = deltaPocMSBCycleLT;
+        }
+        offset += rps->getNumberOfLongtermPictures();
+        rps->setNumberOfPictures(offset);
+      }
+#if DPB_CONSTRAINTS
+      if(pcSlice->getVPS()->getVpsExtensionFlag()==1)
+      {
+#if Q0078_ADD_LAYER_SETS
+        for (Int ii = 1; ii < (pcSlice->getVPS()->getVpsNumLayerSetsMinus1() + 1); ii++)  // prevent assert error when num_add_layer_sets > 0
+#else
+        for (Int ii=1; ii< pcSlice->getVPS()->getNumOutputLayerSets(); ii++ )
+#endif
+        {
+          Int layerSetIdxForOutputLayerSet = pcSlice->getVPS()->getOutputLayerSetIdx( ii );
+          Int chkAssert=0;
+          for(Int kk = 0; kk < pcSlice->getVPS()->getNumLayersInIdList(layerSetIdxForOutputLayerSet); kk++)
+          {
+#if R0235_SMALLEST_LAYER_ID
+            if( pcSlice->getVPS()->getNecessaryLayerFlag(ii, kk) && pcSlice->getLayerId() == pcSlice->getVPS()->getLayerSetLayerIdList(layerSetIdxForOutputLayerSet, kk) )
+#else
+            if(pcSlice->getLayerId() == pcSlice->getVPS()->getLayerSetLayerIdList(layerSetIdxForOutputLayerSet, kk))
+#endif
+            {
+              chkAssert=1;
+            }
+          }
+          if(chkAssert)
+          {
+            UInt layerIdc = pcSlice->getVPS()->getLayerIdcForOls( ii, pcSlice->getLayerId() );
+            assert(rps->getNumberOfNegativePictures() <= pcSlice->getVPS()->getMaxVpsDecPicBufferingMinus1(ii, layerIdc, pcSlice->getVPS()->getMaxSLayersInLayerSetMinus1(ii)));
+            assert(rps->getNumberOfPositivePictures() <= pcSlice->getVPS()->getMaxVpsDecPicBufferingMinus1(ii, layerIdc, pcSlice->getVPS()->getMaxSLayersInLayerSetMinus1(ii)) - rps->getNumberOfNegativePictures());
+            assert((rps->getNumberOfPositivePictures() + rps->getNumberOfNegativePictures() + rps->getNumberOfLongtermPictures()) <= pcSlice->getVPS()->getMaxVpsDecPicBufferingMinus1(ii, layerIdc, pcSlice->getVPS()->getMaxSLayersInLayerSetMinus1(ii)));
+          }
+        }
+
+
+      }
+      if(pcSlice->getLayerId() == 0)
+      {
+        assert(rps->getNumberOfNegativePictures() <= pcSlice->getSPS()->getMaxDecPicBuffering(pcSlice->getSPS()->getMaxTLayers()-1) );
+        assert(rps->getNumberOfPositivePictures() <= pcSlice->getSPS()->getMaxDecPicBuffering(pcSlice->getSPS()->getMaxTLayers()-1) -rps->getNumberOfNegativePictures());
+        assert((rps->getNumberOfPositivePictures() + rps->getNumberOfNegativePictures() + rps->getNumberOfLongtermPictures()) <= pcSlice->getSPS()->getMaxDecPicBuffering(pcSlice->getSPS()->getMaxTLayers()-1));
+      }
+#endif
+      if ( pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_LP
+        || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_RADL
+        || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_N_LP )
+      {
+        // In the case of BLA picture types, rps data is read from slice header but ignored
+        rps = pcSlice->getLocalRPS();
+        rps->setNumberOfNegativePictures(0);
+        rps->setNumberOfPositivePictures(0);
+        rps->setNumberOfLongtermPictures(0);
+        rps->setNumberOfPictures(0);
+        pcSlice->setRPS(rps);
+      }
+      if (pcSlice->getSPS()->getTMVPFlagsPresent())
+      {
+        READ_FLAG( uiCode, "slice_temporal_mvp_enable_flag" );
+        pcSlice->setEnableTMVPFlag( uiCode == 1 ? true : false );
+      }
+      else
+      {
+        pcSlice->setEnableTMVPFlag(false);
+      }
+    }
+
+#if SVC_EXTENSION
+    pcSlice->setActiveNumILRRefIdx(0);
+    if((pcSlice->getLayerId() > 0) && !(pcSlice->getVPS()->getIlpSshSignalingEnabledFlag()) && (pcSlice->getNumILRRefIdx() > 0) )
+    {
+      READ_FLAG(uiCode,"inter_layer_pred_enabled_flag");
+      pcSlice->setInterLayerPredEnabledFlag(uiCode);
+      if( pcSlice->getInterLayerPredEnabledFlag())
+      {
+        if(pcSlice->getNumILRRefIdx() > 1)
+        {
+          Int numBits = 1;
+          while ((1 << numBits) < pcSlice->getNumILRRefIdx())
+          {
+            numBits++;
+          }
+          if( !pcSlice->getVPS()->getMaxOneActiveRefLayerFlag())
+          {
+            READ_CODE( numBits, uiCode,"num_inter_layer_ref_pics_minus1" );
+            pcSlice->setActiveNumILRRefIdx(uiCode + 1);
+          }
+          else
+          {
+#if P0079_DERIVE_NUMACTIVE_REF_PICS
+            for( Int i = 0; i < pcSlice->getNumILRRefIdx(); i++ ) 
+            {
+#if Q0060_MAX_TID_REF_EQUAL_TO_ZERO
+              if((pcSlice->getVPS()->getMaxTidIlRefPicsPlus1(pcSlice->getVPS()->getLayerIdxInVps(i), pcSlice->getLayerIdx()) >  pcSlice->getTLayer() || pcSlice->getTLayer()==0) &&
+                (pcSlice->getVPS()->getMaxTSLayersMinus1(pcSlice->getVPS()->getLayerIdxInVps(i)) >=  pcSlice->getTLayer()) )
+#else 
+              if(pcSlice->getVPS()->getMaxTidIlRefPicsPlus1(pcSlice->getVPS()->getLayerIdxInVps(i), pcSlice->getLayerIdx()) >  pcSlice->getTLayer() &&
+                (pcSlice->getVPS()->getMaxTSLayersMinus1(pcSlice->getVPS()->getLayerIdxInVps(i)) >=  pcSlice->getTLayer()) )
+#endif 
+              {          
+                pcSlice->setActiveNumILRRefIdx(1);
+                break;
+              }
+            }
+#else
+            pcSlice->setActiveNumILRRefIdx(1);
+#endif 
+          }
+
+          if( pcSlice->getActiveNumILRRefIdx() == pcSlice->getNumILRRefIdx() )
+          {
+            for( Int i = 0; i < pcSlice->getActiveNumILRRefIdx(); i++ )
+            {
+              pcSlice->setInterLayerPredLayerIdc(i,i);
+            }
+          }
+          else
+          {
+            for(Int i = 0; i < pcSlice->getActiveNumILRRefIdx(); i++ )
+            {
+              READ_CODE( numBits,uiCode,"inter_layer_pred_layer_idc[i]" );
+              pcSlice->setInterLayerPredLayerIdc(uiCode, i);
+            }
+          }
+        }
+        else
+        {
+#if O0225_TID_BASED_IL_RPS_DERIV && TSLAYERS_IL_RPS
+          Int refLayerId = pcSlice->getVPS()->getRefLayerId(pcSlice->getLayerId(), 0);
+          Int refLayerIdx = pcSlice->getVPS()->getLayerIdxInVps(refLayerId);
+#if Q0060_MAX_TID_REF_EQUAL_TO_ZERO
+          if((pcSlice->getVPS()->getMaxTidIlRefPicsPlus1(refLayerIdx, pcSlice->getLayerIdx()) >  pcSlice->getTLayer() || pcSlice->getTLayer()==0) &&
+            (pcSlice->getVPS()->getMaxTSLayersMinus1(refLayerIdx) >=  pcSlice->getTLayer()) )
+#else
+          if( (pcSlice->getVPS()->getMaxTidIlRefPicsPlus1(refLayerIdx,pcSlice->getLayerIdx()) >  pcSlice->getTLayer()) &&
+            (pcSlice->getVPS()->getMaxTSLayersMinus1(refLayerIdx) >=  pcSlice->getTLayer()) )
+#endif 
+          {
+#endif
+            pcSlice->setActiveNumILRRefIdx(1);
+            pcSlice->setInterLayerPredLayerIdc(0, 0);
+#if O0225_TID_BASED_IL_RPS_DERIV && TSLAYERS_IL_RPS
+          }
+#endif
+        }
+      }
+    }
+    else if( pcSlice->getVPS()->getIlpSshSignalingEnabledFlag() == true &&  (pcSlice->getLayerId() > 0 ))
+    {
+      pcSlice->setInterLayerPredEnabledFlag(true);
+
+#if O0225_TID_BASED_IL_RPS_DERIV && TSLAYERS_IL_RPS
+      Int   numRefLayerPics = 0;
+      Int   i = 0;
+      Int   refLayerPicIdc  [MAX_VPS_LAYER_IDX_PLUS1];
+      for(i = 0, numRefLayerPics = 0;  i < pcSlice->getNumILRRefIdx(); i++ ) 
+      {
+#if Q0060_MAX_TID_REF_EQUAL_TO_ZERO
+        if((pcSlice->getVPS()->getMaxTidIlRefPicsPlus1(pcSlice->getVPS()->getLayerIdxInVps(i), pcSlice->getLayerIdx()) >  pcSlice->getTLayer() || pcSlice->getTLayer()==0) &&
+          (pcSlice->getVPS()->getMaxTSLayersMinus1(pcSlice->getVPS()->getLayerIdxInVps(i)) >=  pcSlice->getTLayer()) )
+#else 
+        if(pcSlice->getVPS()->getMaxTidIlRefPicsPlus1(pcSlice->getVPS()->getLayerIdxInVps(i), pcSlice->getLayerIdx()) >  pcSlice->getTLayer() &&
+          (pcSlice->getVPS()->getMaxTSLayersMinus1(pcSlice->getVPS()->getLayerIdxInVps(i)) >=  pcSlice->getTLayer()) )
+#endif 
+        {          
+          refLayerPicIdc[ numRefLayerPics++ ] = i;
+        }
+      }
+      pcSlice->setActiveNumILRRefIdx(numRefLayerPics);
+      for( i = 0; i < pcSlice->getActiveNumILRRefIdx(); i++ )
+      {
+        pcSlice->setInterLayerPredLayerIdc(refLayerPicIdc[i], i);
+      }
+#else
+      pcSlice->setActiveNumILRRefIdx(pcSlice->getNumILRRefIdx());
+      for( Int i = 0; i < pcSlice->getActiveNumILRRefIdx(); i++ )
+      {
+        pcSlice->setInterLayerPredLayerIdc(i,i);
+      }
+#endif 
+    }
+#if P0312_VERT_PHASE_ADJ
+    for(Int i = 0; i < pcSlice->getActiveNumILRRefIdx(); i++ ) 
+    {
+      UInt refLayerIdc = pcSlice->getInterLayerPredLayerIdc(i);
+#if !MOVE_SCALED_OFFSET_TO_PPS
+      if( pcSlice->getSPS()->getVertPhasePositionEnableFlag(refLayerIdc) )
+#else
+      if( pcSlice->getPPS()->getVertPhasePositionEnableFlag(refLayerIdc) )
+#endif
+      {
+        READ_FLAG( uiCode, "vert_phase_position_flag" ); pcSlice->setVertPhasePositionFlag( uiCode? true : false, refLayerIdc );
+      }
+    }
+#endif
+#endif //SVC_EXTENSION
+
+    if(sps->getUseSAO())
+    {
+      READ_FLAG(uiCode, "slice_sao_luma_flag");  pcSlice->setSaoEnabledFlag(CHANNEL_TYPE_LUMA, (Bool)uiCode);
+#if SVC_EXTENSION
+      ChromaFormat format;
+      if( sps->getLayerId() == 0 )
+      {
+        format = sps->getChromaFormatIdc();
+      }
+      else
+      {
+        format = pcSlice->getVPS()->getVpsRepFormat( sps->getUpdateRepFormatFlag() ? sps->getUpdateRepFormatIndex() : pcSlice->getVPS()->getVpsRepFormatIdx( pcSlice->getVPS()->getLayerIdxInVps(sps->getLayerId()) ) )->getChromaFormatVpsIdc();
+#if Q0195_REP_FORMAT_CLEANUP
+        assert( (sps->getUpdateRepFormatFlag()==false && pcSlice->getVPS()->getVpsNumRepFormats()==1) || pcSlice->getVPS()->getVpsNumRepFormats() > 1 ); //conformance check
+#endif
+      }
+      if (format != CHROMA_400)
+#else
+      if (bChroma)
+#endif
+      {
+        READ_FLAG(uiCode, "slice_sao_chroma_flag");  pcSlice->setSaoEnabledFlag(CHANNEL_TYPE_CHROMA, (Bool)uiCode);
+      }
+#if SVC_EXTENSION
+      else
+      {
+        pcSlice->setSaoEnabledFlag(CHANNEL_TYPE_CHROMA, false);
+      }
+#endif
+    }
+
+    if (pcSlice->getIdrPicFlag())
+    {
+      pcSlice->setEnableTMVPFlag(false);
+    }
+    if (!pcSlice->isIntra())
+    {
+
+      READ_FLAG( uiCode, "num_ref_idx_active_override_flag");
+      if (uiCode)
+      {
+        READ_UVLC (uiCode, "num_ref_idx_l0_active_minus1" );  pcSlice->setNumRefIdx( REF_PIC_LIST_0, uiCode + 1 );
+        if (pcSlice->isInterB())
+        {
+          READ_UVLC (uiCode, "num_ref_idx_l1_active_minus1" );  pcSlice->setNumRefIdx( REF_PIC_LIST_1, uiCode + 1 );
+        }
+        else
+        {
+          pcSlice->setNumRefIdx(REF_PIC_LIST_1, 0);
+        }
+      }
+      else
+      {
+        pcSlice->setNumRefIdx(REF_PIC_LIST_0, pcSlice->getPPS()->getNumRefIdxL0DefaultActive());
+        if (pcSlice->isInterB())
+        {
+          pcSlice->setNumRefIdx(REF_PIC_LIST_1, pcSlice->getPPS()->getNumRefIdxL1DefaultActive());
+        }
+        else
+        {
+          pcSlice->setNumRefIdx(REF_PIC_LIST_1,0);
+        }
+      }
+    }
+    // }
+    TComRefPicListModification* refPicListModification = pcSlice->getRefPicListModification();
+    if(!pcSlice->isIntra())
+    {
+      if( !pcSlice->getPPS()->getListsModificationPresentFlag() || pcSlice->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 = pcSlice->getNumRpsCurrTempList();
+        if ( numRpsCurrTempList0 > 1 )
+        {
+          Int length = 1;
+          numRpsCurrTempList0 --;
+          while ( numRpsCurrTempList0 >>= 1)
+          {
+            length ++;
+          }
+          for (i = 0; i < pcSlice->getNumRefIdx(REF_PIC_LIST_0); i ++)
+          {
+            READ_CODE( length, uiCode, "list_entry_l0" );
+            refPicListModification->setRefPicSetIdxL0(i, uiCode );
+          }
+        }
+        else
+        {
+          for (i = 0; i < pcSlice->getNumRefIdx(REF_PIC_LIST_0); i ++)
+          {
+            refPicListModification->setRefPicSetIdxL0(i, 0 );
+          }
+        }
+      }
+    }
+    else
+    {
+      refPicListModification->setRefPicListModificationFlagL0(0);
+    }
+    if(pcSlice->isInterB())
+    {
+      if( !pcSlice->getPPS()->getListsModificationPresentFlag() || pcSlice->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 = pcSlice->getNumRpsCurrTempList();
+        if ( numRpsCurrTempList1 > 1 )
+        {
+          Int length = 1;
+          numRpsCurrTempList1 --;
+          while ( numRpsCurrTempList1 >>= 1)
+          {
+            length ++;
+          }
+          for (i = 0; i < pcSlice->getNumRefIdx(REF_PIC_LIST_1); i ++)
+          {
+            READ_CODE( length, uiCode, "list_entry_l1" );
+            refPicListModification->setRefPicSetIdxL1(i, uiCode );
+          }
+        }
+        else
+        {
+          for (i = 0; i < pcSlice->getNumRefIdx(REF_PIC_LIST_1); i ++)
+          {
+            refPicListModification->setRefPicSetIdxL1(i, 0 );
+          }
+        }
+      }
+    }
+    else
+    {
+      refPicListModification->setRefPicListModificationFlagL1(0);
+    }
+    if (pcSlice->isInterB())
+    {
+      READ_FLAG( uiCode, "mvd_l1_zero_flag" );       pcSlice->setMvdL1ZeroFlag( (uiCode ? true : false) );
+    }
+
+    pcSlice->setCabacInitFlag( false ); // default
+    if(pps->getCabacInitPresentFlag() && !pcSlice->isIntra())
+    {
+      READ_FLAG(uiCode, "cabac_init_flag");
+      pcSlice->setCabacInitFlag( uiCode ? true : false );
+    }
+
+    if ( pcSlice->getEnableTMVPFlag() )
+    {
+#if SVC_EXTENSION && REF_IDX_MFM
+      // set motion mapping flag
+      pcSlice->setMFMEnabledFlag( ( pcSlice->getNumMotionPredRefLayers() > 0 && pcSlice->getActiveNumILRRefIdx() && !pcSlice->isIntra() ) ? true : false );
+#endif
+      if ( pcSlice->getSliceType() == B_SLICE )
+      {
+        READ_FLAG( uiCode, "collocated_from_l0_flag" );
+        pcSlice->setColFromL0Flag(uiCode);
+      }
+      else
+      {
+        pcSlice->setColFromL0Flag( 1 );
+      }
+
+      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)))
+      {
+        READ_UVLC( uiCode, "collocated_ref_idx" );
+        pcSlice->setColRefIdx(uiCode);
+      }
+      else
+      {
+        pcSlice->setColRefIdx(0);
+      }
+    }
+    if ( (pps->getUseWP() && pcSlice->getSliceType()==P_SLICE) || (pps->getWPBiPred() && pcSlice->getSliceType()==B_SLICE) )
+    {
+      xParsePredWeightTable(pcSlice);
+      pcSlice->initWpScaling();
+    }
+    if (!pcSlice->isIntra())
+    {
+      READ_UVLC( uiCode, "five_minus_max_num_merge_cand");
+      pcSlice->setMaxNumMergeCand(MRG_MAX_NUM_CANDS - uiCode);
+    }
+
+    READ_SVLC( iCode, "slice_qp_delta" );
+    pcSlice->setSliceQp (26 + pps->getPicInitQPMinus26() + iCode);
+
+#if REPN_FORMAT_IN_VPS
+#if O0194_DIFFERENT_BITDEPTH_EL_BL
+    g_bitDepthLayer[CHANNEL_TYPE_LUMA][pcSlice->getLayerId()] = pcSlice->getBitDepthY();
+    g_bitDepthLayer[CHANNEL_TYPE_CHROMA][pcSlice->getLayerId()] = pcSlice->getBitDepthC();
+#endif
+    assert( pcSlice->getSliceQp() >= -pcSlice->getQpBDOffsetY() );
+#else    
+    assert( pcSlice->getSliceQp() >= -sps->getQpBDOffset(CHANNEL_TYPE_LUMA) );
+#endif
+    assert( pcSlice->getSliceQp() <=  51 );
+
+    if (pcSlice->getPPS()->getSliceChromaQpFlag())
+    {
+      if (numValidComp>COMPONENT_Cb)
+      {
+        READ_SVLC( iCode, "slice_qp_delta_cb" );
+        pcSlice->setSliceChromaQpDelta(COMPONENT_Cb, iCode );
+        assert( pcSlice->getSliceChromaQpDelta(COMPONENT_Cb) >= -12 );
+        assert( pcSlice->getSliceChromaQpDelta(COMPONENT_Cb) <=  12 );
+        assert( (pcSlice->getPPS()->getQpOffset(COMPONENT_Cb) + pcSlice->getSliceChromaQpDelta(COMPONENT_Cb)) >= -12 );
+        assert( (pcSlice->getPPS()->getQpOffset(COMPONENT_Cb) + pcSlice->getSliceChromaQpDelta(COMPONENT_Cb)) <=  12 );
+      }
+
+      if (numValidComp>COMPONENT_Cr)
+      {
+        READ_SVLC( iCode, "slice_qp_delta_cr" );
+        pcSlice->setSliceChromaQpDelta(COMPONENT_Cr, iCode );
+        assert( pcSlice->getSliceChromaQpDelta(COMPONENT_Cr) >= -12 );
+        assert( pcSlice->getSliceChromaQpDelta(COMPONENT_Cr) <=  12 );
+        assert( (pcSlice->getPPS()->getQpOffset(COMPONENT_Cr) + pcSlice->getSliceChromaQpDelta(COMPONENT_Cr)) >= -12 );
+        assert( (pcSlice->getPPS()->getQpOffset(COMPONENT_Cr) + pcSlice->getSliceChromaQpDelta(COMPONENT_Cr)) <=  12 );
+      }
+    }
+
+    if (pcSlice->getPPS()->getChromaQpAdjTableSize() > 0)
+    {
+      READ_FLAG(uiCode, "slice_chroma_qp_adjustment_enabled_flag"); pcSlice->setUseChromaQpAdj(uiCode != 0);
+    }
+    else pcSlice->setUseChromaQpAdj(false);
+
+    if (pcSlice->getPPS()->getDeblockingFilterControlPresentFlag())
+    {
+      if(pcSlice->getPPS()->getDeblockingFilterOverrideEnabledFlag())
+      {
+        READ_FLAG ( uiCode, "deblocking_filter_override_flag" );        pcSlice->setDeblockingFilterOverrideFlag(uiCode ? true : false);
+      }
+      else
+      {
+        pcSlice->setDeblockingFilterOverrideFlag(0);
+      }
+      if(pcSlice->getDeblockingFilterOverrideFlag())
+      {
+        READ_FLAG ( uiCode, "slice_disable_deblocking_filter_flag" );   pcSlice->setDeblockingFilterDisable(uiCode ? 1 : 0);
+        if(!pcSlice->getDeblockingFilterDisable())
+        {
+          READ_SVLC( iCode, "slice_beta_offset_div2" );                       pcSlice->setDeblockingFilterBetaOffsetDiv2(iCode);
+          assert(pcSlice->getDeblockingFilterBetaOffsetDiv2() >= -6 &&
+                 pcSlice->getDeblockingFilterBetaOffsetDiv2() <=  6);
+          READ_SVLC( iCode, "slice_tc_offset_div2" );                         pcSlice->setDeblockingFilterTcOffsetDiv2(iCode);
+          assert(pcSlice->getDeblockingFilterTcOffsetDiv2() >= -6 &&
+                 pcSlice->getDeblockingFilterTcOffsetDiv2() <=  6);
+        }
+      }
+      else
+      {
+        pcSlice->setDeblockingFilterDisable   ( pcSlice->getPPS()->getPicDisableDeblockingFilterFlag() );
+        pcSlice->setDeblockingFilterBetaOffsetDiv2( pcSlice->getPPS()->getDeblockingFilterBetaOffsetDiv2() );
+        pcSlice->setDeblockingFilterTcOffsetDiv2  ( pcSlice->getPPS()->getDeblockingFilterTcOffsetDiv2() );
+      }
+    }
+    else
+    {
+      pcSlice->setDeblockingFilterDisable       ( false );
+      pcSlice->setDeblockingFilterBetaOffsetDiv2( 0 );
+      pcSlice->setDeblockingFilterTcOffsetDiv2  ( 0 );
+    }
+
+    Bool isSAOEnabled = pcSlice->getSPS()->getUseSAO() && (pcSlice->getSaoEnabledFlag(CHANNEL_TYPE_LUMA) || (bChroma && pcSlice->getSaoEnabledFlag(CHANNEL_TYPE_CHROMA)));
+    Bool isDBFEnabled = (!pcSlice->getDeblockingFilterDisable());
+
+    if(pcSlice->getPPS()->getLoopFilterAcrossSlicesEnabledFlag() && ( isSAOEnabled || isDBFEnabled ))
+    {
+      READ_FLAG( uiCode, "slice_loop_filter_across_slices_enabled_flag");
+    }
+    else
+    {
+      uiCode = pcSlice->getPPS()->getLoopFilterAcrossSlicesEnabledFlag()?1:0;
+    }
+    pcSlice->setLFCrossSliceBoundaryFlag( (uiCode==1)?true:false);
+
+  }
+
+  std::vector<UInt> entryPointOffset;
+  if( pps->getTilesEnabledFlag() || pps->getEntropyCodingSyncEnabledFlag() )
+  {
+    UInt numEntryPointOffsets;
+    UInt offsetLenMinus1;
+    READ_UVLC(numEntryPointOffsets, "num_entry_point_offsets");
+    if (numEntryPointOffsets>0)
+    {
+      READ_UVLC(offsetLenMinus1, "offset_len_minus1");
+      entryPointOffset.resize(numEntryPointOffsets);
+      for (UInt idx=0; idx<numEntryPointOffsets; idx++)
+      {
+        READ_CODE(offsetLenMinus1+1, uiCode, "entry_point_offset_minus1");
+        entryPointOffset[ idx ] = uiCode + 1;
+      }
+    }
+  }
+
+#if POC_RESET_IDC_SIGNALLING
+  Int sliceHeaderExtensionLength = 0;
+  if(pps->getSliceHeaderExtensionPresentFlag())
+  {
+    READ_UVLC( uiCode, "slice_header_extension_length"); sliceHeaderExtensionLength = uiCode;
+  }
+  else
+  {
+    sliceHeaderExtensionLength = 0;
+#if INFERENCE_POC_MSB_VAL_PRESENT
+    pcSlice->setPocMsbValPresentFlag( false );
+#endif
+  }
+  UInt startBits = m_pcBitstream->getNumBitsRead();     // Start counter of # SH Extn bits
+  if( sliceHeaderExtensionLength > 0 )
+  {
+    if( pcSlice->getPPS()->getPocResetInfoPresentFlag() )
+    {
+      READ_CODE( 2, uiCode,       "poc_reset_idc"); pcSlice->setPocResetIdc(uiCode);
+#if POC_RESET_RESTRICTIONS
+      /* The value of poc_reset_idc shall not be equal to 1 or 2 for a RASL picture, a RADL picture, 
+      a sub-layer non-reference picture, or a picture that has TemporalId greater than 0, 
+      or a picture that has discardable_flag equal to 1. */
+      if( pcSlice->getPocResetIdc() == 1 || pcSlice->getPocResetIdc() == 2 )
+      {
+        assert( !pcSlice->isRASL() );
+        assert( !pcSlice->isRADL() );
+        assert( !pcSlice->isSLNR() );
+        assert( pcSlice->getTLayer() == 0 );
+        assert( pcSlice->getDiscardableFlag() == 0 );
+      }
+
+      // The value of poc_reset_idc of a CRA or BLA picture shall be less than 3.
+      if( pcSlice->getPocResetIdc() == 3)
+      {
+        assert( ! ( pcSlice->isCRA() || pcSlice->isBLA() ) );
+      }
+#endif
+    }
+    else
+    {
+      pcSlice->setPocResetIdc( 0 );
+    }
+#if Q0142_POC_LSB_NOT_PRESENT
+    if ( pcSlice->getVPS()->getPocLsbNotPresentFlag( pcSlice->getVPS()->getLayerIdxInVps(pcSlice->getLayerId()) ) && iPOClsb > 0 )
+    {
+      assert( pcSlice->getPocResetIdc() != 2 );
+    }
+#endif
+    if( pcSlice->getPocResetIdc() > 0 )
+    {
+      READ_CODE(6, uiCode,      "poc_reset_period_id"); pcSlice->setPocResetPeriodId(uiCode);
+    }
+    else
+    {
+
+      pcSlice->setPocResetPeriodId( 0 );
+    }
+
+    if (pcSlice->getPocResetIdc() == 3)
+    {
+      READ_FLAG( uiCode,        "full_poc_reset_flag"); pcSlice->setFullPocResetFlag((uiCode == 1) ? true : false);
+      READ_CODE(pcSlice->getSPS()->getBitsForPOC(), uiCode,"poc_lsb_val"); pcSlice->setPocLsbVal(uiCode);
+#if Q0142_POC_LSB_NOT_PRESENT
+      if ( pcSlice->getVPS()->getPocLsbNotPresentFlag( pcSlice->getVPS()->getLayerIdxInVps(pcSlice->getLayerId()) ) && pcSlice->getFullPocResetFlag() )
+      {
+        assert( pcSlice->getPocLsbVal() == 0 );
+      }
+#endif
+    }
+
+    // Derive the value of PocMsbValRequiredFlag
+#if P0297_VPS_POC_LSB_ALIGNED_FLAG
+    pcSlice->setPocMsbValRequiredFlag( (pcSlice->getCraPicFlag() || pcSlice->getBlaPicFlag())
+      && (!pcSlice->getVPS()->getVpsPocLsbAlignedFlag() ||
+      (pcSlice->getVPS()->getVpsPocLsbAlignedFlag() && pcSlice->getVPS()->getNumDirectRefLayers(pcSlice->getLayerId()) == 0))
+      );
+#else
+    pcSlice->setPocMsbValRequiredFlag( pcSlice->getCraPicFlag() || pcSlice->getBlaPicFlag() );
+#endif
+
+#if P0297_VPS_POC_LSB_ALIGNED_FLAG
+    if (!pcSlice->getPocMsbValRequiredFlag() && pcSlice->getVPS()->getVpsPocLsbAlignedFlag())
+#else
+    if (!pcSlice->getPocMsbValRequiredFlag() /* vps_poc_lsb_aligned_flag */)
+#endif
+    {
+#if P0297_VPS_POC_LSB_ALIGNED_FLAG
+      READ_FLAG(uiCode, "poc_msb_cycle_val_present_flag"); pcSlice->setPocMsbValPresentFlag(uiCode ? true : false);
+#else
+      READ_FLAG(uiCode, "poc_msb_val_present_flag"); pcSlice->setPocMsbValPresentFlag(uiCode ? true : false);
+#endif
+    }
+    else
+    {
+#if POC_MSB_VAL_PRESENT_FLAG_SEM
+      if( sliceHeaderExtensionLength == 0 )
+      {
+        pcSlice->setPocMsbValPresentFlag( false );
+      }
+      else if( pcSlice->getPocMsbValRequiredFlag() )
+#else
+      if( pcSlice->getPocMsbValRequiredFlag() )
+#endif
+      {
+        pcSlice->setPocMsbValPresentFlag( true );
+      }
+      else
+      {
+        pcSlice->setPocMsbValPresentFlag( false );
+      }
+    }
+
+#if !POC_RESET_IDC_DECODER
+    Int maxPocLsb  = 1 << pcSlice->getSPS()->getBitsForPOC();
+#endif
+    if( pcSlice->getPocMsbValPresentFlag() )
+    {
+#if P0297_VPS_POC_LSB_ALIGNED_FLAG
+      READ_UVLC( uiCode,    "poc_msb_cycle_val");             pcSlice->setPocMsbVal( uiCode );
+#else
+      READ_UVLC( uiCode,    "poc_msb_val");             pcSlice->setPocMsbVal( uiCode );
+#endif
+
+#if !POC_RESET_IDC_DECODER
+      // Update POC of the slice based on this MSB val
+      Int pocLsb     = pcSlice->getPOC() % maxPocLsb;
+      pcSlice->setPOC((pcSlice->getPocMsbVal() * maxPocLsb) + pocLsb);
+    }
+    else
+    {
+      pcSlice->setPocMsbVal( pcSlice->getPOC() / maxPocLsb );
+#endif
+    }
+
+    // Read remaining bits in the slice header extension.
+    UInt endBits = m_pcBitstream->getNumBitsRead();
+    Int counter = (endBits - startBits) % 8;
+    if( counter )
+    {
+      counter = 8 - counter;
+    }
+
+    while( counter )
+    {
+#if Q0146_SSH_EXT_DATA_BIT 
+      READ_FLAG( uiCode, "slice_segment_header_extension_data_bit" );
+#else
+      READ_FLAG( uiCode, "slice_segment_header_extension_reserved_bit" ); assert( uiCode == 1 );
+#endif
+      counter--;
+    }
+  }
+#else
+  if(pps->getSliceHeaderExtensionPresentFlag())
+  {
+    READ_UVLC(uiCode,"slice_header_extension_length");
+    for(Int i=0; i<uiCode; i++)
+    {
+      UInt ignore;
+      READ_CODE(8,ignore,"slice_header_extension_data_byte");
+    }
+  }
+#endif
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+  TComCodingStatistics::IncrementStatisticEP(STATS__BYTE_ALIGNMENT_BITS,m_pcBitstream->readByteAlignment(),0);
+#else
+  m_pcBitstream->readByteAlignment();
+#endif
+
+  pcSlice->clearSubstreamSizes();
+
+  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<entryPointOffset.size(); 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;
+      pcSlice->addSubstreamSize(entryPointOffset [ idx ] );
+    }
+  }
+
+  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(Level::Name(uiCode));
+
+  for (Int i = 0; i < maxNumSubLayersMinus1; i++)
+  {
+#if MULTIPLE_PTL_SUPPORT
+    READ_FLAG( uiCode, "sub_layer_profile_present_flag[i]" ); rpcPTL->setSubLayerProfilePresentFlag(i, uiCode);
+#else
+    if(profilePresentFlag)
+    {
+      READ_FLAG( uiCode, "sub_layer_profile_present_flag[i]" ); rpcPTL->setSubLayerProfilePresentFlag(i, uiCode);
+    }
+#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 MULTIPLE_PTL_SUPPORT
+    if( rpcPTL->getSubLayerProfilePresentFlag(i) )
+#else
+    if( profilePresentFlag && rpcPTL->getSubLayerProfilePresentFlag(i) )
+#endif
+    {
+      parseProfileTier(rpcPTL->getSubLayerPTL(i));
+    }
+    if(rpcPTL->getSubLayerLevelPresentFlag(i))
+    {
+      READ_CODE( 8, uiCode, "sub_layer_level_idc[i]" );   rpcPTL->getSubLayerPTL(i)->setLevelIdc(Level::Name(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 ? Level::HIGH : Level::MAIN);
+  READ_CODE(5 , uiCode, "XXX_profile_idc[]"  );   ptl->setProfileIdc  (Profile::Name(uiCode));
+  for(Int j = 0; j < 32; j++)
+  {
+    READ_FLAG(  uiCode, "XXX_profile_compatibility_flag[][j]");   ptl->setProfileCompatibilityFlag(j, uiCode ? 1 : 0);
+  }
+  READ_FLAG(uiCode, "general_progressive_source_flag");
+  ptl->setProgressiveSourceFlag(uiCode ? true : false);
+
+  READ_FLAG(uiCode, "general_interlaced_source_flag");
+  ptl->setInterlacedSourceFlag(uiCode ? true : false);
+
+  READ_FLAG(uiCode, "general_non_packed_constraint_flag");
+  ptl->setNonPackedConstraintFlag(uiCode ? true : false);
+
+  READ_FLAG(uiCode, "general_frame_only_constraint_flag");
+  ptl->setFrameOnlyConstraintFlag(uiCode ? true : false);
+
+  if (ptl->getProfileIdc() == Profile::MAINREXT || ptl->getProfileIdc() == Profile::HIGHTHROUGHPUTREXT )
+  {
+    UInt maxBitDepth=16;
+    READ_FLAG(    uiCode, "general_max_12bit_constraint_flag" ); if (uiCode) maxBitDepth=12;
+    READ_FLAG(    uiCode, "general_max_10bit_constraint_flag" ); if (uiCode) maxBitDepth=10;
+    READ_FLAG(    uiCode, "general_max_8bit_constraint_flag"  ); if (uiCode) maxBitDepth=8;
+    ptl->setBitDepthConstraint(maxBitDepth);
+    ChromaFormat chromaFmtConstraint=CHROMA_444;
+    READ_FLAG(    uiCode, "general_max_422chroma_constraint_flag"  ); if (uiCode) chromaFmtConstraint=CHROMA_422;
+    READ_FLAG(    uiCode, "general_max_420chroma_constraint_flag"  ); if (uiCode) chromaFmtConstraint=CHROMA_420;
+    READ_FLAG(    uiCode, "general_max_monochrome_constraint_flag" ); if (uiCode) chromaFmtConstraint=CHROMA_400;
+    ptl->setChromaFormatConstraint(chromaFmtConstraint);
+    READ_FLAG(    uiCode, "general_intra_constraint_flag");          ptl->setIntraConstraintFlag(uiCode != 0);
+    READ_FLAG(    uiCode, "general_one_picture_only_constraint_flag");
+    READ_FLAG(    uiCode, "general_lower_bit_rate_constraint_flag"); ptl->setLowerBitRateConstraintFlag(uiCode != 0);
+#if MULTIPLE_PTL_SUPPORT
+    READ_CODE(32, uiCode, "general_reserved_zero_34bits");  READ_CODE(2, uiCode, "general_reserved_zero_34bits");
+  }
+  else if( ptl->getProfileIdc() == Profile::SCALABLEMAIN )
+  {
+    READ_FLAG(    uiCode, "general_max_12bit_constraint_flag" ); assert (uiCode == 1);
+    READ_FLAG(    uiCode, "general_max_10bit_constraint_flag" ); assert (uiCode == 1);
+    READ_FLAG(    uiCode, "general_max_8bit_constraint_flag"  ); ptl->setProfileIdc  ((uiCode) ? Profile::SCALABLEMAIN : Profile::SCALABLEMAIN10);
+    READ_FLAG(    uiCode, "general_max_422chroma_constraint_flag"  ); assert (uiCode == 1);
+    READ_FLAG(    uiCode, "general_max_420chroma_constraint_flag"  ); assert (uiCode == 1);
+    READ_FLAG(    uiCode, "general_max_monochrome_constraint_flag" ); assert (uiCode == 0);
+    READ_FLAG(    uiCode, "general_intra_constraint_flag"); assert (uiCode == 0);
+    READ_FLAG(    uiCode, "general_one_picture_only_constraint_flag"); assert (uiCode == 0);
+    READ_FLAG(    uiCode, "general_lower_bit_rate_constraint_flag"); assert (uiCode == 1);
+    READ_CODE(32, uiCode, "general_reserved_zero_34bits");  READ_CODE(2, uiCode, "general_reserved_zero_34bits");
+  }
+  else
+  {
+    ptl->setBitDepthConstraint((ptl->getProfileIdc() == Profile::MAIN10)?10:8);
+    ptl->setChromaFormatConstraint(CHROMA_420);
+    ptl->setIntraConstraintFlag(false);
+    ptl->setLowerBitRateConstraintFlag(true);
+    READ_CODE(32,  uiCode, "general_reserved_zero_43bits");  READ_CODE(11,  uiCode, "general_reserved_zero_43bits");
+  }
+
+  if( ( ptl->getProfileIdc() >= 1 && ptl->getProfileIdc() <= 5 ) || 
+      ptl->getProfileCompatibilityFlag(1) || ptl->getProfileCompatibilityFlag(2) || 
+      ptl->getProfileCompatibilityFlag(3) || ptl->getProfileCompatibilityFlag(4) || 
+      ptl->getProfileCompatibilityFlag(5)                                           )
+  {
+    READ_FLAG(uiCode, "general_inbld_flag");
+  }
+  else
+  {
+    READ_FLAG(uiCode, "general_reserved_zero_bit");
+  }
+#else
+    READ_CODE(16, uiCode, "XXX_reserved_zero_35bits[0..15]");
+    READ_CODE(16, uiCode, "XXX_reserved_zero_35bits[16..31]");
+    READ_CODE(3,  uiCode, "XXX_reserved_zero_35bits[32..34]");
+  }
+  else
+  {
+    ptl->setBitDepthConstraint((ptl->getProfileIdc() == Profile::MAIN10)?10:8);
+    ptl->setChromaFormatConstraint(CHROMA_420);
+    ptl->setIntraConstraintFlag(false);
+    ptl->setLowerBitRateConstraintFlag(true);
+    READ_CODE(16, uiCode, "XXX_reserved_zero_44bits[0..15]");
+    READ_CODE(16, uiCode, "XXX_reserved_zero_44bits[16..31]");
+    READ_CODE(12, uiCode, "XXX_reserved_zero_44bits[32..43]");
+  }
+#endif
+}
+
+Void TDecCavlc::parseTerminatingBit( UInt& ruiBit )
+{
+  ruiBit = false;
+  Int iBitsLeft = m_pcBitstream->getNumBitsLeft();
+  if(iBitsLeft <= 8)
+  {
+    UInt uiPeekValue = m_pcBitstream->peekBits(iBitsLeft);
+    if (uiPeekValue == (1<<(iBitsLeft-1)))
+    {
+      ruiBit = true;
+    }
+  }
+}
+
+Void TDecCavlc::parseRemainingBytes( Bool noTrailingBytesExpected )
+{
+  if (noTrailingBytesExpected)
+  {
+    const UInt numberOfRemainingSubstreamBytes=m_pcBitstream->getNumBitsLeft();
+    assert (numberOfRemainingSubstreamBytes == 0);
+  }
+  else
+  {
+    while (m_pcBitstream->getNumBitsLeft())
+    {
+      UInt trailingNullByte=m_pcBitstream->readByte();
+      if (trailingNullByte!=0)
+      {
+        printf("Trailing byte should be 0, but has value %02x\n", trailingNullByte);
+        assert(trailingNullByte==0);
+      }
+    }
+  }
+}
+
+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::parseCrossComponentPrediction( class TComTU& /*rTu*/, ComponentID /*compID*/ )
+{
+  assert(0);
+}
+
+Void TDecCavlc::parseDeltaQP( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  Int qp;
+  Int  iDQp;
+
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+  READ_SVLC(iDQp, "delta_qp");
+#else
+  xReadSvlc( iDQp );
+#endif
+
+#if REPN_FORMAT_IN_VPS
+  Int qpBdOffsetY = pcCU->getSlice()->getQpBDOffsetY();
+#else
+  Int qpBdOffsetY = pcCU->getSlice()->getSPS()->getQpBDOffset(CHANNEL_TYPE_LUMA);
+#endif
+  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::parseChromaQpAdjustment( TComDataCU* /*pcCU*/, UInt /*uiAbsPartIdx*/, UInt /*uiDepth*/ )
+{
+  assert(0);
+}
+
+Void TDecCavlc::parseCoeffNxN( TComTU &/*rTu*/, ComponentID /*compID*/ )
+{
+  assert(0);
+}
+
+Void TDecCavlc::parseTransformSubdivFlag( UInt& /*ruiSubdivFlag*/, UInt /*uiLog2TransformBlockSize*/ )
+{
+  assert(0);
+}
+
+Void TDecCavlc::parseQtCbf( TComTU &/*rTu*/, const ComponentID /*compID*/, const Bool /*lowestLevel*/ )
+{
+  assert(0);
+}
+
+Void TDecCavlc::parseQtRootCbf( UInt /*uiAbsPartIdx*/, UInt& /*uiQtRootCbf*/ )
+{
+  assert(0);
+}
+
+Void TDecCavlc::parseTransformSkipFlags (TComTU &/*rTu*/, ComponentID /*component*/)
+{
+  assert(0);
+}
+
+Void TDecCavlc::parseMergeFlag ( TComDataCU* /*pcCU*/, UInt /*uiAbsPartIdx*/, UInt /*uiDepth*/, UInt /*uiPUIdx*/ )
+{
+  assert(0);
+}
+
+Void TDecCavlc::parseMergeIndex ( TComDataCU* /*pcCU*/, UInt& /*ruiMergeIndex*/ )
+{
+  assert(0);
+}
+
+// ====================================================================================================================
+// Protected member functions
+// ====================================================================================================================
+
+/** parse explicit wp tables
+* \param TComSlice* pcSlice
+* \returns Void
+*/
+Void TDecCavlc::xParsePredWeightTable( TComSlice* pcSlice )
+{
+        WPScalingParam *wp;
+        TComSPS        *sps          = pcSlice->getSPS();
+  const ChromaFormat    chFmt        = sps->getChromaFormatIdc();
+  const Int             numValidComp = Int(getNumberValidComponents(chFmt));
+  const Bool            bChroma      = (chFmt!=CHROMA_400);
+  const SliceType       eSliceType   = pcSlice->getSliceType();
+  const Int             iNbRef       = (eSliceType == B_SLICE ) ? (2) : (1);
+        UInt            uiLog2WeightDenomLuma=0, uiLog2WeightDenomChroma=0;
+        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[COMPONENT_Y].uiLog2WeightDenom = uiLog2WeightDenomLuma;
+      for(Int j=1; j<numValidComp; j++)
+      {
+        wp[j].uiLog2WeightDenom = uiLog2WeightDenomChroma;
+      }
+
+      UInt  uiCode;
+      READ_FLAG( uiCode, "luma_weight_lX_flag" );           // u(1): luma_weight_l0_flag
+      wp[COMPONENT_Y].bPresentFlag = ( uiCode == 1 );
+      uiTotalSignalledWeightFlags += wp[COMPONENT_Y].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
+        for(Int j=1; j<numValidComp; j++)
+        {
+          wp[j].bPresentFlag = ( uiCode == 1 );
+        }
+        uiTotalSignalledWeightFlags += 2*wp[COMPONENT_Cb].bPresentFlag;
+      }
+    }
+    for ( Int iRefIdx=0 ; iRefIdx<pcSlice->getNumRefIdx(eRefPicList) ; iRefIdx++ )
+    {
+      pcSlice->getWpScaling(eRefPicList, iRefIdx, wp);
+      if ( wp[COMPONENT_Y].bPresentFlag )
+      {
+        Int iDeltaWeight;
+        READ_SVLC( iDeltaWeight, "delta_luma_weight_lX" );  // se(v): delta_luma_weight_l0[i]
+        assert( iDeltaWeight >= -128 );
+        assert( iDeltaWeight <=  127 );
+        wp[COMPONENT_Y].iWeight = (iDeltaWeight + (1<<wp[COMPONENT_Y].uiLog2WeightDenom));
+        READ_SVLC( wp[COMPONENT_Y].iOffset, "luma_offset_lX" );       // se(v): luma_offset_l0[i]
+        Int range=sps->getUseHighPrecisionPredictionWeighting() ? (1<<g_bitDepth[CHANNEL_TYPE_LUMA])/2 : 128;
+        assert( wp[0].iOffset >= -range );
+        assert( wp[0].iOffset <   range );
+      }
+      else
+      {
+        wp[COMPONENT_Y].iWeight = (1 << wp[COMPONENT_Y].uiLog2WeightDenom);
+        wp[COMPONENT_Y].iOffset = 0;
+      }
+      if ( bChroma )
+      {
+        if ( wp[COMPONENT_Cb].bPresentFlag )
+        {
+          Int range=sps->getUseHighPrecisionPredictionWeighting() ? (1<<g_bitDepth[CHANNEL_TYPE_CHROMA])/2 : 128;
+          for ( Int j=1 ; j<numValidComp ; 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[j].uiLog2WeightDenom));
+
+            Int iDeltaChroma;
+            READ_SVLC( iDeltaChroma, "delta_chroma_offset_lX" );  // se(v): delta_chroma_offset_l0[i][j]
+            assert( iDeltaChroma >= -4*range);
+            assert( iDeltaChroma <   4*range);
+            Int pred = ( range - ( ( range*wp[j].iWeight)>>(wp[j].uiLog2WeightDenom) ) );
+            wp[j].iOffset = Clip3(-range, range-1, (iDeltaChroma + pred) );
+          }
+        }
+        else
+        {
+          for ( Int j=1 ; j<numValidComp ; 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 <  SCALING_LIST_NUM; listId++)
+    {
+      if ((sizeId==SCALING_LIST_32x32) && (listId%(SCALING_LIST_NUM/NUMBER_OF_PREDICTION_MODES) != 0))
+      {
+        Int *src = scalingList->getScalingListAddress(sizeId, listId);
+        const Int size = min(MAX_MATRIX_COEF_NUM,(Int)g_scalingListSize[sizeId]);
+        const Int *srcNextSmallerSize = scalingList->getScalingListAddress(sizeId-1, listId);
+        for(Int i=0; i<size; i++)
+        {
+          src[i] = srcNextSmallerSize[i];
+        }
+        scalingList->setScalingListDC(sizeId,listId,(sizeId > SCALING_LIST_8x8) ? scalingList->getScalingListDC(sizeId-1, listId) : src[0]);
+      }
+      else
+      {
+        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");
+
+          if (sizeId==SCALING_LIST_32x32)
+            code*=(SCALING_LIST_NUM/NUMBER_OF_PREDICTION_MODES); // Adjust the decoded code for this size, to cope with the missing 32x32 chroma entries.
+
+          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  = g_scanOrder[SCAN_UNGROUPED][SCAN_DIAG][sizeId==0 ? 2 : 3][sizeId==0 ? 2 : 3];
+  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);
+}
+
+Void TDecCavlc::parseExplicitRdpcmMode( TComTU &rTu, ComponentID compID )
+{
+  assert(0);
+}
+
+#if SVC_EXTENSION
+Void TDecCavlc::parseVPSExtension(TComVPS *vps)
+{
+  UInt uiCode;
+  // ... More syntax elements to be parsed here
+#if P0300_ALT_OUTPUT_LAYER_FLAG
+  Int NumOutputLayersInOutputLayerSet[MAX_VPS_LAYER_SETS_PLUS1];
+  Int OlsHighestOutputLayerId[MAX_VPS_LAYER_SETS_PLUS1];
+#endif
+#if LIST_OF_PTL
+  if( vps->getMaxLayers() > 1 && vps->getBaseLayerInternalFlag() )
+  {
+    vps->setProfilePresentFlag(1, false);
+#if MULTIPLE_PTL_SUPPORT
+    parsePTL( vps->getPTL(1), vps->getProfilePresentFlag(1), vps->getMaxTLayers() - 1 );
+#else
+    vps->getPTLForExtnPtr()->empty();
+    vps->getPTLForExtnPtr()->resize(2);
+    vps->getPTLForExtn(1)->copyProfileInfo( vps->getPTL() );
+    parsePTL( vps->getPTLForExtn(1), vps->getProfilePresentFlag(1), vps->getMaxTLayers() - 1 );
+#endif
+  }
+#endif
+#if VPS_EXTN_MASK_AND_DIM_INFO
+  UInt numScalabilityTypes = 0, i = 0, j = 0;
+
+#if !VPS_AVC_BL_FLAG_REMOVAL
+  READ_FLAG( uiCode, "avc_base_layer_flag" ); vps->setAvcBaseLayerFlag(uiCode ? true : false);
+#endif
+
+#if !P0307_REMOVE_VPS_VUI_OFFSET
+#if O0109_MOVE_VPS_VUI_FLAG
+  READ_FLAG( uiCode, "vps_vui_present_flag"); vps->setVpsVuiPresentFlag(uiCode ? true : false);
+  if ( uiCode )
+  {
+#endif
+#if VPS_VUI_OFFSET
+    READ_CODE( 16, uiCode, "vps_vui_offset" );  vps->setVpsVuiOffset( uiCode );
+#endif
+#if O0109_MOVE_VPS_VUI_FLAG
+  }
+#endif
+#endif
+  READ_FLAG( uiCode, "splitting_flag" ); vps->setSplittingFlag(uiCode ? true : false);
+
+  for(i = 0; i < MAX_VPS_NUM_SCALABILITY_TYPES; i++)
+  {
+    READ_FLAG( uiCode, "scalability_mask[i]" ); vps->setScalabilityMask(i, uiCode ? true : false);
+    numScalabilityTypes += uiCode;
+  }
+  vps->setNumScalabilityTypes(numScalabilityTypes);
+
+  for(j = 0; j < numScalabilityTypes - vps->getSplittingFlag(); j++)
+  {
+    READ_CODE( 3, uiCode, "dimension_id_len_minus1[j]" ); vps->setDimensionIdLen(j, uiCode + 1);
+  }
+
+  // The value of dimBitOffset[ NumScalabilityTypes ] is set equal to 6.
+  if(vps->getSplittingFlag())
+  {
+    UInt numBits = 0;
+    for(j = 0; j < numScalabilityTypes - 1; j++)
+    {
+      numBits += vps->getDimensionIdLen(j);
+    }
+    assert( numBits < 6 );
+    vps->setDimensionIdLen(numScalabilityTypes-1, 6 - numBits);
+    numBits = 6;
+  }
+
+  READ_FLAG( uiCode, "vps_nuh_layer_id_present_flag" ); vps->setNuhLayerIdPresentFlag(uiCode ? true : false);
+  vps->setLayerIdInNuh(0, 0);
+  vps->setLayerIdxInVps(0, 0);
+  for(i = 1; i < vps->getMaxLayers(); i++)
+  {
+    if( vps->getNuhLayerIdPresentFlag() )
+    {
+      READ_CODE( 6, uiCode, "layer_id_in_nuh[i]" ); vps->setLayerIdInNuh(i, uiCode);
+      assert( uiCode > vps->getLayerIdInNuh(i-1) );
+    }
+    else
+    {
+      vps->setLayerIdInNuh(i, i);
+    }
+    vps->setLayerIdxInVps(vps->getLayerIdInNuh(i), i);
+
+    if( !vps->getSplittingFlag() )
+    {
+      for(j = 0; j < numScalabilityTypes; j++)
+      {
+        READ_CODE( vps->getDimensionIdLen(j), uiCode, "dimension_id[i][j]" ); vps->setDimensionId(i, j, uiCode);
+#if !AUXILIARY_PICTURES
+        assert( uiCode <= vps->getMaxLayerId() );
+#endif
+      }
+    }
+  }
+#endif
+#if VIEW_ID_RELATED_SIGNALING
+#if O0109_VIEW_ID_LEN
+  READ_CODE( 4, uiCode, "view_id_len" ); vps->setViewIdLen( uiCode );
+#else
+  READ_CODE( 4, uiCode, "view_id_len_minus1" ); vps->setViewIdLenMinus1( uiCode );
+#endif
+
+#if O0109_VIEW_ID_LEN
+  if ( vps->getViewIdLen() > 0 )
+  {
+    for(  i = 0; i < vps->getNumViews(); i++ )
+    {
+      READ_CODE( vps->getViewIdLen( ), uiCode, "view_id_val[i]" ); vps->setViewIdVal( i, uiCode );
+    }
+  }
+#else
+  for(  i = 0; i < vps->getNumViews(); i++ )
+  {
+    READ_CODE( vps->getViewIdLenMinus1( ) + 1, uiCode, "view_id_val[i]" ); vps->setViewIdVal( i, uiCode );
+  }
+#endif
+#endif // view id related signaling
+#if VPS_EXTN_DIRECT_REF_LAYERS
+  // For layer 0
+  vps->setNumDirectRefLayers(0, 0);
+  // For other layers
+  for( Int layerCtr = 1; layerCtr < vps->getMaxLayers(); layerCtr++)
+  {
+    UInt layerId = vps->getLayerIdInNuh(layerCtr); 
+    UInt numDirectRefLayers = 0;
+    for( Int refLayerCtr = 0; refLayerCtr < layerCtr; refLayerCtr++)
+    {
+      READ_FLAG(uiCode, "direct_dependency_flag[i][j]" ); vps->setDirectDependencyFlag(layerCtr, refLayerCtr, uiCode? true : false);
+      if(uiCode)
+      {
+        vps->setRefLayerId(layerId, numDirectRefLayers, vps->getLayerIdInNuh(refLayerCtr));
+        numDirectRefLayers++;
+      }
+    }
+    vps->setNumDirectRefLayers(layerId, numDirectRefLayers);
+  }
+#endif
+#if Q0078_ADD_LAYER_SETS
+#if O0092_0094_DEPENDENCY_CONSTRAINT // Moved here
+  vps->setNumRefLayers();
+
+  if (vps->getMaxLayers() > MAX_REF_LAYERS)
+  {
+    for (i = 1; i < vps->getMaxLayers(); i++)
+    {
+      assert(vps->getNumRefLayers(vps->getLayerIdInNuh(i)) <= MAX_REF_LAYERS);
+    }
+  }
+#endif
+  vps->setPredictedLayerIds();
+  vps->setTreePartitionLayerIdList();
+#endif
+#if MOVE_ADDN_LS_SIGNALLING
+#if Q0078_ADD_LAYER_SETS
+  if (vps->getNumIndependentLayers() > 1)
+  {
+    READ_UVLC(uiCode, "num_add_layer_sets"); vps->setNumAddLayerSets(uiCode);
+    for (i = 0; i < vps->getNumAddLayerSets(); i++)
+    {
+      for (j = 1; j < vps->getNumIndependentLayers(); j++)
+      {
+        int len = 1;
+        while ((1 << len) < (vps->getNumLayersInTreePartition(j) + 1))
+        {
+          len++;
+        }
+        READ_CODE(len, uiCode, "highest_layer_idx_plus1[i][j]"); vps->setHighestLayerIdxPlus1(i, j, uiCode);
+      }
+    }
+    vps->setNumLayerSets(vps->getNumLayerSets() + vps->getNumAddLayerSets());
+#if FIX_LAYER_ID_INIT
+    vps->deriveLayerIdListVariablesForAddLayerSets();
+#else
+    vps->setLayerIdIncludedFlagsForAddLayerSets();
+#endif
+  }
+  else
+  {
+    vps->setNumAddLayerSets(0);
+  }
+#endif
+#endif
+#if VPS_TSLAYERS
+  READ_FLAG( uiCode, "vps_sub_layers_max_minus1_present_flag"); vps->setMaxTSLayersPresentFlag(uiCode ? true : false);
+
+  if (vps->getMaxTSLayersPresentFlag())
+  {
+    for(i = 0; i < vps->getMaxLayers(); i++)
+    {
+      READ_CODE( 3, uiCode, "sub_layers_vps_max_minus1[i]" ); vps->setMaxTSLayersMinus1(i, uiCode);
+    }
+  }
+  else
+  {
+    for( i = 0; i < vps->getMaxLayers(); i++)
+    {
+      vps->setMaxTSLayersMinus1(i, vps->getMaxTLayers()-1);
+    }
+  }
+#endif
+  READ_FLAG( uiCode, "max_tid_ref_present_flag"); vps->setMaxTidRefPresentFlag(uiCode ? true : false);
+  if (vps->getMaxTidRefPresentFlag())
+  {
+    for(i = 0; i < vps->getMaxLayers() - 1; i++)
+    {
+      for( j = i+1; j < vps->getMaxLayers(); j++)
+      {
+        if(vps->getDirectDependencyFlag(j, i))
+        {
+          READ_CODE( 3, uiCode, "max_tid_il_ref_pics_plus1[i][j]" ); vps->setMaxTidIlRefPicsPlus1(i, j, uiCode);          
+        }
+      }
+    }
+  }
+  else
+  {
+    for(i = 0; i < vps->getMaxLayers() - 1; i++)
+    {
+      for( j = i+1; j < vps->getMaxLayers(); j++)
+      {
+        vps->setMaxTidIlRefPicsPlus1(i, j, 7);
+      }
+    }
+  }
+  READ_FLAG( uiCode, "all_ref_layers_active_flag" ); vps->setIlpSshSignalingEnabledFlag(uiCode ? true : false);
+#if VPS_EXTN_PROFILE_INFO
+  // Profile-tier-level signalling
+#if !VPS_EXTN_UEV_CODING
+  READ_CODE( 10, uiCode, "vps_number_layer_sets_minus1" );     assert( uiCode == (vps->getNumLayerSets() - 1) );
+  READ_CODE(  6, uiCode, "vps_num_profile_tier_level_minus1"); vps->setNumProfileTierLevel( uiCode + 1 );
+#else
+  READ_UVLC(  uiCode, "vps_num_profile_tier_level_minus1"); vps->setNumProfileTierLevel( uiCode + 1 );
+#endif
+#if PER_LAYER_PTL
+  Int const numBitsForPtlIdx = vps->calculateLenOfSyntaxElement( vps->getNumProfileTierLevel() );
+#endif
+#if !MULTIPLE_PTL_SUPPORT
+  vps->getPTLForExtnPtr()->resize(vps->getNumProfileTierLevel());
+#endif
+#if LIST_OF_PTL
+  for(Int idx = vps->getBaseLayerInternalFlag() ? 2 : 1; idx < vps->getNumProfileTierLevel(); idx++)
+#else
+  for(Int idx = 1; idx <= vps->getNumProfileTierLevel() - 1; idx++)
+#endif
+  {
+    READ_FLAG( uiCode, "vps_profile_present_flag[i]" ); vps->setProfilePresentFlag(idx, uiCode ? true : false);
+    if( !vps->getProfilePresentFlag(idx) )
+    {
+#if P0048_REMOVE_PROFILE_REF
+      // Copy profile information from previous one
+#if MULTIPLE_PTL_SUPPORT
+      vps->getPTL(idx)->copyProfileInfo( vps->getPTL( idx - 1 ) );
+#else
+      vps->getPTLForExtn(idx)->copyProfileInfo( (idx==1) ? vps->getPTL() : vps->getPTLForExtn( idx - 1 ) );
+#endif
+#else
+      READ_CODE( 6, uiCode, "profile_ref_minus1[i]" ); vps->setProfileLayerSetRef(idx, uiCode + 1);
+#if O0109_PROF_REF_MINUS1
+      assert( vps->getProfileLayerSetRef(idx) <= idx );
+#else
+      assert( vps->getProfileLayerSetRef(idx) < idx );
+#endif
+      // Copy profile information as indicated
+      vps->getPTLForExtn(idx)->copyProfileInfo( vps->getPTLForExtn( vps->getProfileLayerSetRef(idx) ) );
+#endif
+    }
+#if MULTIPLE_PTL_SUPPORT
+    parsePTL( vps->getPTL(idx), vps->getProfilePresentFlag(idx), vps->getMaxTLayers() - 1 );
+#else
+    parsePTL( vps->getPTLForExtn(idx), vps->getProfilePresentFlag(idx), vps->getMaxTLayers() - 1 );
+#endif
+  }
+#endif
+
+#if !MOVE_ADDN_LS_SIGNALLING
+#if Q0078_ADD_LAYER_SETS
+  if (vps->getNumIndependentLayers() > 1)
+  {
+    READ_UVLC(uiCode, "num_add_layer_sets"); vps->setNumAddLayerSets(uiCode);
+    for (i = 0; i < vps->getNumAddLayerSets(); i++)
+    {
+      for (j = 1; j < vps->getNumIndependentLayers(); j++)
+      {
+        int len = 1;
+        while ((1 << len) < (vps->getNumLayersInTreePartition(j) + 1))
+        {
+          len++;
+        }
+        READ_CODE(len, uiCode, "highest_layer_idx_plus1[i][j]"); vps->setHighestLayerIdxPlus1(i, j, uiCode);
+      }
+    }
+    vps->setNumLayerSets(vps->getNumLayerSets() + vps->getNumAddLayerSets());
+    vps->setLayerIdIncludedFlagsForAddLayerSets();
+  }
+#endif
+#endif
+
+#if !VPS_EXTN_UEV_CODING
+  READ_FLAG( uiCode, "more_output_layer_sets_than_default_flag" ); vps->setMoreOutputLayerSetsThanDefaultFlag( uiCode ? true : false );
+  Int numOutputLayerSets = 0;
+  if(! vps->getMoreOutputLayerSetsThanDefaultFlag() )
+  {
+    numOutputLayerSets = vps->getNumLayerSets();
+  }
+  else
+  {
+    READ_CODE( 10, uiCode, "num_add_output_layer_sets" );          vps->setNumAddOutputLayerSets( uiCode );
+    numOutputLayerSets = vps->getNumLayerSets() + vps->getNumAddOutputLayerSets();
+  }
+#else
+
+#if Q0165_NUM_ADD_OUTPUT_LAYER_SETS
+  if( vps->getNumLayerSets() > 1 )
+  {
+    READ_UVLC( uiCode, "num_add_olss" );            vps->setNumAddOutputLayerSets( uiCode );
+    READ_CODE( 2, uiCode, "default_output_layer_idc" );   vps->setDefaultTargetOutputLayerIdc( uiCode );
+  }
+  else
+  {
+    vps->setNumAddOutputLayerSets( 0 );
+  }
+#else
+  READ_UVLC( uiCode, "num_add_output_layer_sets" );          vps->setNumAddOutputLayerSets( uiCode );
+#endif
+
+  // The value of num_add_olss shall be in the range of 0 to 1023, inclusive.
+  assert( vps->getNumAddOutputLayerSets() >= 0 && vps->getNumAddOutputLayerSets() < 1024 );
+
+  Int numOutputLayerSets = vps->getNumLayerSets() + vps->getNumAddOutputLayerSets();
+#endif
+
+#if P0295_DEFAULT_OUT_LAYER_IDC
+#if !Q0165_NUM_ADD_OUTPUT_LAYER_SETS
+  if( numOutputLayerSets > 1 )
+  {
+    READ_CODE( 2, uiCode, "default_target_output_layer_idc" );   vps->setDefaultTargetOutputLayerIdc( uiCode );
+  }
+#endif
+  vps->setNumOutputLayerSets( numOutputLayerSets );
+#if NECESSARY_LAYER_FLAG
+  // Default output layer set
+  vps->setOutputLayerSetIdx(0, 0);
+  vps->setOutputLayerFlag(0, 0, true);
+  vps->deriveNecessaryLayerFlag(0);
+#if PER_LAYER_PTL
+  vps->getProfileLevelTierIdx()->resize(numOutputLayerSets);
+  vps->getProfileLevelTierIdx(0)->push_back( vps->getBaseLayerInternalFlag() && vps->getMaxLayers() > 1 ? 1 : 0);
+#endif
+#endif
+  for(i = 1; i < numOutputLayerSets; i++)
+  {
+#if VPS_FIX_TO_MATCH_SPEC
+    if( vps->getNumLayerSets() > 2 && i >= vps->getNumLayerSets() )
+#else
+    if( i > (vps->getNumLayerSets() - 1) )
+#endif
+    {
+      Int numBits = 1;
+      while ((1 << numBits) < (vps->getNumLayerSets() - 1))
+      {
+        numBits++;
+      }
+      READ_CODE( numBits, uiCode, "layer_set_idx_for_ols_minus1");   vps->setOutputLayerSetIdx( i, uiCode + 1);
+    }
+    else
+    {
+      vps->setOutputLayerSetIdx( i, i );
+    }
+    Int layerSetIdxForOutputLayerSet = vps->getOutputLayerSetIdx(i);
+#if Q0078_ADD_LAYER_SETS
+#if VPS_FIX_TO_MATCH_SPEC
+    if( i > vps->getVpsNumLayerSetsMinus1() || vps->getDefaultTargetOutputLayerIdc() == 2 )
+#else
+    if( i > vps->getVpsNumLayerSetsMinus1() || vps->getDefaultTargetOutputLayerIdc() >= 2 )
+#endif
+#else
+#if VPS_FIX_TO_MATCH_SPEC
+    if( i > (vps->getNumLayerSets() - 1) || vps->getDefaultTargetOutputLayerIdc() == 2 )
+#else
+    if( i > (vps->getNumLayerSets() - 1) || vps->getDefaultTargetOutputLayerIdc() >= 2 )
+#endif
+#endif
+    {
+#if NUM_OL_FLAGS
+      for(j = 0; j < vps->getNumLayersInIdList(layerSetIdxForOutputLayerSet); j++)
+#else
+      for(j = 0; j < vps->getNumLayersInIdList(lsIdx) - 1; j++)
+#endif
+      {
+        READ_FLAG( uiCode, "output_layer_flag[i][j]"); vps->setOutputLayerFlag(i, j, uiCode);
+      }
+    }
+    else
+    {
+      // i <= (vps->getNumLayerSets() - 1)
+      // Assign OutputLayerFlag depending on default_one_target_output_layer_flag
+      if( vps->getDefaultTargetOutputLayerIdc() == 1 )
+      {
+        for(j = 0; j < vps->getNumLayersInIdList(layerSetIdxForOutputLayerSet); j++)
+        {
+#if DEF_OPT_LAYER_IDC
+          vps->setOutputLayerFlag(i, j, (j == (vps->getNumLayersInIdList(layerSetIdxForOutputLayerSet)-1))  );
+
+#else
+          vps->setOutputLayerFlag(i, j, (j == (vps->getNumLayersInIdList(layerSetIdxForOutputLayerSet)-1)) && (vps->getDimensionId(j,1) == 0) );
+#endif
+        }
+      }
+      else if ( vps->getDefaultTargetOutputLayerIdc() == 0 )
+      {
+        for(j = 0; j < vps->getNumLayersInIdList(layerSetIdxForOutputLayerSet); j++)
+        {
+          vps->setOutputLayerFlag(i, j, 1);
+        }
+      }
+    }
+#if NECESSARY_LAYER_FLAG
+    vps->deriveNecessaryLayerFlag(i);  
+#endif
+#if PER_LAYER_PTL
+    vps->getProfileLevelTierIdx(i)->assign(vps->getNumLayersInIdList(layerSetIdxForOutputLayerSet), -1);
+    for(j = 0; j < vps->getNumLayersInIdList(layerSetIdxForOutputLayerSet) ; j++)
+    {
+#if VPS_FIX_TO_MATCH_SPEC
+      if( vps->getNecessaryLayerFlag(i, j) && (vps->getNumProfileTierLevel()-1) > 0 )
+#else
+      if( vps->getNecessaryLayerFlag(i, j) )
+#endif
+      {
+        READ_CODE( numBitsForPtlIdx, uiCode, "profile_tier_level_idx[i]" ); 
+        vps->setProfileLevelTierIdx(i, j, uiCode );
+
+#if MULTIPLE_PTL_SUPPORT
+        //For conformance checking
+        //Conformance of a layer in an output operation point associated with an OLS in a bitstream to the Scalable Main profile is indicated as follows:
+        //If OpTid of the output operation point is equal to vps_max_sub_layer_minus1, the conformance is indicated by general_profile_idc being equal to 7 or general_profile_compatibility_flag[ 7 ] being equal to 1
+        //Conformance of a layer in an output operation point associated with an OLS in a bitstream to the Scalable Main 10 profile is indicated as follows:
+        //If OpTid of the output operation point is equal to vps_max_sub_layer_minus1, the conformance is indicated by general_profile_idc being equal to 7 or general_profile_compatibility_flag[ 7 ] being equal to 1
+        //The following assert may be updated / upgraded to take care of general_profile_compatibility_flag.
+#if R0235_SMALLEST_LAYER_ID
+        // The assertion below is not valid for independent non-base layers 
+        if (vps->getNumAddLayerSets() == 0)
+        {
+#endif
+        if( j > 0 && vps->getLayerSetLayerIdList(layerSetIdxForOutputLayerSet, j) != 0 && vps->getLayerSetLayerIdList(layerSetIdxForOutputLayerSet, j - 1) != 0 && vps->getNecessaryLayerFlag(i, j-1) )
+        {
+          assert(vps->getPTL(vps->getProfileLevelTierIdx(i, j))->getGeneralPTL()->getProfileIdc() == vps->getPTL(vps->getProfileLevelTierIdx(i, j - 1))->getGeneralPTL()->getProfileIdc() ||
+                 vps->getPTL(vps->getProfileLevelTierIdx(i, j - 1))->getGeneralPTL()->getProfileCompatibilityFlag(vps->getPTL(vps->getProfileLevelTierIdx(i, j))->getGeneralPTL()->getProfileIdc()) ||  
+                 vps->getPTL(vps->getProfileLevelTierIdx(i, j))->getGeneralPTL()->getProfileCompatibilityFlag(vps->getPTL(vps->getProfileLevelTierIdx(i, j - 1))->getGeneralPTL()->getProfileIdc())  );
+        }
+#if R0235_SMALLEST_LAYER_ID
+        }
+#endif
+#endif
+      }
+    }
+#else
+    Int numBits = 1;
+    while ((1 << numBits) < (vps->getNumProfileTierLevel()))
+    {
+      numBits++;
+    }
+    READ_CODE( numBits, uiCode, "profile_tier_level_idx[i]" );     vps->setProfileLevelTierIdx(i, uiCode);
+#endif
+#if P0300_ALT_OUTPUT_LAYER_FLAG
+    NumOutputLayersInOutputLayerSet[i] = 0;
+    for (j = 0; j < vps->getNumLayersInIdList(layerSetIdxForOutputLayerSet); j++)
+    {
+      NumOutputLayersInOutputLayerSet[i] += vps->getOutputLayerFlag(i, j);
+      if (vps->getOutputLayerFlag(i, j))
+      {
+        OlsHighestOutputLayerId[i] = vps->getLayerSetLayerIdList(layerSetIdxForOutputLayerSet, j);
+      }
+    }
+    if (NumOutputLayersInOutputLayerSet[i] == 1 && vps->getNumDirectRefLayers(OlsHighestOutputLayerId[i]) > 0)
+    {
+      READ_FLAG(uiCode, "alt_output_layer_flag[i]");
+      vps->setAltOuputLayerFlag(i, uiCode ? true : false);
+    }
+#if ALT_OPT_LAYER_FLAG
+    else
+    {
+          uiCode=0;
+          vps->setAltOuputLayerFlag(i, uiCode ? true : false);
+    }
+#endif
+#if Q0165_OUTPUT_LAYER_SET
+    assert( NumOutputLayersInOutputLayerSet[i]>0 );
+#endif
+
+#endif
+  }
+#if NECESSARY_LAYER_FLAG
+  vps->checkNecessaryLayerFlagCondition();  
+#endif
+#else
+  if( numOutputLayerSets > 1 )
+  {
+#if O0109_DEFAULT_ONE_OUT_LAYER_IDC
+    READ_CODE( 2, uiCode, "default_one_target_output_layer_idc" );   vps->setDefaultOneTargetOutputLayerIdc( uiCode );
+#else
+    READ_FLAG( uiCode, "default_one_target_output_layer_flag" );   vps->setDefaultOneTargetOutputLayerFlag( uiCode ? true : false );
+#endif
+  }
+  vps->setNumOutputLayerSets( numOutputLayerSets );
+
+  for(i = 1; i < numOutputLayerSets; i++)
+  {
+    if( i > (vps->getNumLayerSets() - 1) )
+    {
+      Int numBits = 1;
+      while ((1 << numBits) < (vps->getNumLayerSets() - 1))
+      {
+        numBits++;
+      }
+      READ_CODE( numBits, uiCode, "output_layer_set_idx_minus1");   vps->setOutputLayerSetIdx( i, uiCode + 1);
+      Int lsIdx = vps->getOutputLayerSetIdx(i);
+#if NUM_OL_FLAGS
+      for(j = 0; j < vps->getNumLayersInIdList(lsIdx) ; j++)
+#else
+      for(j = 0; j < vps->getNumLayersInIdList(lsIdx) - 1; j++)
+#endif
+      {
+        READ_FLAG( uiCode, "output_layer_flag[i][j]"); vps->setOutputLayerFlag(i, j, uiCode);
+      }
+    }
+    else
+    {
+#if VPS_DPB_SIZE_TABLE 
+      vps->setOutputLayerSetIdx( i, i );
+#endif
+      // i <= (vps->getNumLayerSets() - 1)
+      // Assign OutputLayerFlag depending on default_one_target_output_layer_flag
+      Int lsIdx = i;
+#if O0109_DEFAULT_ONE_OUT_LAYER_IDC
+      if( vps->getDefaultOneTargetOutputLayerIdc() == 1 )
+      {
+        for(j = 0; j < vps->getNumLayersInIdList(lsIdx); j++)
+        {
+#if O0135_DEFAULT_ONE_OUT_SEMANTIC
+#if DEF_OPT_LAYER_IDC
+        vps->setOutputLayerFlag(i, j, (j == (vps->getNumLayersInIdList(lsIdx)-1)) );
+#else
+          vps->setOutputLayerFlag(i, j, (j == (vps->getNumLayersInIdList(lsIdx)-1)) && (vps->getDimensionId(j,1)==0) );
+#endif
+#else
+          vps->setOutputLayerFlag(i, j, (j == (vps->getNumLayersInIdList(lsIdx)-1)));
+#endif
+        }
+      }
+      else if ( vps->getDefaultOneTargetOutputLayerIdc() == 0 )
+      {
+        for(j = 0; j < vps->getNumLayersInIdList(lsIdx); j++)
+        {
+          vps->setOutputLayerFlag(i, j, 1);
+        }
+      }
+      else
+      {
+        // Other values of default_one_target_output_layer_idc than 0 and 1 are reserved for future use.
+      }
+#else
+      if( vps->getDefaultOneTargetOutputLayerFlag() )
+      {
+        for(j = 0; j < vps->getNumLayersInIdList(lsIdx); j++)
+        {
+          vps->setOutputLayerFlag(i, j, (j == (vps->getNumLayersInIdList(lsIdx)-1)));
+        }
+      }
+      else
+      {
+        for(j = 0; j < vps->getNumLayersInIdList(lsIdx); j++)
+        {
+          vps->setOutputLayerFlag(i, j, 1);
+        }
+      }
+#endif
+    }
+    Int numBits = 1;
+    while ((1 << numBits) < (vps->getNumProfileTierLevel()))
+    {
+      numBits++;
+    }
+    READ_CODE( numBits, uiCode, "profile_level_tier_idx[i]" );     vps->setProfileLevelTierIdx(i, uiCode);
+  }
+#endif
+
+#if !P0300_ALT_OUTPUT_LAYER_FLAG
+#if O0153_ALT_OUTPUT_LAYER_FLAG
+  if( vps->getMaxLayers() > 1 )
+  {
+    READ_FLAG( uiCode, "alt_output_layer_flag");
+    vps->setAltOuputLayerFlag( uiCode ? true : false );
+  }
+#endif
+#endif
+
+#if REPN_FORMAT_IN_VPS
+#if Q0195_REP_FORMAT_CLEANUP
+  READ_UVLC( uiCode, "vps_num_rep_formats_minus1" );
+  vps->setVpsNumRepFormats( uiCode + 1 );
+
+  // The value of vps_num_rep_formats_minus1 shall be in the range of 0 to 255, inclusive.
+  assert( vps->getVpsNumRepFormats() > 0 && vps->getVpsNumRepFormats() <= 256 );
+
+  for(i = 0; i < vps->getVpsNumRepFormats(); i++)
+  {
+    // Read rep_format_structures
+    parseRepFormat( vps->getVpsRepFormat(i), i > 0 ? vps->getVpsRepFormat(i-1) : 0 );
+  }
+
+  // Default assignment for layer 0
+  vps->setVpsRepFormatIdx( 0, 0 );
+
+  if( vps->getVpsNumRepFormats() > 1 )
+  {
+    READ_FLAG( uiCode, "rep_format_idx_present_flag");
+    vps->setRepFormatIdxPresentFlag( uiCode ? true : false );
+  }
+  else
+  {
+    // When not present, the value of rep_format_idx_present_flag is inferred to be equal to 0
+    vps->setRepFormatIdxPresentFlag( false );
+  }
+
+  if( vps->getRepFormatIdxPresentFlag() )
+  {
+#if VPS_FIX_TO_MATCH_SPEC
+    for( i = vps->getBaseLayerInternalFlag() ? 1 : 0; i < vps->getMaxLayers(); i++ )
+#else
+    for (i = 1; i < vps->getMaxLayers(); i++)
+#endif
+    {
+      Int numBits = 1;
+      while ((1 << numBits) < (vps->getVpsNumRepFormats()))
+      {
+        numBits++;
+      }
+      READ_CODE( numBits, uiCode, "vps_rep_format_idx[i]" );
+      vps->setVpsRepFormatIdx( i, uiCode );
+    }
+  }
+  else
+  {
+    // When not present, the value of vps_rep_format_idx[ i ] is inferred to be equal to Min (i, vps_num_rep_formats_minus1)
+    for(i = 1; i < vps->getMaxLayers(); i++)
+    {
+      vps->setVpsRepFormatIdx( i, min( (Int)i, vps->getVpsNumRepFormats()-1 ) );
+    }
+  }
+#else
+  READ_FLAG( uiCode, "rep_format_idx_present_flag");
+  vps->setRepFormatIdxPresentFlag( uiCode ? true : false );
+
+  if( vps->getRepFormatIdxPresentFlag() )
+  {
+#if O0096_REP_FORMAT_INDEX
+#if !VPS_EXTN_UEV_CODING
+    READ_CODE( 8, uiCode, "vps_num_rep_formats_minus1" );
+#else
+    READ_UVLC( uiCode, "vps_num_rep_formats_minus1" );
+#endif
+#else
+    READ_CODE( 4, uiCode, "vps_num_rep_formats_minus1" );
+#endif
+    vps->setVpsNumRepFormats( uiCode + 1 );
+  }
+  else
+  {
+    // default assignment
+    assert (vps->getMaxLayers() <= 16);       // If max_layers_is more than 15, num_rep_formats has to be signaled
+    vps->setVpsNumRepFormats( vps->getMaxLayers() );
+  }
+
+  // The value of vps_num_rep_formats_minus1 shall be in the range of 0 to 255, inclusive.
+  assert( vps->getVpsNumRepFormats() > 0 && vps->getVpsNumRepFormats() <= 256 );
+
+  for(i = 0; i < vps->getVpsNumRepFormats(); i++)
+  {
+    // Read rep_format_structures
+    parseRepFormat( vps->getVpsRepFormat(i), i > 0 ? vps->getVpsRepFormat(i-1) : 0 );
+  }
+
+  // Default assignment for layer 0
+  vps->setVpsRepFormatIdx( 0, 0 );
+  if( vps->getRepFormatIdxPresentFlag() )
+  {
+    for(i = 1; i < vps->getMaxLayers(); i++)
+    {
+      if( vps->getVpsNumRepFormats() > 1 )
+      {
+#if O0096_REP_FORMAT_INDEX
+#if !VPS_EXTN_UEV_CODING
+        READ_CODE( 8, uiCode, "vps_rep_format_idx[i]" );
+#else
+        Int numBits = 1;
+        while ((1 << numBits) < (vps->getVpsNumRepFormats()))
+        {
+          numBits++;
+        }
+        READ_CODE( numBits, uiCode, "vps_rep_format_idx[i]" );
+#endif
+#else
+        READ_CODE( 4, uiCode, "vps_rep_format_idx[i]" );
+#endif
+        vps->setVpsRepFormatIdx( i, uiCode );
+      }
+      else
+      {
+        // default assignment - only one rep_format() structure
+        vps->setVpsRepFormatIdx( i, 0 );
+      }
+    }
+  }
+  else
+  {
+    // default assignment - each layer assigned each rep_format() structure in the order signaled
+    for(i = 1; i < vps->getMaxLayers(); i++)
+    {
+      vps->setVpsRepFormatIdx( i, i );
+    }
+  }
+#endif
+#endif
+#if RESOLUTION_BASED_DPB
+  vps->assignSubDpbIndices();
+#endif
+  READ_FLAG(uiCode, "max_one_active_ref_layer_flag" );
+  vps->setMaxOneActiveRefLayerFlag(uiCode);
+#if P0297_VPS_POC_LSB_ALIGNED_FLAG
+  READ_FLAG(uiCode, "vps_poc_lsb_aligned_flag");
+  vps->setVpsPocLsbAlignedFlag(uiCode);
+#endif
+#if O0062_POC_LSB_NOT_PRESENT_FLAG
+  for(i = 1; i< vps->getMaxLayers(); i++)
+  {
+    if( vps->getNumDirectRefLayers( vps->getLayerIdInNuh(i) ) == 0  )
+    {
+      READ_FLAG(uiCode, "poc_lsb_not_present_flag[i]");
+      vps->setPocLsbNotPresentFlag(i, uiCode);
+    }
+  }
+#endif
+#if O0215_PHASE_ALIGNMENT
+  READ_FLAG( uiCode, "cross_layer_phase_alignment_flag"); vps->setPhaseAlignFlag( uiCode == 1 ? true : false );
+#endif
+
+#if !IRAP_ALIGN_FLAG_IN_VPS_VUI
+  READ_FLAG(uiCode, "cross_layer_irap_aligned_flag" );
+  vps->setCrossLayerIrapAlignFlag(uiCode);
+#endif
+
+#if VPS_DPB_SIZE_TABLE
+  parseVpsDpbSizeTable(vps);
+#endif
+
+#if VPS_EXTN_DIRECT_REF_LAYERS
+  READ_UVLC( uiCode,           "direct_dep_type_len_minus2"); vps->setDirectDepTypeLen(uiCode+2);
+#if O0096_DEFAULT_DEPENDENCY_TYPE
+  READ_FLAG(uiCode, "default_direct_dependency_type_flag"); 
+  vps->setDefaultDirectDependecyTypeFlag(uiCode == 1? true : false);
+  if (vps->getDefaultDirectDependencyTypeFlag())
+  {
+    READ_CODE( vps->getDirectDepTypeLen(), uiCode, "default_direct_dependency_type" ); 
+    vps->setDefaultDirectDependecyType(uiCode);
+  }
+#endif
+
+#if VPS_FIX_TO_MATCH_SPEC
+  for( i = vps->getBaseLayerInternalFlag() ? 1 : 2; i < vps->getMaxLayers(); i++ )
+#else
+  for(i = 1; i < vps->getMaxLayers(); i++)
+#endif
+  {
+#if VPS_FIX_TO_MATCH_SPEC
+    for( j = vps->getBaseLayerInternalFlag() ? 0 : 1; j < i; j++ )
+#else
+    for(j = 0; j < i; j++)
+#endif
+    {
+      if (vps->getDirectDependencyFlag(i, j))
+      {
+#if O0096_DEFAULT_DEPENDENCY_TYPE
+        if (vps->getDefaultDirectDependencyTypeFlag())
+        {
+          vps->setDirectDependencyType(i, j, vps->getDefaultDirectDependencyType());
+        }
+        else
+        {
+          READ_CODE( vps->getDirectDepTypeLen(), uiCode, "direct_dependency_type[i][j]" ); 
+          vps->setDirectDependencyType(i, j, uiCode);
+        }
+#else
+        READ_CODE( vps->getDirectDepTypeLen(), uiCode, "direct_dependency_type[i][j]" ); 
+        vps->setDirectDependencyType(i, j, uiCode);
+#endif
+      }
+    }
+  }
+#endif
+#if !Q0078_ADD_LAYER_SETS
+#if O0092_0094_DEPENDENCY_CONSTRAINT // Moved up
+  vps->setNumRefLayers();
+
+  if(vps->getMaxLayers() > MAX_REF_LAYERS)
+  {
+    for(i = 1;i < vps->getMaxLayers(); i++)
+    {
+      assert( vps->getNumRefLayers(vps->getLayerIdInNuh(i)) <= MAX_REF_LAYERS);
+    }
+  }
+#endif
+#endif
+
+#if P0307_VPS_NON_VUI_EXTENSION
+  READ_UVLC( uiCode,           "vps_non_vui_extension_length"); vps->setVpsNonVuiExtLength((Int)uiCode);
+
+  // The value of vps_non_vui_extension_length shall be in the range of 0 to 4096, inclusive.
+  assert( vps->getVpsNonVuiExtLength() >= 0 && vps->getVpsNonVuiExtLength() <= 4096 );
+
+#if P0307_VPS_NON_VUI_EXT_UPDATE
+  Int nonVuiExtByte = uiCode;
+  for (i = 1; i <= nonVuiExtByte; i++)
+  {
+    READ_CODE( 8, uiCode, "vps_non_vui_extension_data_byte" ); //just parse and discard for now.
+  }
+#else
+  if ( vps->getVpsNonVuiExtLength() > 0 )
+  {
+    printf("\n\nUp to the current spec, the value of vps_non_vui_extension_length is supposed to be 0\n");
+  }
+#endif
+#endif
+
+#if !O0109_O0199_FLAGS_TO_VUI
+#if M0040_ADAPTIVE_RESOLUTION_CHANGE
+  READ_FLAG(uiCode, "single_layer_for_non_irap_flag" ); vps->setSingleLayerForNonIrapFlag(uiCode == 1 ? true : false);
+#endif
+#if HIGHER_LAYER_IRAP_SKIP_FLAG
+  READ_FLAG(uiCode, "higher_layer_irap_skip_flag" ); vps->setHigherLayerIrapSkipFlag(uiCode == 1 ? true : false);
+#endif
+#endif
+
+#if P0307_REMOVE_VPS_VUI_OFFSET
+  READ_FLAG( uiCode, "vps_vui_present_flag"); vps->setVpsVuiPresentFlag(uiCode ? true : false);
+#endif
+
+#if O0109_MOVE_VPS_VUI_FLAG
+  if ( vps->getVpsVuiPresentFlag() )
+#else
+  READ_FLAG( uiCode,  "vps_vui_present_flag" );
+  if (uiCode)
+#endif
+  {
+    while ( m_pcBitstream->getNumBitsRead() % 8 != 0 )
+    {
+      READ_FLAG( uiCode, "vps_vui_alignment_bit_equal_to_one"); assert(uiCode == 1);
+    }
+    parseVPSVUI(vps);
+  }
+  else
+  {
+    // set default values for VPS VUI
+    defaultVPSVUI( vps );
+  }
+}
+
+Void TDecCavlc::defaultVPSExtension( TComVPS* vps )
+{
+  // set default parameters when they are not present
+  Int i, j;
+
+  // When layer_id_in_nuh[ i ] is not present, the value is inferred to be equal to i.
+  for(i = 0; i < vps->getMaxLayers(); i++)
+  {
+    vps->setLayerIdInNuh(i, i);
+    vps->setLayerIdxInVps(vps->getLayerIdInNuh(i), i);
+  }
+
+  // When not present, sub_layers_vps_max_minus1[ i ] is inferred to be equal to vps_max_sub_layers_minus1.
+  for( i = 0; i < vps->getMaxLayers(); i++)
+  {
+    vps->setMaxTSLayersMinus1(i, vps->getMaxTLayers()-1);
+  }
+
+  // When not present, max_tid_il_ref_pics_plus1[ i ][ j ] is inferred to be equal to 7.
+  for( i = 0; i < vps->getMaxLayers() - 1; i++ )
+  {
+    for( j = i + 1; j < vps->getMaxLayers(); j++ )
+    {
+      vps->setMaxTidIlRefPicsPlus1(i, j, 7);
+    }
+  }
+
+  // When not present, the value of num_add_olss is inferred to be equal to 0.
+  // NumOutputLayerSets = num_add_olss + NumLayerSets
+  vps->setNumOutputLayerSets( vps->getNumLayerSets() );
+
+  // For i in the range of 0 to NumOutputLayerSets-1, inclusive, the variable LayerSetIdxForOutputLayerSet[ i ] is derived as specified in the following: 
+  // LayerSetIdxForOutputLayerSet[ i ] = ( i <= vps_number_layer_sets_minus1 ) ? i : layer_set_idx_for_ols_minus1[ i ] + 1
+  for( i = 1; i < vps->getNumOutputLayerSets(); i++ )
+  {
+    vps->setOutputLayerSetIdx( i, i );
+    Int lsIdx = vps->getOutputLayerSetIdx(i);
+
+    for( j = 0; j < vps->getNumLayersInIdList(lsIdx); j++ )
+    {
+      vps->setOutputLayerFlag(i, j, 1);
+    }
+  }
+
+#if NECESSARY_LAYER_FLAG
+  // Default output layer set
+  // The value of NumLayersInIdList[ 0 ] is set equal to 1 and the value of LayerSetLayerIdList[ 0 ][ 0 ] is set equal to 0.
+  vps->setOutputLayerSetIdx(0, 0);
+
+  // The value of output_layer_flag[ 0 ][ 0 ] is inferred to be equal to 1.
+  vps->setOutputLayerFlag(0, 0, true);
+
+  vps->deriveNecessaryLayerFlag(0);
+#endif
+
+  // The value of sub_layer_dpb_info_present_flag[ i ][ 0 ] for any possible value of i is inferred to be equal to 1
+  // When not present, the value of sub_layer_dpb_info_present_flag[ i ][ j ] for j greater than 0 and any possible value of i, is inferred to be equal to be equal to 0.
+  for( i = 1; i < vps->getNumOutputLayerSets(); i++ )
+  {
+    vps->setSubLayerDpbInfoPresentFlag( i, 0, true );
+  }
+
+  // When not present, the value of vps_num_rep_formats_minus1 is inferred to be equal to MaxLayersMinus1.
+  vps->setVpsNumRepFormats( vps->getMaxLayers() );
+
+  // When not present, the value of rep_format_idx_present_flag is inferred to be equal to 0
+  vps->setRepFormatIdxPresentFlag( false );
+
+  if( !vps->getRepFormatIdxPresentFlag() )
+  {
+    // When not present, the value of vps_rep_format_idx[ i ] is inferred to be equal to Min(i, vps_num_rep_formats_minus1). 
+    for(i = 1; i < vps->getMaxLayers(); i++)
+    {
+      vps->setVpsRepFormatIdx( i, min( (Int)i, vps->getVpsNumRepFormats() - 1 ) );
+    }
+  }
+
+#if P0297_VPS_POC_LSB_ALIGNED_FLAG
+  vps->setVpsPocLsbAlignedFlag(false);
+#endif
+
+#if O0062_POC_LSB_NOT_PRESENT_FLAG
+  // When not present, poc_lsb_not_present_flag[ i ] is inferred to be equal to 0.
+  for(i = 1; i< vps->getMaxLayers(); i++)
+  {
+    vps->setPocLsbNotPresentFlag(i, 0);
+  }
+#endif
+
+  // set default values for VPS VUI
+  defaultVPSVUI( vps );
+}
+
+Void TDecCavlc::defaultVPSVUI( TComVPS* vps )
+{
+  // When not present, the value of all_layers_idr_aligned_flag is inferred to be equal to 0.
+  vps->setCrossLayerIrapAlignFlag( false );
+
+#if M0040_ADAPTIVE_RESOLUTION_CHANGE
+  // When single_layer_for_non_irap_flag is not present, it is inferred to be equal to 0.
+  vps->setSingleLayerForNonIrapFlag( false );
+#endif
+
+#if HIGHER_LAYER_IRAP_SKIP_FLAG
+  // When higher_layer_irap_skip_flag is not present it is inferred to be equal to 0
+  vps->setHigherLayerIrapSkipFlag( false );
+#endif
+}
+
+#if REPN_FORMAT_IN_VPS
+Void  TDecCavlc::parseRepFormat( RepFormat *repFormat, RepFormat *repFormatPrev )
+{
+  UInt uiCode;
+#if REPN_FORMAT_CONTROL_FLAG  
+  READ_CODE( 16, uiCode, "pic_width_vps_in_luma_samples" );        repFormat->setPicWidthVpsInLumaSamples ( uiCode );
+  READ_CODE( 16, uiCode, "pic_height_vps_in_luma_samples" );       repFormat->setPicHeightVpsInLumaSamples( uiCode );
+  READ_FLAG( uiCode, "chroma_and_bit_depth_vps_present_flag" );    repFormat->setChromaAndBitDepthVpsPresentFlag( uiCode ? true : false ); 
+
+  if( !repFormatPrev )
+  {
+    // The value of chroma_and_bit_depth_vps_present_flag of the first rep_format( ) syntax structure in the VPS shall be equal to 1
+    assert( repFormat->getChromaAndBitDepthVpsPresentFlag() );
+  }
+
+  if( repFormat->getChromaAndBitDepthVpsPresentFlag() )
+  {
+    READ_CODE( 2, uiCode, "chroma_format_vps_idc" );
+#if AUXILIARY_PICTURES
+    repFormat->setChromaFormatVpsIdc( ChromaFormat(uiCode) );
+#else
+    repFormat->setChromaFormatVpsIdc( uiCode );
+#endif
+
+    if( repFormat->getChromaFormatVpsIdc() == 3 )
+    {
+      READ_FLAG( uiCode, "separate_colour_plane_vps_flag" );       repFormat->setSeparateColourPlaneVpsFlag( uiCode ? true : false );
+    }
+
+    READ_CODE( 4, uiCode, "bit_depth_vps_luma_minus8" );           repFormat->setBitDepthVpsLuma  ( uiCode + 8 );
+    READ_CODE( 4, uiCode, "bit_depth_vps_chroma_minus8" );         repFormat->setBitDepthVpsChroma( uiCode + 8 );
+  }
+  else if( repFormatPrev )
+  {
+    // chroma_and_bit_depth_vps_present_flag equal to 0 specifies that the syntax elements, chroma_format_vps_idc, separate_colour_plane_vps_flag, bit_depth_vps_luma_minus8, and 
+    // bit_depth_vps_chroma_minus8 are not present and inferred from the previous rep_format( ) syntax structure in the VPS.
+
+    repFormat->setChromaFormatVpsIdc        ( repFormatPrev->getChromaFormatVpsIdc() );
+    repFormat->setSeparateColourPlaneVpsFlag( repFormatPrev->getSeparateColourPlaneVpsFlag() );
+    repFormat->setBitDepthVpsLuma           ( repFormatPrev->getBitDepthVpsLuma() );
+    repFormat->setBitDepthVpsChroma         ( repFormatPrev->getBitDepthVpsChroma() );
+  }
+
+#else 
+#if AUXILIARY_PICTURES
+  READ_CODE( 2, uiCode, "chroma_format_idc" );               repFormat->setChromaFormatVpsIdc( ChromaFormat(uiCode) );
+#else
+  READ_CODE( 2, uiCode, "chroma_format_idc" );               repFormat->setChromaFormatVpsIdc( uiCode );
+#endif
+
+  if( repFormat->getChromaFormatVpsIdc() == 3 )
+  {
+    READ_FLAG( uiCode, "separate_colour_plane_flag");        repFormat->setSeparateColourPlaneVpsFlag(uiCode ? true : false);
+  }
+
+  READ_CODE ( 16, uiCode, "pic_width_in_luma_samples" );     repFormat->setPicWidthVpsInLumaSamples ( uiCode );
+  READ_CODE ( 16, uiCode, "pic_height_in_luma_samples" );    repFormat->setPicHeightVpsInLumaSamples( uiCode );
+
+  READ_CODE( 4, uiCode, "bit_depth_luma_minus8" );           repFormat->setBitDepthVpsLuma  ( uiCode + 8 );
+  READ_CODE( 4, uiCode, "bit_depth_chroma_minus8" );         repFormat->setBitDepthVpsChroma( uiCode + 8 );
+#endif 
+
+#if R0156_CONF_WINDOW_IN_REP_FORMAT
+  READ_FLAG( uiCode, "conformance_window_vps_flag" );
+  if( uiCode != 0) 
+  {
+    Window &conf = repFormat->getConformanceWindowVps();
+    READ_UVLC( uiCode, "conf_win_vps_left_offset" );         conf.setWindowLeftOffset  ( uiCode );
+    READ_UVLC( uiCode, "conf_win_vps_right_offset" );        conf.setWindowRightOffset ( uiCode );
+    READ_UVLC( uiCode, "conf_win_vps_top_offset" );          conf.setWindowTopOffset   ( uiCode );
+    READ_UVLC( uiCode, "conf_win_vps_bottom_offset" );       conf.setWindowBottomOffset( uiCode );
+  }
+#endif
+}
+#endif
+#if VPS_DPB_SIZE_TABLE
+Void TDecCavlc::parseVpsDpbSizeTable( TComVPS *vps )
+{
+  UInt uiCode;
+#if SUB_LAYERS_IN_LAYER_SET
+  vps->calculateMaxSLInLayerSets();
+#else
+#if DPB_PARAMS_MAXTLAYERS
+#if BITRATE_PICRATE_SIGNALLING
+  Int * MaxSubLayersInLayerSetMinus1 = new Int[vps->getNumLayerSets()];
+  for(Int i = 0; i < vps->getNumLayerSets(); i++)
+#else
+  Int * MaxSubLayersInLayerSetMinus1 = new Int[vps->getNumOutputLayerSets()];
+  for(Int i = 1; i < vps->getNumOutputLayerSets(); i++)
+#endif
+  {
+    UInt maxSLMinus1 = 0;
+#if CHANGE_NUMSUBDPB_IDX
+    Int optLsIdx = vps->getOutputLayerSetIdx( i );
+#else
+    Int optLsIdx = i;
+#endif
+#if BITRATE_PICRATE_SIGNALLING
+    optLsIdx = i;
+#endif
+    for(Int k = 0; k < vps->getNumLayersInIdList(optLsIdx); k++ ) {
+      Int  lId = vps->getLayerSetLayerIdList(optLsIdx, k);
+      maxSLMinus1 = max(maxSLMinus1, vps->getMaxTSLayersMinus1(vps->getLayerIdxInVps(lId)));
+    }
+    MaxSubLayersInLayerSetMinus1[ i ] = maxSLMinus1;
+#if BITRATE_PICRATE_SIGNALLING
+    vps->setMaxSLayersInLayerSetMinus1(i,MaxSubLayersInLayerSetMinus1[ i ]);
+#endif
+  }
+#endif
+#endif
+
+#if !RESOLUTION_BASED_DPB
+  vps->deriveNumberOfSubDpbs();
+#endif
+  for(Int i = 1; i < vps->getNumOutputLayerSets(); i++)
+  {
+#if CHANGE_NUMSUBDPB_IDX
+    Int layerSetIdxForOutputLayerSet = vps->getOutputLayerSetIdx( i );
+#endif
+    READ_FLAG( uiCode, "sub_layer_flag_info_present_flag[i]");  vps->setSubLayerFlagInfoPresentFlag( i, uiCode ? true : false );
+#if SUB_LAYERS_IN_LAYER_SET
+    for(Int j = 0; j <= vps->getMaxSLayersInLayerSetMinus1( layerSetIdxForOutputLayerSet ); j++)
+#else
+#if DPB_PARAMS_MAXTLAYERS
+#if BITRATE_PICRATE_SIGNALLING
+    for(Int j = 0; j <= MaxSubLayersInLayerSetMinus1[ vps->getOutputLayerSetIdx( i ) ]; j++)
+#else
+    for(Int j = 0; j <= MaxSubLayersInLayerSetMinus1[ i ]; j++)
+#endif
+#else
+    for(Int j = 0; j <= vps->getMaxTLayers(); j++)
+#endif
+#endif
+    {
+      if( j > 0 && vps->getSubLayerFlagInfoPresentFlag(i) )
+      {
+        READ_FLAG( uiCode, "sub_layer_dpb_info_present_flag[i]");  vps->setSubLayerDpbInfoPresentFlag( i, j, uiCode ? true : false);
+      }
+      else
+      {
+        if( j == 0 )  // Always signal for the first sub-layer
+        {
+          vps->setSubLayerDpbInfoPresentFlag( i, j, true );
+        }
+        else // if (j != 0) && !vps->getSubLayerFlagInfoPresentFlag(i)
+        {
+          vps->setSubLayerDpbInfoPresentFlag( i, j, false );
+        }
+      }
+      if( vps->getSubLayerDpbInfoPresentFlag(i, j) )  // If sub-layer DPB information is present
+      {
+#if CHANGE_NUMSUBDPB_IDX
+        for(Int k = 0; k < vps->getNumSubDpbs(layerSetIdxForOutputLayerSet); k++)
+#else
+        for(Int k = 0; k < vps->getNumSubDpbs(i); k++)
+#endif
+        {
+#if DPB_INTERNAL_BL_SIG
+            uiCode=0;
+
+#if VPS_FIX_TO_MATCH_SPEC
+        if( vps->getNecessaryLayerFlag(i, k) && ( vps->getBaseLayerInternalFlag() || vps->getLayerSetLayerIdList(layerSetIdxForOutputLayerSet, k) ) )
+#else
+        if(vps->getBaseLayerInternalFlag() || ( vps->getLayerSetLayerIdList(layerSetIdxForOutputLayerSet, k) !=  0 ) )
+#endif
+#endif
+          READ_UVLC( uiCode, "max_vps_dec_pic_buffering_minus1[i][k][j]" ); vps->setMaxVpsDecPicBufferingMinus1( i, k, j, uiCode );
+        }
+        READ_UVLC( uiCode, "max_vps_num_reorder_pics[i][j]" );              vps->setMaxVpsNumReorderPics( i, j, uiCode);
+#if RESOLUTION_BASED_DPB
+        if( vps->getNumSubDpbs(layerSetIdxForOutputLayerSet) != vps->getNumLayersInIdList( layerSetIdxForOutputLayerSet ) )  
+        {
+          for(Int k = 0; k < vps->getNumLayersInIdList( layerSetIdxForOutputLayerSet ); k++)
+          {
+            READ_UVLC( uiCode, "max_vps_layer_dec_pic_buff_minus1[i][k][j]" ); vps->setMaxVpsLayerDecPicBuffMinus1( i, k, j, uiCode);
+          }
+        }
+        else  // vps->getNumSubDpbs(layerSetIdxForOutputLayerSet) == vps->getNumLayersInIdList( layerSetIdxForOutputLayerSet )
+        {          
+          for(Int k = 0; k < vps->getNumLayersInIdList( layerSetIdxForOutputLayerSet ); k++)
+          {
+            vps->setMaxVpsLayerDecPicBuffMinus1( i, k, j, vps->getMaxVpsDecPicBufferingMinus1( i, k, j));
+          }
+        }
+#endif
+        READ_UVLC( uiCode, "max_vps_latency_increase_plus1[i][j]" );        vps->setMaxVpsLatencyIncreasePlus1( i, j, uiCode);
+      }
+    }
+    for(Int j = vps->getMaxTLayers(); j < MAX_TLAYER; j++)
+    {
+      vps->setSubLayerDpbInfoPresentFlag( i, j, false );
+    }
+  }
+
+#if !SUB_LAYERS_IN_LAYER_SET
+#if BITRATE_PICRATE_SIGNALLING
+  if( MaxSubLayersInLayerSetMinus1 )
+  {
+    delete [] MaxSubLayersInLayerSetMinus1;
+  }
+#endif
+#endif
+
+  // Infer values when not signalled
+  for(Int i = 1; i < vps->getNumOutputLayerSets(); i++)
+  {
+    Int layerSetIdxForOutputLayerSet = vps->getOutputLayerSetIdx( i );
+    for(Int j = 0; j < MAX_TLAYER; j++)
+    {
+      if( !vps->getSubLayerDpbInfoPresentFlag(i, j) )  // If sub-layer DPB information is NOT present
+      {
+#if RESOLUTION_BASED_DPB
+        for(Int k = 0; k < vps->getNumSubDpbs(layerSetIdxForOutputLayerSet); k++)
+#else
+        for(Int k = 0; k < vps->getNumLayersInIdList( layerSetIdxForOutputLayerSet ); k++)
+#endif
+        {
+          vps->setMaxVpsDecPicBufferingMinus1( i, k, j, vps->getMaxVpsDecPicBufferingMinus1( i, k, j - 1 ) );
+        }
+        vps->setMaxVpsNumReorderPics( i, j, vps->getMaxVpsNumReorderPics( i, j - 1) );
+#if RESOLUTION_BASED_DPB
+        for(Int k = 0; k < vps->getNumLayersInIdList( layerSetIdxForOutputLayerSet ); k++)
+        {
+          vps->setMaxVpsLayerDecPicBuffMinus1( i, k, j, vps->getMaxVpsLayerDecPicBuffMinus1( i, k, j - 1));
+        }
+#endif
+        vps->setMaxVpsLatencyIncreasePlus1( i, j, vps->getMaxVpsLatencyIncreasePlus1( i, j - 1 ) );
+      }
+    }
+  }
+}
+#endif
+
+Void TDecCavlc::parseVPSVUI(TComVPS *vps)
+{
+  UInt i,j;
+  UInt uiCode;
+#if O0223_PICTURE_TYPES_ALIGN_FLAG
+  READ_FLAG(uiCode, "cross_layer_pic_type_aligned_flag" );
+  vps->setCrossLayerPictureTypeAlignFlag(uiCode);
+  if (!uiCode) 
+  {
+#endif
+#if IRAP_ALIGN_FLAG_IN_VPS_VUI
+    READ_FLAG(uiCode, "cross_layer_irap_aligned_flag" );
+    vps->setCrossLayerIrapAlignFlag(uiCode);
+#endif
+#if O0223_PICTURE_TYPES_ALIGN_FLAG
+  }
+  else
+  {
+    vps->setCrossLayerIrapAlignFlag(true);
+  }
+#endif
+#if P0068_CROSS_LAYER_ALIGNED_IDR_ONLY_FOR_IRAP_FLAG
+  if( uiCode )
+  {
+    READ_FLAG( uiCode, "all_layers_idr_aligned_flag" );
+    vps->setCrossLayerAlignedIdrOnlyFlag(uiCode);
+  }
+#endif
+
+  READ_FLAG( uiCode,        "bit_rate_present_vps_flag" );  vps->setBitRatePresentVpsFlag( uiCode ? true : false );
+  READ_FLAG( uiCode,        "pic_rate_present_vps_flag" );  vps->setPicRatePresentVpsFlag( uiCode ? true : false );
+
+#if SIGNALLING_BITRATE_PICRATE_FIX
+  if ( vps->getBitRatePresentVpsFlag() || vps->getPicRatePresentVpsFlag() )
+  {
+    for( i = vps->getBaseLayerInternalFlag() ? 0 : 1; i < vps->getNumLayerSets(); i++ )
+    {
+      for( j = 0; j <= vps->getMaxSLayersInLayerSetMinus1( i ); j++ ) 
+      {
+        if( vps->getBitRatePresentVpsFlag() )
+        {
+          READ_FLAG( uiCode, "bit_rate_present_flag[i][j]" ); vps->setBitRatePresentFlag( i, j, uiCode ? true : false );            
+        }
+        if( vps->getPicRatePresentVpsFlag( )  )
+        {
+          READ_FLAG( uiCode, "pic_rate_present_flag[i][j]" ); vps->setPicRatePresentFlag( i, j, uiCode ? true : false );
+        }
+        if( vps->getBitRatePresentFlag( i, j ) )
+        {
+          READ_CODE( 16, uiCode, "avg_bit_rate" ); vps->setAvgBitRate( i, j, uiCode );
+          READ_CODE( 16, uiCode, "max_bit_rate" ); vps->setMaxBitRate( i, j, uiCode );
+        }
+        else
+        {
+          vps->setAvgBitRate( i, j, 0 );
+          vps->setMaxBitRate( i, j, 0 );
+        }
+        if( vps->getPicRatePresentFlag( i, j ) )
+        {
+          READ_CODE( 2,  uiCode, "constant_pic_rate_idc" ); vps->setConstPicRateIdc( i, j, uiCode );
+          READ_CODE( 16, uiCode, "avg_pic_rate" );          vps->setAvgPicRate( i, j, uiCode );
+        }
+        else
+        {
+          vps->setConstPicRateIdc( i, j, 0 );
+          vps->setAvgPicRate( i, j, 0 );
+        }
+      }
+    }
+  }
+#else
+  Bool parseFlag = vps->getBitRatePresentVpsFlag() || vps->getPicRatePresentVpsFlag();
+
+#if Q0078_ADD_LAYER_SETS
+#if R0227_BR_PR_ADD_LAYER_SET
+  for( i = 0; i < vps->getNumLayerSets(); i++ )
+#else
+  for( i = 0; i <= vps->getVpsNumLayerSetsMinus1(); i++ )
+#endif
+#else
+  for( i = 0; i < vps->getNumLayerSets(); i++ )
+#endif
+  {
+#if BITRATE_PICRATE_SIGNALLING
+    for( j = 0; j <= vps->getMaxSLayersInLayerSetMinus1(i); j++ )
+#else
+    for( j = 0; j < vps->getMaxTLayers(); j++ )
+#endif
+    {
+      if( parseFlag && vps->getBitRatePresentVpsFlag() )
+      {
+        READ_FLAG( uiCode,        "bit_rate_present_flag[i][j]" );  vps->setBitRatePresentFlag( i, j, uiCode ? true : false );
+      }
+      else
+      {
+        vps->setBitRatePresentFlag( i, j, false );
+      }
+      if( parseFlag && vps->getPicRatePresentVpsFlag() )
+      {
+        READ_FLAG( uiCode,        "pic_rate_present_flag[i][j]" );  vps->setPicRatePresentFlag( i, j, uiCode ? true : false );
+      }
+      else
+      {
+        vps->setPicRatePresentFlag( i, j, false );
+      }
+      if( parseFlag && vps->getBitRatePresentFlag(i, j) )
+      {
+        READ_CODE( 16, uiCode,    "avg_bit_rate[i][j]" ); vps->setAvgBitRate( i, j, uiCode );
+        READ_CODE( 16, uiCode,    "max_bit_rate[i][j]" ); vps->setMaxBitRate( i, j, uiCode );
+      }
+      else
+      {
+        vps->setAvgBitRate( i, j, 0 );
+        vps->setMaxBitRate( i, j, 0 );
+      }
+      if( parseFlag && vps->getPicRatePresentFlag(i, j) )
+      {
+        READ_CODE( 2 , uiCode,    "constant_pic_rate_idc[i][j]" ); vps->setConstPicRateIdc( i, j, uiCode );
+        READ_CODE( 16, uiCode,    "avg_pic_rate[i][j]"          ); vps->setAvgPicRate( i, j, uiCode );
+      }
+      else
+      {
+        vps->setConstPicRateIdc( i, j, 0 );
+        vps->setAvgPicRate     ( i, j, 0 );
+      }
+    }
+  }
+#endif
+#if VPS_VUI_VIDEO_SIGNAL_MOVE
+  READ_FLAG( uiCode, "video_signal_info_idx_present_flag" ); vps->setVideoSigPresentVpsFlag( uiCode == 1 );
+  if (vps->getVideoSigPresentVpsFlag())
+  {
+    READ_CODE(4, uiCode, "vps_num_video_signal_info_minus1" ); vps->setNumVideoSignalInfo(uiCode + 1);
+  }
+  else
+  {
+#if VPS_VUI_VST_PARAMS
+    vps->setNumVideoSignalInfo(vps->getMaxLayers() - vps->getBaseLayerInternalFlag() ? 0 : 1);
+#else
+    vps->setNumVideoSignalInfo(vps->getMaxLayers());
+#endif
+  }
+
+  for(i = 0; i < vps->getNumVideoSignalInfo(); i++)
+  {
+    READ_CODE(3, uiCode, "video_vps_format" ); vps->setVideoVPSFormat(i,uiCode);
+    READ_FLAG(uiCode, "video_full_range_vps_flag" ); vps->setVideoFullRangeVpsFlag(i,uiCode);
+    READ_CODE(8, uiCode, "color_primaries_vps" ); vps->setColorPrimaries(i,uiCode);
+    READ_CODE(8, uiCode, "transfer_characteristics_vps" ); vps->setTransCharacter(i,uiCode);
+    READ_CODE(8, uiCode, "matrix_coeffs_vps" );vps->setMaxtrixCoeff(i,uiCode);
+  }
+#if VPS_VUI_VST_PARAMS
+  if( vps->getVideoSigPresentVpsFlag() && vps->getNumVideoSignalInfo() > 1 )
+  {
+    for(i = vps->getBaseLayerInternalFlag() ? 0 : 1; i < vps->getMaxLayers(); i++)
+    {
+      READ_CODE(4, uiCode, "vps_video_signal_info_idx" ); vps->setVideoSignalInfoIdx(i, uiCode);
+    }
+  }
+  else if ( !vps->getVideoSigPresentVpsFlag() )
+  {
+    for(i = vps->getBaseLayerInternalFlag() ? 0 : 1; i < vps->getMaxLayers(); i++)
+    {
+      vps->setVideoSignalInfoIdx( i, i );
+    }
+  }
+  else // ( vps->getNumVideoSignalInfo() = 0 )
+  {
+    for(i = vps->getBaseLayerInternalFlag() ? 0 : 1; i < vps->getMaxLayers(); i++)
+    {
+      vps->setVideoSignalInfoIdx( i, 0 );
+    }
+  }
+#else
+  if(!vps->getVideoSigPresentVpsFlag())
+  {
+    for (i=0; i < vps->getMaxLayers(); i++)
+    {
+      vps->setVideoSignalInfoIdx(i,i);
+    }
+  }
+  else {
+    vps->setVideoSignalInfoIdx(0,0);
+    if (vps->getNumVideoSignalInfo() > 1 )
+    {
+      for (i=1; i < vps->getMaxLayers(); i++)
+        READ_CODE(4, uiCode, "vps_video_signal_info_idx" ); vps->setVideoSignalInfoIdx(i, uiCode);
+    }
+    else {
+      for (i=1; i < vps->getMaxLayers(); i++)
+      {
+        vps->setVideoSignalInfoIdx(i,0);
+      }
+    }
+  }
+#endif
+#endif 
+#if VPS_VUI_TILES_NOT_IN_USE__FLAG
+  UInt layerIdx;
+  READ_FLAG( uiCode, "tiles_not_in_use_flag" ); vps->setTilesNotInUseFlag(uiCode == 1);
+  if (!uiCode)
+  {
+#if VPS_FIX_TO_MATCH_SPEC
+    for( i = vps->getBaseLayerInternalFlag() ? 0 : 1; i < vps->getMaxLayers(); i++ )
+#else
+    for (i = 0; i < vps->getMaxLayers(); i++)
+#endif
+    {
+      READ_FLAG( uiCode, "tiles_in_use_flag[ i ]" ); vps->setTilesInUseFlag(i, (uiCode == 1));
+      if (uiCode)
+      {
+        READ_FLAG( uiCode, "loop_filter_not_across_tiles_flag[ i ]" ); vps->setLoopFilterNotAcrossTilesFlag(i, (uiCode == 1));
+      }
+      else
+      {
+        vps->setLoopFilterNotAcrossTilesFlag(i, false);
+      }
+    }
+#endif
+
+#if VPS_FIX_TO_MATCH_SPEC
+      for( i = vps->getBaseLayerInternalFlag() ? 1 : 2; i < vps->getMaxLayers(); i++ )
+#else
+      for (i = 1; i < vps->getMaxLayers(); i++)
+#endif
+    {
+      for(j = 0; j < vps->getNumDirectRefLayers(vps->getLayerIdInNuh(i)); j++)
+      {
+#if VPS_VUI_TILES_NOT_IN_USE__FLAG
+        layerIdx = vps->getLayerIdxInVps(vps->getRefLayerId(vps->getLayerIdInNuh(i), j));
+        if (vps->getTilesInUseFlag(i) && vps->getTilesInUseFlag(layerIdx)) {
+          READ_FLAG( uiCode, "tile_boundaries_aligned_flag[i][j]" ); vps->setTileBoundariesAlignedFlag(i,j,(uiCode == 1));
+        }
+#else
+        READ_FLAG( uiCode, "tile_boundaries_aligned_flag[i][j]" ); vps->setTileBoundariesAlignedFlag(i,j,(uiCode == 1));
+#endif
+      }
+    }
+#if VPS_VUI_TILES_NOT_IN_USE__FLAG
+  }
+#endif
+#if VPS_VUI_WPP_NOT_IN_USE__FLAG
+  READ_FLAG( uiCode, "wpp_not_in_use_flag" ); vps->setWppNotInUseFlag(uiCode == 1);
+  if (!uiCode)
+  {
+#if VPS_FIX_TO_MATCH_SPEC
+      for (i = vps->getBaseLayerInternalFlag() ? 0 : 1; i < vps->getMaxLayers(); i++)
+#else
+      for (i = 0; i < vps->getMaxLayers(); i++)
+#endif
+    {
+      READ_FLAG( uiCode, "wpp_in_use_flag[ i ]" ); vps->setWppInUseFlag(i, (uiCode == 1));
+    }
+  }
+#endif
+
+#if O0109_O0199_FLAGS_TO_VUI
+#if M0040_ADAPTIVE_RESOLUTION_CHANGE
+  READ_FLAG(uiCode, "single_layer_for_non_irap_flag" ); vps->setSingleLayerForNonIrapFlag(uiCode == 1 ? true : false);
+#endif
+#if HIGHER_LAYER_IRAP_SKIP_FLAG
+  READ_FLAG(uiCode, "higher_layer_irap_skip_flag" ); vps->setHigherLayerIrapSkipFlag(uiCode == 1 ? true : false);
+
+  // When single_layer_for_non_irap_flag is equal to 0, higher_layer_irap_skip_flag shall be equal to 0
+  if( !vps->getSingleLayerForNonIrapFlag() )
+  {
+    assert( !vps->getHigherLayerIrapSkipFlag() );
+  }
+#endif
+#endif
+#if P0312_VERT_PHASE_ADJ
+  READ_FLAG( uiCode, "vps_vui_vert_phase_in_use_flag" ); vps->setVpsVuiVertPhaseInUseFlag(uiCode);
+#endif
+#if N0160_VUI_EXT_ILP_REF
+  READ_FLAG( uiCode, "ilp_restricted_ref_layers_flag" ); vps->setIlpRestrictedRefLayersFlag( uiCode == 1 );
+  if( vps->getIlpRestrictedRefLayersFlag())
+  {
+    for(i = 1; i < vps->getMaxLayers(); i++)
+    {
+      for(j = 0; j < vps->getNumDirectRefLayers(vps->getLayerIdInNuh(i)); j++)
+      {
+#if VPS_FIX_TO_MATCH_SPEC
+        if( vps->getBaseLayerInternalFlag() || vps->getRefLayerId(vps->getLayerIdInNuh(i), j) )
+        {
+#endif
+          READ_UVLC( uiCode, "min_spatial_segment_offset_plus1[i][j]" ); vps->setMinSpatialSegmentOffsetPlus1( i, j, uiCode );
+          if( vps->getMinSpatialSegmentOffsetPlus1(i,j ) > 0 )
+          {
+            READ_FLAG( uiCode, "ctu_based_offset_enabled_flag[i][j]"); vps->setCtuBasedOffsetEnabledFlag(i, j, uiCode == 1 );
+            if(vps->getCtuBasedOffsetEnabledFlag(i,j))
+            {
+              READ_UVLC( uiCode, "min_horizontal_ctu_offset_plus1[i][j]"); vps->setMinHorizontalCtuOffsetPlus1( i,j, uiCode );
+            }
+          }
+#if VPS_FIX_TO_MATCH_SPEC
+        }
+#endif
+      }
+    }
+  }
+#endif
+#if VPS_VUI_VIDEO_SIGNAL
+#if VPS_VUI_VIDEO_SIGNAL_MOVE
+#else
+  READ_FLAG( uiCode, "video_signal_info_idx_present_flag" ); vps->setVideoSigPresentVpsFlag( uiCode == 1 );
+  if (vps->getVideoSigPresentVpsFlag())
+  {
+    READ_CODE(4, uiCode, "vps_num_video_signal_info_minus1" ); vps->setNumVideoSignalInfo(uiCode + 1);
+  }
+  else
+  {
+    vps->setNumVideoSignalInfo(vps->getMaxLayers());
+  }
+
+
+  for(i = 0; i < vps->getNumVideoSignalInfo(); i++)
+  {
+    READ_CODE(3, uiCode, "video_vps_format" ); vps->setVideoVPSFormat(i,uiCode);
+    READ_FLAG(uiCode, "video_full_range_vps_flag" ); vps->setVideoFullRangeVpsFlag(i,uiCode);
+    READ_CODE(8, uiCode, "color_primaries_vps" ); vps->setColorPrimaries(i,uiCode);
+    READ_CODE(8, uiCode, "transfer_characteristics_vps" ); vps->setTransCharacter(i,uiCode);
+    READ_CODE(8, uiCode, "matrix_coeffs_vps" );vps->setMaxtrixCoeff(i,uiCode);
+  }
+  if(!vps->getVideoSigPresentVpsFlag())
+  {
+    for (i=0; i < vps->getMaxLayers(); i++)
+    {
+      vps->setVideoSignalInfoIdx(i,i);
+    }
+  }
+  else {
+    vps->setVideoSignalInfoIdx(0,0);
+    if (vps->getNumVideoSignalInfo() > 1 )
+    {
+      for (i=1; i < vps->getMaxLayers(); i++)
+        READ_CODE(4, uiCode, "vps_video_signal_info_idx" ); vps->setVideoSignalInfoIdx(i, uiCode);
+    }
+    else {
+      for (i=1; i < vps->getMaxLayers(); i++)
+      {
+        vps->setVideoSignalInfoIdx(i,0);
+      }
+    }
+  }
+#endif 
+#endif
+
+#if O0164_MULTI_LAYER_HRD
+  READ_FLAG(uiCode, "vps_vui_bsp_hrd_present_flag" ); vps->setVpsVuiBspHrdPresentFlag(uiCode);
+  if (vps->getVpsVuiBspHrdPresentFlag())
+  {
+#if VPS_VUI_BSP_HRD_PARAMS
+    parseVpsVuiBspHrdParams(vps);
+#else
+#if R0227_VUI_BSP_HRD_FLAG
+    assert (vps->getTimingInfo()->getTimingInfoPresentFlag() == 1);
+#endif
+    READ_UVLC( uiCode, "vps_num_bsp_hrd_parameters_minus1" ); vps->setVpsNumBspHrdParametersMinus1(uiCode);
+    vps->createBspHrdParamBuffer(vps->getVpsNumBspHrdParametersMinus1() + 1);
+    for( i = 0; i <= vps->getVpsNumBspHrdParametersMinus1(); i++ )
+    {
+      if( i > 0 )
+      {
+        READ_FLAG( uiCode, "bsp_cprms_present_flag[i]" ); vps->setBspCprmsPresentFlag(i, uiCode);
+      }
+      parseHrdParameters(vps->getBspHrd(i), i==0 ? 1 : vps->getBspCprmsPresentFlag(i), vps->getMaxTLayers()-1);
+    }
+#if Q0078_ADD_LAYER_SETS
+    for (UInt h = 1; h <= vps->getVpsNumLayerSetsMinus1(); h++)
+#else
+    for( UInt h = 1; h <= (vps->getNumLayerSets()-1); h++ )
+#endif
+    {
+      READ_UVLC( uiCode, "num_bitstream_partitions[i]"); vps->setNumBitstreamPartitions(h, uiCode);
+#if HRD_BPB
+      Int chkPart=0;
+#endif
+      for( i = 0; i < vps->getNumBitstreamPartitions(h); i++ )
+      {
+        for( j = 0; j <= (vps->getMaxLayers()-1); j++ )
+        {
+          if( vps->getLayerIdIncludedFlag(h, j) )
+          {
+            READ_FLAG( uiCode, "layer_in_bsp_flag[h][i][j]" ); vps->setLayerInBspFlag(h, i, j, uiCode);
+          }
+        }
+#if HRD_BPB
+        chkPart+=vps->getLayerInBspFlag(h, i, j);
+#endif
+      }
+#if HRD_BPB
+      assert(chkPart<=1);
+#endif
+#if HRD_BPB
+      if(vps->getNumBitstreamPartitions(h)==1)
+      {
+        Int chkPartition1=0; Int chkPartition2=0;
+        for( j = 0; j <= (vps->getMaxLayers()-1); j++ )
+        {
+          if( vps->getLayerIdIncludedFlag(h, j) )
+          {
+            chkPartition1+=vps->getLayerInBspFlag(h, 0, j);
+            chkPartition2++;
+          }
+        }
+        assert(chkPartition1!=chkPartition2);
+      }
+#endif
+      if (vps->getNumBitstreamPartitions(h))
+      {
+#if Q0182_MULTI_LAYER_HRD_UPDATE
+        READ_UVLC( uiCode, "num_bsp_sched_combinations_minus1[h]"); vps->setNumBspSchedCombinations(h, uiCode + 1);
+#else
+        READ_UVLC( uiCode, "num_bsp_sched_combinations[h]"); vps->setNumBspSchedCombinations(h, uiCode);
+#endif
+        for( i = 0; i < vps->getNumBspSchedCombinations(h); i++ )
+        {
+          for( j = 0; j < vps->getNumBitstreamPartitions(h); j++ )
+          {
+            READ_UVLC( uiCode, "bsp_comb_hrd_idx[h][i][j]"); vps->setBspCombHrdIdx(h, i, j, uiCode);
+#if HRD_BPB
+            assert(uiCode <= vps->getVpsNumBspHrdParametersMinus1());
+#endif
+
+            READ_UVLC( uiCode, "bsp_comb_sched_idx[h][i][j]"); vps->setBspCombSchedIdx(h, i, j, uiCode);
+#if HRD_BPB
+            assert(uiCode <= vps->getBspHrdParamBufferCpbCntMinus1(uiCode,vps->getMaxTLayers()-1));
+#endif
+          }
+        }
+      }
+    }
+#endif
+  }
+#endif
+#if P0182_VPS_VUI_PS_FLAG
+  for(i = 1; i < vps->getMaxLayers(); i++)
+  {
+    if (vps->getNumRefLayers(vps->getLayerIdInNuh(i)) == 0)
+    {
+      READ_FLAG( uiCode, "base_layer_parameter_set_compatibility_flag" ); 
+      vps->setBaseLayerPSCompatibilityFlag( i, uiCode );
+    }
+    else
+    {
+      vps->setBaseLayerPSCompatibilityFlag( i, 0 );
+    }
+  }
+#endif
+}
+
+Void TDecCavlc::parseSPSExtension( TComSPS* pcSPS )
+{
+  UInt uiCode;
+  // more syntax elements to be parsed here
+
+  READ_FLAG( uiCode, "inter_view_mv_vert_constraint_flag" );
+  // Vertical MV component restriction is not used in SHVC CTC
+  assert( uiCode == 0 );
+
+#if !MOVE_SCALED_OFFSET_TO_PPS
+  if( pcSPS->getLayerId() > 0 )
+  {
+    Int iCode;
+    READ_UVLC( uiCode,      "num_scaled_ref_layer_offsets" ); pcSPS->setNumScaledRefLayerOffsets(uiCode);
+    for(Int i = 0; i < pcSPS->getNumScaledRefLayerOffsets(); i++)
+    {
+      Window& scaledWindow = pcSPS->getScaledRefLayerWindow(i);
+#if O0098_SCALED_REF_LAYER_ID
+      READ_CODE( 6,  uiCode,  "scaled_ref_layer_id" );       pcSPS->setScaledRefLayerId( i, uiCode );
+#endif
+      READ_SVLC( iCode, "scaled_ref_layer_left_offset" );    scaledWindow.setWindowLeftOffset  (iCode << 1);
+      READ_SVLC( iCode, "scaled_ref_layer_top_offset" );     scaledWindow.setWindowTopOffset   (iCode << 1);
+      READ_SVLC( iCode, "scaled_ref_layer_right_offset" );   scaledWindow.setWindowRightOffset (iCode << 1);
+      READ_SVLC( iCode, "scaled_ref_layer_bottom_offset" );  scaledWindow.setWindowBottomOffset(iCode << 1);
+#if P0312_VERT_PHASE_ADJ
+      READ_FLAG( uiCode, "vert_phase_position_enable_flag" ); scaledWindow.setVertPhasePositionEnableFlag(uiCode);  pcSPS->setVertPhasePositionEnableFlag( pcSPS->getScaledRefLayerId(i), uiCode);    
+#endif
+    }
+  }
+#endif
+}
+#endif
+
+#if Q0048_CGS_3D_ASYMLUT
+Void TDecCavlc::xParse3DAsymLUT( TCom3DAsymLUT * pc3DAsymLUT )
+{
+#if R0150_CGS_SIGNAL_CONSTRAINTS
+  UInt uiNumRefLayersM1;
+  READ_UVLC( uiNumRefLayersM1 , "num_cm_ref_layers_minus1" );
+  assert( uiNumRefLayersM1 <= 61 );
+  for( UInt i = 0 ; i <= uiNumRefLayersM1 ; i++ )
+  {
+    UInt uiRefLayerId;
+    READ_CODE( 6 , uiRefLayerId , "cm_ref_layer_id" );
+    pc3DAsymLUT->addRefLayerId( uiRefLayerId );
+  }
+#endif
+  UInt uiCurOctantDepth , uiCurPartNumLog2 , uiInputBitDepthM8 , uiOutputBitDepthM8 , uiResQaunBit;
+#if R0300_CGS_RES_COEFF_CODING
+  UInt uiDeltaBits; 
+#endif 
+  READ_CODE( 2 , uiCurOctantDepth , "cm_octant_depth" ); 
+  READ_CODE( 2 , uiCurPartNumLog2 , "cm_y_part_num_log2" );     
+#if R0150_CGS_SIGNAL_CONSTRAINTS
+  UInt uiChromaInputBitDepthM8 , uiChromaOutputBitDepthM8;
+  READ_UVLC( uiInputBitDepthM8 , "cm_input_luma_bit_depth_minus8" );
+  READ_UVLC( uiChromaInputBitDepthM8 , "cm_input_chroma_bit_depth_minus8" );
+  READ_UVLC( uiOutputBitDepthM8 , "cm_output_luma_bit_depth_minus8" );
+  READ_UVLC( uiChromaOutputBitDepthM8 , "cm_output_chroma_bit_depth_minus8" );
+#else
+  READ_CODE( 3 , uiInputBitDepthM8 , "cm_input_bit_depth_minus8" );
+  Int iInputBitDepthCDelta;
+  READ_SVLC(iInputBitDepthCDelta, "cm_input_bit_depth_chroma delta");
+  READ_CODE( 3 , uiOutputBitDepthM8 , "cm_output_bit_depth_minus8" ); 
+  Int iOutputBitDepthCDelta;
+  READ_SVLC(iOutputBitDepthCDelta, "cm_output_bit_depth_chroma_delta");
+#endif
+  READ_CODE( 2 , uiResQaunBit , "cm_res_quant_bit" );
+#if R0300_CGS_RES_COEFF_CODING
+  READ_CODE( 2 , uiDeltaBits , "cm_flc_bits" );
+  pc3DAsymLUT->setDeltaBits(uiDeltaBits + 1);
+#endif
+
+#if R0151_CGS_3D_ASYMLUT_IMPROVE
+#if R0150_CGS_SIGNAL_CONSTRAINTS
+  Int nAdaptCThresholdU = 1 << ( uiChromaInputBitDepthM8 + 8 - 1 );
+  Int nAdaptCThresholdV = 1 << ( uiChromaInputBitDepthM8 + 8 - 1 );
+#else
+  Int nAdaptCThresholdU = 1 << ( uiInputBitDepthM8 + 8 + iInputBitDepthCDelta - 1 );
+  Int nAdaptCThresholdV = 1 << ( uiInputBitDepthM8 + 8 + iInputBitDepthCDelta - 1 );
+#endif
+  if( uiCurOctantDepth == 1 )
+  {
+    Int delta = 0;
+    READ_SVLC( delta , "cm_adapt_threshold_u_delta" );
+    nAdaptCThresholdU += delta;
+    READ_SVLC( delta , "cm_adapt_threshold_v_delta" );
+    nAdaptCThresholdV += delta;
+  }
+#endif
+  pc3DAsymLUT->destroy();
+  pc3DAsymLUT->create( uiCurOctantDepth , uiInputBitDepthM8 + 8 ,  
+#if R0150_CGS_SIGNAL_CONSTRAINTS
+    uiChromaInputBitDepthM8 + 8 ,
+#else
+    uiInputBitDepthM8 + 8 + iInputBitDepthCDelta, 
+#endif
+    uiOutputBitDepthM8 + 8 , 
+#if R0150_CGS_SIGNAL_CONSTRAINTS
+    uiChromaOutputBitDepthM8 + 8 ,
+#else
+    uiOutputBitDepthM8 + 8 + iOutputBitDepthCDelta ,
+#endif
+    uiCurPartNumLog2 
+#if R0151_CGS_3D_ASYMLUT_IMPROVE
+    , nAdaptCThresholdU , nAdaptCThresholdV 
+#endif    
+    );
+  pc3DAsymLUT->setResQuantBit( uiResQaunBit );
+
+#if R0164_CGS_LUT_BUGFIX_CHECK
+  pc3DAsymLUT->xInitCuboids();
+#endif
+  xParse3DAsymLUTOctant( pc3DAsymLUT , 0 , 0 , 0 , 0 , 1 << pc3DAsymLUT->getCurOctantDepth() );
+#if R0164_CGS_LUT_BUGFIX
+#if R0164_CGS_LUT_BUGFIX_CHECK
+  printf("============= Before 'xCuboidsFilledCheck()': ================\n");
+  pc3DAsymLUT->display();
+  pc3DAsymLUT->xCuboidsFilledCheck( false );
+  printf("============= After 'xCuboidsFilledCheck()': =================\n");
+  pc3DAsymLUT->display();
+#endif
+#endif
+}
+
+Void TDecCavlc::xParse3DAsymLUTOctant( TCom3DAsymLUT * pc3DAsymLUT , Int nDepth , Int yIdx , Int uIdx , Int vIdx , Int nLength )
+{
+  UInt uiOctantSplit = nDepth < pc3DAsymLUT->getCurOctantDepth();
+  if( nDepth < pc3DAsymLUT->getCurOctantDepth() )
+    READ_FLAG( uiOctantSplit , "split_octant_flag" );
+  Int nYPartNum = 1 << pc3DAsymLUT->getCurYPartNumLog2();
+  if( uiOctantSplit )
+  {
+    Int nHalfLength = nLength >> 1;
+    for( Int l = 0 ; l < 2 ; l++ )
+    {
+      for( Int m = 0 ; m < 2 ; m++ )
+      {
+        for( Int n = 0 ; n < 2 ; n++ )
+        {
+          xParse3DAsymLUTOctant( pc3DAsymLUT , nDepth + 1 , yIdx + l * nHalfLength * nYPartNum , uIdx + m * nHalfLength , vIdx + n * nHalfLength , nHalfLength );
+        }
+      }
+    }
+  }
+  else
+  {
+#if R0300_CGS_RES_COEFF_CODING
+    Int nFLCbits = pc3DAsymLUT->getMappingShift()-pc3DAsymLUT->getResQuantBit()-pc3DAsymLUT->getDeltaBits() ; 
+    nFLCbits = nFLCbits >= 0 ? nFLCbits:0;
+#endif
+    for( Int l = 0 ; l < nYPartNum ; l++ )
+    {
+#if R0164_CGS_LUT_BUGFIX
+      Int shift = pc3DAsymLUT->getCurOctantDepth() - nDepth ;
+#endif
+      for( Int nVertexIdx = 0 ; nVertexIdx < 4 ; nVertexIdx++ )
+      {
+        UInt uiCodeVertex = 0;
+        Int deltaY = 0 , deltaU = 0 , deltaV = 0;
+        READ_FLAG( uiCodeVertex , "coded_vertex_flag" );
+        if( uiCodeVertex )
+        {
+#if R0151_CGS_3D_ASYMLUT_IMPROVE
+#if R0300_CGS_RES_COEFF_CODING
+          xReadParam( deltaY, nFLCbits );
+          xReadParam( deltaU, nFLCbits );
+          xReadParam( deltaV, nFLCbits );
+#else
+          xReadParam( deltaY );
+          xReadParam( deltaU );
+          xReadParam( deltaV );
+#endif
+#else
+          READ_SVLC( deltaY , "resY" );
+          READ_SVLC( deltaU , "resU" );
+          READ_SVLC( deltaV , "resV" );
+#endif
+        }
+#if R0164_CGS_LUT_BUGFIX
+        pc3DAsymLUT->setCuboidVertexResTree( yIdx + (l<<shift) , uIdx , vIdx , nVertexIdx , deltaY , deltaU , deltaV );
+        for (Int m = 1; m < (1<<shift); m++) {
+          pc3DAsymLUT->setCuboidVertexResTree( yIdx + (l<<shift) + m , uIdx , vIdx , nVertexIdx , 0 , 0 , 0 );
+#if R0164_CGS_LUT_BUGFIX_CHECK
+          pc3DAsymLUT->xSetFilled( yIdx + (l<<shift) + m , uIdx , vIdx );
+#endif
+        }
+#else
+        pc3DAsymLUT->setCuboidVertexResTree( yIdx + l , uIdx , vIdx , nVertexIdx , deltaY , deltaU , deltaV );
+#endif
+      }
+#if R0164_CGS_LUT_BUGFIX_CHECK
+      pc3DAsymLUT->xSetExplicit( yIdx + (l<<shift) , uIdx , vIdx );
+#endif
+    }
+#if R0164_CGS_LUT_BUGFIX
+    for ( Int u=0 ; u<nLength ; u++ ) {
+      for ( Int v=0 ; v<nLength ; v++ ) {
+        if ( u!=0 || v!=0 ) {
+          for ( Int y=0 ; y<nLength*nYPartNum ; y++ ) {
+            for( Int nVertexIdx = 0 ; nVertexIdx < 4 ; nVertexIdx++ )
+            {
+              pc3DAsymLUT->setCuboidVertexResTree( yIdx + y , uIdx + u , vIdx + v , nVertexIdx , 0 , 0 , 0 );
+#if R0164_CGS_LUT_BUGFIX_CHECK
+              pc3DAsymLUT->xSetFilled( yIdx + y , uIdx + u , vIdx + v );
+#endif
+            }
+          }
+        }
+      }
+    }
+#endif
+  }
+}
+
+#if R0151_CGS_3D_ASYMLUT_IMPROVE
+#if R0300_CGS_RES_COEFF_CODING
+Void TDecCavlc::xReadParam( Int& param, Int rParam )
+#else
+Void TDecCavlc::xReadParam( Int& param )
+#endif
+{
+#if !R0300_CGS_RES_COEFF_CODING
+  const UInt rParam = 7;
+#endif
+  UInt prefix;
+  UInt codeWord ;
+  UInt rSymbol;
+  UInt sign;
+
+  READ_UVLC( prefix, "quotient")  ;
+  READ_CODE (rParam, codeWord, "remainder");
+  rSymbol = (prefix<<rParam) + codeWord;
+
+  if(rSymbol)
+  {
+    READ_FLAG(sign, "sign");
+    param = sign ? -(Int)(rSymbol) : (Int)(rSymbol);
+  }
+  else param = 0;
+}
+#endif
+#if VPS_VUI_BSP_HRD_PARAMS
+Void TDecCavlc::parseVpsVuiBspHrdParams( TComVPS *vps )
+{
+  UInt uiCode;
+  assert (vps->getTimingInfo()->getTimingInfoPresentFlag() == 1);
+  READ_UVLC( uiCode, "vps_num_add_hrd_params" ); vps->setVpsNumAddHrdParams(uiCode);
+  vps->createBspHrdParamBuffer(vps->getVpsNumAddHrdParams()); // Also allocates m_cprmsAddPresentFlag and m_numSubLayerHrdMinus
+
+  for( Int i = vps->getNumHrdParameters(), j = 0; i < vps->getNumHrdParameters() + vps->getVpsNumAddHrdParams(); i++, j++ ) // j = i - vps->getNumHrdParameters()
+  {
+    if( i > 0 )
+    {
+      READ_FLAG( uiCode, "cprms_add_present_flag[i]" );   vps->setCprmsAddPresentFlag(j, uiCode ? true : false);
+    }
+    else
+    {
+      // i == 0
+      if( vps->getNumHrdParameters() == 0 )
+      {
+        vps->setCprmsAddPresentFlag(0, true);
+      }
+    }
+    READ_UVLC( uiCode, "num_sub_layer_hrd_minus1[i]" ); vps->setNumSubLayerHrdMinus1(j, uiCode );
+    assert( uiCode <= vps->getMaxTLayers() - 1 );
+    
+    parseHrdParameters( vps->getBspHrd(j), vps->getCprmsAddPresentFlag(j), vps->getNumSubLayerHrdMinus1(j) );
+    if( i > 0 && !vps->getCprmsAddPresentFlag(i) )
+    {
+      // Copy common information parameters
+      if( i == vps->getNumHrdParameters() )
+      {
+        vps->getBspHrd(j)->copyCommonInformation( vps->getHrdParameters( vps->getNumHrdParameters() - 1 ) );
+      }
+      else
+      {
+        vps->getBspHrd(j)->copyCommonInformation( vps->getBspHrd( j - 1 ) );
+      }
+    }
+  }
+#if VPS_FIX_TO_MATCH_SPEC
+  if( vps->getNumHrdParameters() + vps->getVpsNumAddHrdParams() > 0 )
+  {
+#endif
+    for (Int h = 1; h < vps->getNumOutputLayerSets(); h++)
+    {
+      Int lsIdx = vps->getOutputLayerSetIdx(h);
+      READ_UVLC(uiCode, "num_signalled_partitioning_schemes[h]"); vps->setNumSignalledPartitioningSchemes(h, uiCode);
+#if VPS_FIX_TO_MATCH_SPEC
+      for (Int j = 1; j < vps->getNumSignalledPartitioningSchemes(h) + 1; j++)
+#else
+      for (Int j = 0; j < vps->getNumSignalledPartitioningSchemes(h); j++)
+#endif
+      {
+        READ_UVLC(uiCode, "num_partitions_in_scheme_minus1[h][j]"); vps->setNumPartitionsInSchemeMinus1(h, j, uiCode);
+        for (Int k = 0; k <= vps->getNumPartitionsInSchemeMinus1(h, j); k++)
+        {
+          for (Int r = 0; r < vps->getNumLayersInIdList(lsIdx); r++)
+          {
+            READ_FLAG(uiCode, "layer_included_in_partition_flag[h][j][k][r]"); vps->setLayerIncludedInPartitionFlag(h, j, k, r, uiCode ? true : false);
+          }
+        }
+      }
+      for (Int i = 0; i < vps->getNumSignalledPartitioningSchemes(h) + 1; i++)
+      {
+        for (Int t = 0; t <= vps->getMaxSLayersInLayerSetMinus1(lsIdx); t++)
+        {
+          READ_UVLC(uiCode, "num_bsp_schedules_minus1[h][i][t]");              vps->setNumBspSchedulesMinus1(h, i, t, uiCode);
+          for (Int j = 0; j <= vps->getNumBspSchedulesMinus1(h, i, t); j++)
+          {
+#if VPS_FIX_TO_MATCH_SPEC
+            for( Int k = 0; k <= vps->getNumPartitionsInSchemeMinus1(h, i); k++ )
+#else
+            for (Int k = 0; k < vps->getNumPartitionsInSchemeMinus1(h, i); k++)
+#endif
+            {
+#if VPS_FIX_TO_MATCH_SPEC
+              if( vps->getNumHrdParameters() + vps->getVpsNumAddHrdParams() > 1 )
+              {
+                Int numBits = 1;
+                while ((1 << numBits) < (vps->getNumHrdParameters() + vps->getVpsNumAddHrdParams()))
+                {
+                  numBits++;
+                }
+                READ_CODE(numBits, uiCode, "bsp_comb_hrd_idx[h][i][t][j][k]");      vps->setBspHrdIdx(h, i, t, j, k, uiCode);
+              }
+#else
+              READ_UVLC(uiCode, "bsp_comb_hrd_idx[h][i][t][j][k]");      vps->setBspHrdIdx(h, i, t, j, k, uiCode);
+#endif
+              READ_UVLC(uiCode, "bsp_comb_sched_idx[h][i][t][j][k]");    vps->setBspSchedIdx(h, i, t, j, k, uiCode);
+            }
+          }
+        }
+      }
+
+      // To be done: Check each layer included in not more than one BSP in every partitioning scheme,
+      // and other related checks associated with layers in bitstream partitions.
+
+    }
+#if VPS_FIX_TO_MATCH_SPEC
+  }
+#endif
+}
+#endif
+#endif
+//! \}
+
Index: /tags/SHM-9.0/source/Lib/TLibDecoder/TDecCAVLC.h
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibDecoder/TDecCAVLC.h	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibDecoder/TDecCAVLC.h	(revision 1088)
@@ -0,0 +1,173 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     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"
+
+#if Q0048_CGS_3D_ASYMLUT
+class TCom3DAsymLUT;
+#endif
+//! \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);
+
+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          ( class TComTU &rTu, const ComponentID compID, const Bool lowestLevel );
+  Void  parseQtRootCbf      ( UInt uiAbsPartIdx, UInt& uiQtRootCbf );
+  Void  parseVPS            ( TComVPS* pcVPS );
+#if !SVC_EXTENSION
+  Void  parseSPS            ( TComSPS* pcSPS );
+  Void  parsePPS            ( TComPPS* pcPPS );
+#endif
+  Void  parseVUI            ( TComVUI* pcVUI, TComSPS* pcSPS );
+  Void  parseSEI            ( SEIMessages& );
+  Void  parsePTL            ( TComPTL *rpcPTL, Bool profilePresentFlag, Int maxNumSubLayersMinus1 );
+  Void  parseProfileTier    (ProfileTierLevel *ptl);
+  Void  parseHrdParameters  (TComHRD *hrd, Bool cprms_present_flag, UInt tempLevelHigh);
+  Void  parseSliceHeader    ( TComSlice* pcSlice, ParameterSetManagerDecoder *parameterSetManager);
+  Void  parseTerminatingBit ( UInt& ruiBit );
+  Void  parseRemainingBytes ( Bool noTrailingBytesExpected );
+
+  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 );
+  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 parseCrossComponentPrediction( class TComTU &rTu, ComponentID compID );
+
+  Void parseDeltaQP         ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+  Void parseChromaQpAdjustment( TComDataCU* cu, UInt absPartIdx, UInt depth);
+
+  Void parseCoeffNxN        ( class TComTU &rTu, ComponentID compID );
+
+  Void parseTransformSkipFlags ( class TComTU &rTu, ComponentID component );
+
+  Void parseIPCMInfo        ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth);
+
+  Void xParsePredWeightTable ( TComSlice* pcSlice );
+  Void  parseScalingList     ( TComScalingList* scalingList );
+  Void xDecodeScalingList    ( TComScalingList *scalingList, UInt sizeId, UInt listId);
+
+  Void  parseExplicitRdpcmMode( TComTU &rTu, ComponentID compID );
+
+protected:
+  Bool  xMoreRbspData();
+
+#if SVC_EXTENSION
+public:
+  Void  parseVPSExtension   ( TComVPS* pcVPS );
+  Void  defaultVPSExtension ( TComVPS* pcVPS );
+  Void  parseVPSVUI         ( TComVPS* pcVPS );
+  Void  defaultVPSVUI       ( TComVPS* pcVPS );
+#if REPN_FORMAT_IN_VPS
+  Void  parseRepFormat      ( RepFormat *repFormat, RepFormat *repFormatPrev );
+#endif
+#if VPS_DPB_SIZE_TABLE
+  Void  parseVpsDpbSizeTable( TComVPS *vps );
+#endif
+#if VPS_VUI_BSP_HRD_PARAMS
+  Void  parseVpsVuiBspHrdParams( TComVPS *vps );
+#endif
+#if SPS_DPB_PARAMS
+  Void  parseSPS            ( TComSPS* pcSPS ); // it should be removed after macro clean up
+#else
+  Void  parseSPS            ( TComSPS* pcSPS, ParameterSetManagerDecoder *parameterSetManager );
+#endif
+  Void  parseSPSExtension    ( TComSPS* pcSPS );
+#if Q0048_CGS_3D_ASYMLUT
+  Void  parsePPS            ( TComPPS* pcPPS, TCom3DAsymLUT * pc3DAsymLUT , Int nLayerID );
+#else
+  Void  parsePPS            ( TComPPS* pcPPS );
+#endif
+
+protected:
+#if Q0048_CGS_3D_ASYMLUT
+  Void xParse3DAsymLUT( TCom3DAsymLUT * pc3DAsymLUT );
+  Void xParse3DAsymLUTOctant( TCom3DAsymLUT * pc3DAsymLUT , Int nDepth , Int yIdx , Int uIdx , Int vIdx , Int nLength );
+#if R0151_CGS_3D_ASYMLUT_IMPROVE
+#if R0300_CGS_RES_COEFF_CODING
+  Void xReadParam( Int& param, Int flc_bits );
+#else
+  Void xReadParam( Int& param );
+#endif
+#endif
+#endif
+#endif //SVC_EXTENSION
+
+};
+
+//! \}
+
+#endif // !defined(AFX_TDECCAVLC_H__9732DD64_59B0_4A41_B29E_1A5B18821EAD__INCLUDED_)
Index: /tags/SHM-9.0/source/Lib/TLibDecoder/TDecCu.cpp
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibDecoder/TDecCu.cpp	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibDecoder/TDecCu.cpp	(revision 1088)
@@ -0,0 +1,871 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TDecCu.cpp
+    \brief    CU decoder class
+*/
+
+#include "TDecCu.h"
+#include "TLibCommon/TComTU.h"
+#if SVC_EXTENSION
+#include "TDecTop.h"
+#endif
+
+
+//! \ingroup TLibDecoder
+//! \{
+
+// ====================================================================================================================
+// Constructor / destructor / create / destroy
+// ====================================================================================================================
+
+TDecCu::TDecCu()
+{
+  m_ppcYuvResi = NULL;
+  m_ppcYuvReco = NULL;
+  m_ppcCU      = NULL;
+}
+
+TDecCu::~TDecCu()
+{
+}
+
+#if SVC_EXTENSION
+Void TDecCu::init(TDecTop** ppcDecTop, TDecEntropy* pcEntropyDecoder, TComTrQuant* pcTrQuant, TComPrediction* pcPrediction, UInt layerId)
+{
+  m_pcEntropyDecoder  = pcEntropyDecoder;
+  m_pcTrQuant         = pcTrQuant;
+  m_pcPrediction      = pcPrediction; 
+  m_ppcTDecTop = ppcDecTop;
+  m_layerId = layerId; 
+
+  for ( UInt ui = 0; ui < m_uiMaxDepth-1; ui++ )
+  {
+    m_ppcCU     [ui]->setLayerId(layerId);
+  }
+  
+#if LAYER_CTB
+  memcpy(g_auiLayerZscanToRaster[m_layerId], g_auiZscanToRaster, sizeof( g_auiZscanToRaster ) );
+  memcpy(g_auiLayerRasterToZscan[m_layerId], g_auiRasterToZscan, sizeof( g_auiRasterToZscan ) );
+  memcpy(g_auiLayerRasterToPelX[m_layerId],  g_auiRasterToPelX,  sizeof( g_auiRasterToPelX ) );
+  memcpy(g_auiLayerRasterToPelY[m_layerId],  g_auiRasterToPelY,  sizeof( g_auiRasterToPelY ) );
+#endif
+}
+#else
+Void TDecCu::init( TDecEntropy* pcEntropyDecoder, TComTrQuant* pcTrQuant, TComPrediction* pcPrediction)
+{
+  m_pcEntropyDecoder  = pcEntropyDecoder;
+  m_pcTrQuant         = pcTrQuant;
+  m_pcPrediction      = pcPrediction;
+}
+#endif
+
+/**
+ \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, ChromaFormat chromaFormatIDC )
+{
+  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, chromaFormatIDC );
+    m_ppcYuvReco[ui] = new TComYuv;    m_ppcYuvReco[ui]->create( uiWidth, uiHeight, chromaFormatIDC );
+    m_ppcCU     [ui] = new TComDataCU; m_ppcCU     [ui]->create( chromaFormatIDC, uiNumPartitions, uiWidth, uiHeight, true, uiMaxWidth >> (m_uiMaxDepth - 1) );
+  }
+
+  m_bDecodeDQP = false;
+  m_IsChromaQpAdjCoded = 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::decodeCtu( TComDataCU* pCtu, Bool& isLastCtuOfSliceSegment )
+{
+  if ( pCtu->getSlice()->getPPS()->getUseDQP() )
+  {
+    setdQPFlag(true);
+  }
+
+  if ( pCtu->getSlice()->getUseChromaQpAdj() )
+  {
+    setIsChromaQpAdjCoded(true);
+  }
+
+#if SVC_EXTENSION
+  pCtu->setLayerId(m_layerId);
+#endif
+
+  // start from the top level CU
+  xDecodeCU( pCtu, 0, 0, isLastCtuOfSliceSegment);
+}
+
+/** \param    pcCU        pointer of CU data
+ */
+Void TDecCu::decompressCtu( TComDataCU* pCtu )
+{
+  xDecompressCU( pCtu, 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 uiIsLastCtuOfSliceSegment;
+
+  if (pcCU->isLastSubCUOfCtu(uiAbsPartIdx))
+  {
+    m_pcEntropyDecoder->decodeTerminatingBit( uiIsLastCtuOfSliceSegment );
+  }
+  else
+  {
+    uiIsLastCtuOfSliceSegment=0;
+  }
+
+  return uiIsLastCtuOfSliceSegment>0;
+}
+
+/** decode CU block recursively
+ * \param pcCU
+ * \param uiAbsPartIdx
+ * \param uiDepth
+ * \returns Void
+ */
+
+Void TDecCu::xDecodeCU( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, Bool &isLastCtuOfSliceSegment)
+{
+  TComPic* pcPic = pcCU->getPic();
+  UInt uiCurNumParts    = pcPic->getNumPartitionsInCtu() >> (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;
+
+  TComSlice * pcSlice = pcCU->getPic()->getSlice(pcCU->getPic()->getCurrSliceIdx());
+#if REPN_FORMAT_IN_VPS
+  if( ( uiRPelX < pcSlice->getPicWidthInLumaSamples() ) && ( uiBPelY < pcSlice->getPicHeightInLumaSamples() ) )
+#else
+  if( ( uiRPelX < pcSlice->getSPS()->getPicWidthInLumaSamples() ) && ( uiBPelY < pcSlice->getSPS()->getPicHeightInLumaSamples() ) )
+#endif
+  {
+    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
+    }
+
+    if( (g_uiMaxCUWidth>>uiDepth) == pcCU->getSlice()->getPPS()->getMinCuChromaQpAdjSize() && pcCU->getSlice()->getUseChromaQpAdj() )
+    {
+      setIsChromaQpAdjCoded(true);
+    }
+
+    for ( UInt uiPartUnitIdx = 0; uiPartUnitIdx < 4; uiPartUnitIdx++ )
+    {
+      uiLPelX   = pcCU->getCUPelX() + g_auiRasterToPelX[ g_auiZscanToRaster[uiIdx] ];
+      uiTPelY   = pcCU->getCUPelY() + g_auiRasterToPelY[ g_auiZscanToRaster[uiIdx] ];
+
+#if REPN_FORMAT_IN_VPS
+      if ( !isLastCtuOfSliceSegment && ( uiLPelX < pcCU->getSlice()->getPicWidthInLumaSamples() ) && ( uiTPelY < pcCU->getSlice()->getPicHeightInLumaSamples() ) )
+#else
+      if ( !isLastCtuOfSliceSegment && ( uiLPelX < pcCU->getSlice()->getSPS()->getPicWidthInLumaSamples() ) && ( uiTPelY < pcCU->getSlice()->getSPS()->getPicHeightInLumaSamples() ) )
+#endif
+      {
+        xDecodeCU( pcCU, uiIdx, uiDepth+1, isLastCtuOfSliceSegment );
+      }
+      else
+      {
+        pcCU->setOutsideCUPart( uiIdx, uiDepth+1 );
+      }
+
+      uiIdx += uiQNumParts;
+    }
+    if( (g_uiMaxCUWidth>>uiDepth) == pcCU->getSlice()->getPPS()->getMinCuDQPSize() && pcCU->getSlice()->getPPS()->getUseDQP())
+    {
+      if ( getdQPFlag() )
+      {
+        UInt uiQPSrcPartIdx = uiAbsPartIdx;
+        pcCU->setQPSubParts( pcCU->getRefQP( uiQPSrcPartIdx ), uiAbsPartIdx, uiDepth ); // set QP to default QP
+      }
+    }
+    return;
+  }
+
+  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( (g_uiMaxCUWidth>>uiDepth) >= pcCU->getSlice()->getPPS()->getMinCuChromaQpAdjSize() && pcCU->getSlice()->getUseChromaQpAdj() )
+  {
+    setIsChromaQpAdjCoded(true);
+  }
+
+  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 HIGHER_LAYER_IRAP_SKIP_FLAG
+  if (pcCU->getSlice()->getVPS()->getHigherLayerIrapSkipFlag() && pcCU->getSlice()->getVPS()->getSingleLayerForNonIrapFlag() && pcCU->getLayerId() > 0)
+  {
+    Bool lowerLayerExist = false;
+    for(int i=0;i<pcCU->getLayerId();i++)
+    {
+      if(pcCU->getSlice()->getBaseColPic(pcCU->getSlice()->getInterLayerPredLayerIdc(i)))
+      {
+        lowerLayerExist = true;
+      }
+    }
+    if(lowerLayerExist)
+    {
+      assert(pcCU->isSkipped(uiAbsPartIdx));
+    }
+  }
+#endif
+ 
+  if( pcCU->isSkipped(uiAbsPartIdx) )
+  {
+    m_ppcCU[uiDepth]->copyInterPredInfoFrom( pcCU, uiAbsPartIdx, REF_PIC_LIST_0 );
+    m_ppcCU[uiDepth]->copyInterPredInfoFrom( pcCU, uiAbsPartIdx, REF_PIC_LIST_1 );
+    TComMvField cMvFieldNeighbours[MRG_MAX_NUM_CANDS << 1]; // double length for mv of both lists
+    UChar uhInterDirNeighbours[MRG_MAX_NUM_CANDS];
+    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);
+    m_ppcCU[uiDepth]->getInterMergeCandidates( 0, 0, cMvFieldNeighbours, uhInterDirNeighbours, numValidMergeCand, uiMergeIndex );
+    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 );
+      }
+    }
+    xFinishDecodeCU( pcCU, uiAbsPartIdx, uiDepth, isLastCtuOfSliceSegment );
+    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, isLastCtuOfSliceSegment );
+      return;
+    }
+  }
+
+  // prediction mode ( Intra : direction mode, Inter : Mv, reference idx )
+  m_pcEntropyDecoder->decodePredInfo( pcCU, uiAbsPartIdx, uiDepth, m_ppcCU[uiDepth]);
+
+  // Coefficient decoding
+  Bool bCodeDQP = getdQPFlag();
+  Bool isChromaQpAdjCoded = getIsChromaQpAdjCoded();
+  m_pcEntropyDecoder->decodeCoeff( pcCU, uiAbsPartIdx, uiDepth, bCodeDQP, isChromaQpAdjCoded );
+  setIsChromaQpAdjCoded( isChromaQpAdjCoded );
+  setdQPFlag( bCodeDQP );
+  xFinishDecodeCU( pcCU, uiAbsPartIdx, uiDepth, isLastCtuOfSliceSegment );
+}
+
+Void TDecCu::xFinishDecodeCU( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, Bool &isLastCtuOfSliceSegment)
+{
+  if(  pcCU->getSlice()->getPPS()->getUseDQP())
+  {
+    pcCU->setQPSubParts( getdQPFlag()?pcCU->getRefQP(uiAbsPartIdx):pcCU->getCodedQP(), uiAbsPartIdx, uiDepth ); // set QP
+  }
+
+  if (pcCU->getSlice()->getUseChromaQpAdj() && !getIsChromaQpAdjCoded())
+  {
+    pcCU->setChromaQpAdjSubParts( pcCU->getCodedChromaQpAdj(), uiAbsPartIdx, uiDepth ); // set QP
+  }
+
+  isLastCtuOfSliceSegment = xDecodeSliceEnd( pcCU, uiAbsPartIdx );
+}
+
+Void TDecCu::xDecompressCU( TComDataCU* pCtu, UInt uiAbsPartIdx,  UInt uiDepth )
+{
+  TComPic* pcPic = pCtu->getPic();
+
+  Bool bBoundary = false;
+  UInt uiLPelX   = pCtu->getCUPelX() + g_auiRasterToPelX[ g_auiZscanToRaster[uiAbsPartIdx] ];
+  UInt uiRPelX   = uiLPelX + (g_uiMaxCUWidth>>uiDepth)  - 1;
+  UInt uiTPelY   = pCtu->getCUPelY() + g_auiRasterToPelY[ g_auiZscanToRaster[uiAbsPartIdx] ];
+  UInt uiBPelY   = uiTPelY + (g_uiMaxCUHeight>>uiDepth) - 1;
+
+  TComSlice * pcSlice = pCtu->getPic()->getSlice(pCtu->getPic()->getCurrSliceIdx());
+
+#if REPN_FORMAT_IN_VPS
+  if( ( uiRPelX >= pcSlice->getPicWidthInLumaSamples() ) || ( uiBPelY >= pcSlice->getPicHeightInLumaSamples() ) )
+
+#else
+  if( ( uiRPelX >= pcSlice->getSPS()->getPicWidthInLumaSamples() ) || ( uiBPelY >= pcSlice->getSPS()->getPicHeightInLumaSamples() ) )
+#endif
+  {
+    bBoundary = true;
+  }
+
+  if( ( ( uiDepth < pCtu->getDepth( uiAbsPartIdx ) ) && ( uiDepth < g_uiMaxCUDepth - g_uiAddCUDepth ) ) || bBoundary )
+  {
+    UInt uiNextDepth = uiDepth + 1;
+    UInt uiQNumParts = pCtu->getTotalNumPart() >> (uiNextDepth<<1);
+    UInt uiIdx = uiAbsPartIdx;
+    for ( UInt uiPartIdx = 0; uiPartIdx < 4; uiPartIdx++ )
+    {
+      uiLPelX = pCtu->getCUPelX() + g_auiRasterToPelX[ g_auiZscanToRaster[uiIdx] ];
+      uiTPelY = pCtu->getCUPelY() + g_auiRasterToPelY[ g_auiZscanToRaster[uiIdx] ];
+
+#if REPN_FORMAT_IN_VPS
+      if( ( uiLPelX < pcSlice->getPicWidthInLumaSamples() ) && ( uiTPelY < pcSlice->getPicHeightInLumaSamples() ) )
+#else
+      if( ( uiLPelX < pcSlice->getSPS()->getPicWidthInLumaSamples() ) && ( uiTPelY < pcSlice->getSPS()->getPicHeightInLumaSamples() ) )
+#endif
+      {
+        xDecompressCU(pCtu, uiIdx, uiNextDepth );
+      }
+
+      uiIdx += uiQNumParts;
+    }
+    return;
+  }
+
+  // Residual reconstruction
+  m_ppcYuvResi[uiDepth]->clear();
+
+  m_ppcCU[uiDepth]->copySubCU( pCtu, uiAbsPartIdx, uiDepth );
+
+  switch( m_ppcCU[uiDepth]->getPredictionMode(0) )
+  {
+    case MODE_INTER:
+      xReconInter( m_ppcCU[uiDepth], uiDepth );
+      break;
+    case MODE_INTRA:
+      xReconIntraQT( m_ppcCU[uiDepth], uiDepth );
+      break;
+    default:
+      assert(0);
+      break;
+  }
+
+#ifdef DEBUG_STRING
+  const PredMode predMode=m_ppcCU[uiDepth]->getPredictionMode(0);
+  if (DebugOptionList::DebugString_Structure.getInt()&DebugStringGetPredModeMask(predMode))
+  {
+    PartSize eSize=m_ppcCU[uiDepth]->getPartitionSize(0);
+    std::ostream &ss(std::cout);
+
+    ss <<"###: " << (predMode==MODE_INTRA?"Intra   ":"Inter   ") << partSizeToString[eSize] << " CU at " << m_ppcCU[uiDepth]->getCUPelX() << ", " << m_ppcCU[uiDepth]->getCUPelY() << " width=" << UInt(m_ppcCU[uiDepth]->getWidth(0)) << std::endl;
+  }
+#endif
+
+  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] );
+
+#ifdef DEBUG_STRING
+  const Int debugPredModeMask=DebugStringGetPredModeMask(MODE_INTER);
+  if (DebugOptionList::DebugString_Pred.getInt()&debugPredModeMask) printBlockToStream(std::cout, "###inter-pred: ", *(m_ppcYuvReco[uiDepth]));
+#endif
+
+  // inter recon
+  xDecodeInterTexture( pcCU, uiDepth );
+
+#ifdef DEBUG_STRING
+  if (DebugOptionList::DebugString_Resi.getInt()&debugPredModeMask) printBlockToStream(std::cout, "###inter-resi: ", *(m_ppcYuvResi[uiDepth]));
+#endif
+
+  // clip for only non-zero cbp case
+  if  ( pcCU->getQtRootCbf( 0) )
+  {
+    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 ));
+  }
+#ifdef DEBUG_STRING
+  if (DebugOptionList::DebugString_Reco.getInt()&debugPredModeMask) printBlockToStream(std::cout, "###inter-reco: ", *(m_ppcYuvReco[uiDepth]));
+#endif
+
+}
+
+
+Void
+TDecCu::xIntraRecBlk(       TComYuv*    pcRecoYuv,
+                            TComYuv*    pcPredYuv,
+                            TComYuv*    pcResiYuv,
+                      const ComponentID compID,
+                            TComTU     &rTu)
+{
+  if (!rTu.ProcessComponentSection(compID)) return;
+  const Bool       bIsLuma = isLuma(compID);
+
+
+  TComDataCU *pcCU = rTu.getCU();
+  const UInt uiAbsPartIdx=rTu.GetAbsPartIdxTU();
+
+  const TComRectangle &tuRect  =rTu.getRect(compID);
+  const UInt uiWidth           = tuRect.width;
+  const UInt uiHeight          = tuRect.height;
+  const UInt uiStride          = pcRecoYuv->getStride (compID);
+        Pel* piPred            = pcPredYuv->getAddr( compID, uiAbsPartIdx );
+  const ChromaFormat chFmt     = rTu.GetChromaFormat();
+
+  if (uiWidth != uiHeight)
+  {
+    //------------------------------------------------
+
+    //split at current level if dividing into square sub-TUs
+
+    TComTURecurse subTURecurse(rTu, false, TComTU::VERTICAL_SPLIT, true, compID);
+
+    //recurse further
+    do
+    {
+      xIntraRecBlk(pcRecoYuv, pcPredYuv, pcResiYuv, compID, subTURecurse);
+    }
+    while (subTURecurse.nextSection(rTu));
+
+    //------------------------------------------------
+
+    return;
+  }
+
+  const UInt uiChPredMode  = pcCU->getIntraDir( toChannelType(compID), uiAbsPartIdx );
+  const UInt uiChCodedMode = (uiChPredMode==DM_CHROMA_IDX && !bIsLuma) ? pcCU->getIntraDir(CHANNEL_TYPE_LUMA, getChromasCorrespondingPULumaIdx(uiAbsPartIdx, chFmt)) : uiChPredMode;
+  const UInt uiChFinalMode = ((chFmt == CHROMA_422)       && !bIsLuma) ? g_chroma422IntraAngleMappingTable[uiChCodedMode] : uiChCodedMode;
+
+  //===== init availability pattern =====
+  Bool  bAboveAvail = false;
+  Bool  bLeftAvail  = false;
+
+  const Bool bUseFilteredPredictions=TComPrediction::filteringIntraReferenceSamples(compID, uiChFinalMode, uiWidth, uiHeight, chFmt, pcCU->getSlice()->getSPS()->getDisableIntraReferenceSmoothing());
+
+#ifdef DEBUG_STRING
+  std::ostream &ss(std::cout);
+#endif
+
+  DEBUG_STRING_NEW(sTemp)
+  m_pcPrediction->initAdiPatternChType( rTu, bAboveAvail, bLeftAvail, compID, bUseFilteredPredictions  DEBUG_STRING_PASS_INTO(sTemp) );
+
+
+  //===== get prediction signal =====
+
+  m_pcPrediction->predIntraAng( compID,   uiChFinalMode, 0 /* Decoder does not have an original image */, 0, piPred, uiStride, rTu, bAboveAvail, bLeftAvail, bUseFilteredPredictions );
+
+#ifdef DEBUG_STRING
+  ss << sTemp;
+#endif
+
+  //===== inverse transform =====
+  Pel*      piResi            = pcResiYuv->getAddr( compID, uiAbsPartIdx );
+  TCoeff*   pcCoeff           = pcCU->getCoeff(compID) + rTu.getCoefficientOffset(compID);//( uiNumCoeffInc * uiAbsPartIdx );
+
+  const QpParam cQP(*pcCU, compID);
+
+
+  DEBUG_STRING_NEW(sDebug);
+#ifdef DEBUG_STRING
+  const Int debugPredModeMask=DebugStringGetPredModeMask(MODE_INTRA);
+  std::string *psDebug=(DebugOptionList::DebugString_InvTran.getInt()&debugPredModeMask) ? &sDebug : 0;
+#endif
+
+  if (pcCU->getCbf(uiAbsPartIdx, compID, rTu.GetTransformDepthRel()) != 0)
+  {
+    m_pcTrQuant->invTransformNxN( rTu, compID, piResi, uiStride, pcCoeff, cQP DEBUG_STRING_PASS_INTO(psDebug) );
+  }
+  else
+  {
+    for (UInt y = 0; y < uiHeight; y++)
+      for (UInt x = 0; x < uiWidth; x++)
+      {
+        piResi[(y * uiStride) + x] = 0;
+      }
+  }
+
+#ifdef DEBUG_STRING
+  if (psDebug)
+    ss << (*psDebug);
+#endif
+
+  //===== reconstruction =====
+  const UInt uiRecIPredStride  = pcCU->getPic()->getPicYuvRec()->getStride(compID);
+
+  const Bool useCrossComponentPrediction = isChroma(compID) && (pcCU->getCrossComponentPredictionAlpha(uiAbsPartIdx, compID) != 0);
+  const Pel* pResiLuma  = pcResiYuv->getAddr( COMPONENT_Y, uiAbsPartIdx );
+  const Int  strideLuma = pcResiYuv->getStride( COMPONENT_Y );
+
+        Pel* pPred      = piPred;
+        Pel* pResi      = piResi;
+        Pel* pReco      = pcRecoYuv->getAddr( compID, uiAbsPartIdx );
+        Pel* pRecIPred  = pcCU->getPic()->getPicYuvRec()->getAddr( compID, pcCU->getCtuRsAddr(), pcCU->getZorderIdxInCtu() + uiAbsPartIdx );
+
+
+#ifdef DEBUG_STRING
+  const Bool bDebugPred=((DebugOptionList::DebugString_Pred.getInt()&debugPredModeMask) && DEBUG_STRING_CHANNEL_CONDITION(compID));
+  const Bool bDebugResi=((DebugOptionList::DebugString_Resi.getInt()&debugPredModeMask) && DEBUG_STRING_CHANNEL_CONDITION(compID));
+  const Bool bDebugReco=((DebugOptionList::DebugString_Reco.getInt()&debugPredModeMask) && DEBUG_STRING_CHANNEL_CONDITION(compID));
+  if (bDebugPred || bDebugResi || bDebugReco)
+    ss << "###: " << "CompID: " << compID << " pred mode (ch/fin): " << uiChPredMode << "/" << uiChFinalMode << " absPartIdx: " << rTu.GetAbsPartIdxTU() << std::endl;
+#endif
+
+#if O0043_BEST_EFFORT_DECODING
+  const Int bitDepthDelta = g_bitDepthInStream[toChannelType(compID)] - g_bitDepth[toChannelType(compID)];
+#endif
+  const Int clipbd = g_bitDepth[toChannelType(compID)];
+
+  if( useCrossComponentPrediction )
+  {
+    TComTrQuant::crossComponentPrediction( rTu, compID, pResiLuma, piResi, piResi, uiWidth, uiHeight, strideLuma, uiStride, uiStride, true );
+  }
+
+  for( UInt uiY = 0; uiY < uiHeight; uiY++ )
+  {
+#ifdef DEBUG_STRING
+    if (bDebugPred || bDebugResi || bDebugReco) ss << "###: ";
+
+    if (bDebugPred)
+    {
+      ss << " - pred: ";
+      for( UInt uiX = 0; uiX < uiWidth; uiX++ )
+      {
+        ss << pPred[ uiX ] << ", ";
+      }
+    }
+    if (bDebugResi) ss << " - resi: ";
+#endif
+
+    for( UInt uiX = 0; uiX < uiWidth; uiX++ )
+    {
+#ifdef DEBUG_STRING
+      if (bDebugResi)
+        ss << pResi[ uiX ] << ", ";
+#endif
+#if O0043_BEST_EFFORT_DECODING
+      pReco    [ uiX ] = ClipBD( rightShiftEvenRounding<Pel>(pPred[ uiX ] + pResi[ uiX ], bitDepthDelta), clipbd );
+#else
+      pReco    [ uiX ] = ClipBD( pPred[ uiX ] + pResi[ uiX ], clipbd );
+#endif
+      pRecIPred[ uiX ] = pReco[ uiX ];
+    }
+#ifdef DEBUG_STRING
+    if (bDebugReco)
+    {
+      ss << " - reco: ";
+      for( UInt uiX = 0; uiX < uiWidth; uiX++ )
+      {
+        ss << pReco[ uiX ] << ", ";
+      }
+    }
+
+    if (bDebugPred || bDebugResi || bDebugReco)
+      ss << "\n";
+#endif
+    pPred     += uiStride;
+    pResi     += uiStride;
+    pReco     += uiStride;
+    pRecIPred += uiRecIPredStride;
+  }
+}
+
+
+Void
+TDecCu::xReconIntraQT( TComDataCU* pcCU, UInt uiDepth )
+{
+  if (pcCU->getIPCMFlag(0))
+  {
+    xReconPCM( pcCU, uiDepth );
+    return;
+  }
+  const UInt numChType = pcCU->getPic()->getChromaFormat()!=CHROMA_400 ? 2 : 1;
+  for (UInt chType=CHANNEL_TYPE_LUMA; chType<numChType; chType++)
+  {
+    const ChannelType chanType=ChannelType(chType);
+    const Bool NxNPUHas4Parts = ::isChroma(chanType) ? enable4ChromaPUsInIntraNxNCU(pcCU->getPic()->getChromaFormat()) : true;
+    const UInt uiInitTrDepth = ( pcCU->getPartitionSize(0) != SIZE_2Nx2N && NxNPUHas4Parts ? 1 : 0 );
+
+    TComTURecurse tuRecurseCU(pcCU, 0);
+    TComTURecurse tuRecurseWithPU(tuRecurseCU, false, (uiInitTrDepth==0)?TComTU::DONT_SPLIT : TComTU::QUAD_SPLIT);
+
+    do
+    {
+      xIntraRecQT( m_ppcYuvReco[uiDepth], m_ppcYuvReco[uiDepth], m_ppcYuvResi[uiDepth], chanType, tuRecurseWithPU );
+    } while (tuRecurseWithPU.nextSection(tuRecurseCU));
+  }
+}
+
+
+
+/** 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::xIntraRecQT(TComYuv*    pcRecoYuv,
+                    TComYuv*    pcPredYuv,
+                    TComYuv*    pcResiYuv,
+                    const ChannelType chType,
+                    TComTU     &rTu)
+{
+  UInt uiTrDepth    = rTu.GetTransformDepthRel();
+  TComDataCU *pcCU  = rTu.getCU();
+  UInt uiAbsPartIdx = rTu.GetAbsPartIdxTU();
+  UInt uiTrMode     = pcCU->getTransformIdx( uiAbsPartIdx );
+  if( uiTrMode == uiTrDepth )
+  {
+    if (isLuma(chType))
+      xIntraRecBlk( pcRecoYuv, pcPredYuv, pcResiYuv, COMPONENT_Y,  rTu );
+    else
+    {
+      const UInt numValidComp=getNumberValidComponents(rTu.GetChromaFormat());
+      for(UInt compID=COMPONENT_Cb; compID<numValidComp; compID++)
+      {
+        xIntraRecBlk( pcRecoYuv, pcPredYuv, pcResiYuv, ComponentID(compID), rTu );
+      }
+    }
+  }
+  else
+  {
+    TComTURecurse tuRecurseChild(rTu, false);
+    do
+    {
+      xIntraRecQT( pcRecoYuv, pcPredYuv, pcResiYuv, chType, tuRecurseChild );
+    } while (tuRecurseChild.nextSection(rTu));
+  }
+}
+
+Void TDecCu::xCopyToPic( TComDataCU* pcCU, TComPic* pcPic, UInt uiZorderIdx, UInt uiDepth )
+{
+  UInt uiCtuRsAddr = pcCU->getCtuRsAddr();
+
+  m_ppcYuvReco[uiDepth]->copyToPicYuv  ( pcPic->getPicYuvRec (), uiCtuRsAddr, uiZorderIdx );
+
+  return;
+}
+
+Void TDecCu::xDecodeInterTexture ( TComDataCU* pcCU, UInt uiDepth )
+{
+
+  TComTURecurse tuRecur(pcCU, 0, uiDepth);
+
+  for(UInt ch=0; ch<pcCU->getPic()->getNumberValidComponents(); ch++)
+  {
+    const ComponentID compID=ComponentID(ch);
+    DEBUG_STRING_OUTPUT(std::cout, debug_reorder_data_inter_token[compID])
+
+    m_pcTrQuant->invRecurTransformNxN ( compID, m_ppcYuvResi[uiDepth], tuRecur );
+  }
+
+  DEBUG_STRING_OUTPUT(std::cout, debug_reorder_data_inter_token[MAX_NUM_COMPONENT])
+}
+
+/** 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, const UInt uiPartIdx, const Pel *piPCM, Pel* piReco, const UInt uiStride, const UInt uiWidth, const UInt uiHeight, const ComponentID compID)
+{
+        Pel* piPicReco         = pcCU->getPic()->getPicYuvRec()->getAddr(compID, pcCU->getCtuRsAddr(), pcCU->getZorderIdxInCtu()+uiPartIdx);
+  const UInt uiPicStride       = pcCU->getPic()->getPicYuvRec()->getStride(compID);
+  const UInt uiPcmLeftShiftBit = g_bitDepth[toChannelType(compID)] - pcCU->getSlice()->getSPS()->getPCMBitDepth(toChannelType(compID));
+
+  for(UInt uiY = 0; uiY < uiHeight; uiY++ )
+  {
+    for(UInt 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 )
+{
+  for (UInt ch=0; ch < pcCU->getPic()->getNumberValidComponents(); ch++)
+  {
+    const ComponentID compID = ComponentID(ch);
+    const UInt width  = (g_uiMaxCUWidth >>(uiDepth+m_ppcYuvResi[uiDepth]->getComponentScaleX(compID)));
+    const UInt height = (g_uiMaxCUHeight>>(uiDepth+m_ppcYuvResi[uiDepth]->getComponentScaleY(compID)));
+    const UInt stride = m_ppcYuvResi[uiDepth]->getStride(compID);
+    Pel * pPCMChannel = pcCU->getPCMSample(compID);
+    Pel * pRecChannel = m_ppcYuvReco[uiDepth]->getAddr(compID);
+    xDecodePCMTexture( pcCU, 0, pPCMChannel, pRecChannel, stride, width, height, compID );
+  }
+}
+
+/** 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)
+{
+  const ChromaFormat format = pCU->getPic()->getChromaFormat();
+  const UInt numValidComp=getNumberValidComponents(format);
+
+  for (UInt componentIndex = 0; componentIndex < numValidComp; componentIndex++)
+  {
+    const ComponentID component = ComponentID(componentIndex);
+
+    const UInt width  = g_uiMaxCUWidth  >> (depth + getComponentScaleX(component, format));
+    const UInt height = g_uiMaxCUHeight >> (depth + getComponentScaleY(component, format));
+
+    Pel *source      = m_ppcYuvReco[depth]->getAddr(component, 0, width);
+    Pel *destination = pCU->getPCMSample(component);
+
+    const UInt sourceStride = m_ppcYuvReco[depth]->getStride(component);
+
+    for (Int line = 0; line < height; line++)
+    {
+      for (Int column = 0; column < width; column++)
+      {
+        destination[column] = source[column];
+      }
+
+      source      += sourceStride;
+      destination += width;
+    }
+  }
+}
+
+//! \}
Index: /tags/SHM-9.0/source/Lib/TLibDecoder/TDecCu.h
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibDecoder/TDecCu.h	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibDecoder/TDecCu.h	(revision 1088)
@@ -0,0 +1,138 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TDecCu.h
+    \brief    CU decoder class (header)
+*/
+
+#ifndef __TDECCU__
+#define __TDECCU__
+
+#if _MSC_VER > 1000
+#pragma once
+#endif // _MSC_VER > 1000
+
+#include "TLibCommon/TComTrQuant.h"
+#include "TLibCommon/TComPrediction.h"
+#include "TDecEntropy.h"
+
+//! \ingroup TLibDecoder
+//! \{
+#if SVC_EXTENSION
+class TDecTop;
+#endif
+
+// ====================================================================================================================
+// 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;
+  Bool                m_IsChromaQpAdjCoded;
+
+#if SVC_EXTENSION
+  TDecTop**           m_ppcTDecTop;
+  UInt                m_layerId;   
+#endif
+  
+public:
+  TDecCu();
+  virtual ~TDecCu();
+
+  /// initialize access channels
+#if SVC_EXTENSION
+  Void  init                    ( TDecTop** ppcDecTop, TDecEntropy* pcEntropyDecoder, TComTrQuant* pcTrQuant, TComPrediction* pcPrediction, UInt layerId );
+#else
+  Void  init                    ( TDecEntropy* pcEntropyDecoder, TComTrQuant* pcTrQuant, TComPrediction* pcPrediction );
+#endif 
+  
+  /// create internal buffers
+  Void  create                  ( UInt uiMaxDepth, UInt uiMaxWidth, UInt uiMaxHeight, ChromaFormat chromaFormatIDC );
+
+  /// destroy internal buffers
+  Void  destroy                 ();
+
+  /// decode Ctu information
+  Void  decodeCtu               ( TComDataCU* pCtu, Bool &isLastCtuOfSliceSegment );
+
+  /// reconstruct Ctu information
+  Void  decompressCtu           ( TComDataCU* pCtu );
+ 
+#if SVC_EXTENSION
+  TDecTop*   getLayerDec        ( UInt layerId )  { return m_ppcTDecTop[layerId]; }
+#endif
+protected:
+
+  Void xDecodeCU                ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, Bool &isLastCtuOfSliceSegment);
+  Void xFinishDecodeCU          ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, Bool &isLastCtuOfSliceSegment);
+  Bool xDecodeSliceEnd          ( TComDataCU* pcCU, UInt uiAbsPartIdx );
+  Void xDecompressCU            ( TComDataCU* pCtu, UInt uiAbsPartIdx, UInt uiDepth );
+
+  Void xReconInter              ( TComDataCU* pcCU, UInt uiDepth );
+
+  Void xReconIntraQT            ( TComDataCU* pcCU, UInt uiDepth );
+  Void xIntraRecBlk             ( TComYuv* pcRecoYuv, TComYuv* pcPredYuv, TComYuv* pcResiYuv, const ComponentID component, TComTU &rTu );
+  Void xIntraRecQT              ( TComYuv* pcRecoYuv, TComYuv* pcPredYuv, TComYuv* pcResiYuv, const ChannelType chType, TComTU &rTu );
+
+  Void xReconPCM                ( TComDataCU* pcCU, UInt uiDepth );
+
+  Void xDecodeInterTexture      ( TComDataCU* pcCU, UInt uiDepth );
+  Void xDecodePCMTexture        ( TComDataCU* pcCU, const UInt uiPartIdx, const Pel *piPCM, Pel* piReco, const UInt uiStride, const UInt uiWidth, const UInt uiHeight, const ComponentID compID);
+
+  Void xCopyToPic               ( TComDataCU* pcCU, TComPic* pcPic, UInt uiZorderIdx, UInt uiDepth );
+
+  Bool getdQPFlag               ()                        { return m_bDecodeDQP;        }
+  Void setdQPFlag               ( Bool b )                { m_bDecodeDQP = b;           }
+  Bool getIsChromaQpAdjCoded    ()                        { return m_IsChromaQpAdjCoded;        }
+  Void setIsChromaQpAdjCoded    ( Bool b )                { m_IsChromaQpAdjCoded = b;           }
+
+  Void xFillPCMBuffer           (TComDataCU* pCU, UInt depth);
+};
+
+//! \}
+
+#endif
+
Index: /tags/SHM-9.0/source/Lib/TLibDecoder/TDecEntropy.cpp
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibDecoder/TDecEntropy.cpp	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibDecoder/TDecEntropy.cpp	(revision 1088)
@@ -0,0 +1,646 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TDecEntropy.cpp
+    \brief    entropy decoder class
+*/
+
+#include "TDecEntropy.h"
+#include "TLibCommon/TComTU.h"
+
+#if ENVIRONMENT_VARIABLE_DEBUG_AND_TEST
+#include "../TLibCommon/Debug.h"
+static const Bool bDebugRQT = DebugOptionList::DebugRQT.getInt()!=0;
+static const Bool bDebugPredEnabled = DebugOptionList::DebugPred.getInt()!=0;
+Bool g_bFinalEncode=true;
+#endif
+
+//! \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 );
+}
+
+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 (pcCU->getPic()->getChromaFormat()!=CHROMA_400)
+    {
+      decodeIntraDirModeChroma( pcCU, uiAbsPartIdx, uiDepth );
+      if (enable4ChromaPUsInIntraNxNCU(pcCU->getPic()->getChromaFormat()) && pcCU->getPartitionSize( uiAbsPartIdx )==SIZE_NxN)
+      {
+        UInt uiPartOffset = ( pcCU->getPic()->getNumPartitionsInCtu() >> ( pcCU->getDepth(uiAbsPartIdx) << 1 ) ) >> 2;
+        decodeIntraDirModeChroma( pcCU, uiAbsPartIdx + uiPartOffset,   uiDepth+1 );
+        decodeIntraDirModeChroma( pcCU, uiAbsPartIdx + uiPartOffset*2, uiDepth+1 );
+        decodeIntraDirModeChroma( pcCU, uiAbsPartIdx + uiPartOffset*3, uiDepth+1 );
+      }
+    }
+  }
+  else                                                                // if it is Inter mode, encode motion vector and reference index
+  {
+    decodePUWise( pcCU, uiAbsPartIdx, uiDepth, pcSubCU );
+  }
+}
+
+/** Parse I_PCM information.
+ * \param pcCU  pointer to CUpointer to CU
+ * \param uiAbsPartIdx CU index
+ * \param uiDepth CU depth
+ * \returns Void
+ */
+Void TDecEntropy::decodeIPCMInfo( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  if(!pcCU->getSlice()->getSPS()->getUsePCM()
+    || pcCU->getWidth(uiAbsPartIdx) > (1<<pcCU->getSlice()->getSPS()->getPCMLog2MaxSize())
+    || pcCU->getWidth(uiAbsPartIdx) < (1<<pcCU->getSlice()->getSPS()->getPCMLog2MinSize()) )
+  {
+    return;
+  }
+
+  m_pcEntropyDecoderIf->parseIPCMInfo( pcCU, uiAbsPartIdx, uiDepth );
+}
+
+Void TDecEntropy::decodeIntraDirModeLuma  ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  m_pcEntropyDecoderIf->parseIntraDirLumaAng( pcCU, uiAbsPartIdx, uiDepth );
+}
+
+Void TDecEntropy::decodeIntraDirModeChroma( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  m_pcEntropyDecoderIf->parseIntraDirChroma( pcCU, uiAbsPartIdx, uiDepth );
+#if ENVIRONMENT_VARIABLE_DEBUG_AND_TEST
+  if (bDebugPredEnabled)
+  {
+    UInt cdir=pcCU->getIntraDir(CHANNEL_TYPE_CHROMA, uiAbsPartIdx);
+    if (cdir==36) cdir=pcCU->getIntraDir(CHANNEL_TYPE_LUMA, uiAbsPartIdx);
+    printf("coding chroma Intra dir: %d, uiAbsPartIdx: %d, luma dir: %d\n", cdir, uiAbsPartIdx, pcCU->getIntraDir(CHANNEL_TYPE_LUMA, uiAbsPartIdx));
+  }
+#endif
+}
+
+
+/** 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;
+
+  TComMvField cMvFieldNeighbours[MRG_MAX_NUM_CANDS << 1]; // double length for mv of both lists
+  UChar uhInterDirNeighbours[MRG_MAX_NUM_CANDS];
+
+  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 );
+  for ( UInt uiPartIdx = 0, uiSubPartIdx = uiAbsPartIdx; uiPartIdx < uiNumPU; uiPartIdx++, uiSubPartIdx += uiPUOffset )
+  {
+    decodeMergeFlag( pcCU, uiSubPartIdx, uiDepth, uiPartIdx );
+    if ( pcCU->getMergeFlag( uiSubPartIdx ) )
+    {
+      decodeMergeIndex( pcCU, uiPartIdx, uiSubPartIdx, uiDepth );
+#if ENVIRONMENT_VARIABLE_DEBUG_AND_TEST
+      if (bDebugPredEnabled)
+      {
+        std::cout << "Coded merge flag, CU absPartIdx: " << uiAbsPartIdx << " PU(" << uiPartIdx << ") absPartIdx: " << uiSubPartIdx;
+        std::cout << " merge index: " << (UInt)pcCU->getMergeIndex(uiSubPartIdx) << std::endl;
+      }
+#endif
+
+      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 )
+        {
+          pcSubCU->getInterMergeCandidates( 0, 0, cMvFieldNeighbours, uhInterDirNeighbours, numValidMergeCand );
+          isMerged = true;
+        }
+        pcSubCU->setPartSizeSubParts( ePartSize, 0, uiDepth );
+      }
+      else
+      {
+        uiMergeIndex = pcCU->getMergeIndex(uiSubPartIdx);
+        pcSubCU->getInterMergeCandidates( uiSubPartIdx-uiAbsPartIdx, uiPartIdx, cMvFieldNeighbours, uhInterDirNeighbours, numValidMergeCand, uiMergeIndex );
+      }
+
+      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 ENVIRONMENT_VARIABLE_DEBUG_AND_TEST
+          if (bDebugPredEnabled)
+          {
+            std::cout << "refListIdx: " << uiRefListIdx << std::endl;
+            std::cout << "MVD horizontal: " << pcCU->getCUMvField(RefPicList(uiRefListIdx))->getMvd( uiAbsPartIdx ).getHor() << std::endl;
+            std::cout << "MVD vertical:   " << pcCU->getCUMvField(RefPicList(uiRefListIdx))->getMvd( uiAbsPartIdx ).getVer() << std::endl;
+            std::cout << "MVPIdxPU: " << pcCU->getMVPIdx(RefPicList( uiRefListIdx ), uiSubPartIdx) << std::endl;
+            std::cout << "InterDir: " << (UInt)pcCU->getInterDir(uiSubPartIdx) << std::endl;
+          }
+#endif
+        }
+      }
+    }
+
+    if ( (pcCU->getInterDir(uiSubPartIdx) == 3) && pcSubCU->isBipredRestriction(uiPartIdx) )
+    {
+      pcCU->getCUMvField( REF_PIC_LIST_1 )->setAllMv( TComMv(0,0), ePartSize, uiSubPartIdx, uiDepth, uiPartIdx);
+      pcCU->getCUMvField( REF_PIC_LIST_1 )->setAllRefIdx( -1, ePartSize, uiSubPartIdx, uiDepth, uiPartIdx);
+      pcCU->setInterDirSubParts( 1, uiSubPartIdx, uiPartIdx, uiDepth);
+    }
+  }
+  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 );
+  }
+  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        ( Bool& bCodeDQP, Bool& isChromaQpAdjCoded, TComTU &rTu, const Int quadtreeTULog2MinSizeInCU )
+{
+  TComDataCU *pcCU=rTu.getCU();
+  const UInt uiAbsPartIdx=rTu.GetAbsPartIdxTU();
+  const UInt uiDepth=rTu.GetTransformDepthTotal();
+  const UInt uiTrDepth = rTu.GetTransformDepthRel();
+
+  UInt uiSubdiv;
+  const UInt numValidComponent = pcCU->getPic()->getNumberValidComponents();
+  const Bool bChroma = isChromaEnabled(pcCU->getPic()->getChromaFormat());
+
+  const UInt uiLog2TrafoSize = rTu.GetLog2LumaTrSize();
+#if ENVIRONMENT_VARIABLE_DEBUG_AND_TEST
+  if (bDebugRQT)
+  {
+    printf("x..codeTransform: offsetLuma=%d offsetChroma=%d absPartIdx=%d, uiDepth=%d\n width=%d, height=%d, uiTrIdx=%d, uiInnerQuadIdx=%d\n",
+        rTu.getCoefficientOffset(COMPONENT_Y), rTu.getCoefficientOffset(COMPONENT_Cb), uiAbsPartIdx, uiDepth, rTu.getRect(COMPONENT_Y).width, rTu.getRect(COMPONENT_Y).height, rTu.GetTransformDepthRel(), rTu.GetSectionNumber());
+    fflush(stdout);
+  }
+#endif
+
+  if( pcCU->isIntra(uiAbsPartIdx) && pcCU->getPartitionSize(uiAbsPartIdx) == SIZE_NxN && uiDepth == pcCU->getDepth(uiAbsPartIdx) )
+  {
+    uiSubdiv = 1;
+  }
+  else if( (pcCU->getSlice()->getSPS()->getQuadtreeTUMaxDepthInter() == 1) && (pcCU->isInter(uiAbsPartIdx)) && ( pcCU->getPartitionSize(uiAbsPartIdx) != SIZE_2Nx2N ) && (uiDepth == pcCU->getDepth(uiAbsPartIdx)) )
+  {
+    uiSubdiv = (uiLog2TrafoSize >quadtreeTULog2MinSizeInCU);
+  }
+  else if( uiLog2TrafoSize > pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() )
+  {
+    uiSubdiv = 1;
+  }
+  else if( uiLog2TrafoSize == pcCU->getSlice()->getSPS()->getQuadtreeTULog2MinSize() )
+  {
+    uiSubdiv = 0;
+  }
+  else if( uiLog2TrafoSize == quadtreeTULog2MinSizeInCU )
+  {
+    uiSubdiv = 0;
+  }
+  else
+  {
+    assert( uiLog2TrafoSize > quadtreeTULog2MinSizeInCU );
+    m_pcEntropyDecoderIf->parseTransformSubdivFlag( uiSubdiv, 5 - uiLog2TrafoSize );
+  }
+
+  for(Int chan=COMPONENT_Cb; chan<numValidComponent; chan++)
+  {
+    const ComponentID compID=ComponentID(chan);
+    const UInt trDepthTotalAdj=rTu.GetTransformDepthTotalAdj(compID);
+
+    const Bool bFirstCbfOfCU = uiTrDepth == 0;
+
+    if( bFirstCbfOfCU )
+    {
+      pcCU->setCbfSubParts( 0, compID, rTu.GetAbsPartIdxTU(compID), trDepthTotalAdj);
+    }
+    if( bFirstCbfOfCU || rTu.ProcessingAllQuadrants(compID) )
+    {
+      if( bFirstCbfOfCU || pcCU->getCbf( uiAbsPartIdx, compID, uiTrDepth - 1 ) )
+      {
+        m_pcEntropyDecoderIf->parseQtCbf( rTu, compID, (uiSubdiv == 0) );
+      }
+    }
+  }
+
+  if( uiSubdiv )
+  {
+    const UInt uiQPartNum = pcCU->getPic()->getNumPartitionsInCtu() >> ((uiDepth+1) << 1);
+    UInt uiYUVCbf[MAX_NUM_COMPONENT] = {0,0,0};
+
+    TComTURecurse tuRecurseChild(rTu, true);
+
+    do
+    {
+      xDecodeTransform( bCodeDQP, isChromaQpAdjCoded, tuRecurseChild, quadtreeTULog2MinSizeInCU );
+      UInt childTUAbsPartIdx=tuRecurseChild.GetAbsPartIdxTU();
+      for(UInt ch=0; ch<numValidComponent; ch++)
+      {
+        uiYUVCbf[ch] |= pcCU->getCbf(childTUAbsPartIdx , ComponentID(ch),  uiTrDepth+1 );
+      }
+
+    } while (tuRecurseChild.nextSection(rTu) );
+
+    for(UInt ch=0; ch<numValidComponent; ch++)
+    {
+      UChar *pBase = pcCU->getCbf( ComponentID(ch) ) + uiAbsPartIdx;
+      const UChar flag = uiYUVCbf[ch] << uiTrDepth;
+
+      for( UInt ui = 0; ui < 4 * uiQPartNum; ++ui )
+      {
+        pBase[ui] |= flag;
+      }
+    }
+  }
+  else
+  {
+    assert( uiDepth >= pcCU->getDepth( uiAbsPartIdx ) );
+    pcCU->setTrIdxSubParts( uiTrDepth, uiAbsPartIdx, uiDepth );
+
+    {
+      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" );
+    }
+
+    pcCU->setCbfSubParts ( 0, COMPONENT_Y, uiAbsPartIdx, uiDepth );
+
+    if( (!pcCU->isIntra(uiAbsPartIdx)) && uiDepth == pcCU->getDepth( uiAbsPartIdx ) && ((!bChroma) || (!pcCU->getCbf( uiAbsPartIdx, COMPONENT_Cb, 0 ) && !pcCU->getCbf( uiAbsPartIdx, COMPONENT_Cr, 0 )) ))
+    {
+      pcCU->setCbfSubParts( 1 << uiTrDepth, COMPONENT_Y, uiAbsPartIdx, uiDepth );
+    }
+    else
+    {
+      m_pcEntropyDecoderIf->parseQtCbf( rTu, COMPONENT_Y, true );
+    }
+
+
+    // transform_unit begin
+    UInt cbf[MAX_NUM_COMPONENT]={0,0,0};
+    Bool validCbf       = false;
+    Bool validChromaCbf = false;
+    const UInt uiTrIdx = rTu.GetTransformDepthRel();
+
+    for(UInt ch=0; ch<pcCU->getPic()->getNumberValidComponents(); ch++)
+    {
+      const ComponentID compID = ComponentID(ch);
+
+      cbf[compID] = pcCU->getCbf( uiAbsPartIdx, compID, uiTrIdx );
+
+      if (cbf[compID] != 0)
+      {
+        validCbf = true;
+        if (isChroma(compID)) validChromaCbf = true;
+      }
+    }
+
+    if ( validCbf )
+    {
+
+      // dQP: only for CTU
+      if ( pcCU->getSlice()->getPPS()->getUseDQP() )
+      {
+        if ( bCodeDQP )
+        {
+          const UInt uiAbsPartIdxCU=rTu.GetAbsPartIdxCU();
+          decodeQP( pcCU, uiAbsPartIdxCU);
+          bCodeDQP = false;
+        }
+      }
+
+      if ( pcCU->getSlice()->getUseChromaQpAdj() )
+      {
+        if ( validChromaCbf && isChromaQpAdjCoded && !pcCU->getCUTransquantBypass(rTu.GetAbsPartIdxCU()) )
+        {
+          decodeChromaQpAdjustment( pcCU, rTu.GetAbsPartIdxCU() );
+          isChromaQpAdjCoded = false;
+        }
+      }
+
+      const UInt numValidComp=pcCU->getPic()->getNumberValidComponents();
+
+      for(UInt ch=COMPONENT_Y; ch<numValidComp; ch++)
+      {
+        const ComponentID compID=ComponentID(ch);
+
+        if( rTu.ProcessComponentSection(compID) )
+        {
+#if ENVIRONMENT_VARIABLE_DEBUG_AND_TEST
+          if (bDebugRQT) printf("Call NxN for chan %d width=%d height=%d cbf=%d\n", compID, rTu.getRect(compID).width, rTu.getRect(compID).height, 1);
+#endif
+
+          if (rTu.getRect(compID).width != rTu.getRect(compID).height)
+          {
+            //code two sub-TUs
+            TComTURecurse subTUIterator(rTu, false, TComTU::VERTICAL_SPLIT, true, compID);
+
+            do
+            {
+              const UInt subTUCBF = pcCU->getCbf(subTUIterator.GetAbsPartIdxTU(), compID, (uiTrIdx + 1));
+
+              if (subTUCBF != 0)
+              {
+#if ENVIRONMENT_VARIABLE_DEBUG_AND_TEST
+                if (bDebugRQT) printf("Call NxN for chan %d width=%d height=%d cbf=%d\n", compID, subTUIterator.getRect(compID).width, subTUIterator.getRect(compID).height, 1);
+#endif
+                m_pcEntropyDecoderIf->parseCoeffNxN( subTUIterator, compID );
+              }
+            }
+            while (subTUIterator.nextSection(rTu));
+          }
+          else
+          {
+            if(isChroma(compID) && (cbf[COMPONENT_Y] != 0))
+            {
+              m_pcEntropyDecoderIf->parseCrossComponentPrediction( rTu, compID );
+            }
+
+            if(cbf[compID] != 0)
+            {
+              m_pcEntropyDecoderIf->parseCoeffNxN( rTu, compID );
+            }
+          }
+        }
+      }
+    }
+    // transform_unit end
+  }
+}
+
+Void TDecEntropy::decodeQP          ( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  if ( pcCU->getSlice()->getPPS()->getUseDQP() )
+  {
+    m_pcEntropyDecoderIf->parseDeltaQP( pcCU, uiAbsPartIdx, pcCU->getDepth( uiAbsPartIdx ) );
+  }
+}
+
+Void TDecEntropy::decodeChromaQpAdjustment( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  if ( pcCU->getSlice()->getUseChromaQpAdj() )
+  {
+    m_pcEntropyDecoderIf->parseChromaQpAdjustment( 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, Bool& bCodeDQP, Bool& isChromaQpAdjCoded )
+{
+  if( pcCU->isIntra(uiAbsPartIdx) )
+  {
+  }
+  else
+  {
+    UInt uiQtRootCbf = 1;
+    if( !( pcCU->getPartitionSize( uiAbsPartIdx) == SIZE_2Nx2N && pcCU->getMergeFlag( uiAbsPartIdx ) ) )
+    {
+      m_pcEntropyDecoderIf->parseQtRootCbf( uiAbsPartIdx, uiQtRootCbf );
+    }
+    if ( !uiQtRootCbf )
+    {
+      static const UInt cbfZero[MAX_NUM_COMPONENT]={0,0,0};
+      pcCU->setCbfSubParts( cbfZero, uiAbsPartIdx, uiDepth );
+      pcCU->setTrIdxSubParts( 0 , uiAbsPartIdx, uiDepth );
+      return;
+    }
+
+  }
+
+  TComTURecurse tuRecurse(pcCU, uiAbsPartIdx, uiDepth);
+
+#if ENVIRONMENT_VARIABLE_DEBUG_AND_TEST
+  if (bDebugRQT)
+    printf("..codeCoeff: uiAbsPartIdx=%d, PU format=%d, 2Nx2N=%d, NxN=%d\n", uiAbsPartIdx, pcCU->getPartitionSize(uiAbsPartIdx), SIZE_2Nx2N, SIZE_NxN);
+#endif
+
+  Int quadtreeTULog2MinSizeInCU = pcCU->getQuadtreeTULog2MinSizeInCU(uiAbsPartIdx);
+  
+  xDecodeTransform( bCodeDQP, isChromaQpAdjCoded, tuRecurse, quadtreeTULog2MinSizeInCU );
+}
+
+//! \}
Index: /tags/SHM-9.0/source/Lib/TLibDecoder/TDecEntropy.h
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibDecoder/TDecEntropy.h	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibDecoder/TDecEntropy.h	(revision 1088)
@@ -0,0 +1,191 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TDecEntropy.h
+    \brief    entropy decoder class (header)
+*/
+
+#ifndef __TDECENTROPY__
+#define __TDECENTROPY__
+
+#include "TLibCommon/CommonDef.h"
+#include "TLibCommon/TComBitStream.h"
+#include "TLibCommon/TComSlice.h"
+#include "TLibCommon/TComPic.h"
+#include "TLibCommon/TComPrediction.h"
+#include "TLibCommon/TComSampleAdaptiveOffset.h"
+#include "TLibCommon/TComRectangle.h"
+
+class TDecSbac;
+class TDecCavlc;
+class ParameterSetManagerDecoder;
+#if Q0048_CGS_3D_ASYMLUT
+class TCom3DAsymLUT;
+#endif
+
+//! \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;
+  virtual Void  parseSPS                  ( TComSPS* pcSPS )     = 0;
+#if Q0048_CGS_3D_ASYMLUT
+  virtual Void  parsePPS                  ( TComPPS* pcPPS, TCom3DAsymLUT * pc3DAsymLUT , Int nLayerID )     = 0;
+#else
+  virtual Void  parsePPS                  ( TComPPS* pcPPS )     = 0;
+#endif
+
+  virtual Void parseSliceHeader          ( TComSlice* pcSlice, ParameterSetManagerDecoder *parameterSetManager)       = 0;
+
+  virtual Void parseTerminatingBit       ( UInt& ruilsLast )                                     = 0;
+  virtual Void parseRemainingBytes( Bool noTrailingBytesExpected ) = 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;
+  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 parseCrossComponentPrediction ( class TComTU &rTu, ComponentID compID ) = 0;
+
+  virtual Void parseTransformSubdivFlag( UInt& ruiSubdivFlag, UInt uiLog2TransformBlockSize ) = 0;
+  virtual Void parseQtCbf         ( TComTU &rTu, const ComponentID compID, const Bool lowestLevel ) = 0;
+  virtual Void parseQtRootCbf     ( UInt uiAbsPartIdx, UInt& uiQtRootCbf ) = 0;
+
+  virtual Void parseDeltaQP       ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth ) = 0;
+  virtual Void parseChromaQpAdjustment( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth ) = 0;
+
+  virtual Void parseIPCMInfo     ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth) = 0;
+
+  virtual Void parseCoeffNxN( class TComTU &rTu, ComponentID compID  ) = 0;
+
+  virtual Void parseTransformSkipFlags ( class TComTU &rTu, ComponentID component ) = 0;
+
+  virtual Void parseExplicitRdpcmMode ( TComTU &rTu, ComponentID compID ) = 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); }
+  Void    decodeSPS                   ( TComSPS* pcSPS ) { m_pcEntropyDecoderIf->parseSPS(pcSPS); }
+
+#if Q0048_CGS_3D_ASYMLUT
+  Void    decodePPS                   ( TComPPS* pcPPS, TCom3DAsymLUT * pc3DAsymLUT, Int nLayerID )    { m_pcEntropyDecoderIf->parsePPS(pcPPS, pc3DAsymLUT , nLayerID );                     }
+#else
+  Void    decodePPS                   ( TComPPS* pcPPS ) { m_pcEntropyDecoderIf->parsePPS(pcPPS); }
+#endif
+  Void    decodeSliceHeader           ( TComSlice* pcSlice, ParameterSetManagerDecoder *parameterSetManager)  { m_pcEntropyDecoderIf->parseSliceHeader(pcSlice, parameterSetManager);         }
+
+  Void    decodeTerminatingBit        ( UInt& ruiIsLast )       { m_pcEntropyDecoderIf->parseTerminatingBit(ruiIsLast);     }
+  Void    decodeRemainingBytes( Bool noTrailingBytesExpected ) { m_pcEntropyDecoderIf->parseRemainingBytes(noTrailingBytesExpected); }
+
+  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 );
+
+  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 decodeChromaQpAdjustment( TComDataCU* pcCU, UInt uiAbsPartIdx );
+
+private:
+
+  Void xDecodeTransform        ( Bool& bCodeDQP, Bool& isChromaQpAdjCoded, TComTU &rTu, const Int quadtreeTULog2MinSizeInCU );
+
+public:
+
+  Void decodeCoeff             ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, Bool& bCodeDQP, Bool& isChromaQpAdjCoded );
+
+};// END CLASS DEFINITION TDecEntropy
+
+//! \}
+
+#endif // __TDECENTROPY__
+
Index: /tags/SHM-9.0/source/Lib/TLibDecoder/TDecGop.cpp
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibDecoder/TDecGop.cpp	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibDecoder/TDecGop.cpp	(revision 1088)
@@ -0,0 +1,516 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TDecGop.cpp
+    \brief    GOP decoder class
+*/
+
+#include "TDecGop.h"
+#include "TDecCAVLC.h"
+#include "TDecSbac.h"
+#include "TDecBinCoder.h"
+#include "TDecBinCoderCABAC.h"
+#include "libmd5/MD5.h"
+#include "TLibCommon/SEI.h"
+#if SVC_EXTENSION
+#include "TDecTop.h"
+#if CONFORMANCE_BITSTREAM_MODE
+#include <algorithm>
+#endif
+#endif
+
+#include <time.h>
+
+extern Bool g_md5_mismatch; ///< top level flag to signal when there is a decode problem
+
+#if CONFORMANCE_BITSTREAM_MODE
+Bool pocCompareFunction( const TComPic &pic1, const TComPic &pic2 )
+{
+  return (const_cast<TComPic&>(pic1).getPOC() < const_cast<TComPic&>(pic2).getPOC());
+}
+#endif
+
+//! \ingroup TLibDecoder
+//! \{
+static Void calcAndPrintHashStatus(TComPicYuv& pic, const SEIDecodedPictureHash* pictureHashSEI);
+#if Q0074_COLOUR_REMAPPING_SEI
+static Void applyColourRemapping(TComPicYuv& pic, const SEIColourRemappingInfo* colourRemappingInfoSEI, UInt layerId=0 );
+static std::vector<SEIColourRemappingInfo> storeCriSEI; //Persistent Colour Remapping Information SEI
+#endif
+// ====================================================================================================================
+// Constructor / destructor / initialization / destroy
+// ====================================================================================================================
+
+TDecGop::TDecGop()
+{
+  m_dDecTime = 0;
+}
+
+TDecGop::~TDecGop()
+{
+
+}
+
+#if SVC_EXTENSION
+Void TDecGop::create(UInt layerId)
+{
+  m_layerId = layerId;
+}
+#else
+Void TDecGop::create()
+{
+
+}
+#endif
+
+Void TDecGop::destroy()
+{
+}
+
+#if SVC_EXTENSION
+Void TDecGop::init( TDecTop**               ppcDecTop,
+                   TDecEntropy*             pcEntropyDecoder,
+#else
+Void TDecGop::init( TDecEntropy*            pcEntropyDecoder,
+#endif
+                   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;
+#if SVC_EXTENSION   
+  m_ppcTDecTop            = ppcDecTop;
+#endif
+}
+
+
+// ====================================================================================================================
+// Private member functions
+// ====================================================================================================================
+// ====================================================================================================================
+// Public member functions
+// ====================================================================================================================
+
+Void TDecGop::decompressSlice(TComInputBitstream* pcBitstream, TComPic* pcPic)
+{
+  TComSlice*  pcSlice = pcPic->getSlice(pcPic->getCurrSliceIdx());
+  // Table of extracted substreams.
+  // These must be deallocated AND their internal fifos, too.
+  TComInputBitstream **ppcSubstreams = NULL;
+
+  //-- For time output for each slice
+  clock_t iBeforeTime = clock();
+  m_pcSbacDecoder->init( (TDecBinIf*)m_pcBinCABAC );
+  m_pcEntropyDecoder->setEntropyDecoder (m_pcSbacDecoder);
+
+  const UInt uiNumSubstreams = pcSlice->getNumberOfSubstreamSizes()+1;
+//  const UInt uiNumSubstreams = pcSlice->getPPS()->getEntropyCodingSyncEnabledFlag() ? pcSlice->getNumberOfSubstreamSizes()+1 : pcSlice->getPPS()->getNumSubstreams();
+
+  // init each couple {EntropyDecoder, Substream}
+  ppcSubstreams    = new TComInputBitstream*[uiNumSubstreams];
+  for ( UInt ui = 0 ; ui < uiNumSubstreams ; ui++ )
+  {
+    ppcSubstreams[ui] = pcBitstream->extractSubstream(ui+1 < uiNumSubstreams ? (pcSlice->getSubstreamSize(ui)<<3) : pcBitstream->getNumBitsLeft());
+  }
+
+  m_pcSliceDecoder->decompressSlice( ppcSubstreams, pcPic, m_pcSbacDecoder);
+  // deallocate all created substreams, including internal buffers.
+  for (UInt ui = 0; ui < uiNumSubstreams; ui++)
+  {
+    ppcSubstreams[ui]->deleteFifo();
+    delete ppcSubstreams[ui];
+  }
+  delete[] ppcSubstreams;
+
+  m_dDecTime += (Double)(clock()-iBeforeTime) / CLOCKS_PER_SEC;
+}
+
+Void TDecGop::filterPicture(TComPic* pcPic)
+{
+  TComSlice*  pcSlice = pcPic->getSlice(pcPic->getCurrSliceIdx());
+
+  //-- For time output for each slice
+  clock_t iBeforeTime = clock();
+
+  // deblocking filter
+  Bool bLFCrossTileBoundary = pcSlice->getPPS()->getLoopFilterAcrossTilesEnabledFlag();
+  m_pcLoopFilter->setCfg(bLFCrossTileBoundary);
+  m_pcLoopFilter->loopFilterPic( pcPic );
+
+  if( pcSlice->getSPS()->getUseSAO() )
+  {
+    m_pcSAO->reconstructBlkSAOParams(pcPic, pcPic->getPicSym()->getSAOBlkParam());
+    m_pcSAO->SAOProcess(pcPic);
+    m_pcSAO->PCMLFDisableProcess(pcPic);
+  }
+
+  pcPic->compressMotion();
+  Char c = (pcSlice->isIntra() ? 'I' : pcSlice->isInterP() ? 'P' : 'B');
+  if (!pcSlice->isReferenced()) c += 32;
+
+  //-- For time output for each slice
+#if SVC_EXTENSION
+  printf("POC %4d LId: %1d TId: %1d ( %c-SLICE %s, QP%3d ) ", pcSlice->getPOC(),
+                                                    pcPic->getLayerId(),
+                                                    pcSlice->getTLayer(),
+                                                    c,
+                                                    NaluToStr( pcSlice->getNalUnitType() ).data(),
+                                                    pcSlice->getSliceQp() );
+#else
+  printf("POC %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 SVC_EXTENSION
+#if VPS_EXTN_DIRECT_REF_LAYERS
+      if( pcSlice->getRefPic(RefPicList(iRefList), iRefIndex)->isILR( m_layerId ) )
+      {
+        UInt refLayerId = pcSlice->getRefPic(RefPicList(iRefList), iRefIndex)->getLayerId();
+        UInt refLayerIdc = pcSlice->getReferenceLayerIdc(refLayerId);
+        assert( g_posScalingFactor[refLayerIdc][0] );
+        assert( g_posScalingFactor[refLayerIdc][1] );
+
+        printf( "%d(%d, {%1.2f, %1.2f}x)", pcSlice->getRefPOC(RefPicList(iRefList), iRefIndex), refLayerId, 65536.0/g_posScalingFactor[refLayerIdc][0], 65536.0/g_posScalingFactor[refLayerIdc][1] );
+      }
+      else
+      {
+        printf ("%d", pcSlice->getRefPOC(RefPicList(iRefList), iRefIndex));
+      }
+#endif
+      if( pcSlice->getEnableTMVPFlag() && iRefList == 1 - pcSlice->getColFromL0Flag() && iRefIndex == pcSlice->getColRefIdx() )
+      {
+        printf( "c" );
+      }
+
+      printf( " " );
+#else
+      printf ("%d ", pcSlice->getRefPOC(RefPicList(iRefList), iRefIndex));
+#endif
+    }
+    printf ("] ");
+  }
+  if (m_decodedPictureHashSEIEnabled)
+  {
+    SEIMessages pictureHashes = getSeisByType(pcPic->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(*(pcPic->getPicYuvRec()), hash);
+  }
+#if CONFORMANCE_BITSTREAM_MODE
+  if( this->getLayerDec(pcPic->getLayerId())->getConfModeFlag() )
+  {
+    // Add this reconstructed picture to the parallel buffer.
+    std::vector<TComPic> *thisLayerBuffer = (this->getLayerDec(pcPic->getLayerId()))->getConfListPic();
+    thisLayerBuffer->push_back(*pcPic);
+    std::sort( thisLayerBuffer->begin(), thisLayerBuffer->end(), pocCompareFunction );
+  }
+#endif
+#if Q0074_COLOUR_REMAPPING_SEI
+  if (m_colourRemapSEIEnabled)
+  {
+    SEIMessages colourRemappingInfo = getSeisByType(pcPic->getSEIs(), SEI::COLOUR_REMAPPING_INFO );
+    const SEIColourRemappingInfo *seiColourRemappingInfo = ( colourRemappingInfo.size() > 0 ) ? (SEIColourRemappingInfo*) *(colourRemappingInfo.begin()) : NULL;
+    if (colourRemappingInfo.size() > 1)
+    {
+      printf ("Warning: Got multiple Colour Remapping Information SEI messages. Using first.");
+    }
+    applyColourRemapping(*pcPic->getPicYuvRec(), seiColourRemappingInfo
+#if SVC_EXTENSION
+     , pcPic->getLayerId()
+#endif
+     );
+  }
+#endif
+
+  printf("\n");
+
+  pcPic->setOutputMark(pcPic->getSlice(0)->getPicOutputFlag() ? true : false);
+  pcPic->setReconMark(true);
+}
+
+/**
+ * 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 */
+  TComDigest recon_digest;
+  Int numChar=0;
+  const Char* hashType = "\0";
+
+  if (pictureHashSEI)
+  {
+    switch (pictureHashSEI->method)
+    {
+      case SEIDecodedPictureHash::MD5:
+        {
+          hashType = "MD5";
+          numChar = calcMD5(pic, recon_digest);
+          break;
+        }
+      case SEIDecodedPictureHash::CRC:
+        {
+          hashType = "CRC";
+          numChar = calcCRC(pic, recon_digest);
+          break;
+        }
+      case SEIDecodedPictureHash::CHECKSUM:
+        {
+          hashType = "Checksum";
+          numChar = calcChecksum(pic, recon_digest);
+          break;
+        }
+      default:
+        {
+          assert (!"unknown hash type");
+          break;
+        }
+    }
+  }
+
+  /* compare digest against received version */
+  const Char* ok = "(unk)";
+  Bool mismatch = false;
+
+  if (pictureHashSEI)
+  {
+    ok = "(OK)";
+    if (recon_digest != pictureHashSEI->m_digest)
+    {
+      ok = "(***ERROR***)";
+      mismatch = true;
+    }
+  }
+
+  printf("[%s:%s,%s] ", hashType, digestToString(recon_digest, numChar).c_str(), ok);
+
+  if (mismatch)
+  {
+    g_md5_mismatch = true;
+    printf("[rx%s:%s] ", hashType, digestToString(pictureHashSEI->m_digest, numChar).c_str());
+  }
+}
+
+#if Q0074_COLOUR_REMAPPING_SEI
+Void xInitColourRemappingLut( const Int bitDepthY, const Int bitDepthC, std::vector<Int>(&preLut)[3], std::vector<Int>(&postLut)[3], const SEIColourRemappingInfo* const pCriSEI )
+{
+  for ( Int c=0 ; c<3 ; c++ )
+  {  
+    Int bitDepth = c ? bitDepthC : bitDepthY ;
+    preLut[c].resize(1 << bitDepth);
+    postLut[c].resize(1 << pCriSEI->m_colourRemapBitDepth);
+    
+    Int bitDepthDiff = pCriSEI->m_colourRemapBitDepth - bitDepth;
+    Int iShift1 = (bitDepthDiff>0) ? bitDepthDiff : 0; //bit scale from bitdepth to ColourRemapBitdepth (manage only case colourRemapBitDepth>= bitdepth)
+    if( bitDepthDiff<0 )
+      printf ("Warning: CRI SEI - colourRemapBitDepth (%d) <bitDepth (%d) - case not handled\n", pCriSEI->m_colourRemapBitDepth, bitDepth);
+    bitDepthDiff = pCriSEI->m_colourRemapBitDepth - pCriSEI->m_colourRemapInputBitDepth;
+    Int iShift2 = (bitDepthDiff>0) ? bitDepthDiff : 0; //bit scale from ColourRemapInputBitdepth to ColourRemapBitdepth (manage only case colourRemapBitDepth>= colourRemapInputBitDepth)
+    if( bitDepthDiff<0 )
+      printf ("Warning: CRI SEI - colourRemapBitDepth (%d) <colourRemapInputBitDepth (%d) - case not handled\n", pCriSEI->m_colourRemapBitDepth, pCriSEI->m_colourRemapInputBitDepth);
+
+    //Fill preLut
+    for ( Int k=0 ; k<(1<<bitDepth) ; k++ )
+    {
+      Int iSample = k << iShift1 ;
+      for ( Int iPivot=0 ; iPivot<=pCriSEI->m_preLutNumValMinus1[c] ; iPivot++ )
+      {
+        Int iCodedPrev  = pCriSEI->m_preLutCodedValue[c][iPivot]    << iShift2; //Coded in CRInputBitdepth
+        Int iCodedNext  = pCriSEI->m_preLutCodedValue[c][iPivot+1]  << iShift2; //Coded in CRInputBitdepth
+        Int iTargetPrev = pCriSEI->m_preLutTargetValue[c][iPivot];              //Coded in CRBitdepth
+        Int iTargetNext = pCriSEI->m_preLutTargetValue[c][iPivot+1];            //Coded in CRBitdepth
+        if ( iCodedPrev <= iSample && iSample <= iCodedNext )
+        {
+          Float fInterpol = (Float)( (iCodedNext - iSample)*iTargetPrev + (iSample - iCodedPrev)*iTargetNext ) * 1.f / (Float)(iCodedNext - iCodedPrev);
+          preLut[c][k]  = (Int)( 0.5f + fInterpol );
+          iPivot = pCriSEI->m_preLutNumValMinus1[c] + 1;
+        }
+      }
+    }
+    
+    //Fill postLut
+    for ( Int k=0 ; k<(1<<pCriSEI->m_colourRemapBitDepth) ; k++ )
+    {
+      Int iSample = k;
+      for ( Int iPivot=0 ; iPivot<=pCriSEI->m_postLutNumValMinus1[c] ; iPivot++ )
+      {
+        Int iCodedPrev  = pCriSEI->m_postLutCodedValue[c][iPivot];    //Coded in CRBitdepth
+        Int iCodedNext  = pCriSEI->m_postLutCodedValue[c][iPivot+1];  //Coded in CRBitdepth
+        Int iTargetPrev = pCriSEI->m_postLutTargetValue[c][iPivot];   //Coded in CRBitdepth
+        Int iTargetNext = pCriSEI->m_postLutTargetValue[c][iPivot+1]; //Coded in CRBitdepth
+        if ( iCodedPrev <= iSample && iSample <= iCodedNext )
+        {
+          Float fInterpol =  (Float)( (iCodedNext - iSample)*iTargetPrev + (iSample - iCodedPrev)*iTargetNext ) * 1.f / (Float)(iCodedNext - iCodedPrev) ;
+          postLut[c][k]  = (Int)( 0.5f + fInterpol );
+          iPivot = pCriSEI->m_postLutNumValMinus1[c] + 1;
+        }
+      }
+    }
+  }
+}
+
+static Void applyColourRemapping(TComPicYuv& pic, const SEIColourRemappingInfo* pCriSEI, UInt layerId )
+{  
+  if( !storeCriSEI.size() )
+#if SVC_EXTENSION
+    storeCriSEI.resize(MAX_LAYERS);
+#else
+    storeCriSEI.resize(1);
+#endif
+
+  if ( pCriSEI ) //if a CRI SEI has just been retrieved, keep it in memory (persistence management)
+    storeCriSEI[layerId] = *pCriSEI;
+
+  if( !storeCriSEI[layerId].m_colourRemapCancelFlag )
+  {
+    Int iHeight  = pic.getHeight(COMPONENT_Y);
+    Int iWidth   = pic.getWidth(COMPONENT_Y);
+    Int iStride  = pic.getStride(COMPONENT_Y);
+    Int iCStride = pic.getStride(COMPONENT_Cb);
+
+    Pel *YUVIn[3], *YUVOut[3];
+    YUVIn[0] = pic.getAddr(COMPONENT_Y);
+    YUVIn[1] = pic.getAddr(COMPONENT_Cb);
+    YUVIn[2] = pic.getAddr(COMPONENT_Cr);
+    
+    TComPicYuv picColourRemapped;
+#if SVC_EXTENSION
+    picColourRemapped.create( pic.getWidth(COMPONENT_Y), pic.getHeight(COMPONENT_Y), pic.getChromaFormat(), g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth, NULL );
+#else
+    picColourRemapped.create( pic.getWidth(COMPONENT_Y), pic.getHeight(COMPONENT_Y), pic.getChromaFormat(), g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth );
+#endif 
+    YUVOut[0] = picColourRemapped.getAddr(COMPONENT_Y);
+    YUVOut[1] = picColourRemapped.getAddr(COMPONENT_Cb);
+    YUVOut[2] = picColourRemapped.getAddr(COMPONENT_Cr);
+
+#if SVC_EXTENSION
+    Int bitDepthY = g_bitDepthLayer[CHANNEL_TYPE_LUMA][layerId];
+    Int bitDepthC = g_bitDepthLayer[CHANNEL_TYPE_CHROMA][layerId];
+
+    assert( g_bitDepth[CHANNEL_TYPE_LUMA] == bitDepthY );
+    assert( g_bitDepth[CHANNEL_TYPE_CHROMA] == bitDepthC );
+#else
+    Int bitDepthY = g_bitDepth[CHANNEL_TYPE_LUMA];
+    Int bitDepthC = g_bitDepth[CHANNEL_TYPE_CHROMA];
+#endif
+
+    std::vector<Int> preLut[3];
+    std::vector<Int> postLut[3];
+    xInitColourRemappingLut( bitDepthY, bitDepthC, preLut, postLut, &storeCriSEI[layerId] );
+    
+    Int roundingOffset = (storeCriSEI[layerId].m_log2MatrixDenom==0) ? 0 : (1 << (storeCriSEI[layerId].m_log2MatrixDenom - 1));
+
+    for( Int y = 0; y < iHeight ; y++ )
+    {
+      for( Int x = 0; x < iWidth ; x++ )
+      {
+        Int YUVPre[3], YUVMat[3];
+        YUVPre[0] = preLut[0][ YUVIn[0][x]   ];
+        YUVPre[1] = preLut[1][ YUVIn[1][x>>1] ];
+        YUVPre[2] = preLut[2][ YUVIn[2][x>>1] ];
+
+        YUVMat[0] = ( storeCriSEI[layerId].m_colourRemapCoeffs[0][0]*YUVPre[0]
+                    + storeCriSEI[layerId].m_colourRemapCoeffs[0][1]*YUVPre[1] 
+                    + storeCriSEI[layerId].m_colourRemapCoeffs[0][2]*YUVPre[2] 
+                    + roundingOffset ) >> ( storeCriSEI[layerId].m_log2MatrixDenom );
+        YUVMat[0] = Clip3( 0, (1<<storeCriSEI[layerId].m_colourRemapBitDepth)-1, YUVMat[0] );
+        YUVOut[0][x] = postLut[0][ YUVMat[0] ];
+
+        if( (y&1) && (x&1) )
+        {
+          for(Int c=1 ; c<3 ; c++)
+          {
+            YUVMat[c] = ( storeCriSEI[layerId].m_colourRemapCoeffs[c][0]*YUVPre[0] 
+                        + storeCriSEI[layerId].m_colourRemapCoeffs[c][1]*YUVPre[1] 
+                        + storeCriSEI[layerId].m_colourRemapCoeffs[c][2]*YUVPre[2] 
+                        + roundingOffset ) >> ( storeCriSEI[layerId].m_log2MatrixDenom );
+            YUVMat[c] = Clip3( 0, (1<<storeCriSEI[layerId].m_colourRemapBitDepth)-1, YUVMat[c] );
+            YUVOut[c][x>>1] = postLut[c][ YUVMat[c] ];   
+          }
+        }
+      }
+      YUVIn[0]  += iStride;
+      YUVOut[0] += iStride;
+      if( y&1 )
+      {
+        YUVIn[1]  += iCStride;
+        YUVIn[2]  += iCStride;
+        YUVOut[1] += iCStride;
+        YUVOut[2] += iCStride;
+      }
+    }
+
+    //Write remapped picture in decoding order
+    Char  cTemp[255];
+    sprintf(cTemp, "seiColourRemappedPic_L%d_%dx%d_%dbits.yuv", layerId, iWidth, iHeight, storeCriSEI[layerId].m_colourRemapBitDepth );
+    picColourRemapped.dump( cTemp, true, storeCriSEI[layerId].m_colourRemapBitDepth );
+
+    picColourRemapped.destroy();
+
+    storeCriSEI[layerId].m_colourRemapCancelFlag = !storeCriSEI[layerId].m_colourRemapPersistenceFlag; //Handling persistence
+  }
+}
+#endif
+//! \}
Index: /tags/SHM-9.0/source/Lib/TLibDecoder/TDecGop.h
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibDecoder/TDecGop.h	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibDecoder/TDecGop.h	(revision 1088)
@@ -0,0 +1,128 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TDecGop.h
+    \brief    GOP decoder class (header)
+*/
+
+#ifndef __TDECGOP__
+#define __TDECGOP__
+
+#if _MSC_VER > 1000
+#pragma once
+#endif // _MSC_VER > 1000
+
+#include "TLibCommon/CommonDef.h"
+#include "TLibCommon/TComBitStream.h"
+#include "TLibCommon/TComList.h"
+#include "TLibCommon/TComPicYuv.h"
+#include "TLibCommon/TComPic.h"
+#include "TLibCommon/TComLoopFilter.h"
+#include "TLibCommon/TComSampleAdaptiveOffset.h"
+
+#include "TDecEntropy.h"
+#include "TDecSlice.h"
+#include "TDecBinCoder.h"
+#include "TDecBinCoderCABAC.h"
+
+//! \ingroup TLibDecoder
+//! \{
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// GOP decoder class
+class TDecGop
+{
+private:
+  TComList<TComPic*>    m_cListPic;         //  Dynamic buffer
+
+  //  Access channel
+  TDecEntropy*          m_pcEntropyDecoder;
+  TDecSbac*             m_pcSbacDecoder;
+  TDecBinCABAC*         m_pcBinCABAC;
+  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
+#if Q0074_COLOUR_REMAPPING_SEI
+  Bool                  m_colourRemapSEIEnabled;         ///< Enable/disable Colour Remapping Information SEI message acting on decoded pictures
+#endif
+#if SVC_EXTENSION
+  UInt                  m_layerId;
+  TDecTop**             m_ppcTDecTop;
+#endif
+public:
+  TDecGop();
+  virtual ~TDecGop();
+  
+#if SVC_EXTENSION
+Void  init      ( TDecTop**               ppcDecTop,
+                  TDecEntropy*            pcEntropyDecoder, 
+#else
+  Void  init    ( TDecEntropy*            pcEntropyDecoder, 
+#endif
+                 TDecSbac*               pcSbacDecoder, 
+                 TDecBinCABAC*           pcBinCABAC,
+                 TDecCavlc*              pcCavlcDecoder,
+                 TDecSlice*              pcSliceDecoder,
+                 TComLoopFilter*         pcLoopFilter,
+                 TComSampleAdaptiveOffset* pcSAO
+                 );
+#if SVC_EXTENSION
+  Void  create  (UInt layerId);
+#else
+  Void  create  ();
+#endif
+  Void  destroy ();
+  Void  decompressSlice(TComInputBitstream* pcBitstream, TComPic* pcPic );
+  Void  filterPicture  (TComPic* pcPic );
+
+  Void setDecodedPictureHashSEIEnabled(Int enabled) { m_decodedPictureHashSEIEnabled = enabled; }
+#if Q0074_COLOUR_REMAPPING_SEI
+  Void setColourRemappingInfoSEIEnabled(Int enabled) { m_colourRemapSEIEnabled = enabled; }
+#endif
+#if SVC_EXTENSION
+  TDecTop*   getLayerDec(UInt layerId)  { return m_ppcTDecTop[layerId]; }
+#endif 
+
+};
+
+//! \}
+
+#endif // !defined(AFX_TDECGOP_H__29440B7A_7CC0_48C7_8DD5_1A531D3CED45__INCLUDED_)
+
Index: /tags/SHM-9.0/source/Lib/TLibDecoder/TDecSbac.cpp
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibDecoder/TDecSbac.cpp	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibDecoder/TDecSbac.cpp	(revision 1088)
@@ -0,0 +1,1894 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TDecSbac.cpp
+    \brief    Context-adaptive entropy decoder class
+*/
+
+#include "TDecSbac.h"
+#include "TLibCommon/TComTU.h"
+
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+#include "TLibCommon/TComCodingStatistics.h"
+//
+#define RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(a) , a
+#else
+#define RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(a)
+#endif
+
+//! \ingroup TLibDecoder
+//! \{
+
+#if ENVIRONMENT_VARIABLE_DEBUG_AND_TEST
+#include "../TLibCommon/Debug.h"
+#endif
+
+
+//////////////////////////////////////////////////////////////////////
+// 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)
+, 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,             NUM_QT_CBF_CTX_SETS,    NUM_QT_CBF_CTX_PER_SET               , 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,             NUM_CTX_LAST_FLAG_SETS, NUM_CTX_LAST_FLAG_XY                 , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCuCtxLastY                              ( 1,             NUM_CTX_LAST_FLAG_SETS, NUM_CTX_LAST_FLAG_XY                 , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCUOneSCModel                            ( 1,             1,                      NUM_ONE_FLAG_CTX                     , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCUAbsSCModel                            ( 1,             1,                      NUM_ABS_FLAG_CTX                     , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cMVPIdxSCModel                           ( 1,             1,                      NUM_MVP_IDX_CTX                      , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cSaoMergeSCModel                         ( 1,             1,                      NUM_SAO_MERGE_FLAG_CTX               , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cSaoTypeIdxSCModel                       ( 1,             1,                      NUM_SAO_TYPE_IDX_CTX                 , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cTransformSkipSCModel                    ( 1,             MAX_NUM_CHANNEL_TYPE,   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)
+, m_explicitRdpcmFlagSCModel                 ( 1,             MAX_NUM_CHANNEL_TYPE,   NUM_EXPLICIT_RDPCM_FLAG_CTX          , m_contextModels + m_numContextModels, m_numContextModels)
+, m_explicitRdpcmDirSCModel                  ( 1,             MAX_NUM_CHANNEL_TYPE,   NUM_EXPLICIT_RDPCM_DIR_CTX           , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCrossComponentPredictionSCModel         ( 1,             1,                      NUM_CROSS_COMPONENT_PREDICTION_CTX   , m_contextModels + m_numContextModels, m_numContextModels)
+, m_ChromaQpAdjFlagSCModel                   ( 1,             1,                      NUM_CHROMA_QP_ADJ_FLAG_CTX           , m_contextModels + m_numContextModels, m_numContextModels)
+, m_ChromaQpAdjIdcSCModel                    ( 1,             1,                      NUM_CHROMA_QP_ADJ_IDC_CTX            , m_contextModels + m_numContextModels, m_numContextModels)
+{
+  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);
+      break;
+    }
+  }
+
+  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 );
+  m_cCUPartSizeSCModel.initBuffer                 ( sliceType, qp, (UChar*)INIT_PART_SIZE );
+  m_cCUPredModeSCModel.initBuffer                 ( sliceType, qp, (UChar*)INIT_PRED_MODE );
+  m_cCUIntraPredSCModel.initBuffer                ( sliceType, qp, (UChar*)INIT_INTRA_PRED_MODE );
+  m_cCUChromaPredSCModel.initBuffer               ( sliceType, qp, (UChar*)INIT_CHROMA_PRED_MODE );
+  m_cCUInterDirSCModel.initBuffer                 ( sliceType, qp, (UChar*)INIT_INTER_DIR );
+  m_cCUMvdSCModel.initBuffer                      ( sliceType, qp, (UChar*)INIT_MVD );
+  m_cCURefPicSCModel.initBuffer                   ( sliceType, qp, (UChar*)INIT_REF_PIC );
+  m_cCUDeltaQpSCModel.initBuffer                  ( sliceType, qp, (UChar*)INIT_DQP );
+  m_cCUQtCbfSCModel.initBuffer                    ( sliceType, qp, (UChar*)INIT_QT_CBF );
+  m_cCUQtRootCbfSCModel.initBuffer                ( sliceType, qp, (UChar*)INIT_QT_ROOT_CBF );
+  m_cCUSigCoeffGroupSCModel.initBuffer            ( sliceType, qp, (UChar*)INIT_SIG_CG_FLAG );
+  m_cCUSigSCModel.initBuffer                      ( sliceType, qp, (UChar*)INIT_SIG_FLAG );
+  m_cCuCtxLastX.initBuffer                        ( sliceType, qp, (UChar*)INIT_LAST );
+  m_cCuCtxLastY.initBuffer                        ( sliceType, qp, (UChar*)INIT_LAST );
+  m_cCUOneSCModel.initBuffer                      ( sliceType, qp, (UChar*)INIT_ONE_FLAG );
+  m_cCUAbsSCModel.initBuffer                      ( sliceType, qp, (UChar*)INIT_ABS_FLAG );
+  m_cMVPIdxSCModel.initBuffer                     ( sliceType, qp, (UChar*)INIT_MVP_IDX );
+  m_cSaoMergeSCModel.initBuffer                   ( sliceType, qp, (UChar*)INIT_SAO_MERGE_FLAG );
+  m_cSaoTypeIdxSCModel.initBuffer                 ( sliceType, qp, (UChar*)INIT_SAO_TYPE_IDX );
+  m_cCUTransSubdivFlagSCModel.initBuffer          ( sliceType, qp, (UChar*)INIT_TRANS_SUBDIV_FLAG );
+  m_cTransformSkipSCModel.initBuffer              ( sliceType, qp, (UChar*)INIT_TRANSFORMSKIP_FLAG );
+  m_CUTransquantBypassFlagSCModel.initBuffer      ( sliceType, qp, (UChar*)INIT_CU_TRANSQUANT_BYPASS_FLAG );
+  m_explicitRdpcmFlagSCModel.initBuffer           ( sliceType, qp, (UChar*)INIT_EXPLICIT_RDPCM_FLAG);
+  m_explicitRdpcmDirSCModel.initBuffer            ( sliceType, qp, (UChar*)INIT_EXPLICIT_RDPCM_DIR);
+  m_cCrossComponentPredictionSCModel.initBuffer   ( sliceType, qp, (UChar*)INIT_CROSS_COMPONENT_PREDICTION );
+  m_ChromaQpAdjFlagSCModel.initBuffer             ( sliceType, qp, (UChar*)INIT_CHROMA_QP_ADJ_FLAG );
+  m_ChromaQpAdjIdcSCModel.initBuffer              ( sliceType, qp, (UChar*)INIT_CHROMA_QP_ADJ_IDC );
+
+  for (UInt statisticIndex = 0; statisticIndex < RExt__GOLOMB_RICE_ADAPTATION_STATISTICS_SETS ; statisticIndex++)
+  {
+    m_golombRiceAdaptationStatistics[statisticIndex] = 0;
+  }
+
+  m_pcTDecBinIf->start();
+}
+
+Void TDecSbac::parseTerminatingBit( UInt& ruiBit )
+{
+  m_pcTDecBinIf->decodeBinTrm( ruiBit );
+  if ( ruiBit == 1 )
+  {
+    m_pcTDecBinIf->finish();
+
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+    TComCodingStatistics::IncrementStatisticEP(STATS__TRAILING_BITS, m_pcBitstream->readOutTrailingBits(),0);
+#else
+    m_pcBitstream->readOutTrailingBits();
+#endif
+  }
+}
+
+Void TDecSbac::parseRemainingBytes( Bool noTrailingBytesExpected )
+{
+  if (noTrailingBytesExpected)
+  {
+    const UInt numberOfRemainingSubstreamBytes=m_pcBitstream->getNumBitsLeft();
+    assert (numberOfRemainingSubstreamBytes == 0);
+  }
+  else
+  {
+    while (m_pcBitstream->getNumBitsLeft())
+    {
+      UInt trailingNullByte=m_pcBitstream->readByte();
+      if (trailingNullByte!=0)
+      {
+        printf("Trailing byte should be 0, but has value %02x\n", trailingNullByte);
+        assert(trailingNullByte==0);
+      }
+    }
+  }
+}
+
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+Void TDecSbac::xReadUnaryMaxSymbol( UInt& ruiSymbol, ContextModel* pcSCModel, Int iOffset, UInt uiMaxSymbol, const class TComCodingStatisticsClassType &whichStat )
+#else
+Void TDecSbac::xReadUnaryMaxSymbol( UInt& ruiSymbol, ContextModel* pcSCModel, Int iOffset, UInt uiMaxSymbol )
+#endif
+{
+  if (uiMaxSymbol == 0)
+  {
+    ruiSymbol = 0;
+    return;
+  }
+
+  m_pcTDecBinIf->decodeBin( ruiSymbol, pcSCModel[0] RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(whichStat) );
+
+  if( ruiSymbol == 0 || uiMaxSymbol == 1 )
+  {
+    return;
+  }
+
+  UInt uiSymbol = 0;
+  UInt uiCont;
+
+  do
+  {
+    m_pcTDecBinIf->decodeBin( uiCont, pcSCModel[ iOffset ] RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(whichStat) );
+    uiSymbol++;
+  }
+  while( uiCont && ( uiSymbol < uiMaxSymbol - 1 ) );
+
+  if( uiCont && ( uiSymbol == uiMaxSymbol - 1 ) )
+  {
+    uiSymbol++;
+  }
+
+  ruiSymbol = uiSymbol;
+}
+
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+Void TDecSbac::xReadEpExGolomb( UInt& ruiSymbol, UInt uiCount, const class TComCodingStatisticsClassType &whichStat )
+#else
+Void TDecSbac::xReadEpExGolomb( UInt& ruiSymbol, UInt uiCount )
+#endif
+{
+  UInt uiSymbol = 0;
+  UInt uiBit = 1;
+
+  while( uiBit )
+  {
+    m_pcTDecBinIf->decodeBinEP( uiBit RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(whichStat) );
+    uiSymbol += uiBit << uiCount++;
+  }
+
+  if ( --uiCount )
+  {
+    UInt bins;
+    m_pcTDecBinIf->decodeBinsEP( bins, uiCount RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(whichStat) );
+    uiSymbol += bins;
+  }
+
+  ruiSymbol = uiSymbol;
+}
+
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+Void TDecSbac::xReadUnarySymbol( UInt& ruiSymbol, ContextModel* pcSCModel, Int iOffset, const class TComCodingStatisticsClassType &whichStat )
+#else
+Void TDecSbac::xReadUnarySymbol( UInt& ruiSymbol, ContextModel* pcSCModel, Int iOffset )
+#endif
+{
+  m_pcTDecBinIf->decodeBin( ruiSymbol, pcSCModel[0] RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(whichStat));
+
+  if( !ruiSymbol )
+  {
+    return;
+  }
+
+  UInt uiSymbol = 0;
+  UInt uiCont;
+
+  do
+  {
+    m_pcTDecBinIf->decodeBin( uiCont, pcSCModel[ iOffset ] RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(whichStat));
+    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
+ */
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+Void TDecSbac::xReadCoefRemainExGolomb ( UInt &rSymbol, UInt &rParam, const Bool useLimitedPrefixLength, const ChannelType channelType, const class TComCodingStatisticsClassType &whichStat )
+#else
+Void TDecSbac::xReadCoefRemainExGolomb ( UInt &rSymbol, UInt &rParam, const Bool useLimitedPrefixLength, const ChannelType channelType )
+#endif
+{
+  UInt prefix   = 0;
+  UInt codeWord = 0;
+
+  if (useLimitedPrefixLength)
+  {
+    const UInt longestPossiblePrefix = (32 - (COEF_REMAIN_BIN_REDUCTION + g_maxTrDynamicRange[channelType])) + COEF_REMAIN_BIN_REDUCTION;
+
+    do
+    {
+      prefix++;
+      m_pcTDecBinIf->decodeBinEP( codeWord RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(whichStat) );
+    }
+    while((codeWord != 0) && (prefix < longestPossiblePrefix));
+  }
+  else
+  {
+    do
+    {
+      prefix++;
+      m_pcTDecBinIf->decodeBinEP( codeWord RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(whichStat) );
+    }
+    while( codeWord);
+  }
+
+  codeWord  = 1 - codeWord;
+  prefix -= codeWord;
+  codeWord=0;
+
+  if (prefix < COEF_REMAIN_BIN_REDUCTION )
+  {
+    m_pcTDecBinIf->decodeBinsEP(codeWord,rParam RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(whichStat));
+    rSymbol = (prefix<<rParam) + codeWord;
+  }
+  else if (useLimitedPrefixLength)
+  {
+    const UInt maximumPrefixLength = (32 - (COEF_REMAIN_BIN_REDUCTION + g_maxTrDynamicRange[channelType]));
+
+    const UInt prefixLength = prefix - COEF_REMAIN_BIN_REDUCTION;
+    const UInt suffixLength = (prefixLength == maximumPrefixLength) ? (g_maxTrDynamicRange[channelType] - rParam) : prefixLength;
+
+    m_pcTDecBinIf->decodeBinsEP(codeWord, (suffixLength + rParam) RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(whichStat));
+
+    rSymbol = codeWord + ((((1 << prefixLength) - 1) + COEF_REMAIN_BIN_REDUCTION) << rParam);
+  }
+  else
+  {
+    m_pcTDecBinIf->decodeBinsEP(codeWord,prefix-COEF_REMAIN_BIN_REDUCTION+rParam RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(whichStat));
+    rSymbol = (((1<<(prefix-COEF_REMAIN_BIN_REDUCTION))+COEF_REMAIN_BIN_REDUCTION-1)<<rParam)+codeWord;
+  }
+}
+
+
+/** 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 (uiSymbol == 1)
+  {
+    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 );
+
+    const UInt minCoeffSizeY = pcCU->getPic()->getMinCUWidth() * pcCU->getPic()->getMinCUHeight();
+    const UInt offsetY       = minCoeffSizeY * uiAbsPartIdx;
+    for (UInt ch=0; ch < pcCU->getPic()->getNumberValidComponents(); ch++)
+    {
+      const ComponentID compID = ComponentID(ch);
+      const UInt offset = offsetY >> (pcCU->getPic()->getComponentScaleX(compID) + pcCU->getPic()->getComponentScaleY(compID));
+      Pel * pPCMSample  = pcCU->getPCMSample(compID) + offset;
+      const UInt width  = pcCU->getWidth (uiAbsPartIdx) >> pcCU->getPic()->getComponentScaleX(compID);
+      const UInt height = pcCU->getHeight(uiAbsPartIdx) >> pcCU->getPic()->getComponentScaleY(compID);
+      const UInt sampleBits = pcCU->getSlice()->getSPS()->getPCMBitDepth(toChannelType(compID));
+      for (UInt y=0; y<height; y++)
+      {
+        for (UInt x=0; x<width; x++)
+        {
+          UInt sample;
+          m_pcTDecBinIf->xReadPCMCode(sampleBits, sample);
+          pPCMSample[x] = sample;
+        }
+        pPCMSample += width;
+      }
+    }
+
+    m_pcTDecBinIf->start();
+  }
+}
+
+Void TDecSbac::parseCUTransquantBypassFlag( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  UInt uiSymbol;
+  m_pcTDecBinIf->decodeBin( uiSymbol, m_CUTransquantBypassFlagSCModel.get( 0, 0, 0 ) RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(STATS__CABAC_BITS__TQ_BYPASS_FLAG) );
+  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 ) RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(STATS__CABAC_BITS__SKIP_FLAG) );
+  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");
+
+  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 );
+  }
+}
+
+
+/** 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 ) RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(STATS__CABAC_BITS__MERGE_FLAG) );
+  pcCU->setMergeFlagSubParts( uiSymbol ? true : false, uiAbsPartIdx, uiPUIdx, uiDepth );
+
+  DTRACE_CABAC_VL( g_nSymbolCounter++ );
+  DTRACE_CABAC_T( "\tMergeFlag: " );
+  DTRACE_CABAC_V( uiSymbol );
+  DTRACE_CABAC_T( "\tAddress: " );
+  DTRACE_CABAC_V( pcCU->getCtuRsAddr() );
+  DTRACE_CABAC_T( "\tuiAbsPartIdx: " );
+  DTRACE_CABAC_V( uiAbsPartIdx );
+  DTRACE_CABAC_T( "\n" );
+}
+
+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 ) RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(STATS__CABAC_BITS__MERGE_INDEX) );
+      }
+      else
+      {
+        m_pcTDecBinIf->decodeBinEP( uiSymbol RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(STATS__CABAC_BITS__MERGE_INDEX) );
+      }
+      if( uiSymbol == 0 )
+      {
+        break;
+      }
+    }
+  }
+  ruiMergeIndex = uiUnaryIdx;
+
+  DTRACE_CABAC_VL( g_nSymbolCounter++ )
+  DTRACE_CABAC_T( "\tparseMergeIndex()" )
+  DTRACE_CABAC_T( "\tuiMRGIdx= " )
+  DTRACE_CABAC_V( ruiMergeIndex )
+  DTRACE_CABAC_T( "\n" )
+}
+
+Void TDecSbac::parseMVPIdx      ( Int& riMVPIdx )
+{
+  UInt uiSymbol;
+  xReadUnaryMaxSymbol(uiSymbol, m_cMVPIdxSCModel.get(0), 1, AMVP_MAX_NUM_CANDS-1 RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(STATS__CABAC_BITS__MVP_IDX) );
+  riMVPIdx = uiSymbol;
+}
+
+Void TDecSbac::parseSplitFlag     ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  if( uiDepth == g_uiMaxCUDepth - g_uiAddCUDepth )
+  {
+    pcCU->setDepthSubParts( uiDepth, uiAbsPartIdx );
+    return;
+  }
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+  const TComCodingStatisticsClassType ctype(STATS__CABAC_BITS__SPLIT_FLAG, g_aucConvertToBit[g_uiMaxCUWidth>>uiDepth]+2);
+#endif
+
+  UInt uiSymbol;
+  m_pcTDecBinIf->decodeBin( uiSymbol, m_cCUSplitFlagSCModel.get( 0, 0, pcCU->getCtxSplitFlag( uiAbsPartIdx, uiDepth ) ) RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(ctype) );
+  DTRACE_CABAC_VL( g_nSymbolCounter++ )
+  DTRACE_CABAC_T( "\tSplitFlag\n" )
+  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 RExt__DECODER_DEBUG_BIT_STATISTICS
+  const TComCodingStatisticsClassType ctype(STATS__CABAC_BITS__PART_SIZE, g_aucConvertToBit[g_uiMaxCUWidth>>uiDepth]+2);
+#endif
+
+  if ( pcCU->isIntra( uiAbsPartIdx ) )
+  {
+    uiSymbol = 1;
+    if( uiDepth == g_uiMaxCUDepth - g_uiAddCUDepth )
+    {
+      m_pcTDecBinIf->decodeBin( uiSymbol, m_cCUPartSizeSCModel.get( 0, 0, 0) RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(ctype) );
+    }
+    eMode = uiSymbol ? SIZE_2Nx2N : SIZE_NxN;
+    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
+  {
+    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) RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(ctype) );
+      if ( uiSymbol )
+      {
+        break;
+      }
+      uiMode++;
+    }
+    eMode = (PartSize) uiMode;
+    if ( pcCU->getSlice()->getSPS()->getAMPAcc( uiDepth ) )
+    {
+      if (eMode == SIZE_2NxN)
+      {
+        m_pcTDecBinIf->decodeBin(uiSymbol, m_cCUPartSizeSCModel.get( 0, 0, 3 ) RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(ctype));
+        if (uiSymbol == 0)
+        {
+          m_pcTDecBinIf->decodeBinEP(uiSymbol RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(ctype) );
+          eMode = (uiSymbol == 0? SIZE_2NxnU : SIZE_2NxnD);
+        }
+      }
+      else if (eMode == SIZE_Nx2N)
+      {
+        m_pcTDecBinIf->decodeBin(uiSymbol, m_cCUPartSizeSCModel.get( 0, 0, 3 ) RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(ctype) );
+        if (uiSymbol == 0)
+        {
+          m_pcTDecBinIf->decodeBinEP(uiSymbol RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(ctype) );
+          eMode = (uiSymbol == 0? SIZE_nLx2N : SIZE_nRx2N);
+        }
+      }
+    }
+  }
+  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 ) RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(STATS__CABAC_BITS__PRED_MODE) );
+  iPredMode += uiSymbol;
+  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()->getNumPartitionsInCtu() >> ( pcCU->getDepth(absPartIdx) << 1 ) ) >> 2;
+  UInt mpmPred[4],symbol;
+  Int j,intraPredMode;
+  if (mode==SIZE_NxN)
+  {
+    depth++;
+  }
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+  const TComCodingStatisticsClassType ctype(STATS__CABAC_BITS__INTRA_DIR_ANG, g_aucConvertToBit[g_uiMaxCUWidth>>depth]+2, CHANNEL_TYPE_LUMA);
+#endif
+  for (j=0;j<partNum;j++)
+  {
+    m_pcTDecBinIf->decodeBin( symbol, m_cCUIntraPredSCModel.get( 0, 0, 0) RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(ctype) );
+    mpmPred[j] = symbol;
+  }
+  for (j=0;j<partNum;j++)
+  {
+    Int preds[NUM_MOST_PROBABLE_MODES] = {-1, -1, -1};
+    Int predNum = pcCU->getIntraDirPredictor(absPartIdx+partOffset*j, preds, COMPONENT_Y);
+    if (mpmPred[j])
+    {
+      m_pcTDecBinIf->decodeBinEP( symbol RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(ctype) );
+      if (symbol)
+      {
+        m_pcTDecBinIf->decodeBinEP( symbol RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(ctype) );
+        symbol++;
+      }
+      intraPredMode = preds[symbol];
+    }
+    else
+    {
+      m_pcTDecBinIf->decodeBinsEP( symbol, 5 RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(ctype) );
+      intraPredMode = symbol;
+
+      //postponed sorting of MPMs (only in remaining branch)
+      assert(predNum>=3); // It is currently always 3!
+      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->setIntraDirSubParts(CHANNEL_TYPE_LUMA, (UChar)intraPredMode, absPartIdx+partOffset*j, depth );
+  }
+}
+
+
+Void TDecSbac::parseIntraDirChroma( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  UInt uiSymbol;
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+  const TComCodingStatisticsClassType ctype(STATS__CABAC_BITS__INTRA_DIR_ANG, g_aucConvertToBit[g_uiMaxCUWidth>>uiDepth]+2, CHANNEL_TYPE_CHROMA);
+#endif
+
+  m_pcTDecBinIf->decodeBin( uiSymbol, m_cCUChromaPredSCModel.get( 0, 0, 0 ) RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(ctype) );
+  if( uiSymbol == 0 )
+  {
+    uiSymbol = DM_CHROMA_IDX;
+  }
+  else
+  {
+    UInt uiIPredMode;
+    m_pcTDecBinIf->decodeBinsEP( uiIPredMode, 2 RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(ctype) );
+    UInt uiAllowedChromaDir[ NUM_CHROMA_MODE ];
+    pcCU->getAllowedChromaDir( uiAbsPartIdx, uiAllowedChromaDir );
+    uiSymbol = uiAllowedChromaDir[ uiIPredMode ];
+  }
+
+  pcCU->setIntraDirSubParts( CHANNEL_TYPE_CHROMA, uiSymbol, uiAbsPartIdx, uiDepth );
+}
+
+
+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 ) RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(STATS__CABAC_BITS__INTER_DIR) );
+  }
+
+  if( uiSymbol )
+  {
+    uiSymbol = 2;
+  }
+  else
+  {
+    m_pcTDecBinIf->decodeBin( uiSymbol, *( pCtx + 4 ) RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(STATS__CABAC_BITS__INTER_DIR) );
+    assert(uiSymbol == 0 || uiSymbol == 1);
+  }
+
+  uiSymbol++;
+  ruiInterDir = uiSymbol;
+  return;
+}
+
+Void TDecSbac::parseRefFrmIdx( TComDataCU* pcCU, Int& riRefFrmIdx, RefPicList eRefList )
+{
+  UInt uiSymbol;
+
+  ContextModel *pCtx = m_cCURefPicSCModel.get( 0 );
+  m_pcTDecBinIf->decodeBin( uiSymbol, *pCtx RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(STATS__CABAC_BITS__REF_FRM_IDX) );
+
+  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 RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(STATS__CABAC_BITS__REF_FRM_IDX) );
+      }
+      else
+      {
+        m_pcTDecBinIf->decodeBinEP( uiSymbol RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(STATS__CABAC_BITS__REF_FRM_IDX) );
+      }
+      if( uiSymbol == 0 )
+      {
+        break;
+      }
+    }
+    uiSymbol = ui + 1;
+  }
+  riRefFrmIdx = uiSymbol;
+
+  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 RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(STATS__CABAC_BITS__MVD) );
+    m_pcTDecBinIf->decodeBin( uiVerAbs, *pCtx RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(STATS__CABAC_BITS__MVD) );
+
+    const Bool bHorAbsGr0 = uiHorAbs != 0;
+    const Bool bVerAbsGr0 = uiVerAbs != 0;
+    pCtx++;
+
+    if( bHorAbsGr0 )
+    {
+      m_pcTDecBinIf->decodeBin( uiSymbol, *pCtx RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(STATS__CABAC_BITS__MVD) );
+      uiHorAbs += uiSymbol;
+    }
+
+    if( bVerAbsGr0 )
+    {
+      m_pcTDecBinIf->decodeBin( uiSymbol, *pCtx RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(STATS__CABAC_BITS__MVD) );
+      uiVerAbs += uiSymbol;
+    }
+
+    if( bHorAbsGr0 )
+    {
+      if( 2 == uiHorAbs )
+      {
+        xReadEpExGolomb( uiSymbol, 1 RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(STATS__CABAC_BITS__MVD_EP) );
+        uiHorAbs += uiSymbol;
+      }
+
+      m_pcTDecBinIf->decodeBinEP( uiHorSign RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(STATS__CABAC_BITS__MVD_EP) );
+    }
+
+    if( bVerAbsGr0 )
+    {
+      if( 2 == uiVerAbs )
+      {
+        xReadEpExGolomb( uiSymbol, 1 RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(STATS__CABAC_BITS__MVD_EP) );
+        uiVerAbs += uiSymbol;
+      }
+
+      m_pcTDecBinIf->decodeBinEP( uiVerSign RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(STATS__CABAC_BITS__MVD_EP) );
+    }
+
+  }
+
+  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::parseCrossComponentPrediction( TComTU &rTu, ComponentID compID )
+{
+  TComDataCU *pcCU = rTu.getCU();
+
+  if( isLuma(compID) || !pcCU->getSlice()->getPPS()->getUseCrossComponentPrediction() ) return;
+
+  const UInt uiAbsPartIdx = rTu.GetAbsPartIdxTU();
+
+  if (!pcCU->isIntra(uiAbsPartIdx) || (pcCU->getIntraDir( CHANNEL_TYPE_CHROMA, uiAbsPartIdx ) == DM_CHROMA_IDX))
+  {
+    Char alpha  = 0;
+    UInt symbol = 0;
+
+    DTRACE_CABAC_VL( g_nSymbolCounter++ )
+    DTRACE_CABAC_T("\tparseCrossComponentPrediction()")
+    DTRACE_CABAC_T( "\tAddr=" )
+    DTRACE_CABAC_V( compID )
+    DTRACE_CABAC_T( "\tuiAbsPartIdx=" )
+    DTRACE_CABAC_V( uiAbsPartIdx )
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+    TComCodingStatisticsClassType ctype(STATS__CABAC_BITS__CROSS_COMPONENT_PREDICTION, (g_aucConvertToBit[rTu.getRect(compID).width] + 2), compID);
+#endif
+    ContextModel *pCtx = m_cCrossComponentPredictionSCModel.get(0, 0) + ((compID == COMPONENT_Cr) ? (NUM_CROSS_COMPONENT_PREDICTION_CTX >> 1) : 0);
+    m_pcTDecBinIf->decodeBin( symbol, pCtx[0] RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(ctype) );
+
+    if(symbol != 0)
+    {
+      // Cross-component prediction alpha is non-zero.
+      UInt sign = 0;
+      m_pcTDecBinIf->decodeBin( symbol, pCtx[1] RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(ctype) );
+
+      if (symbol != 0)
+      {
+        // alpha is 2 (symbol=1), 4(symbol=2) or 8(symbol=3).
+        // Read up to two more bits
+        xReadUnaryMaxSymbol( symbol, (pCtx + 2), 1, 2 RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(ctype) );
+        symbol += 1;
+      }
+      m_pcTDecBinIf->decodeBin( sign, pCtx[4] RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(ctype) );
+
+      alpha = (sign != 0) ? -(1 << symbol) : (1 << symbol);
+    }
+    DTRACE_CABAC_T( "\tAlpha=" )
+    DTRACE_CABAC_V( alpha )
+    DTRACE_CABAC_T( "\n" )
+
+    pcCU->setCrossComponentPredictionAlphaPartRange( alpha, compID, uiAbsPartIdx, rTu.GetAbsPartIdxNumParts( compID ) );
+  }
+}
+
+Void TDecSbac::parseTransformSubdivFlag( UInt& ruiSubdivFlag, UInt uiLog2TransformBlockSize )
+{
+  m_pcTDecBinIf->decodeBin( ruiSubdivFlag, m_cCUTransSubdivFlagSCModel.get( 0, 0, uiLog2TransformBlockSize )
+      RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(TComCodingStatisticsClassType(STATS__CABAC_BITS__TRANSFORM_SUBDIV_FLAG, 5-uiLog2TransformBlockSize))
+                          );
+  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" )
+}
+
+Void TDecSbac::parseQtRootCbf( UInt uiAbsPartIdx, UInt& uiQtRootCbf )
+{
+  UInt uiSymbol;
+  const UInt uiCtx = 0;
+  m_pcTDecBinIf->decodeBin( uiSymbol , m_cCUQtRootCbfSCModel.get( 0, 0, uiCtx ) RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(STATS__CABAC_BITS__QT_ROOT_CBF) );
+  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" )
+
+  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 RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(STATS__CABAC_BITS__DELTA_QP_EP) );
+
+  if( uiDQp >= CU_DQP_TU_CMAX)
+  {
+    xReadEpExGolomb( uiSymbol, CU_DQP_EG_k RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(STATS__CABAC_BITS__DELTA_QP_EP));
+    uiDQp+=uiSymbol;
+  }
+
+  if ( uiDQp > 0 )
+  {
+    UInt uiSign;
+#if REPN_FORMAT_IN_VPS
+    Int qpBdOffsetY = pcCU->getSlice()->getQpBDOffsetY();
+#else
+    Int qpBdOffsetY = pcCU->getSlice()->getSPS()->getQpBDOffset(CHANNEL_TYPE_LUMA);
+#endif
+    m_pcTDecBinIf->decodeBinEP(uiSign RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(STATS__CABAC_BITS__DELTA_QP_EP));
+    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);
+}
+
+/** parse chroma qp adjustment, converting to the internal table representation.
+ * \returns Void
+ */
+Void TDecSbac::parseChromaQpAdjustment( TComDataCU* cu, UInt absPartIdx, UInt depth )
+{
+  UInt symbol;
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+  const TComCodingStatisticsClassType ctype(STATS__CABAC_BITS__CHROMA_QP_ADJUSTMENT, g_aucConvertToBit[g_uiMaxCUWidth>>depth]+2, CHANNEL_TYPE_CHROMA);
+#endif
+
+  Int tableSize = cu->getSlice()->getPPS()->getChromaQpAdjTableSize();
+
+  /* cu_chroma_qp_adjustment_flag */
+  m_pcTDecBinIf->decodeBin( symbol, m_ChromaQpAdjFlagSCModel.get( 0, 0, 0 ) RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(ctype) );
+
+  if (symbol && tableSize > 1) {
+    /* cu_chroma_qp_adjustment_idc */
+    xReadUnaryMaxSymbol( symbol,  &m_ChromaQpAdjIdcSCModel.get( 0, 0, 0 ), 0, tableSize - 1 RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(ctype) );
+    symbol++;
+  }
+  /* NB, symbol = 0 if outer flag is not set,
+   *              1 if outer flag is set and there is no inner flag
+   *              1+ otherwise */
+  cu->setChromaQpAdjSubParts( symbol, absPartIdx, depth );
+  cu->setCodedChromaQpAdj(symbol);
+}
+
+Void TDecSbac::parseQtCbf( TComTU &rTu, const ComponentID compID, const Bool lowestLevel )
+{
+  TComDataCU* pcCU = rTu.getCU();
+
+  const UInt absPartIdx       = rTu.GetAbsPartIdxTU(compID);
+  const UInt TUDepth          = rTu.GetTransformDepthRel();
+  const UInt uiCtx            = pcCU->getCtxQtCbf( rTu, toChannelType(compID) );
+  const UInt contextSet       = toChannelType(compID);
+
+  const UInt width            = rTu.getRect(compID).width;
+  const UInt height           = rTu.getRect(compID).height;
+  const Bool canQuadSplit     = (width >= (MIN_TU_SIZE * 2)) && (height >= (MIN_TU_SIZE * 2));
+  const UInt coveredPartIdxes = rTu.GetAbsPartIdxNumParts(compID);
+
+  //             Since the CBF for chroma is coded at the highest level possible, if sub-TUs are
+  //             to be coded for a 4x8 chroma TU, their CBFs must be coded at the highest 4x8 level
+  //             (i.e. where luma TUs are 8x8 rather than 4x4)
+  //    ___ ___
+  //   |   |   | <- 4 x (8x8 luma + 4x8 4:2:2 chroma)
+  //   |___|___|    each quadrant has its own chroma CBF
+  //   |   |   | _ _ _ _
+  //   |___|___|        |
+  //   <--16--->        V
+  //                   _ _
+  //                  |_|_| <- 4 x 4x4 luma + 1 x 4x8 4:2:2 chroma
+  //                  |_|_|    no chroma CBF is coded - instead the parent CBF is inherited
+  //                  <-8->    if sub-TUs are present, their CBFs had to be coded at the parent level
+
+  const UInt lowestTUDepth = TUDepth + ((!lowestLevel && !canQuadSplit) ? 1 : 0); //unsplittable TUs inherit their parent's CBF
+        UInt lowestTUCBF   = 0;
+
+  if ((width != height) && (lowestLevel || !canQuadSplit)) //if sub-TUs are present
+  {
+    const UInt subTUDepth        = lowestTUDepth + 1;
+    const UInt partIdxesPerSubTU = rTu.GetAbsPartIdxNumParts(compID) >> 1;
+
+    UInt combinedSubTUCBF = 0;
+
+    for (UInt subTU = 0; subTU < 2; subTU++)
+    {
+      UInt uiCbf = MAX_UINT;
+      m_pcTDecBinIf->decodeBin(uiCbf, m_cCUQtCbfSCModel.get(0, contextSet, uiCtx) RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(TComCodingStatisticsClassType(STATS__CABAC_BITS__QT_CBF, g_aucConvertToBit[rTu.getRect(compID).width]+2, compID)));
+
+      const UInt subTUAbsPartIdx = absPartIdx + (subTU * partIdxesPerSubTU);
+      pcCU->setCbfPartRange((uiCbf << subTUDepth), compID, subTUAbsPartIdx, partIdxesPerSubTU);
+      combinedSubTUCBF |= uiCbf;
+
+      DTRACE_CABAC_VL( g_nSymbolCounter++ )
+      DTRACE_CABAC_T( "\tparseQtCbf()" )
+      DTRACE_CABAC_T( "\tsub-TU=" )
+      DTRACE_CABAC_V( subTU )
+      DTRACE_CABAC_T( "\tsymbol=" )
+      DTRACE_CABAC_V( uiCbf )
+      DTRACE_CABAC_T( "\tctx=" )
+      DTRACE_CABAC_V( uiCtx )
+      DTRACE_CABAC_T( "\tetype=" )
+      DTRACE_CABAC_V( compID )
+      DTRACE_CABAC_T( "\tuiAbsPartIdx=" )
+      DTRACE_CABAC_V( subTUAbsPartIdx )
+      DTRACE_CABAC_T( "\n" )
+    }
+
+    //propagate the sub-TU CBF up to the lowest TU level
+    if (combinedSubTUCBF != 0)
+    {
+      pcCU->bitwiseOrCbfPartRange((combinedSubTUCBF << lowestTUDepth), compID, absPartIdx, coveredPartIdxes);
+      lowestTUCBF = combinedSubTUCBF;
+    }
+  }
+  else
+  {
+    UInt uiCbf = MAX_UINT;
+    m_pcTDecBinIf->decodeBin(uiCbf, m_cCUQtCbfSCModel.get(0, contextSet, uiCtx) RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(TComCodingStatisticsClassType(STATS__CABAC_BITS__QT_CBF, g_aucConvertToBit[rTu.getRect(compID).width]+2, compID)));
+
+    pcCU->setCbfSubParts((uiCbf << lowestTUDepth), compID, absPartIdx, rTu.GetTransformDepthTotalAdj(compID));
+
+    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( compID )
+    DTRACE_CABAC_T( "\tuiAbsPartIdx=" )
+    DTRACE_CABAC_V( rTu.GetAbsPartIdxTU(compID) )
+    DTRACE_CABAC_T( "\n" )
+
+    lowestTUCBF = uiCbf;
+  }
+
+  //propagate the lowest level CBF up to the current level
+  if (lowestTUCBF != 0)
+  {
+    for (UInt depth = TUDepth; depth < lowestTUDepth; depth++)
+    {
+      pcCU->bitwiseOrCbfPartRange((lowestTUCBF << depth), compID, absPartIdx, coveredPartIdxes);
+    }
+  }
+}
+
+
+Void TDecSbac::parseTransformSkipFlags (TComTU &rTu, ComponentID component)
+{
+  TComDataCU* pcCU=rTu.getCU();
+  UInt uiAbsPartIdx=rTu.GetAbsPartIdxTU(component);
+
+  if (pcCU->getCUTransquantBypass(uiAbsPartIdx))
+  {
+    return;
+  }
+
+  if (!TUCompRectHasAssociatedTransformSkipFlag(rTu.getRect(component), pcCU->getSlice()->getPPS()->getTransformSkipLog2MaxSize()))
+  {
+    return;
+  }
+
+  UInt useTransformSkip;
+
+  m_pcTDecBinIf->decodeBin( useTransformSkip , m_cTransformSkipSCModel.get( 0, toChannelType(component), 0 )
+      RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(TComCodingStatisticsClassType(STATS__CABAC_BITS__TRANSFORM_SKIP_FLAGS, component))
+                          );
+
+  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->getCtuRsAddr() )
+  DTRACE_CABAC_T( "\tetype=" )
+  DTRACE_CABAC_V( component )
+  DTRACE_CABAC_T( "\tuiAbsPartIdx=" )
+  DTRACE_CABAC_V( rTu.GetAbsPartIdxTU() )
+  DTRACE_CABAC_T( "\n" )
+
+  pcCU->setTransformSkipPartRange( useTransformSkip, component, uiAbsPartIdx, rTu.GetAbsPartIdxNumParts(component));
+}
+
+
+/** 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, ComponentID component, UInt uiScanIdx )
+{
+  UInt uiLast;
+
+  ContextModel *pCtxX = m_cCuCtxLastX.get( 0, toChannelType(component) );
+  ContextModel *pCtxY = m_cCuCtxLastY.get( 0, toChannelType(component) );
+
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+  TComCodingStatisticsClassType ctype(STATS__CABAC_BITS__LAST_SIG_X_Y, g_aucConvertToBit[width]+2, component);
+#endif
+
+
+  if ( uiScanIdx == SCAN_VER )
+  {
+    swap( width, height );
+  }
+
+  Int blkSizeOffsetX, blkSizeOffsetY, shiftX, shiftY;
+  getLastSignificantContextParameters(component, width, height, blkSizeOffsetX, blkSizeOffsetY, shiftX, shiftY);
+
+  //------------------
+
+  // posX
+
+  for( uiPosLastX = 0; uiPosLastX < g_uiGroupIdx[ width - 1 ]; uiPosLastX++ )
+  {
+    m_pcTDecBinIf->decodeBin( uiLast, *( pCtxX + blkSizeOffsetX + (uiPosLastX >>shiftX) ) RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(ctype) );
+
+    if( !uiLast )
+    {
+      break;
+    }
+  }
+
+  // posY
+
+  for( uiPosLastY = 0; uiPosLastY < g_uiGroupIdx[ height - 1 ]; uiPosLastY++ )
+  {
+    m_pcTDecBinIf->decodeBin( uiLast, *( pCtxY + blkSizeOffsetY + (uiPosLastY >>shiftY)) RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(ctype) );
+
+    if( !uiLast )
+    {
+      break;
+    }
+  }
+
+  // EP-coded part
+
+  if ( uiPosLastX > 3 )
+  {
+    UInt uiTemp  = 0;
+    UInt uiCount = ( uiPosLastX - 2 ) >> 1;
+    for ( Int i = uiCount - 1; i >= 0; i-- )
+    {
+      m_pcTDecBinIf->decodeBinEP( uiLast RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(ctype) );
+      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 RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(ctype) );
+      uiTemp += uiLast << i;
+    }
+    uiPosLastY = g_uiMinInGroup[ uiPosLastY ] + uiTemp;
+  }
+
+  if( uiScanIdx == SCAN_VER )
+  {
+    swap( uiPosLastX, uiPosLastY );
+  }
+}
+
+Void TDecSbac::parseCoeffNxN(  TComTU &rTu, ComponentID compID )
+{
+  TComDataCU* pcCU=rTu.getCU();
+  const UInt uiAbsPartIdx=rTu.GetAbsPartIdxTU(compID);
+  const TComRectangle &rRect=rTu.getRect(compID);
+  const UInt uiWidth=rRect.width;
+  const UInt uiHeight=rRect.height;
+  TCoeff* pcCoef=(pcCU->getCoeff(compID)+rTu.getCoefficientOffset(compID));
+
+  DTRACE_CABAC_VL( g_nSymbolCounter++ )
+  DTRACE_CABAC_T( "\tparseCoeffNxN()\teType=" )
+  DTRACE_CABAC_V( compID )
+  DTRACE_CABAC_T( "\twidth=" )
+  DTRACE_CABAC_V( uiWidth )
+  DTRACE_CABAC_T( "\theight=" )
+  DTRACE_CABAC_V( uiHeight )
+  DTRACE_CABAC_T( "\tdepth=" )
+//  DTRACE_CABAC_V( rTu.GetTransformDepthTotalAdj(compID) )
+  DTRACE_CABAC_V( rTu.GetTransformDepthTotal() )
+  DTRACE_CABAC_T( "\tabspartidx=" )
+//  DTRACE_CABAC_V( uiAbsPartIdx )
+  DTRACE_CABAC_V( rTu.GetAbsPartIdxTU(compID) )
+  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->getCtuRsAddr() )
+  DTRACE_CABAC_T( "\tinCU-X=" )
+//  DTRACE_CABAC_V( g_auiRasterToPelX[ g_auiZscanToRaster[uiAbsPartIdx] ] )
+  DTRACE_CABAC_V( g_auiRasterToPelX[ g_auiZscanToRaster[rTu.GetAbsPartIdxTU(compID)] ] )
+  DTRACE_CABAC_T( "\tinCU-Y=" )
+// DTRACE_CABAC_V( g_auiRasterToPelY[ g_auiZscanToRaster[uiAbsPartIdx] ] )
+  DTRACE_CABAC_V( g_auiRasterToPelY[ g_auiZscanToRaster[rTu.GetAbsPartIdxTU(compID)] ] )
+  DTRACE_CABAC_T( "\tpredmode=" )
+  DTRACE_CABAC_V(  pcCU->getPredictionMode( uiAbsPartIdx ) )
+  DTRACE_CABAC_T( "\n" )
+
+  //--------------------------------------------------------------------------------------------------
+
+  if( uiWidth > pcCU->getSlice()->getSPS()->getMaxTrSize() )
+  {
+    std::cerr << "ERROR: parseCoeffNxN was passed a TU with dimensions larger than the maximum allowed size" << std::endl;
+    assert(false);
+    exit(1);
+  }
+
+  //--------------------------------------------------------------------------------------------------
+
+  //set parameters
+
+  const ChannelType  chType            = toChannelType(compID);
+  const UInt         uiLog2BlockWidth  = g_aucConvertToBit[ uiWidth  ] + 2;
+  const UInt         uiLog2BlockHeight = g_aucConvertToBit[ uiHeight ] + 2;
+  const UInt         uiMaxNumCoeff     = uiWidth * uiHeight;
+  const UInt         uiMaxNumCoeffM1   = uiMaxNumCoeff - 1;
+
+  const ChannelType  channelType       = toChannelType(compID);
+  const Bool         extendedPrecision = pcCU->getSlice()->getSPS()->getUseExtendedPrecision();
+
+  const Bool         alignCABACBeforeBypass = pcCU->getSlice()->getSPS()->getAlignCABACBeforeBypass();
+
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+  TComCodingStatisticsClassType ctype_group(STATS__CABAC_BITS__SIG_COEFF_GROUP_FLAG, uiLog2BlockWidth, compID);
+  TComCodingStatisticsClassType ctype_map(STATS__CABAC_BITS__SIG_COEFF_MAP_FLAG, uiLog2BlockWidth, compID);
+  TComCodingStatisticsClassType ctype_gt1(STATS__CABAC_BITS__GT1_FLAG, uiLog2BlockWidth, compID);
+  TComCodingStatisticsClassType ctype_gt2(STATS__CABAC_BITS__GT2_FLAG, uiLog2BlockWidth, compID);
+#endif
+
+  Bool beValid;
+  if (pcCU->getCUTransquantBypass(uiAbsPartIdx))
+  {
+    beValid = false;
+    if((!pcCU->isIntra(uiAbsPartIdx)) && pcCU->isRDPCMEnabled(uiAbsPartIdx))
+      parseExplicitRdpcmMode(rTu, compID);
+  }
+  else
+  {
+    beValid = pcCU->getSlice()->getPPS()->getSignHideFlag() > 0;
+  }
+
+  UInt absSum = 0;
+
+  //--------------------------------------------------------------------------------------------------
+
+  if(pcCU->getSlice()->getPPS()->getUseTransformSkip())
+  {
+    parseTransformSkipFlags(rTu, compID);
+    //  This TU has coefficients and is transform skipped. Check whether is inter coded and if yes decode the explicit RDPCM mode
+    if(pcCU->getTransformSkip(uiAbsPartIdx, compID) && (!pcCU->isIntra(uiAbsPartIdx)) && pcCU->isRDPCMEnabled(uiAbsPartIdx) )
+    {
+      parseExplicitRdpcmMode(rTu, compID);
+      if(pcCU->getExplicitRdpcmMode(compID, uiAbsPartIdx) != RDPCM_OFF)
+      {
+        //  Sign data hiding is avoided for horizontal and vertical RDPCM modes
+        beValid = false;
+      }
+    }
+  }
+
+  Int uiIntraMode = -1;
+  const Bool       bIsLuma = isLuma(compID);
+  Int isIntra = pcCU->isIntra(uiAbsPartIdx) ? 1 : 0;
+  if ( isIntra && pcCU->isRDPCMEnabled(uiAbsPartIdx) )
+  {
+    uiIntraMode = pcCU->getIntraDir( toChannelType(compID), uiAbsPartIdx );
+    uiIntraMode = (uiIntraMode==DM_CHROMA_IDX && !bIsLuma) ? pcCU->getIntraDir(CHANNEL_TYPE_LUMA, getChromasCorrespondingPULumaIdx(uiAbsPartIdx, rTu.GetChromaFormat())) : uiIntraMode;
+    uiIntraMode = ((rTu.GetChromaFormat() == CHROMA_422) && !bIsLuma) ? g_chroma422IntraAngleMappingTable[uiIntraMode] : uiIntraMode;
+
+    Bool transformSkip = pcCU->getTransformSkip( uiAbsPartIdx,compID);
+    Bool rdpcm_lossy = ( transformSkip /*&& isIntra*/ && ( (uiIntraMode == HOR_IDX) || (uiIntraMode == VER_IDX) ) );
+    if ( rdpcm_lossy )
+    {
+      beValid = false;
+    }
+  }
+
+  //--------------------------------------------------------------------------------------------------
+
+  const Bool  bUseGolombRiceParameterAdaptation = pcCU->getSlice()->getSPS()->getUseGolombRiceParameterAdaptation();
+        UInt &currentGolombRiceStatistic        = m_golombRiceAdaptationStatistics[rTu.getGolombRiceStatisticsIndex(compID)];
+
+  //select scans
+  TUEntropyCodingParameters codingParameters;
+  getTUEntropyCodingParameters(codingParameters, rTu, compID);
+
+  //===== decode last significant =====
+  UInt uiPosLastX, uiPosLastY;
+  parseLastSignificantXY( uiPosLastX, uiPosLastY, uiWidth, uiHeight, compID, codingParameters.scanType );
+  UInt uiBlkPosLast      = uiPosLastX + (uiPosLastY<<uiLog2BlockWidth);
+  pcCoef[ uiBlkPosLast ] = 1;
+
+  //===== decode significance flags =====
+  UInt uiScanPosLast;
+  for( uiScanPosLast = 0; uiScanPosLast < uiMaxNumCoeffM1; uiScanPosLast++ )
+  {
+    UInt uiBlkPos = codingParameters.scan[ uiScanPosLast ];
+    if( uiBlkPosLast == uiBlkPos )
+    {
+      break;
+    }
+  }
+
+  ContextModel * const baseCoeffGroupCtx = m_cCUSigCoeffGroupSCModel.get( 0, isChroma(chType) );
+  ContextModel * const baseCtx = m_cCUSigSCModel.get( 0, 0 ) + getSignificanceMapContextOffset(compID);
+
+  const Int  iLastScanSet  = uiScanPosLast >> MLS_CG_SIZE;
+  UInt c1                  = 1;
+  UInt uiGoRiceParam       = 0;
+
+
+  UInt uiSigCoeffGroupFlag[ MLS_GRP_NUM ];
+  memset( uiSigCoeffGroupFlag, 0, sizeof(UInt) * MLS_GRP_NUM );
+
+  Int  iScanPosSig             = (Int) uiScanPosLast;
+  for( Int iSubSet = iLastScanSet; iSubSet >= 0; iSubSet-- )
+  {
+    Int  iSubPos   = iSubSet << MLS_CG_SIZE;
+    uiGoRiceParam  = currentGolombRiceStatistic / RExt__GOLOMB_RICE_INCREMENT_DIVISOR;
+    Bool updateGolombRiceStatistics = bUseGolombRiceParameterAdaptation; //leave the statistics at 0 when not using the adaptation system
+    Int numNonZero = 0;
+
+    Int lastNZPosInCG  = -1;
+    Int firstNZPosInCG = 1 << MLS_CG_SIZE;
+
+    Bool escapeDataPresentInGroup = false;
+
+    Int pos[1 << MLS_CG_SIZE];
+
+    if( iScanPosSig == (Int) uiScanPosLast )
+    {
+      lastNZPosInCG  = iScanPosSig;
+      firstNZPosInCG = iScanPosSig;
+      iScanPosSig--;
+      pos[ numNonZero ] = uiBlkPosLast;
+      numNonZero = 1;
+    }
+
+    // decode significant_coeffgroup_flag
+    Int iCGBlkPos = codingParameters.scanCG[ iSubSet ];
+    Int iCGPosY   = iCGBlkPos / codingParameters.widthInGroups;
+    Int iCGPosX   = iCGBlkPos - (iCGPosY * codingParameters.widthInGroups);
+
+    if( iSubSet == iLastScanSet || iSubSet == 0)
+    {
+      uiSigCoeffGroupFlag[ iCGBlkPos ] = 1;
+    }
+    else
+    {
+      UInt uiSigCoeffGroup;
+      UInt uiCtxSig  = TComTrQuant::getSigCoeffGroupCtxInc( uiSigCoeffGroupFlag, iCGPosX, iCGPosY, codingParameters.widthInGroups, codingParameters.heightInGroups );
+      m_pcTDecBinIf->decodeBin( uiSigCoeffGroup, baseCoeffGroupCtx[ uiCtxSig ] RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(ctype_group) );
+      uiSigCoeffGroupFlag[ iCGBlkPos ] = uiSigCoeffGroup;
+    }
+
+    // decode significant_coeff_flag
+    const Int patternSigCtx = TComTrQuant::calcPatternSigCtx(uiSigCoeffGroupFlag, iCGPosX, iCGPosY, codingParameters.widthInGroups, codingParameters.heightInGroups);
+
+    UInt uiBlkPos, uiSig, uiCtxSig;
+    for( ; iScanPosSig >= iSubPos; iScanPosSig-- )
+    {
+      uiBlkPos  = codingParameters.scan[ iScanPosSig ];
+      uiSig     = 0;
+
+      if( uiSigCoeffGroupFlag[ iCGBlkPos ] )
+      {
+        if( iScanPosSig > iSubPos || iSubSet == 0  || numNonZero )
+        {
+          uiCtxSig  = TComTrQuant::getSigCtxInc( patternSigCtx, codingParameters, iScanPosSig, uiLog2BlockWidth, uiLog2BlockHeight, chType );
+          m_pcTDecBinIf->decodeBin( uiSig, baseCtx[ uiCtxSig ] RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(ctype_map) );
+        }
+        else
+        {
+          uiSig = 1;
+        }
+      }
+      pcCoef[ uiBlkPos ] = uiSig;
+      if( uiSig )
+      {
+        pos[ numNonZero ] = uiBlkPos;
+        numNonZero ++;
+        if( lastNZPosInCG == -1 )
+        {
+          lastNZPosInCG = iScanPosSig;
+        }
+        firstNZPosInCG = iScanPosSig;
+      }
+    }
+
+    if( numNonZero > 0 )
+    {
+      Bool signHidden = ( lastNZPosInCG - firstNZPosInCG >= SBH_THRESHOLD );
+
+      absSum = 0;
+
+      const UInt uiCtxSet = getContextSetIndex(compID, iSubSet, (c1 == 0));
+      c1 = 1;
+      UInt uiBin;
+
+      ContextModel *baseCtxMod = m_cCUOneSCModel.get( 0, 0 ) + (NUM_ONE_FLAG_CTX_PER_SET * uiCtxSet);
+
+      Int absCoeff[1 << MLS_CG_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] RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(ctype_gt1) );
+        if( uiBin == 1 )
+        {
+          c1 = 0;
+          if (firstC2FlagIdx == -1)
+          {
+            firstC2FlagIdx = idx;
+          }
+          else //if a greater-than-one has been encountered already this group
+          {
+            escapeDataPresentInGroup = true;
+          }
+        }
+        else if( (c1 < 3) && (c1 > 0) )
+        {
+          c1++;
+        }
+        absCoeff[ idx ] = uiBin + 1;
+      }
+
+      if (c1 == 0)
+      {
+        baseCtxMod = m_cCUAbsSCModel.get( 0, 0 ) + (NUM_ABS_FLAG_CTX_PER_SET * uiCtxSet);
+        if ( firstC2FlagIdx != -1)
+        {
+          m_pcTDecBinIf->decodeBin( uiBin, baseCtxMod[0] RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(ctype_gt2) );
+          absCoeff[ firstC2FlagIdx ] = uiBin + 2;
+          if (uiBin != 0)
+          {
+            escapeDataPresentInGroup = true;
+          }
+        }
+      }
+
+      escapeDataPresentInGroup = escapeDataPresentInGroup || (numNonZero > C1FLAG_NUMBER);
+
+      const Bool alignGroup = escapeDataPresentInGroup && alignCABACBeforeBypass;
+
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+      TComCodingStatisticsClassType ctype_signs((alignGroup ? STATS__CABAC_BITS__ALIGNED_SIGN_BIT    : STATS__CABAC_BITS__SIGN_BIT   ), uiLog2BlockWidth, compID);
+      TComCodingStatisticsClassType ctype_escs ((alignGroup ? STATS__CABAC_BITS__ALIGNED_ESCAPE_BITS : STATS__CABAC_BITS__ESCAPE_BITS), uiLog2BlockWidth, compID);
+#endif
+
+      if (alignGroup)
+      {
+        m_pcTDecBinIf->align();
+      }
+
+      UInt coeffSigns;
+      if ( signHidden && beValid )
+      {
+        m_pcTDecBinIf->decodeBinsEP( coeffSigns, numNonZero-1 RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(ctype_signs) );
+        coeffSigns <<= 32 - (numNonZero-1);
+      }
+      else
+      {
+        m_pcTDecBinIf->decodeBinsEP( coeffSigns, numNonZero RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(ctype_signs) );
+        coeffSigns <<= 32 - numNonZero;
+      }
+
+      Int iFirstCoeff2 = 1;
+      if (escapeDataPresentInGroup)
+      {
+        for( Int idx = 0; idx < numNonZero; idx++ )
+        {
+          UInt baseLevel  = (idx < C1FLAG_NUMBER)? (2 + iFirstCoeff2) : 1;
+
+          if( absCoeff[ idx ] == baseLevel)
+          {
+            UInt uiLevel;
+            xReadCoefRemainExGolomb( uiLevel, uiGoRiceParam, extendedPrecision, channelType RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(ctype_escs) );
+
+            absCoeff[ idx ] = uiLevel + baseLevel;
+
+            if (absCoeff[idx] > (3 << uiGoRiceParam))
+            {
+              uiGoRiceParam = bUseGolombRiceParameterAdaptation ? (uiGoRiceParam + 1) : (std::min<UInt>((uiGoRiceParam + 1), 4));
+            }
+
+            if (updateGolombRiceStatistics)
+            {
+              const UInt initialGolombRiceParameter = currentGolombRiceStatistic / RExt__GOLOMB_RICE_INCREMENT_DIVISOR;
+
+              if (uiLevel >= (3 << initialGolombRiceParameter))
+              {
+                currentGolombRiceStatistic++;
+              }
+              else if (((uiLevel * 2) < (1 << initialGolombRiceParameter)) && (currentGolombRiceStatistic > 0))
+              {
+                currentGolombRiceStatistic--;
+              }
+
+              updateGolombRiceStatistics = false;
+            }
+          }
+
+          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;
+        }
+      }
+    }
+  }
+
+#if ENVIRONMENT_VARIABLE_DEBUG_AND_TEST
+  printSBACCoeffData(uiPosLastX, uiPosLastY, uiWidth, uiHeight, compID, uiAbsPartIdx, codingParameters.scanType, pcCoef);
+#endif
+
+  return;
+}
+
+Void TDecSbac::parseSaoMaxUvlc ( UInt& val, UInt maxSymbol )
+{
+  if (maxSymbol == 0)
+  {
+    val = 0;
+    return;
+  }
+
+  UInt code;
+  Int  i;
+  m_pcTDecBinIf->decodeBinEP( code RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(STATS__CABAC_BITS__SAO) );
+  if ( code == 0 )
+  {
+    val = 0;
+    return;
+  }
+
+  i=1;
+  while (1)
+  {
+    m_pcTDecBinIf->decodeBinEP( code RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(STATS__CABAC_BITS__SAO) );
+    if ( code == 0 )
+    {
+      break;
+    }
+    i++;
+    if (i == maxSymbol)
+    {
+      break;
+    }
+  }
+
+  val = i;
+}
+
+Void TDecSbac::parseSaoUflc (UInt uiLength, UInt&  riVal)
+{
+  m_pcTDecBinIf->decodeBinsEP ( riVal, uiLength RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(STATS__CABAC_BITS__SAO) );
+}
+
+Void TDecSbac::parseSaoMerge (UInt&  ruiVal)
+{
+  UInt uiCode;
+  m_pcTDecBinIf->decodeBin( uiCode, m_cSaoMergeSCModel.get( 0, 0, 0 ) RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(STATS__CABAC_BITS__SAO) );
+  ruiVal = (Int)uiCode;
+}
+
+Void TDecSbac::parseSaoTypeIdx (UInt&  ruiVal)
+{
+  UInt uiCode;
+  m_pcTDecBinIf->decodeBin( uiCode, m_cSaoTypeIdxSCModel.get( 0, 0, 0 ) RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(STATS__CABAC_BITS__SAO) );
+  if (uiCode == 0)
+  {
+    ruiVal = 0;
+  }
+  else
+  {
+    m_pcTDecBinIf->decodeBinEP( uiCode RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(STATS__CABAC_BITS__SAO) );
+    if (uiCode == 0)
+    {
+      ruiVal = 1;
+    }
+    else
+    {
+      ruiVal = 2;
+    }
+  }
+}
+
+Void TDecSbac::parseSaoSign(UInt& val)
+{
+  m_pcTDecBinIf->decodeBinEP ( val RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(STATS__CABAC_BITS__SAO) );
+}
+
+Void TDecSbac::parseSAOBlkParam (SAOBlkParam& saoBlkParam
+#if SVC_EXTENSION
+                                , UInt* saoMaxOffsetQVal
+#endif
+                                , Bool* sliceEnabled
+                                , Bool leftMergeAvail
+                                , Bool aboveMergeAvail
+                                )
+{
+  UInt uiSymbol;
+
+  Bool isLeftMerge = false;
+  Bool isAboveMerge= false;
+
+  if(leftMergeAvail)
+  {
+    parseSaoMerge(uiSymbol); //sao_merge_left_flag
+    isLeftMerge = (uiSymbol?true:false);
+  }
+
+  if( aboveMergeAvail && !isLeftMerge)
+  {
+    parseSaoMerge(uiSymbol); //sao_merge_up_flag
+    isAboveMerge = (uiSymbol?true:false);
+  }
+
+  if(isLeftMerge || isAboveMerge) //merge mode
+  {
+    for (UInt componentIndex = 0; componentIndex < MAX_NUM_COMPONENT; componentIndex++)
+    {
+      saoBlkParam[componentIndex].modeIdc = (sliceEnabled[componentIndex]) ? SAO_MODE_MERGE : SAO_MODE_OFF;
+      saoBlkParam[componentIndex].typeIdc = (isLeftMerge)?SAO_MERGE_LEFT:SAO_MERGE_ABOVE;
+    }
+  }
+  else //new or off mode
+  {
+    for(Int compId=COMPONENT_Y; compId < MAX_NUM_COMPONENT; compId++)
+    {
+      const ComponentID compIdx=ComponentID(compId);
+      const ComponentID firstCompOfChType = getFirstComponentOfChannel(toChannelType(compIdx));
+      SAOOffset& ctbParam = saoBlkParam[compIdx];
+
+      if(!sliceEnabled[compIdx])
+      {
+        //off
+        ctbParam.modeIdc = SAO_MODE_OFF;
+        continue;
+      }
+
+      //type
+      if(compIdx == firstCompOfChType)
+      {
+        parseSaoTypeIdx(uiSymbol); //sao_type_idx_luma or sao_type_idx_chroma
+
+        assert(uiSymbol ==0 || uiSymbol ==1 || uiSymbol ==2);
+
+        if(uiSymbol ==0) //OFF
+        {
+          ctbParam.modeIdc = SAO_MODE_OFF;
+        }
+        else if(uiSymbol == 1) //BO
+        {
+          ctbParam.modeIdc = SAO_MODE_NEW;
+          ctbParam.typeIdc = SAO_TYPE_START_BO;
+        }
+        else //2, EO
+        {
+          ctbParam.modeIdc = SAO_MODE_NEW;
+          ctbParam.typeIdc = SAO_TYPE_START_EO;
+        }
+
+      }
+      else //Cr, follow Cb SAO type
+      {
+        ctbParam.modeIdc = saoBlkParam[COMPONENT_Cb].modeIdc;
+        ctbParam.typeIdc = saoBlkParam[COMPONENT_Cb].typeIdc;
+      }
+
+      if(ctbParam.modeIdc == SAO_MODE_NEW)
+      {
+#if O0043_BEST_EFFORT_DECODING
+        Int bitDepthOrig = g_bitDepthInStream[toChannelType(compIdx)];
+        Int forceBitDepthAdjust = bitDepthOrig - g_bitDepth[toChannelType(compIdx)];
+#endif
+        Int offset[4];
+        for(Int i=0; i< 4; i++)
+        {
+#if SVC_EXTENSION
+          parseSaoMaxUvlc(uiSymbol,  saoMaxOffsetQVal[compIdx] ); //sao_offset_abs
+#else
+#if O0043_BEST_EFFORT_DECODING
+          Int saoMaxOffsetQVal = (1<<(min(bitDepthOrig, MAX_SAO_TRUNCATED_BITDEPTH)-5))-1;
+          parseSaoMaxUvlc(uiSymbol, saoMaxOffsetQVal); //sao_offset_abs
+#else
+          parseSaoMaxUvlc(uiSymbol,  g_saoMaxOffsetQVal[compIdx] ); //sao_offset_abs
+#endif
+#endif
+          offset[i] = (Int)uiSymbol;
+        }
+
+        if(ctbParam.typeIdc == SAO_TYPE_START_BO)
+        {
+          for(Int i=0; i< 4; i++)
+          {
+            if(offset[i] != 0)
+            {
+              parseSaoSign(uiSymbol); //sao_offset_sign
+              if(uiSymbol)
+              {
+#if O0043_BEST_EFFORT_DECODING
+                offset[i] >>= forceBitDepthAdjust;
+#endif
+                offset[i] = -offset[i];
+              }
+            }
+          }
+          parseSaoUflc(NUM_SAO_BO_CLASSES_LOG2, uiSymbol ); //sao_band_position
+          ctbParam.typeAuxInfo = uiSymbol;
+
+          for(Int i=0; i<4; i++)
+          {
+            ctbParam.offset[(ctbParam.typeAuxInfo+i)%MAX_NUM_SAO_CLASSES] = offset[i];
+          }
+
+        }
+        else //EO
+        {
+          ctbParam.typeAuxInfo = 0;
+
+          if(firstCompOfChType == compIdx)
+          {
+            parseSaoUflc(NUM_SAO_EO_TYPES_LOG2, uiSymbol ); //sao_eo_class_luma or sao_eo_class_chroma
+            ctbParam.typeIdc += uiSymbol;
+          }
+          else
+          {
+            ctbParam.typeIdc = saoBlkParam[firstCompOfChType].typeIdc;
+          }
+          ctbParam.offset[SAO_CLASS_EO_FULL_VALLEY] = offset[0];
+          ctbParam.offset[SAO_CLASS_EO_HALF_VALLEY] = offset[1];
+          ctbParam.offset[SAO_CLASS_EO_PLAIN      ] = 0;
+          ctbParam.offset[SAO_CLASS_EO_HALF_PEAK  ] = -offset[2];
+          ctbParam.offset[SAO_CLASS_EO_FULL_PEAK  ] = -offset[3];
+        }
+      }
+    }
+  }
+}
+
+/**
+ - Initialize our contexts from the nominated source.
+ .
+ \param pSrc Contexts to be copied.
+ */
+Void TDecSbac::xCopyContextsFrom( const TDecSbac* pSrc )
+{
+  memcpy(m_contextModels, pSrc->m_contextModels, m_numContextModels*sizeof(m_contextModels[0]));
+  memcpy(m_golombRiceAdaptationStatistics, pSrc->m_golombRiceAdaptationStatistics, (sizeof(UInt) * RExt__GOLOMB_RICE_ADAPTATION_STATISTICS_SETS));
+}
+
+Void TDecSbac::xCopyFrom( const TDecSbac* pSrc )
+{
+  m_pcTDecBinIf->copyState( pSrc->m_pcTDecBinIf );
+  xCopyContextsFrom( pSrc );
+}
+
+Void TDecSbac::load ( const TDecSbac* pSrc )
+{
+  xCopyFrom(pSrc);
+}
+
+Void TDecSbac::loadContexts ( const TDecSbac* pSrc )
+{
+  xCopyContextsFrom(pSrc);
+}
+
+/** Performs CABAC decoding of the explicit RDPCM mode
+ * \param rTu current TU data structure
+ * \param compID component identifier
+ */
+Void TDecSbac::parseExplicitRdpcmMode( TComTU &rTu, ComponentID compID )
+{
+  TComDataCU* cu = rTu.getCU();
+  const UInt absPartIdx=rTu.GetAbsPartIdxTU(compID);
+  const TComRectangle &rect = rTu.getRect(compID);
+  const UInt tuHeight = g_aucConvertToBit[rect.height];
+  const UInt tuWidth  = g_aucConvertToBit[rect.width];
+  UInt code = 0;
+
+  assert(tuHeight == tuWidth);
+
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+  const TComCodingStatisticsClassType ctype(STATS__EXPLICIT_RDPCM_BITS, g_aucConvertToBit[g_uiMaxCUWidth>>rTu.GetTransformDepthTotal()]+2);
+#endif
+
+  m_pcTDecBinIf->decodeBin(code, m_explicitRdpcmFlagSCModel.get (0, toChannelType(compID), 0) RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(ctype));
+
+  if(code == 0)
+  {
+    cu->setExplicitRdpcmModePartRange( RDPCM_OFF, compID, absPartIdx, rTu.GetAbsPartIdxNumParts(compID));
+  }
+  else
+  {
+    m_pcTDecBinIf->decodeBin(code, m_explicitRdpcmDirSCModel.get (0, toChannelType(compID), 0) RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(ctype));
+    if(code == 0)
+    {
+      cu->setExplicitRdpcmModePartRange( RDPCM_HOR, compID, absPartIdx, rTu.GetAbsPartIdxNumParts(compID));
+    }
+    else
+    {
+      cu->setExplicitRdpcmModePartRange( RDPCM_VER, compID, absPartIdx, rTu.GetAbsPartIdxNumParts(compID));
+    }
+  }
+}
+
+
+//! \}
Index: /tags/SHM-9.0/source/Lib/TLibDecoder/TDecSbac.h
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibDecoder/TDecSbac.h	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibDecoder/TDecSbac.h	(revision 1088)
@@ -0,0 +1,199 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TDecSbac.h
+    \brief    SBAC decoder class (header)
+*/
+
+#ifndef __TDECSBAC__
+#define __TDECSBAC__
+
+
+#if _MSC_VER > 1000
+#pragma once
+#endif // _MSC_VER > 1000
+
+
+#include "TDecEntropy.h"
+#include "TDecBinCoder.h"
+#include "TLibCommon/ContextTables.h"
+#include "TLibCommon/ContextModel.h"
+#include "TLibCommon/ContextModel3DBuffer.h"
+
+//! \ingroup TLibDecoder
+//! \{
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+class SEImessages;
+
+/// 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                       ( const TDecSbac* pSrc );
+  Void loadContexts               ( const TDecSbac* pSrc );
+  Void xCopyFrom                  ( const TDecSbac* pSrc );
+  Void xCopyContextsFrom          ( const TDecSbac* pSrc );
+
+  Void  resetEntropy (TComSlice* pSlice );
+  Void  setBitstream              ( TComInputBitstream* p  ) { m_pcBitstream = p; m_pcTDecBinIf->init( p ); }
+  Void  parseVPS                  ( TComVPS* /*pcVPS*/ ) {}
+  Void  parseSPS                  ( TComSPS* /*pcSPS*/ ) {}
+  Void  parsePPS                  ( TComPPS* /*pcPPS*/ 
+#if Q0048_CGS_3D_ASYMLUT
+    , TCom3DAsymLUT * /*pc3DAsymLUT*/ , Int /*nLayerID*/
+#endif
+    ) {}
+
+  Void  parseSliceHeader          ( TComSlice* /*pcSlice*/, ParameterSetManagerDecoder* /*parameterSetManager*/) {}
+  Void  parseTerminatingBit       ( UInt& ruiBit );
+  Void  parseRemainingBytes       ( Bool noTrailingBytesExpected);
+  Void  parseMVPIdx               ( Int& riMVPIdx          );
+  Void  parseSaoMaxUvlc           ( UInt& val, UInt maxSymbol );
+  Void  parseSaoMerge             ( UInt&  ruiVal   );
+  Void  parseSaoTypeIdx           ( UInt&  ruiVal  );
+  Void  parseSaoUflc              ( UInt uiLength, UInt& ruiVal     );
+
+#if SVC_EXTENSION
+  Void parseSAOBlkParam           (SAOBlkParam& saoBlkParam, UInt* saoMaxOffsetQVal, Bool* sliceEnabled, Bool leftMergeAvail, Bool aboveMergeAvail );
+#else
+  Void parseSAOBlkParam           (SAOBlkParam& saoBlkParam, Bool* sliceEnabled, Bool leftMergeAvail, Bool aboveMergeAvail);
+#endif
+  Void parseSaoSign               (UInt& val);
+
+private:
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+  Void  xReadUnarySymbol    ( UInt& ruiSymbol, ContextModel* pcSCModel, Int iOffset, const class TComCodingStatisticsClassType &whichStat );
+  Void  xReadUnaryMaxSymbol ( UInt& ruiSymbol, ContextModel* pcSCModel, Int iOffset, UInt uiMaxSymbol, const class TComCodingStatisticsClassType &whichStat );
+  Void  xReadEpExGolomb     ( UInt& ruiSymbol, UInt uiCount, const class TComCodingStatisticsClassType &whichStat );
+  Void  xReadCoefRemainExGolomb ( UInt &rSymbol, UInt &rParam, const Bool useLimitedPrefixLength, const ChannelType channelType, const class TComCodingStatisticsClassType &whichStat );
+#else
+  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, const Bool useLimitedPrefixLength, const ChannelType channelType );
+#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 );
+  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 uiAbsPartIdx, UInt uiPartIdx, UInt uiDepth, RefPicList eRefList );
+
+  Void parseCrossComponentPrediction ( class TComTU &rTu, ComponentID compID );
+
+  Void parseTransformSubdivFlag( UInt& ruiSubdivFlag, UInt uiLog2TransformBlockSize );
+  Void parseQtCbf         ( TComTU &rTu, const ComponentID compID, const Bool lowestLevel );
+  Void parseQtRootCbf     ( UInt uiAbsPartIdx, UInt& uiQtRootCbf );
+
+  Void parseDeltaQP       ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+  Void parseChromaQpAdjustment( TComDataCU* cu, UInt absPartIdx, UInt depth );
+
+  Void parseIPCMInfo      ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth);
+
+  Void parseLastSignificantXY( UInt& uiPosLastX, UInt& uiPosLastY, Int width, Int height, ComponentID component, UInt uiScanIdx );
+  Void parseCoeffNxN      ( class TComTU &rTu, ComponentID compID  );
+  Void parseTransformSkipFlags ( class TComTU &rTu, ComponentID component );
+
+  Void  parseScalingList ( TComScalingList* /*scalingList*/ ) {}
+
+  Void  parseExplicitRdpcmMode( TComTU &rTu, ComponentID compID );
+
+private:
+  ContextModel         m_contextModels[MAX_NUM_CTX_MOD];
+  Int                  m_numContextModels;
+  ContextModel3DBuffer m_cCUSplitFlagSCModel;
+  ContextModel3DBuffer m_cCUSkipFlagSCModel;
+  ContextModel3DBuffer m_cCUMergeFlagExtSCModel;
+  ContextModel3DBuffer m_cCUMergeIdxExtSCModel;
+  ContextModel3DBuffer m_cCUPartSizeSCModel;
+  ContextModel3DBuffer m_cCUPredModeSCModel;
+  ContextModel3DBuffer m_cCUIntraPredSCModel;
+  ContextModel3DBuffer m_cCUChromaPredSCModel;
+  ContextModel3DBuffer m_cCUDeltaQpSCModel;
+  ContextModel3DBuffer m_cCUInterDirSCModel;
+  ContextModel3DBuffer m_cCURefPicSCModel;
+  ContextModel3DBuffer m_cCUMvdSCModel;
+  ContextModel3DBuffer m_cCUQtCbfSCModel;
+  ContextModel3DBuffer m_cCUTransSubdivFlagSCModel;
+  ContextModel3DBuffer m_cCUQtRootCbfSCModel;
+
+  ContextModel3DBuffer m_cCUSigCoeffGroupSCModel;
+  ContextModel3DBuffer m_cCUSigSCModel;
+  ContextModel3DBuffer m_cCuCtxLastX;
+  ContextModel3DBuffer m_cCuCtxLastY;
+  ContextModel3DBuffer m_cCUOneSCModel;
+  ContextModel3DBuffer m_cCUAbsSCModel;
+
+  ContextModel3DBuffer m_cMVPIdxSCModel;
+
+  ContextModel3DBuffer m_cSaoMergeSCModel;
+  ContextModel3DBuffer m_cSaoTypeIdxSCModel;
+  ContextModel3DBuffer m_cTransformSkipSCModel;
+  ContextModel3DBuffer m_CUTransquantBypassFlagSCModel;
+  ContextModel3DBuffer m_explicitRdpcmFlagSCModel;
+  ContextModel3DBuffer m_explicitRdpcmDirSCModel;
+  ContextModel3DBuffer m_cCrossComponentPredictionSCModel;
+
+  ContextModel3DBuffer m_ChromaQpAdjFlagSCModel;
+  ContextModel3DBuffer m_ChromaQpAdjIdcSCModel;
+
+  UInt m_golombRiceAdaptationStatistics[RExt__GOLOMB_RICE_ADAPTATION_STATISTICS_SETS];
+};
+
+//! \}
+
+#endif // !defined(AFX_TDECSBAC_H__CFCAAA19_8110_47F4_9A16_810C4B5499D5__INCLUDED_)
Index: /tags/SHM-9.0/source/Lib/TLibDecoder/TDecSlice.cpp
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibDecoder/TDecSlice.cpp	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibDecoder/TDecSlice.cpp	(revision 1088)
@@ -0,0 +1,331 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TDecSlice.cpp
+    \brief    slice decoder class
+*/
+
+#include "TDecSlice.h"
+
+//! \ingroup TLibDecoder
+//! \{
+
+#if SVC_EXTENSION
+ParameterSetMap<TComVPS> ParameterSetManagerDecoder::m_vpsBuffer(MAX_NUM_VPS);
+ParameterSetMap<TComSPS> ParameterSetManagerDecoder::m_spsBuffer(MAX_NUM_SPS);
+ParameterSetMap<TComPPS> ParameterSetManagerDecoder::m_ppsBuffer(MAX_NUM_PPS);
+#endif
+
+//////////////////////////////////////////////////////////////////////
+// Construction/Destruction
+//////////////////////////////////////////////////////////////////////
+
+TDecSlice::TDecSlice()
+{
+}
+
+TDecSlice::~TDecSlice()
+{
+}
+
+Void TDecSlice::create()
+{
+}
+
+Void TDecSlice::destroy()
+{
+}
+
+#if SVC_EXTENSION
+Void TDecSlice::init(TDecEntropy* pcEntropyDecoder, TDecCu* pcCuDecoder, UInt* saoMaxOffsetQVal)
+{
+  m_pcEntropyDecoder  = pcEntropyDecoder;
+  m_pcCuDecoder       = pcCuDecoder;
+  m_saoMaxOffsetQVal  = saoMaxOffsetQVal;
+}
+#else
+Void TDecSlice::init(TDecEntropy* pcEntropyDecoder, TDecCu* pcCuDecoder)
+{
+  m_pcEntropyDecoder  = pcEntropyDecoder;
+  m_pcCuDecoder       = pcCuDecoder;
+}
+#endif
+
+Void TDecSlice::decompressSlice(TComInputBitstream** ppcSubstreams, TComPic* pcPic, TDecSbac* pcSbacDecoder)
+{
+  TComSlice* pcSlice                 = pcPic->getSlice(pcPic->getCurrSliceIdx());
+
+  const Int  startCtuTsAddr          = pcSlice->getSliceSegmentCurStartCtuTsAddr();
+  const Int  startCtuRsAddr          = pcPic->getPicSym()->getCtuTsToRsAddrMap(startCtuTsAddr);
+  const UInt numCtusInFrame          = pcPic->getNumberOfCtusInFrame();
+
+  const UInt frameWidthInCtus        = pcPic->getPicSym()->getFrameWidthInCtus();
+  const Bool depSliceSegmentsEnabled = pcSlice->getPPS()->getDependentSliceSegmentsEnabledFlag();
+  const Bool wavefrontsEnabled       = pcSlice->getPPS()->getEntropyCodingSyncEnabledFlag();
+
+  m_pcEntropyDecoder->setEntropyDecoder ( pcSbacDecoder  );
+  m_pcEntropyDecoder->setBitstream      ( ppcSubstreams[0] );
+  m_pcEntropyDecoder->resetEntropy      (pcSlice);
+
+  // decoder doesn't need prediction & residual frame buffer
+  pcPic->setPicYuvPred( 0 );
+  pcPic->setPicYuvResi( 0 );
+
+#if ENC_DEC_TRACE
+  g_bJustDoIt = g_bEncDecTraceEnable;
+#endif
+  DTRACE_CABAC_VL( g_nSymbolCounter++ );
+  DTRACE_CABAC_T( "\tPOC: " );
+  DTRACE_CABAC_V( pcPic->getPOC() );
+  DTRACE_CABAC_T( "\n" );
+
+#if ENC_DEC_TRACE
+  g_bJustDoIt = g_bEncDecTraceDisable;
+#endif
+
+  // The first CTU of the slice is the first coded substream, but the global substream number, as calculated by getSubstreamForCtuAddr may be higher.
+  // This calculates the common offset for all substreams in this slice.
+  const UInt subStreamOffset=pcPic->getSubstreamForCtuAddr(startCtuRsAddr, true, pcSlice);
+
+
+  if (depSliceSegmentsEnabled)
+  {
+    // modify initial contexts with previous slice segment if this is a dependent slice.
+    const UInt startTileIdx=pcPic->getPicSym()->getTileIdxMap(startCtuRsAddr);
+    const TComTile *pCurrentTile=pcPic->getPicSym()->getTComTile(startTileIdx);
+    const UInt firstCtuRsAddrOfTile = pCurrentTile->getFirstCtuRsAddr();
+
+    if( pcSlice->getDependentSliceSegmentFlag() && startCtuRsAddr != firstCtuRsAddrOfTile)
+    {
+      if ( pCurrentTile->getTileWidthInCtus() >= 2 || !wavefrontsEnabled)
+      {
+        pcSbacDecoder->loadContexts(&m_lastSliceSegmentEndContextState);
+      }
+    }
+  }
+
+  // for every CTU in the slice segment...
+
+  Bool isLastCtuOfSliceSegment = false;
+  for( UInt ctuTsAddr = startCtuTsAddr; !isLastCtuOfSliceSegment && ctuTsAddr < numCtusInFrame; ctuTsAddr++)
+  {
+    const UInt ctuRsAddr = pcPic->getPicSym()->getCtuTsToRsAddrMap(ctuTsAddr);
+    const TComTile &currentTile = *(pcPic->getPicSym()->getTComTile(pcPic->getPicSym()->getTileIdxMap(ctuRsAddr)));
+    const UInt firstCtuRsAddrOfTile = currentTile.getFirstCtuRsAddr();
+    const UInt tileXPosInCtus = firstCtuRsAddrOfTile % frameWidthInCtus;
+    const UInt tileYPosInCtus = firstCtuRsAddrOfTile / frameWidthInCtus;
+    const UInt ctuXPosInCtus  = ctuRsAddr % frameWidthInCtus;
+    const UInt ctuYPosInCtus  = ctuRsAddr / frameWidthInCtus;
+    const UInt uiSubStrm=pcPic->getSubstreamForCtuAddr(ctuRsAddr, true, pcSlice)-subStreamOffset;
+    TComDataCU* pCtu = pcPic->getCtu( ctuRsAddr );
+    pCtu->initCtu( pcPic, ctuRsAddr );
+
+    m_pcEntropyDecoder->setBitstream( ppcSubstreams[uiSubStrm] );
+
+    // set up CABAC contexts' state for this CTU
+    if (ctuRsAddr == firstCtuRsAddrOfTile)
+    {
+      if (ctuTsAddr != startCtuTsAddr) // if it is the first CTU, then the entropy coder has already been reset
+      {
+        m_pcEntropyDecoder->resetEntropy(pcSlice);
+      }
+    }
+    else if (ctuXPosInCtus == tileXPosInCtus && wavefrontsEnabled)
+    {
+      // Synchronize cabac probabilities with upper-right CTU if it's available and at the start of a line.
+      if (ctuTsAddr != startCtuTsAddr) // if it is the first CTU, then the entropy coder has already been reset
+      {
+        m_pcEntropyDecoder->resetEntropy(pcSlice);
+      }
+      TComDataCU *pCtuUp = pCtu->getCtuAbove();
+      if ( pCtuUp && ((ctuRsAddr%frameWidthInCtus+1) < frameWidthInCtus)  )
+      {
+        TComDataCU *pCtuTR = pcPic->getCtu( ctuRsAddr - frameWidthInCtus + 1 );
+        if ( pCtu->CUIsFromSameSliceAndTile(pCtuTR) )
+        {
+          // Top-right is available, so use it.
+          pcSbacDecoder->loadContexts( &m_entropyCodingSyncContextState );
+        }
+      }
+    }
+
+#if ENC_DEC_TRACE
+    g_bJustDoIt = g_bEncDecTraceEnable;
+#endif
+
+    if ( pcSlice->getSPS()->getUseSAO() )
+    {
+      SAOBlkParam& saoblkParam = (pcPic->getPicSym()->getSAOBlkParam())[ctuRsAddr];
+      Bool bIsSAOSliceEnabled = false;
+      Bool sliceEnabled[MAX_NUM_COMPONENT];
+      for(Int comp=0; comp < MAX_NUM_COMPONENT; comp++)
+      {
+        ComponentID compId=ComponentID(comp);
+        sliceEnabled[compId] = pcSlice->getSaoEnabledFlag(toChannelType(compId)) && (comp < pcPic->getNumberValidComponents());
+        if (sliceEnabled[compId]) bIsSAOSliceEnabled=true;
+        saoblkParam[compId].modeIdc = SAO_MODE_OFF;
+      }
+      if (bIsSAOSliceEnabled)
+      {
+        Bool leftMergeAvail = false;
+        Bool aboveMergeAvail= false;
+
+        //merge left condition
+        Int rx = (ctuRsAddr % frameWidthInCtus);
+        if(rx > 0)
+        {
+          leftMergeAvail = pcPic->getSAOMergeAvailability(ctuRsAddr, ctuRsAddr-1);
+        }
+        //merge up condition
+        Int ry = (ctuRsAddr / frameWidthInCtus);
+        if(ry > 0)
+        {
+          aboveMergeAvail = pcPic->getSAOMergeAvailability(ctuRsAddr, ctuRsAddr-frameWidthInCtus);
+        }
+#if SVC_EXTENSION
+        pcSbacDecoder->parseSAOBlkParam( saoblkParam, m_saoMaxOffsetQVal, sliceEnabled, leftMergeAvail, aboveMergeAvail);
+#else
+        pcSbacDecoder->parseSAOBlkParam( saoblkParam, sliceEnabled, leftMergeAvail, aboveMergeAvail);
+#endif      
+      }
+    }
+
+    m_pcCuDecoder->decodeCtu     ( pCtu, isLastCtuOfSliceSegment );
+    m_pcCuDecoder->decompressCtu ( pCtu );
+
+#if ENC_DEC_TRACE
+    g_bJustDoIt = g_bEncDecTraceDisable;
+#endif
+
+    //Store probabilities of second CTU in line into buffer
+    if ( ctuXPosInCtus == tileXPosInCtus+1 && wavefrontsEnabled)
+    {
+      m_entropyCodingSyncContextState.loadContexts( pcSbacDecoder );
+    }
+
+    // Should the sub-stream/stream be terminated after this CTU?
+    // (end of slice-segment, end of tile, end of wavefront-CTU-row)
+    if (isLastCtuOfSliceSegment ||
+         (  ctuXPosInCtus + 1 == tileXPosInCtus + currentTile.getTileWidthInCtus() &&
+          ( ctuYPosInCtus + 1 == tileYPosInCtus + currentTile.getTileHeightInCtus() || wavefrontsEnabled)
+         )
+       )
+    {
+      UInt binVal;
+      pcSbacDecoder->parseTerminatingBit( binVal );
+      assert( binVal );
+#if DECODER_CHECK_SUBSTREAM_AND_SLICE_TRAILING_BYTES
+      pcSbacDecoder->parseRemainingBytes(!isLastCtuOfSliceSegment);
+#endif
+
+      if (isLastCtuOfSliceSegment)
+      {
+        if(!pcSlice->getDependentSliceSegmentFlag())
+        {
+          pcSlice->setSliceCurEndCtuTsAddr( ctuTsAddr+1 );
+        }
+        pcSlice->setSliceSegmentCurEndCtuTsAddr( ctuTsAddr+1 );
+        break;
+      }
+    }
+  }
+
+  assert(isLastCtuOfSliceSegment == true);
+
+
+  if( depSliceSegmentsEnabled )
+  {
+    m_lastSliceSegmentEndContextState.loadContexts( pcSbacDecoder );//ctx end of dep.slice
+  }
+
+}
+
+ParameterSetManagerDecoder::ParameterSetManagerDecoder()
+#if !SVC_EXTENSION
+: m_vpsBuffer(MAX_NUM_VPS)
+, m_spsBuffer(MAX_NUM_SPS)
+, m_ppsBuffer(MAX_NUM_PPS)
+#endif
+{
+}
+
+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: /tags/SHM-9.0/source/Lib/TLibDecoder/TDecSlice.h
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibDecoder/TDecSlice.h	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibDecoder/TDecSlice.h	(revision 1088)
@@ -0,0 +1,120 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TDecSlice.h
+    \brief    slice decoder class (header)
+*/
+
+#ifndef __TDECSLICE__
+#define __TDECSLICE__
+
+#if _MSC_VER > 1000
+#pragma once
+#endif // _MSC_VER > 1000
+
+#include "TLibCommon/CommonDef.h"
+#include "TLibCommon/TComBitStream.h"
+#include "TLibCommon/TComPic.h"
+#include "TDecEntropy.h"
+#include "TDecCu.h"
+#include "TDecSbac.h"
+#include "TDecBinCoderCABAC.h"
+
+//! \ingroup TLibDecoder
+//! \{
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// slice decoder class
+class TDecSlice
+{
+private:
+  // access channel
+  TDecEntropy*    m_pcEntropyDecoder;
+  TDecCu*         m_pcCuDecoder;
+
+  TDecSbac        m_lastSliceSegmentEndContextState;    ///< context storage for state at the end of the previous slice-segment (used for dependent slices only).
+  TDecSbac        m_entropyCodingSyncContextState;      ///< context storate for state of contexts at the wavefront/WPP/entropy-coding-sync second CTU of tile-row
+
+#if SVC_EXTENSION
+  UInt*           m_saoMaxOffsetQVal; 
+#endif 
+
+public:
+  TDecSlice();
+  virtual ~TDecSlice();
+  
+#if SVC_EXTENSION  
+  Void  init              ( TDecEntropy* pcEntropyDecoder, TDecCu* pcMbDecoder, UInt* saoMaxOffsetQVal );
+#else
+  Void  init              ( TDecEntropy* pcEntropyDecoder, TDecCu* pcMbDecoder );
+#endif
+  Void  create            ();
+  Void  destroy           ();
+
+  Void  decompressSlice   ( TComInputBitstream** ppcSubstreams,   TComPic* pcPic, TDecSbac* pcSbacDecoder );
+};
+
+
+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:
+#if SVC_EXTENSION
+  static ParameterSetMap<TComVPS> m_vpsBuffer;
+  static ParameterSetMap<TComSPS> m_spsBuffer; 
+  static ParameterSetMap<TComPPS> m_ppsBuffer;
+#else
+  ParameterSetMap<TComVPS> m_vpsBuffer;
+  ParameterSetMap<TComSPS> m_spsBuffer;
+  ParameterSetMap<TComPPS> m_ppsBuffer;
+#endif
+};
+
+
+//! \}
+
+#endif
+
Index: /tags/SHM-9.0/source/Lib/TLibDecoder/TDecTop.cpp
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibDecoder/TDecTop.cpp	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibDecoder/TDecTop.cpp	(revision 1088)
@@ -0,0 +1,3233 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TDecTop.cpp
+    \brief    decoder class
+*/
+
+#include "NALread.h"
+#include "TDecTop.h"
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+#include "TLibCommon/TComCodingStatistics.h"
+#endif
+
+#if SVC_EXTENSION
+UInt  TDecTop::m_prevPOC = MAX_UINT;
+UInt  TDecTop::m_uiPrevLayerId = MAX_UINT;
+Bool  TDecTop::m_bFirstSliceInSequence = true;
+#if POC_RESET_RESTRICTIONS
+Bool  TDecTop::m_checkPocRestrictionsForCurrAu       = false;
+Int   TDecTop::m_pocResetIdcOrCurrAu                 = -1;
+Bool  TDecTop::m_baseLayerIdrFlag                    = false;
+Bool  TDecTop::m_baseLayerPicPresentFlag             = false;
+Bool  TDecTop::m_baseLayerIrapFlag                   = false;
+Bool  TDecTop::m_nonBaseIdrPresentFlag               = false;
+Int   TDecTop::m_nonBaseIdrType                      = -1;
+Bool  TDecTop::m_picNonIdrWithRadlPresentFlag        = false;
+Bool  TDecTop::m_picNonIdrNoLpPresentFlag            = false;
+#endif
+#if POC_RESET_VALUE_RESTRICTION
+Int   TDecTop::m_crossLayerPocResetPeriodId          = -1;
+Int   TDecTop::m_crossLayerPocResetIdc               = -1;
+#endif
+#endif
+
+//! \ingroup TLibDecoder
+//! \{
+
+TDecTop::TDecTop()
+  : m_pDecodedSEIOutputStream(NULL)
+{
+  m_pcPic = 0;
+  m_iMaxRefPicNum = 0;
+#if ENC_DEC_TRACE
+  if (g_hTrace == NULL)
+  {
+    g_hTrace = fopen( "TraceDec.txt", "wb" );
+  }
+  g_bJustDoIt = g_bEncDecTraceDisable;
+  g_nSymbolCounter = 0;
+#endif
+  m_associatedIRAPType = NAL_UNIT_INVALID;
+  m_pocCRA = 0;
+  m_pocRandomAccess = MAX_INT;
+#if !SVC_EXTENSION
+  m_prevPOC                = MAX_INT;
+#endif
+  m_bFirstSliceInPicture    = true;
+#if !SVC_EXTENSION
+  m_bFirstSliceInSequence   = true;
+#endif
+#if SVC_EXTENSION 
+  m_layerId = 0;
+#if R0235_SMALLEST_LAYER_ID
+  m_smallestLayerId = 0;
+#endif
+#if AVC_BASE
+  m_pBLReconFile = NULL;
+#endif
+  memset(m_cIlpPic, 0, sizeof(m_cIlpPic));
+#endif
+  m_prevSliceSkipped = false;
+  m_skippedPOC = 0;
+  m_bFirstSliceInBitstream  = true;
+  m_lastPOCNoOutputPriorPics = -1;
+  m_craNoRaslOutputFlag = false;
+  m_isNoOutputPriorPics = false;
+#if Q0177_EOS_CHECKS
+  m_isLastNALWasEos = false;
+#endif
+#if R0071_IRAP_EOS_CROSS_LAYER_IMPACTS
+  m_lastPicHasEos = false;
+#endif
+#if NO_CLRAS_OUTPUT_FLAG
+  m_noClrasOutputFlag          = false;
+  m_layerInitializedFlag       = false;
+  m_firstPicInLayerDecodedFlag = false;  
+#endif
+#if RESOLUTION_BASED_DPB
+  m_subDpbIdx = -1;
+#endif
+#if POC_RESET_IDC_DECODER
+  m_parseIdc = -1;
+  m_lastPocPeriodId = -1;
+  m_prevPicOrderCnt = 0;
+#endif
+#if Q0048_CGS_3D_ASYMLUT
+  m_pColorMappedPic = NULL;
+#endif
+
+#if POC_RESET_RESTRICTIONS
+  resetPocRestrictionCheckParameters();
+#endif
+#if P0297_VPS_POC_LSB_ALIGNED_FLAG
+  m_pocResettingFlag        = false;
+  m_pocDecrementedInDPBFlag = false;
+#endif
+#if CONFORMANCE_BITSTREAM_MODE
+  m_confModeFlag = false;
+#endif
+#if FIX_NON_OUTPUT_LAYER
+  m_isOutputLayerFlag = false;
+#endif
+}
+
+TDecTop::~TDecTop()
+{
+#if ENC_DEC_TRACE
+  if (g_hTrace != stdout)
+  {
+    fclose( g_hTrace );
+  }
+#endif
+#if Q0048_CGS_3D_ASYMLUT
+  if(m_pColorMappedPic)
+  {
+    m_pColorMappedPic->destroy();
+    delete m_pColorMappedPic;
+    m_pColorMappedPic = NULL;
+  }
+#endif
+}
+
+Void TDecTop::create()
+{
+#if SVC_EXTENSION
+  m_cGopDecoder.create( m_layerId );
+#else
+  m_cGopDecoder.create();
+#endif
+  m_apcSlicePilot = new TComSlice;
+  m_uiSliceIdx = 0;
+}
+
+Void TDecTop::destroy()
+{
+  m_cGopDecoder.destroy();
+
+  delete m_apcSlicePilot;
+  m_apcSlicePilot = NULL;
+
+  m_cSliceDecoder.destroy();
+#if SVC_EXTENSION
+  for(Int i=0; i<MAX_NUM_REF; i++)
+  {
+    if(m_cIlpPic[i])
+    {
+      m_cIlpPic[i]->destroy();
+      delete m_cIlpPic[i];
+      m_cIlpPic[i] = NULL;
+    }
+  }
+#endif
+}
+
+Void TDecTop::init()
+{
+#if !SVC_EXTENSION
+  // initialize ROM
+  initROM();
+#endif
+#if SVC_EXTENSION
+  m_cGopDecoder.init( m_ppcTDecTop, &m_cEntropyDecoder, &m_cSbacDecoder, &m_cBinCABAC, &m_cCavlcDecoder, &m_cSliceDecoder, &m_cLoopFilter, &m_cSAO);
+  m_cSliceDecoder.init( &m_cEntropyDecoder, &m_cCuDecoder, m_cSAO.getSaoMaxOffsetQVal() );
+#else
+  m_cGopDecoder.init( &m_cEntropyDecoder, &m_cSbacDecoder, &m_cBinCABAC, &m_cCavlcDecoder, &m_cSliceDecoder, &m_cLoopFilter, &m_cSAO);
+  m_cSliceDecoder.init( &m_cEntropyDecoder, &m_cCuDecoder );
+#endif
+  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 SVC_EXTENSION
+    if( pcPic )
+    {
+      pcPic->destroy();
+
+      delete pcPic;
+      pcPic = NULL;
+    }
+#else
+    pcPic->destroy();
+
+    delete pcPic;
+    pcPic = NULL;
+#endif
+  }
+
+  m_cSAO.destroy();
+
+  m_cLoopFilter.        destroy();
+  
+#if !SVC_EXTENSION
+  // destroy ROM
+  destroyROM();
+#endif
+}
+
+Void TDecTop::xGetNewPicBuffer ( TComSlice* pcSlice, TComPic*& rpcPic )
+{
+  Int  numReorderPics[MAX_TLAYER];
+#if R0156_CONF_WINDOW_IN_REP_FORMAT
+  Window &conformanceWindow = pcSlice->getConformanceWindow();
+#else
+  Window &conformanceWindow = pcSlice->getSPS()->getConformanceWindow();
+#endif
+  Window defaultDisplayWindow = pcSlice->getSPS()->getVuiParametersPresentFlag() ? pcSlice->getSPS()->getVuiParameters()->getDefaultDisplayWindow() : Window();
+
+  for( Int temporalLayer=0; temporalLayer < MAX_TLAYER; temporalLayer++)
+  {
+#if USE_DPB_SIZE_TABLE
+    if( m_commonDecoderParams->getTargetOutputLayerSetIdx() == 0 )
+    {
+      assert( this->getLayerId() == 0 );
+      numReorderPics[temporalLayer] = pcSlice->getSPS()->getNumReorderPics(temporalLayer);
+    }
+    else
+    {
+      TComVPS *vps = pcSlice->getVPS();
+      // SHM decoders will use DPB size table in the VPS to determine the number of reorder pictures.
+      numReorderPics[temporalLayer] = vps->getMaxVpsNumReorderPics( getCommonDecoderParams()->getTargetOutputLayerSetIdx() , temporalLayer);
+    }
+#else
+    numReorderPics[temporalLayer] = pcSlice->getSPS()->getNumReorderPics(temporalLayer);
+#endif
+  }
+
+#if USE_DPB_SIZE_TABLE
+  if( m_commonDecoderParams->getTargetOutputLayerSetIdx() == 0 )
+  {
+    assert( this->getLayerId() == 0 );
+    m_iMaxRefPicNum = pcSlice->getSPS()->getMaxDecPicBuffering(pcSlice->getTLayer());     // m_uiMaxDecPicBuffering has the space for the picture currently being decoded
+  }
+  else
+  {
+#if RESOLUTION_BASED_DPB
+    Int layerSetIdxForOutputLayerSet = pcSlice->getVPS()->getOutputLayerSetIdx( getCommonDecoderParams()->getTargetOutputLayerSetIdx() );
+    Int layerIdx = pcSlice->getVPS()->findLayerIdxInLayerSet( layerSetIdxForOutputLayerSet, pcSlice->getLayerId() );  assert( layerIdx != -1 );
+    m_iMaxRefPicNum = pcSlice->getVPS()->getMaxVpsLayerDecPicBuffMinus1( getCommonDecoderParams()->getTargetOutputLayerSetIdx(), layerIdx, pcSlice->getTLayer() ) + 1; // m_uiMaxDecPicBuffering has the space for the picture currently being decoded
+#else
+    m_iMaxRefPicNum = pcSlice->getVPS()->getMaxVpsDecPicBufferingMinus1( m_commonDecoderParams->getTargetOutputLayerSetIdx(), pcSlice->getVPS()->getLayerIdcForOls( pcSlice->getVPS()->getOutputLayerSetIdx( m_commonDecoderParams->getTargetOutputLayerSetIdx()), pcSlice->getLayerId() ), pcSlice->getTLayer() ) + 1; // m_uiMaxDecPicBuffering has the space for the picture currently being decoded
+#endif
+  }
+#else
+  m_iMaxRefPicNum = pcSlice->getSPS()->getMaxDecPicBuffering(pcSlice->getTLayer());     // m_uiMaxDecPicBuffering has the space for the picture currently being decoded
+#endif
+
+#if SVC_EXTENSION
+  m_iMaxRefPicNum += 1; // it should be updated if more than 1 resampling picture is used
+#endif
+
+  if (m_cListPic.size() < (UInt)m_iMaxRefPicNum)
+  {
+    rpcPic = new TComPic();
+
+#if SVC_EXTENSION
+    if(m_layerId > 0)
+    {
+      xSetSpatialEnhLayerFlag( pcSlice, rpcPic );
+    }
+
+#if REPN_FORMAT_IN_VPS
+    rpcPic->create ( pcSlice->getPicWidthInLumaSamples(), pcSlice->getPicHeightInLumaSamples(), pcSlice->getChromaFormatIdc(), g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth, 
+                     conformanceWindow, defaultDisplayWindow, numReorderPics, pcSlice->getSPS(), true);
+#else
+    rpcPic->create ( pcSlice->getSPS()->getPicWidthInLumaSamples(), pcSlice->getSPS()->getPicHeightInLumaSamples(), pcSlice->getSPS()->getChromaFormatIdc(), g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth, 
+                     conformanceWindow, defaultDisplayWindow, numReorderPics, pcSlice->getSPS(), true);
+#endif
+
+#else //SVC_EXTENSION
+    rpcPic->create ( pcSlice->getSPS()->getPicWidthInLumaSamples(), pcSlice->getSPS()->getPicHeightInLumaSamples(), pcSlice->getSPS()->getChromaFormatIdc(), g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth,
+                     conformanceWindow, defaultDisplayWindow, numReorderPics, true);
+#endif //SVC_EXTENSION
+    
+    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)
+    {
+#if !SVC_EXTENSION
+      rpcPic->setOutputMark(false);
+#endif
+      rpcPic->setReconMark( false );
+      rpcPic->getPicYuvRec()->setBorderExtension( false );
+      bBufferIsAvailable = true;
+      break;
+    }
+  }
+
+  if ( !bBufferIsAvailable )
+  {
+    //There is no room for this picture, either because of faulty encoder or dropped NAL. Extend the buffer.
+    m_iMaxRefPicNum++;
+    rpcPic = new TComPic();
+    m_cListPic.pushBack( rpcPic );
+  }
+  rpcPic->destroy();
+
+#if SVC_EXTENSION
+  if( m_layerId > 0 )
+  {
+    xSetSpatialEnhLayerFlag( pcSlice, rpcPic );
+  }
+
+#if REPN_FORMAT_IN_VPS
+  rpcPic->create ( pcSlice->getPicWidthInLumaSamples(), pcSlice->getPicHeightInLumaSamples(), pcSlice->getChromaFormatIdc(), g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth,
+                   conformanceWindow, defaultDisplayWindow, numReorderPics, pcSlice->getSPS(), true);
+#else
+  rpcPic->create ( pcSlice->getSPS()->getPicWidthInLumaSamples(), pcSlice->getSPS()->getPicHeightInLumaSamples(), pcSlice->getSPS()->getChromaFormatIdc(), g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth,
+                   conformanceWindow, defaultDisplayWindow, numReorderPics, pcSlice->getSPS(), true);
+#endif
+#else  //SVC_EXTENSION
+  rpcPic->create ( pcSlice->getSPS()->getPicWidthInLumaSamples(), pcSlice->getSPS()->getPicHeightInLumaSamples(), pcSlice->getSPS()->getChromaFormatIdc(), g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth,
+                   conformanceWindow, defaultDisplayWindow, numReorderPics, true);
+#endif //SVC_EXTENSION
+}
+
+Void TDecTop::executeLoopFilters(Int& poc, TComList<TComPic*>*& rpcListPic)
+{
+  if (!m_pcPic)
+  {
+    /* nothing to deblock */
+    return;
+  }
+
+  TComPic*   pcPic         = m_pcPic;
+
+  // Execute Deblock + Cleanup
+
+  m_cGopDecoder.filterPicture(pcPic);
+
+#if FIX_NON_OUTPUT_LAYER
+  if( this->getLayerDec(pcPic->getLayerId())->m_isOutputLayerFlag == false )
+  {
+    pcPic->setOutputMark( false );
+  }
+#endif
+
+  TComSlice::sortPicList( m_cListPic ); // sorting for application output
+  poc                 = pcPic->getSlice(m_uiSliceIdx-1)->getPOC();
+  rpcListPic          = &m_cListPic;
+  m_cCuDecoder.destroy();
+  m_bFirstSliceInPicture  = true;
+
+  return;
+}
+
+Void TDecTop::checkNoOutputPriorPics (TComList<TComPic*>* pcListPic)
+{
+  if (!pcListPic || !m_isNoOutputPriorPics) return;
+
+  TComList<TComPic*>::iterator  iterPic   = pcListPic->begin();
+
+  while (iterPic != pcListPic->end())
+  {
+    TComPic* pcPicTmp = *(iterPic++);
+    if (m_lastPOCNoOutputPriorPics != pcPicTmp->getPOC())
+    {
+      pcPicTmp->setOutputMark(false);
+    }
+  }
+}
+
+Void TDecTop::xCreateLostPicture(Int iLostPoc)
+{
+  printf("\ninserting lost poc : %d\n",iLostPoc);
+  TComSlice cFillSlice;
+  cFillSlice.setSPS( m_parameterSetManagerDecoder.getFirstSPS() );
+  cFillSlice.setPPS( m_parameterSetManagerDecoder.getFirstPPS() );
+#if SVC_EXTENSION
+  cFillSlice.setVPS( m_parameterSetManagerDecoder.getFirstVPS() );
+  cFillSlice.initSlice( m_layerId );
+#else
+  cFillSlice.initSlice();
+#endif
+  TComPic *cFillPic;
+  xGetNewPicBuffer(&cFillSlice,cFillPic);
+  cFillPic->getSlice(0)->setSPS( m_parameterSetManagerDecoder.getFirstSPS() );
+  cFillPic->getSlice(0)->setPPS( m_parameterSetManagerDecoder.getFirstPPS() );
+#if SVC_EXTENSION
+  cFillPic->getSlice(0)->setVPS( m_parameterSetManagerDecoder.getFirstVPS() );
+  cFillPic->getSlice(0)->initSlice( m_layerId );
+#else
+  cFillPic->getSlice(0)->initSlice();
+#endif
+  
+  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 ctuRsAddr=0; ctuRsAddr<cFillPic->getNumberOfCtusInFrame(); ctuRsAddr++)
+  {
+    cFillPic->getCtu(ctuRsAddr)->initCtu(cFillPic, ctuRsAddr);
+  }
+  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 SCALINGLIST_INFERRING
+  // scaling list settings and checks
+  TComVPS *activeVPS = m_parameterSetManagerDecoder.getActiveVPS();
+  TComSPS *activeSPS = m_parameterSetManagerDecoder.getActiveSPS();
+  TComPPS *activePPS = m_parameterSetManagerDecoder.getActivePPS();
+
+  if( activeSPS->getInferScalingListFlag() )
+  {
+    UInt refLayerId = activeSPS->getScalingListRefLayerId();
+    TComSPS *refSps = m_ppcTDecTop[refLayerId]->getParameterSetManager()->getActiveSPS(); assert( refSps != NULL );
+
+    // When avc_base_layer_flag is equal to 1, it is a requirement of bitstream conformance that the value of sps_scaling_list_ref_layer_id shall be greater than 0
+#if VPS_AVC_BL_FLAG_REMOVAL
+    if( activeVPS->getNonHEVCBaseLayerFlag() )
+#else
+    if( activeVPS->getAvcBaseLayerFlag() )
+#endif
+    {
+      assert( refLayerId > 0 );
+    }
+
+    // It is a requirement of bitstream conformance that, when an SPS with nuh_layer_id equal to nuhLayerIdA is active for a layer with nuh_layer_id equal to nuhLayerIdB and
+    // sps_infer_scaling_list_flag in the SPS is equal to 1, sps_infer_scaling_list_flag shall be equal to 0 for the SPS that is active for the layer with nuh_layer_id equal to sps_scaling_list_ref_layer_id
+    assert( refSps->getInferScalingListFlag() == false );
+
+    // It is a requirement of bitstream conformance that, when an SPS with nuh_layer_id equal to nuhLayerIdA is active for a layer with nuh_layer_id equal to nuhLayerIdB,
+    // the layer with nuh_layer_id equal to sps_scaling_list_ref_layer_id shall be a direct or indirect reference layer of the layer with nuh_layer_id equal to nuhLayerIdB
+    assert( activeVPS->getRecursiveRefLayerFlag( activeSPS->getLayerId(), refLayerId ) == true );
+    
+    if( activeSPS->getScalingList() != refSps->getScalingList() )
+    {
+      // delete created instance of scaling list since it will be inferred
+      delete activeSPS->getScalingList();
+
+      // infer scaling list
+      activeSPS->setScalingList( refSps->getScalingList() );
+    }
+  }
+
+  if( activePPS->getInferScalingListFlag() )
+  {
+    UInt refLayerId = activePPS->getScalingListRefLayerId();
+    TComPPS *refPps = m_ppcTDecTop[refLayerId]->getParameterSetManager()->getActivePPS(); assert( refPps != NULL );
+
+    // When avc_base_layer_flag is equal to 1, it is a requirement of bitstream conformance that the value of sps_scaling_list_ref_layer_id shall be greater than 0
+#if VPS_AVC_BL_FLAG_REMOVAL
+    if( activeVPS->getNonHEVCBaseLayerFlag() )
+#else
+    if( activeVPS->getAvcBaseLayerFlag() )
+#endif
+    {
+      assert( refLayerId > 0 );
+    }
+
+    // It is a requirement of bitstream conformance that, when an PPS with nuh_layer_id equal to nuhLayerIdA is active for a layer with nuh_layer_id equal to nuhLayerIdB and
+    // pps_infer_scaling_list_flag in the PPS is equal to 1, pps_infer_scaling_list_flag shall be equal to 0 for the PPS that is active for the layer with nuh_layer_id equal to pps_scaling_list_ref_layer_id
+    assert( refPps->getInferScalingListFlag() == false );
+
+    // It is a requirement of bitstream conformance that, when an PPS with nuh_layer_id equal to nuhLayerIdA is active for a layer with nuh_layer_id equal to nuhLayerIdB,
+    // the layer with nuh_layer_id equal to pps_scaling_list_ref_layer_id shall be a direct or indirect reference layer of the layer with nuh_layer_id equal to nuhLayerIdB
+    assert( activeVPS->getRecursiveRefLayerFlag( activePPS->getLayerId(), refLayerId ) == true );
+    
+    if( activePPS->getScalingList() != refPps->getScalingList() )
+    {
+      // delete created instance of scaling list since it will be inferred
+      delete activePPS->getScalingList();
+
+      // infer scaling list
+      activePPS->setScalingList( refPps->getScalingList() );
+    }
+
+  }
+#endif
+
+#if AVC_BASE
+#if VPS_AVC_BL_FLAG_REMOVAL
+  if( activeVPS->getNonHEVCBaseLayerFlag() )
+#else
+  if( activeVPS->getAvcBaseLayerFlag() )
+#endif
+  {
+    TComPic* pBLPic = (*m_ppcTDecTop[0]->getListPic()->begin());
+    if( m_layerId > 0 && pBLPic->getPicYuvRec() == NULL )
+    {
+      UInt refLayerId = 0;
+      RepFormat* repFormat = activeVPS->getVpsRepFormat( activeVPS->getVpsRepFormatIdx(refLayerId) );
+
+      Int  numReorderPics[MAX_TLAYER];
+#if !R0156_CONF_WINDOW_IN_REP_FORMAT
+      Window conformanceWindow;
+#endif
+      Window defaultDisplayWindow;
+
+#if R0156_CONF_WINDOW_IN_REP_FORMAT
+#if AUXILIARY_PICTURES
+      pBLPic->create( repFormat->getPicWidthVpsInLumaSamples(), repFormat->getPicHeightVpsInLumaSamples(), repFormat->getChromaFormatVpsIdc(), activeSPS->getMaxCUWidth(), activeSPS->getMaxCUHeight(), activeSPS->getMaxCUDepth(), repFormat->getConformanceWindowVps(), defaultDisplayWindow, numReorderPics, NULL, true);
+#else
+      pBLPic->create( repFormat->getPicWidthVpsInLumaSamples(), repFormat->getPicHeightVpsInLumaSamples(), activeSPS->getMaxCUWidth(), activeSPS->getMaxCUHeight(), activeSPS->getMaxCUDepth(), repFormat->getConformanceWindowVps(), defaultDisplayWindow, numReorderPics, NULL, true);
+#endif
+#else
+#if AUXILIARY_PICTURES
+      pBLPic->create( repFormat->getPicWidthVpsInLumaSamples(), repFormat->getPicHeightVpsInLumaSamples(), repFormat->getChromaFormatVpsIdc(), activeSPS->getMaxCUWidth(), activeSPS->getMaxCUHeight(), activeSPS->getMaxCUDepth(), conformanceWindow, defaultDisplayWindow, numReorderPics, NULL, true);
+#else
+      pBLPic->create( repFormat->getPicWidthVpsInLumaSamples(), repFormat->getPicHeightVpsInLumaSamples(), activeSPS->getMaxCUWidth(), activeSPS->getMaxCUHeight(), activeSPS->getMaxCUDepth(), conformanceWindow, defaultDisplayWindow, numReorderPics, NULL, true);
+#endif
+#endif
+      // it is needed where the VPS is accessed through the slice
+      pBLPic->getSlice(0)->setVPS( activeVPS );
+
+#if O0194_DIFFERENT_BITDEPTH_EL_BL
+      g_bitDepthLayer[CHANNEL_TYPE_LUMA][0] = repFormat->getBitDepthVpsLuma();
+      g_bitDepthLayer[CHANNEL_TYPE_CHROMA][0] = repFormat->getBitDepthVpsChroma();
+#endif
+    }
+  }
+#endif
+
+#if P0312_VERT_PHASE_ADJ
+#if MOVE_SCALED_OFFSET_TO_PPS
+  if( activeVPS->getVpsVuiVertPhaseInUseFlag() == 0 )
+  {    
+    for(Int i = 0; i < activePPS->getNumScaledRefLayerOffsets(); i++)
+    {
+      UInt scaledRefLayerId = activePPS->getScaledRefLayerId(i);
+      if( activePPS->getVertPhasePositionEnableFlag( scaledRefLayerId ) )
+      {
+        printf("\nWarning: LayerId = %d: vert_phase_position_enable_flag[%d] = 1, however indication vert_phase_position_in_use_flag = 0\n", m_layerId, scaledRefLayerId );
+        break;
+      }
+    }
+  }
+#else
+  if( activeVPS->getVpsVuiVertPhaseInUseFlag() == 0 )
+  {    
+    for(Int i = 0; i < activeSPS->getNumScaledRefLayerOffsets(); i++)
+    {
+      UInt scaledRefLayerId = activeSPS->getScaledRefLayerId(i);
+      if( activeSPS->getVertPhasePositionEnableFlag( scaledRefLayerId ) )
+      {
+        printf("\nWarning: LayerId = %d: vert_phase_position_enable_flag[%d] = 1, however indication vert_phase_position_in_use_flag = 0\n", m_layerId, scaledRefLayerId );
+        break;
+      }
+    }
+  }
+#endif
+#endif
+
+#if SPS_DPB_PARAMS
+  if( m_layerId > 0 )
+  {
+    // When not present sps_max_sub_layers_minus1 is inferred to be equal to vps_max_sub_layers_minus1.
+    sps->setMaxTLayers( activeVPS->getMaxTLayers() );
+
+    // When not present sps_temporal_id_nesting_flag is inferred to be equal to vps_temporal_id_nesting_flag
+#if Q0177_SPS_TEMP_NESTING_FIX
+    sps->setTemporalIdNestingFlag( (sps->getMaxTLayers() > 1) ? activeVPS->getTemporalNestingFlag() : true );
+#else
+    sps->setTemporalIdNestingFlag( activeVPS->getTemporalNestingFlag() );
+#endif
+
+    // When sps_max_dec_pic_buffering_minus1[ i ] is not present for i in the range of 0 to sps_max_sub_layers_minus1, inclusive, due to nuh_layer_id being greater than 0, 
+    // it is inferred to be equal to max_vps_dec_pic_buffering_minus1[ TargetOptLayerSetIdx ][ currLayerId ][ i ] of the active VPS, where currLayerId is the nuh_layer_id of the layer that refers to the SPS.
+    for(UInt i=0; i < sps->getMaxTLayers(); i++)
+    {
+      // to avoid compiler warning "array subscript is above array bounds"
+      assert( i < MAX_TLAYER );
+
+      // When sps_max_dec_pic_buffering_minus1[ i ] is not present for i in the range of 0 to sps_max_sub_layers_minus1, inclusive, 
+      // due to MultiLayerExtSpsFlag being equal to 1, for a layer that refers to the SPS and has nuh_layer_id equal to currLayerId, 
+      // the value of sps_max_dec_pic_buffering_minus1[ i ] is inferred to be equal to max_vps_dec_pic_buffering_minus1[ TargetOlsIdx ][ layerIdx ][ i ] of the active VPS, 
+      // where layerIdx is equal to the value such that LayerSetLayerIdList[ TargetDecLayerSetIdx ][ layerIdx ] is equal to currLayerId.
+      if( sps->getMultiLayerExtSpsFlag() )
+      {
+        sps->setMaxDecPicBuffering( activeVPS->getMaxVpsDecPicBufferingMinus1( m_commonDecoderParams->getTargetOutputLayerSetIdx(), activeVPS->getLayerIdcForOls( activeVPS->getOutputLayerSetIdx( m_commonDecoderParams->getTargetOutputLayerSetIdx() ), m_layerId ), i) + 1, i);
+      }
+
+      // The value of sps_max_dec_pic_buffering_minus1[ i ] shall be less than or equal to vps_max_dec_pic_buffering_minus1[ i ] for each value of i.
+      assert( sps->getMaxDecPicBuffering(i) <= activeVPS->getMaxDecPicBuffering(i) );      
+    }
+
+#if P0182_VPS_VUI_PS_FLAG
+    UInt layerIdx = activeVPS->getLayerIdxInVps( m_layerId );
+
+    if( activeVPS->getBaseLayerPSCompatibilityFlag(layerIdx) )
+    {
+      RepFormat* repFormat = activeVPS->getVpsRepFormat(activeVPS->getVpsRepFormatIdx(layerIdx));
+
+      assert( pps->getLayerId() == 0 );
+      assert( sps->getLayerId() == 0 );
+      assert( repFormat->getChromaFormatVpsIdc() == sps->getChromaFormatIdc() );
+      assert( repFormat->getSeparateColourPlaneVpsFlag() == 0 );
+      assert( repFormat->getPicHeightVpsInLumaSamples() == sps->getPicHeightInLumaSamples() );
+      assert( repFormat->getPicWidthVpsInLumaSamples()  == sps->getPicWidthInLumaSamples() );
+      assert( repFormat->getBitDepthVpsLuma()   == sps->getBitDepth(CHANNEL_TYPE_LUMA) );
+      assert( repFormat->getBitDepthVpsChroma() == sps->getBitDepth(CHANNEL_TYPE_CHROMA) );
+      assert( repFormat->getConformanceWindowVps().getWindowLeftOffset()   == sps->getConformanceWindow().getWindowLeftOffset() );
+      assert( repFormat->getConformanceWindowVps().getWindowRightOffset()  == sps->getConformanceWindow().getWindowRightOffset() );
+      assert( repFormat->getConformanceWindowVps().getWindowTopOffset()    == sps->getConformanceWindow().getWindowTopOffset() );
+      assert( repFormat->getConformanceWindowVps().getWindowBottomOffset() == sps->getConformanceWindow().getWindowBottomOffset() );
+    }    
+#endif
+  }
+#endif
+
+#if R0227_REP_FORMAT_CONSTRAINT //Conformance checking for rep format -- rep format of current picture of current layer shall never be greater rep format defined in VPS for the current layer
+  UInt layerIdx = activeVPS->getLayerIdxInVps(m_apcSlicePilot->getLayerId());
+
+  if ( activeVPS->getVpsExtensionFlag() == 1 && (m_apcSlicePilot->getLayerId() == 0 || sps->getV1CompatibleSPSFlag() == 1) )
+  {
+    assert( sps->getPicWidthInLumaSamples()        <= activeVPS->getVpsRepFormat( activeVPS->getVpsRepFormatIdx(layerIdx) )->getPicWidthVpsInLumaSamples() );
+    assert( sps->getPicHeightInLumaSamples()       <= activeVPS->getVpsRepFormat( activeVPS->getVpsRepFormatIdx(layerIdx) )->getPicHeightVpsInLumaSamples() );
+    assert( sps->getChromaFormatIdc()              <= activeVPS->getVpsRepFormat( activeVPS->getVpsRepFormatIdx(layerIdx) )->getChromaFormatVpsIdc() );
+    assert( sps->getBitDepth(CHANNEL_TYPE_LUMA)    <= activeVPS->getVpsRepFormat( activeVPS->getVpsRepFormatIdx(layerIdx) )->getBitDepthVpsLuma() );
+    assert( sps->getBitDepth(CHANNEL_TYPE_CHROMA)  <= activeVPS->getVpsRepFormat( activeVPS->getVpsRepFormatIdx(layerIdx) )->getBitDepthVpsChroma() );
+  }
+  else if ( activeVPS->getVpsExtensionFlag() == 1 )
+  {
+    assert( activeVPS->getVpsRepFormat( sps->getUpdateRepFormatFlag() ? sps->getUpdateRepFormatIndex() : activeVPS->getVpsRepFormatIdx(layerIdx))->getPicWidthVpsInLumaSamples()  <= activeVPS->getVpsRepFormat( activeVPS->getVpsRepFormatIdx(layerIdx))->getPicWidthVpsInLumaSamples());
+    assert( activeVPS->getVpsRepFormat( sps->getUpdateRepFormatFlag() ? sps->getUpdateRepFormatIndex() : activeVPS->getVpsRepFormatIdx(layerIdx))->getPicHeightVpsInLumaSamples() <= activeVPS->getVpsRepFormat( activeVPS->getVpsRepFormatIdx(layerIdx))->getPicHeightVpsInLumaSamples());
+    assert( activeVPS->getVpsRepFormat( sps->getUpdateRepFormatFlag() ? sps->getUpdateRepFormatIndex() : activeVPS->getVpsRepFormatIdx(layerIdx))->getChromaFormatVpsIdc()        <= activeVPS->getVpsRepFormat( activeVPS->getVpsRepFormatIdx(layerIdx))->getChromaFormatVpsIdc());
+    assert( activeVPS->getVpsRepFormat( sps->getUpdateRepFormatFlag() ? sps->getUpdateRepFormatIndex() : activeVPS->getVpsRepFormatIdx(layerIdx))->getBitDepthVpsLuma()           <= activeVPS->getVpsRepFormat( activeVPS->getVpsRepFormatIdx(layerIdx))->getBitDepthVpsLuma());
+    assert( activeVPS->getVpsRepFormat( sps->getUpdateRepFormatFlag() ? sps->getUpdateRepFormatIndex() : activeVPS->getVpsRepFormatIdx(layerIdx))->getBitDepthVpsChroma()         <= activeVPS->getVpsRepFormat( activeVPS->getVpsRepFormatIdx(layerIdx))->getBitDepthVpsChroma());
+  }
+#endif
+
+  m_apcSlicePilot->setPPS(pps);
+  m_apcSlicePilot->setSPS(sps);
+  pps->setSPS(sps);
+  pps->setNumSubstreams(pps->getEntropyCodingSyncEnabledFlag() ? ((sps->getPicHeightInLumaSamples() + sps->getMaxCUHeight() - 1) / sps->getMaxCUHeight()) * (pps->getNumTileColumnsMinus1() + 1) : ((pps->getNumTileRowsMinus1() + 1)*(pps->getNumTileColumnsMinus1() + 1)));
+  pps->setMinCuDQPSize( sps->getMaxCUWidth() >> ( pps->getMaxCuDQPDepth()) );
+  pps->setMinCuChromaQpAdjSize( sps->getMaxCUWidth() >> ( pps->getMaxCuChromaQpAdjDepth()) );
+
+  for (UInt channel = 0; channel < MAX_NUM_CHANNEL_TYPE; channel++)
+  {
+#if REPN_FORMAT_IN_VPS
+    g_bitDepth[channel] = isLuma(ChannelType(channel)) ? m_apcSlicePilot->getBitDepthY() : m_apcSlicePilot->getBitDepthC();
+#else
+    g_bitDepth[channel] = sps->getBitDepth(ChannelType(channel));
+#endif
+
+    if (sps->getUseExtendedPrecision()) g_maxTrDynamicRange[channel] = std::max<Int>(15, (g_bitDepth[channel] + 6));
+    else                                g_maxTrDynamicRange[channel] = 15;
+  }
+  g_uiMaxCUWidth  = sps->getMaxCUWidth();
+  g_uiMaxCUHeight = sps->getMaxCUHeight();
+  g_uiMaxCUDepth  = sps->getMaxCUDepth();
+  g_uiAddCUDepth  = max (0, sps->getLog2MinCodingBlockSize() - (Int)sps->getQuadtreeTULog2MinSize() + (Int)getMaxCUDepthOffset(sps->getChromaFormatIdc(), 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();
+#if REPN_FORMAT_IN_VPS
+  m_cSAO.create( m_apcSlicePilot->getPicWidthInLumaSamples(), m_apcSlicePilot->getPicHeightInLumaSamples(), sps->getChromaFormatIdc(), sps->getMaxCUWidth(), sps->getMaxCUHeight(), sps->getMaxCUDepth(), pps->getSaoOffsetBitShift(CHANNEL_TYPE_LUMA), pps->getSaoOffsetBitShift(CHANNEL_TYPE_CHROMA) );
+#else
+  m_cSAO.create( sps->getPicWidthInLumaSamples(), sps->getPicHeightInLumaSamples(), sps->getChromaFormatIdc(), sps->getMaxCUWidth(), sps->getMaxCUHeight(), sps->getMaxCUDepth(), pps->getSaoOffsetBitShift(CHANNEL_TYPE_LUMA), pps->getSaoOffsetBitShift(CHANNEL_TYPE_CHROMA) );
+#endif
+  m_cLoopFilter.create( sps->getMaxCUDepth() );
+}
+
+#if SVC_EXTENSION
+#if POC_RESET_FLAG
+Bool TDecTop::xDecodeSlice(InputNALUnit &nalu, Int &iSkipFrame, Int &iPOCLastDisplay, UInt& curLayerId, Bool& bNewPOC )
+#else
+Bool TDecTop::xDecodeSlice(InputNALUnit &nalu, Int &iSkipFrame, Int iPOCLastDisplay, UInt& curLayerId, Bool& bNewPOC )
+#endif
+#else
+Bool TDecTop::xDecodeSlice(InputNALUnit &nalu, Int &iSkipFrame, Int iPOCLastDisplay )
+#endif
+{
+#if SVC_EXTENSION
+  m_apcSlicePilot->setVPS( m_parameterSetManagerDecoder.getPrefetchedVPS(0) );
+#if OUTPUT_LAYER_SET_INDEX
+  // Following check should go wherever the VPS is activated
+#if R0235_SMALLEST_LAYER_ID
+  if (!m_apcSlicePilot->getVPS()->getBaseLayerAvailableFlag())
+  {
+    assert(nalu.m_layerId != 0);
+    assert(m_apcSlicePilot->getVPS()->getNumAddLayerSets() > 0);
+    if (getCommonDecoderParams()->getTargetOutputLayerSetIdx() >= 0)
+    {
+      UInt layerIdx = m_apcSlicePilot->getVPS()->getOutputLayerSetIdx(getCommonDecoderParams()->getTargetOutputLayerSetIdx());
+      assert(layerIdx > m_apcSlicePilot->getVPS()->getVpsNumLayerSetsMinus1());
+    }
+  }  
+#else
+  checkValueOfTargetOutputLayerSetIdx( m_apcSlicePilot->getVPS());
+#endif
+#endif
+#if RESOLUTION_BASED_DPB
+  // Following assignment should go wherever a new VPS is activated
+  assignSubDpbs(m_apcSlicePilot->getVPS());
+#endif
+  m_apcSlicePilot->initSlice( nalu.m_layerId );
+#else //SVC_EXTENSION
+  m_apcSlicePilot->initSlice();
+#endif
+
+  if (m_bFirstSliceInPicture)
+  {
+    m_uiSliceIdx = 0;
+  }
+  else
+  {
+    m_apcSlicePilot->copySliceInfo( m_pcPic->getPicSym()->getSlice(m_uiSliceIdx-1) );
+  }
+  m_apcSlicePilot->setSliceIdx(m_uiSliceIdx);
+
+  m_apcSlicePilot->setNalUnitType(nalu.m_nalUnitType);
+#if POC_RESET_RESTRICTIONS
+  m_apcSlicePilot->setTLayer( nalu.m_temporalId );
+#endif
+  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 ENC_DEC_TRACE
+  const UInt64 originalSymbolCount = g_nSymbolCounter;
+#endif
+
+#if SVC_EXTENSION
+#if VPS_EXTN_DIRECT_REF_LAYERS
+  setRefLayerParams(m_apcSlicePilot->getVPS());
+#endif
+  m_apcSlicePilot->setNumMotionPredRefLayers(m_numMotionPredRefLayers);
+#endif
+  m_cEntropyDecoder.decodeSliceHeader (m_apcSlicePilot, &m_parameterSetManagerDecoder);
+
+  // set POC for dependent slices in skipped pictures
+  if(m_apcSlicePilot->getDependentSliceSegmentFlag() && m_prevSliceSkipped)
+  {
+    m_apcSlicePilot->setPOC(m_skippedPOC);
+  }
+
+  m_apcSlicePilot->setAssociatedIRAPPOC(m_pocCRA);
+  m_apcSlicePilot->setAssociatedIRAPType(m_associatedIRAPType);
+
+  //For inference of NoOutputOfPriorPicsFlag
+  if (m_apcSlicePilot->getRapPicFlag())
+  {
+    if ((m_apcSlicePilot->getNalUnitType() >= NAL_UNIT_CODED_SLICE_BLA_W_LP && m_apcSlicePilot->getNalUnitType() <= NAL_UNIT_CODED_SLICE_IDR_N_LP) || 
+        (m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_CRA && m_bFirstSliceInSequence) ||
+        (m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_CRA && m_apcSlicePilot->getHandleCraAsBlaFlag()))
+    {
+      m_apcSlicePilot->setNoRaslOutputFlag(true);
+    }
+    //the inference for NoOutputPriorPicsFlag
+    if (!m_bFirstSliceInBitstream && m_apcSlicePilot->getRapPicFlag() && m_apcSlicePilot->getNoRaslOutputFlag())
+    {
+      if (m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_CRA)
+      {
+        m_apcSlicePilot->setNoOutputPriorPicsFlag(true);
+      }
+    }
+    else
+    {
+      m_apcSlicePilot->setNoOutputPriorPicsFlag(false);
+    }
+
+    if(m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_CRA)
+    {
+      m_craNoRaslOutputFlag = m_apcSlicePilot->getNoRaslOutputFlag();
+    }
+  }
+  if (m_apcSlicePilot->getRapPicFlag() && m_apcSlicePilot->getNoOutputPriorPicsFlag())
+  {
+    m_lastPOCNoOutputPriorPics = m_apcSlicePilot->getPOC();
+    m_isNoOutputPriorPics = true;
+  }
+  else
+  {
+    m_isNoOutputPriorPics = false;
+  }
+
+  //For inference of PicOutputFlag
+  if (m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_RASL_N || m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_RASL_R)
+  {
+    if ( m_craNoRaslOutputFlag )
+    {
+      m_apcSlicePilot->setPicOutputFlag(false);
+    }
+  }
+
+  if (m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_CRA && m_craNoRaslOutputFlag) //Reset POC MSB when CRA has NoRaslOutputFlag equal to 1
+  {
+    Int iMaxPOClsb = 1 << m_apcSlicePilot->getSPS()->getBitsForPOC();
+    m_apcSlicePilot->setPOC( m_apcSlicePilot->getPOC() & (iMaxPOClsb - 1) );
+  }
+
+  // Skip pictures due to random access
+  if (isRandomAccessSkipPicture(iSkipFrame, iPOCLastDisplay))
+  {
+    m_prevSliceSkipped = true;
+    m_skippedPOC = m_apcSlicePilot->getPOC();
+    return false;
+  }
+  // Skip TFD pictures associated with BLA/BLANT pictures
+  if (isSkipPictureForBLA(iPOCLastDisplay))
+  {
+    m_prevSliceSkipped = true;
+    m_skippedPOC = m_apcSlicePilot->getPOC();
+    return false;
+  }
+
+  // clear previous slice skipped flag
+  m_prevSliceSkipped = false;
+
+  // exit when a new picture is found
+#if SVC_EXTENSION
+  bNewPOC = (m_apcSlicePilot->getPOC()!= m_prevPOC);
+
+#if NO_OUTPUT_OF_PRIOR_PICS
+#if NO_CLRAS_OUTPUT_FLAG
+#if R0235_SMALLEST_LAYER_ID
+  if (m_layerId == m_smallestLayerId && m_apcSlicePilot->getRapPicFlag())
+#else
+  if (m_layerId == 0 && m_apcSlicePilot->getRapPicFlag() )
+#endif
+  {
+    if (m_bFirstSliceInSequence)
+    {
+      setNoClrasOutputFlag(true);
+    }
+#if R0071_IRAP_EOS_CROSS_LAYER_IMPACTS
+    else if( m_lastPicHasEos )
+    {
+      setNoClrasOutputFlag(true);
+    }
+#endif
+    else if ( m_apcSlicePilot->getBlaPicFlag() )
+    {
+      setNoClrasOutputFlag(true);
+    }
+#if O0149_CROSS_LAYER_BLA_FLAG
+    else if (m_apcSlicePilot->getIdrPicFlag() && m_apcSlicePilot->getCrossLayerBLAFlag())
+    {
+      setNoClrasOutputFlag(true);
+    }
+#endif
+    else
+    {
+      setNoClrasOutputFlag(false);
+    }      
+  }
+  else
+  {
+    setNoClrasOutputFlag(false);
+  }
+
+#if R0235_SMALLEST_LAYER_ID
+  m_apcSlicePilot->decodingRefreshMarking( m_cListPic, m_noClrasOutputFlag, m_smallestLayerId );
+#else
+  m_apcSlicePilot->decodingRefreshMarking( m_cListPic, m_noClrasOutputFlag );
+#endif
+#endif
+
+  // Derive the value of NoOutputOfPriorPicsFlag
+  if( bNewPOC || m_layerId!=m_uiPrevLayerId )   // i.e. new coded picture
+  {
+    if( m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_CRA && m_apcSlicePilot->getNoRaslOutputFlag() )
+    {
+      this->setNoOutputPriorPicsFlag( true );
+    }
+    else if( m_apcSlicePilot->getRapPicFlag() && m_apcSlicePilot->getNoRaslOutputFlag() )
+    {
+      this->setNoOutputPriorPicsFlag( m_apcSlicePilot->getNoOutputPriorPicsFlag() );
+    }
+    else
+    {
+      if( this->m_ppcTDecTop[0]->getNoClrasOutputFlag() )
+      {
+        this->setNoOutputPriorPicsFlag( true );
+      }
+    }
+  }
+#endif
+
+#if POC_RESET_IDC_DECODER
+  if( m_parseIdc != -1 ) // Second pass for a POC resetting picture
+  {
+    m_parseIdc++; // Proceed to POC decoding and RPS derivation
+  }
+  
+  if( m_parseIdc == 2 )
+  {
+    bNewPOC = false;
+  }
+
+  if( (bNewPOC || m_layerId!=m_uiPrevLayerId) && (m_parseIdc == -1) ) // Will be true at the first pass
+  {
+  //if (bNewPOC || m_layerId!=m_uiPrevLayerId)
+  // Check if new reset period has started - this is needed just so that the SHM decoder which calls slice header decoding twice 
+  // does not invoke the output twice
+  //if( m_lastPocPeriodId[m_apcSlicePilot->getLayerId()] == m_apcSlicePilot->getPocResetPeriodId() )
+    // Update CurrAU marking
+    if(( m_layerId < m_uiPrevLayerId) ||( ( m_layerId == m_uiPrevLayerId) && bNewPOC)) // Decoding a lower layer than or same layer as previous - mark all earlier pictures as not in current AU
+    {
+#if POC_RESET_RESTRICTIONS
+      // New access unit; reset all variables related to POC reset restrictions
+      resetPocRestrictionCheckParameters();
+#endif
+      markAllPicsAsNoCurrAu(m_apcSlicePilot->getVPS());
+#if P0297_VPS_POC_LSB_ALIGNED_FLAG
+      for (UInt i = 0; i < MAX_LAYERS; i++)
+      {
+        m_ppcTDecTop[m_apcSlicePilot->getVPS()->getLayerIdInNuh(i)]->m_pocDecrementedInDPBFlag = false;
+      }
+#endif
+    }
+
+
+#if P0297_VPS_POC_LSB_ALIGNED_FLAG
+    m_pocResettingFlag = false;
+
+    if (m_apcSlicePilot->getPocResetIdc() != 0)
+    {
+      if (m_apcSlicePilot->getVPS()->getVpsPocLsbAlignedFlag())
+      {
+        m_pocResettingFlag = true;
+      }
+      else if (m_pocDecrementedInDPBFlag)
+      {
+        m_pocResettingFlag = false;
+      }
+      else
+      {
+        m_pocResettingFlag = true;
+      }
+    }
+#endif
+
+    if( m_apcSlicePilot->getPocResetIdc() && m_apcSlicePilot->getSliceIdx() == 0 )
+    {
+      Int pocResetPeriodId = m_apcSlicePilot->getPocResetPeriodId();
+      if ( m_apcSlicePilot->getPocResetIdc() == 1 || m_apcSlicePilot->getPocResetIdc() == 2 ||
+        ( m_apcSlicePilot->getPocResetIdc() == 3 && pocResetPeriodId != getLastPocPeriodId() ) )
+      {
+        setLastPocPeriodId(pocResetPeriodId);
+        m_parseIdc = 0;
+      }
+#if POC_RESET_VALUE_RESTRICTION
+      // Check if the POC Reset period ID matches with the Reset Period ID 
+      if( pocResetPeriodId == m_crossLayerPocResetPeriodId )
+      {
+        // If matching, and current poc_reset_idc = 3, then the values should match
+        if( m_apcSlicePilot->getPocResetIdc() == 3 )
+        {
+          assert( ( m_apcSlicePilot->getFullPocResetFlag() == false && m_crossLayerPocResetIdc == 1 ) ||
+                  ( m_apcSlicePilot->getFullPocResetFlag() == true  && m_crossLayerPocResetIdc == 2 ) );
+        }
+      }
+      else
+      {
+        // This is the first picture of a POC resetting access unit
+        m_crossLayerPocResetPeriodId = pocResetPeriodId;
+        if( m_apcSlicePilot->getPocResetIdc() == 1 || m_apcSlicePilot->getPocResetIdc() == 2 )
+        {
+          m_crossLayerPocResetIdc = m_apcSlicePilot->getPocResetIdc();
+        }
+        else
+        { // poc_reset_idc = 3
+          // In this case, the entire POC resetting access unit has been lost. 
+          // Need more checking to ensure poc_reset_idc = 3 works.
+          assert ( 0 );
+        }
+      }
+#endif
+    }
+    else
+    {
+      m_parseIdc = 3; // Proceed to decoding POC and RPS
+    }
+  }
+#endif
+
+#if ALIGNED_BUMPING
+#if POC_RESET_IDC_DECODER
+
+#if P0297_VPS_POC_LSB_ALIGNED_FLAG
+  UInt affectedLayerList[MAX_LAYERS];
+  Int  numAffectedLayers;
+
+  affectedLayerList[0] = m_apcSlicePilot->getLayerId();
+  numAffectedLayers = 1;
+
+  if (m_apcSlicePilot->getVPS()->getVpsPocLsbAlignedFlag())
+  {
+    for (UInt j = 0; j < m_apcSlicePilot->getVPS()->getNumPredictedLayers(m_apcSlicePilot->getLayerId()); j++)
+    {
+      affectedLayerList[j + 1] = m_apcSlicePilot->getVPS()->getPredictedLayerId(m_apcSlicePilot->getLayerId(), j);
+    }
+    numAffectedLayers = m_apcSlicePilot->getVPS()->getNumPredictedLayers(m_apcSlicePilot->getLayerId()) + 1;
+  }
+#endif
+
+  //if(  (bNewPOC || m_layerId != m_uiPrevLayerId) && ( m_parseIdc != 1) )
+#if P0297_VPS_POC_LSB_ALIGNED_FLAG
+  if (m_parseIdc == 1 && m_pocResettingFlag)
+#else
+  if (m_parseIdc == 1)
+#endif
+  {
+    // Invoke output of pictures if the current picture is a POC reset picture
+    bNewPOC = true;
+    /* Include reset of all POCs in the layer */
+
+  // This operation would do the following:
+  // 1. Update the other picture in the DPB. This should be done only for the first slice of the picture.
+  // 2. Update the value of m_pocCRA.
+  // 3. Reset the POC values at the decoder for the current picture to be zero - will be done later
+  // 4. update value of POCLastDisplay
+      
+  //Do the reset stuff here
+    Int maxPocLsb = 1 << m_apcSlicePilot->getSPS()->getBitsForPOC();
+    Int pocLsbVal;
+    if( m_apcSlicePilot->getPocResetIdc() == 3 )
+    {
+      pocLsbVal = m_apcSlicePilot->getPocLsbVal() ;
+    }
+    else
+    {
+      pocLsbVal = (m_apcSlicePilot->getPOC() % maxPocLsb);
+    }
+
+    Int pocMsbDelta = 0;
+    if ( m_apcSlicePilot->getPocMsbValPresentFlag() ) 
+    {
+      pocMsbDelta = m_apcSlicePilot->getPocMsbVal() * maxPocLsb;
+    }
+    else
+    {
+      //This MSB derivation can be made into one function. Item to do next.
+      Int prevPoc     = this->getPrevPicOrderCnt();
+      Int prevPocLsb  = prevPoc & (maxPocLsb - 1);
+      Int prevPocMsb  = prevPoc - prevPocLsb;
+
+      pocMsbDelta = m_apcSlicePilot->getCurrMsb( pocLsbVal, prevPocLsb, prevPocMsb, maxPocLsb );
+    }
+
+    Int pocLsbDelta;
+    if( m_apcSlicePilot->getPocResetIdc() == 2 ||  ( m_apcSlicePilot->getPocResetIdc() == 3 && m_apcSlicePilot->getFullPocResetFlag() ))
+    {
+      pocLsbDelta = pocLsbVal;
+    }
+    else
+    {
+      pocLsbDelta = 0; 
+    }
+
+    Int deltaPocVal  =  pocMsbDelta + pocLsbDelta;
+
+#if P0297_VPS_POC_LSB_ALIGNED_FLAG
+    for (UInt layerIdx = 0; layerIdx < numAffectedLayers; layerIdx++)
+    {
+      if (!m_ppcTDecTop[affectedLayerList[layerIdx]]->m_pocDecrementedInDPBFlag)
+      {
+        m_ppcTDecTop[affectedLayerList[layerIdx]]->m_pocDecrementedInDPBFlag = true;
+        TComList<TComPic*>::iterator  iterPic = m_ppcTDecTop[affectedLayerList[layerIdx]]->getListPic()->begin();
+        while (iterPic != m_ppcTDecTop[affectedLayerList[layerIdx]]->getListPic()->end())
+#else
+    //Reset all POC for DPB -> basically do it for each slice in the picutre
+    TComList<TComPic*>::iterator  iterPic = m_cListPic.begin();  
+
+    // Iterate through all picture in DPB
+    while( iterPic != m_cListPic.end() )
+#endif
+    {
+      TComPic *dpbPic = *iterPic;
+      // Check if the picture pointed to by iterPic is either used for reference or
+      // needed for output, are in the same layer, and not the current picture.
+#if P0297_VPS_POC_LSB_ALIGNED_FLAG
+      assert(dpbPic->getLayerId() == affectedLayerList[layerIdx]);
+      if ( (dpbPic->getReconMark()) && (dpbPic->getPicSym()->getSlice(0)->getPicOutputFlag()) )
+#else
+      if ( /*  ( ( dpbPic->getSlice(0)->isReferenced() ) || ( dpbPic->getOutputMark() ) )
+          &&*/ ( dpbPic->getLayerId() == m_apcSlicePilot->getLayerId() )
+            && ( dpbPic->getReconMark() ) && ( dpbPic->getPicSym()->getSlice(0)->getPicOutputFlag() ))
+#endif
+      {
+        for(Int i = dpbPic->getNumAllocatedSlice()-1; i >= 0; i--)
+        {
+
+          TComSlice *slice = dpbPic->getSlice(i);
+          TComReferencePictureSet *rps = slice->getRPS();
+          slice->setPOC( slice->getPOC() - deltaPocVal );
+
+          // Also adjust the POC value stored in the RPS of each such slice
+          for(Int j = rps->getNumberOfPictures(); j >= 0; j--)
+          {
+            rps->setPOC( j, rps->getPOC(j) - deltaPocVal );
+          }
+          // Also adjust the value of refPOC
+          for(Int k = 0; k < 2; k++)  // For List 0 and List 1
+          {
+            RefPicList list = (k == 1) ? REF_PIC_LIST_1 : REF_PIC_LIST_0;
+            for(Int j = 0; j < slice->getNumRefIdx(list); j++)
+            {
+              slice->setRefPOC( slice->getRefPOC(list, j) - deltaPocVal, list, j);
+            }
+          }
+        }
+      }
+      iterPic++;
+    }
+#if P0297_VPS_POC_LSB_ALIGNED_FLAG
+        // Update the value of pocCRA
+        m_ppcTDecTop[affectedLayerList[layerIdx]]->m_pocCRA -= deltaPocVal;
+      }
+    }
+#else
+    // Update the value of pocCRA
+    m_pocCRA -= deltaPocVal;
+#endif
+
+    // Update value of POCLastDisplay
+    iPOCLastDisplay -= deltaPocVal;
+  }
+  Int maxPocLsb = 1 << m_apcSlicePilot->getSPS()->getBitsForPOC();
+  Int slicePicOrderCntLsb = m_apcSlicePilot->getPicOrderCntLsb();
+
+#if P0297_VPS_POC_LSB_ALIGNED_FLAG
+  if (m_pocResettingFlag && (m_parseIdc == 1 || m_parseIdc == 2))
+#else
+  if (m_parseIdc == 1 || m_parseIdc == 2) // TODO This should be replaced by pocResettingFlag.
+#endif
+  {
+    // Set poc for current slice
+    if( m_apcSlicePilot->getPocResetIdc() == 1 )
+    {        
+      m_apcSlicePilot->setPOC( slicePicOrderCntLsb );
+    }
+    else if( m_apcSlicePilot->getPocResetIdc() == 2 )
+    {
+      m_apcSlicePilot->setPOC( 0 );
+    }
+    else 
+    {
+      Int picOrderCntMsb = m_apcSlicePilot->getCurrMsb( slicePicOrderCntLsb, m_apcSlicePilot->getFullPocResetFlag() ? 0 : m_apcSlicePilot->getPocLsbVal(), 0 , maxPocLsb );
+      m_apcSlicePilot->setPOC( picOrderCntMsb + slicePicOrderCntLsb );
+    }
+  }
+  else if (m_parseIdc == 3)
+  {
+    Int picOrderCntMsb = 0;
+    if( m_apcSlicePilot->getPocMsbValPresentFlag() )
+    {
+      picOrderCntMsb = m_apcSlicePilot->getPocMsbVal() * maxPocLsb;
+    }
+    else if( m_apcSlicePilot->getIdrPicFlag() )
+    {
+      picOrderCntMsb = 0;
+    }
+    else
+    {
+      Int prevPicOrderCntLsb = this->getPrevPicOrderCnt() & ( maxPocLsb - 1);
+      Int prevPicOrderCntMsb  = this->getPrevPicOrderCnt() - prevPicOrderCntLsb;
+      picOrderCntMsb = m_apcSlicePilot->getCurrMsb(slicePicOrderCntLsb, prevPicOrderCntLsb, prevPicOrderCntMsb, maxPocLsb );
+    }
+    m_apcSlicePilot->setPOC( picOrderCntMsb + slicePicOrderCntLsb );
+  }
+
+  if( m_parseIdc == 1 || m_parseIdc == 3)
+  {
+    // Adjust prevPicOrderCnt
+    if(    !m_apcSlicePilot->getRaslPicFlag() 
+        && !m_apcSlicePilot->getRadlPicFlag()
+        && (m_apcSlicePilot->getNalUnitType() % 2 == 1)
+        && ( nalu.m_temporalId == 0 )
+        && !m_apcSlicePilot->getDiscardableFlag() )
+    {
+#if P0297_VPS_POC_LSB_ALIGNED_FLAG
+      for (UInt i = 0; i < numAffectedLayers; i++)
+      {
+        m_ppcTDecTop[affectedLayerList[i]]->setPrevPicOrderCnt(m_apcSlicePilot->getPOC());
+      }
+#else
+      this->setPrevPicOrderCnt( m_apcSlicePilot->getPOC() );
+#endif
+    }
+    else if ( m_apcSlicePilot->getPocResetIdc() == 3 )
+    {
+#if P0297_VPS_POC_LSB_ALIGNED_FLAG
+      if (!m_firstPicInLayerDecodedFlag || (m_firstPicInLayerDecodedFlag && m_pocResettingFlag))
+      {
+        for (UInt i = 0; i < numAffectedLayers; i++)
+        {
+          m_ppcTDecTop[affectedLayerList[i]]->setPrevPicOrderCnt( m_apcSlicePilot->getFullPocResetFlag() 
+                                                                  ? 0 : m_apcSlicePilot->getPocLsbVal() );
+        }
+      }
+#else
+      this->setPrevPicOrderCnt( m_apcSlicePilot->getFullPocResetFlag() 
+                                            ? 0 : m_apcSlicePilot->getPocLsbVal() );
+#endif
+    }
+#else
+  if (bNewPOC || m_layerId!=m_uiPrevLayerId)
+  {
+#endif
+    m_apcSlicePilot->applyReferencePictureSet(m_cListPic, m_apcSlicePilot->getRPS());
+  }
+#endif
+#if POC_RESET_IDC_DECODER
+  if (!m_apcSlicePilot->getDependentSliceSegmentFlag() && (bNewPOC || m_layerId!=m_uiPrevLayerId || m_parseIdc == 1) && !m_bFirstSliceInSequence )
+#else
+  if (!m_apcSlicePilot->getDependentSliceSegmentFlag() && (bNewPOC || m_layerId!=m_uiPrevLayerId) && !m_bFirstSliceInSequence )
+#endif
+  {
+    m_prevPOC = m_apcSlicePilot->getPOC();
+    curLayerId = m_uiPrevLayerId; 
+    m_uiPrevLayerId = m_layerId;
+    return true;
+  }
+
+#if POC_RESET_IDC_DECODER
+  m_parseIdc = -1;
+#endif
+
+
+#if R0226_SLICE_TMVP
+  if ( m_apcSlicePilot->getTLayer() == 0 && m_apcSlicePilot->getEnableTMVPFlag() == 0 )
+  {
+    //update all pics in the DPB such that they cannot be used for TMPV ref
+    TComList<TComPic*>::iterator  iterRefPic = m_cListPic.begin();  
+    while( iterRefPic != m_cListPic.end() )
+    {
+      TComPic *refPic = *iterRefPic;
+      if( ( refPic->getLayerId() == m_apcSlicePilot->getLayerId() ) && refPic->getReconMark() )
+      {
+        for(Int i = refPic->getNumAllocatedSlice()-1; i >= 0; i--)
+        {
+
+          TComSlice *refSlice = refPic->getSlice(i);
+          refSlice->setAvailableForTMVPRefFlag( false );
+        }
+      }
+      iterRefPic++;
+    }
+  }
+  m_apcSlicePilot->setAvailableForTMVPRefFlag( true );
+#endif
+
+  // actual decoding starts here
+  xActivateParameterSets();
+
+#if REPN_FORMAT_IN_VPS
+  // Initialize ILRP if needed, only for the current layer  
+  // ILRP intialization should go along with activation of parameters sets, 
+  // although activation of parameter sets itself need not be done for each and every slice!!!
+  xInitILRP(m_apcSlicePilot);
+#endif
+  if (!m_apcSlicePilot->getDependentSliceSegmentFlag()) 
+  {
+    m_prevPOC = m_apcSlicePilot->getPOC();
+    curLayerId = m_layerId;
+    m_uiPrevLayerId = m_layerId;
+  }
+  m_bFirstSliceInSequence = false;
+  m_bFirstSliceInBitstream  = false;
+#if POC_RESET_FLAG
+  // This operation would do the following:
+  // 1. Update the other picture in the DPB. This should be done only for the first slice of the picture.
+  // 2. Update the value of m_pocCRA.
+  // 3. Reset the POC values at the decoder for the current picture to be zero.
+  // 4. update value of POCLastDisplay
+  if( m_apcSlicePilot->getPocResetFlag() )
+  {
+    if( m_apcSlicePilot->getSliceIdx() == 0 )
+    {
+      Int pocAdjustValue = m_apcSlicePilot->getPOC();
+
+#if PREVTID0_POC_RESET
+      m_apcSlicePilot->adjustPrevTid0POC(pocAdjustValue);
+#endif
+      // If poc reset flag is set to 1, reset all POC for DPB -> basically do it for each slice in the picutre
+      TComList<TComPic*>::iterator  iterPic = m_cListPic.begin();  
+
+      // Iterate through all picture in DPB
+      while( iterPic != m_cListPic.end() )
+      {
+        TComPic *dpbPic = *iterPic;
+        // Check if the picture pointed to by iterPic is either used for reference or
+        // needed for output, are in the same layer, and not the current picture.
+        if( /*  ( ( dpbPic->getSlice(0)->isReferenced() ) || ( dpbPic->getOutputMark() ) )
+            &&*/ ( dpbPic->getLayerId() == m_apcSlicePilot->getLayerId() )
+              && ( dpbPic->getReconMark() ) 
+          )
+        {
+          for(Int i = dpbPic->getNumAllocatedSlice()-1; i >= 0; i--)
+          {
+
+            TComSlice *slice = dpbPic->getSlice(i);
+            TComReferencePictureSet *rps = slice->getRPS();
+            slice->setPOC( slice->getPOC() - pocAdjustValue );
+
+            // Also adjust the POC value stored in the RPS of each such slice
+            for(Int j = rps->getNumberOfPictures(); j >= 0; j--)
+            {
+              rps->setPOC( j, rps->getPOC(j) - pocAdjustValue );
+            }
+            // Also adjust the value of refPOC
+            for(Int k = 0; k < 2; k++)  // For List 0 and List 1
+            {
+              RefPicList list = (k == 1) ? REF_PIC_LIST_1 : REF_PIC_LIST_0;
+              for(Int j = 0; j < slice->getNumRefIdx(list); j++)
+              {
+                slice->setRefPOC( slice->getRefPOC(list, j) - pocAdjustValue, list, j);
+              }
+            }
+          }
+        }
+        iterPic++;
+      }
+      // Update the value of pocCRA
+      m_pocCRA -= pocAdjustValue;
+      // Update value of POCLastDisplay
+      iPOCLastDisplay -= pocAdjustValue;
+    }
+    // Reset current poc for current slice and RPS
+    m_apcSlicePilot->setPOC( 0 );
+  }
+#endif
+  // Alignment of TSA and STSA pictures across AU
+#if !Q0108_TSA_STSA
+  if( m_apcSlicePilot->getLayerId() > 0 )
+  {
+    // Check for TSA alignment
+    if( m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_TSA_N ||
+        m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_TSA_R 
+         )
+    {
+      for(Int dependentLayerIdx = 0; dependentLayerIdx < m_apcSlicePilot->getVPS()->getNumDirectRefLayers(m_layerId); dependentLayerIdx++)
+      {
+        TComList<TComPic*> *cListPic = getRefLayerDec( dependentLayerIdx )->getListPic();
+        TComPic* refpicLayer = m_apcSlicePilot->getRefPic(*cListPic, m_apcSlicePilot->getPOC() );
+        if( refpicLayer )
+        {
+          assert( m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_TSA_N ||
+                    m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_TSA_R );    // TSA pictures should be aligned among depenedent layers
+        } 
+      }
+    }
+    // Check for STSA alignment
+    if( m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_STSA_N ||
+         m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_STSA_R 
+         )
+    {
+      for(Int dependentLayerIdx = 0; dependentLayerIdx < m_apcSlicePilot->getVPS()->getNumDirectRefLayers(m_layerId); dependentLayerIdx++)
+      {
+        TComList<TComPic*> *cListPic = getRefLayerDec( dependentLayerIdx )->getListPic();
+        TComPic* refpicLayer = m_apcSlicePilot->getRefPic(*cListPic, m_apcSlicePilot->getPOC() ); // STSA pictures should be aligned among dependent layers
+        if( refpicLayer )
+
+        {
+          assert( m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_STSA_N ||
+                    m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_STSA_R );
+        }
+      }
+    }
+  }
+#endif
+
+#else //SVC_EXTENSION
+  //we should only get a different poc for a new picture (with CTU address==0)
+  if (!m_apcSlicePilot->getDependentSliceSegmentFlag() && m_apcSlicePilot->getPOC()!=m_prevPOC && !m_bFirstSliceInSequence && (m_apcSlicePilot->getSliceCurStartCtuTsAddr() != 0))  
+  {
+    printf ("Warning, the first slice of a picture might have been lost!\n");
+  }
+
+  // exit when a new picture is found
+  if (!m_apcSlicePilot->getDependentSliceSegmentFlag() && (m_apcSlicePilot->getSliceCurStartCtuTsAddr() == 0 && !m_bFirstSliceInPicture) )
+  {
+    if (m_prevPOC >= m_pocRandomAccess)
+    {
+      m_prevPOC = m_apcSlicePilot->getPOC();
+#if ENC_DEC_TRACE
+      //rewind the trace counter since we didn't actually decode the slice
+      g_nSymbolCounter = originalSymbolCount;
+#endif
+      return true;
+    }
+    m_prevPOC = m_apcSlicePilot->getPOC();
+  }
+
+  // actual decoding starts here
+  xActivateParameterSets();
+
+  if (!m_apcSlicePilot->getDependentSliceSegmentFlag())
+  {
+    m_prevPOC = m_apcSlicePilot->getPOC();
+  }
+  m_bFirstSliceInSequence = false;
+  m_bFirstSliceInBitstream  = false;
+#endif //SVC_EXTENSION
+  //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)
+  {
+#if AVC_BASE
+#if VPS_AVC_BL_FLAG_REMOVAL
+    if( m_layerId > 0 && m_parameterSetManagerDecoder.getPrefetchedVPS(0)->getNonHEVCBaseLayerFlag() )
+#else
+    if( m_layerId > 0 && m_parameterSetManagerDecoder.getPrefetchedVPS(0)->getAvcBaseLayerFlag() )
+#endif
+    {
+      TComPic* pBLPic = (*m_ppcTDecTop[0]->getListPic()->begin());
+      pBLPic->getSlice(0)->setReferenced(true);
+      fstream* pFile  = m_ppcTDecTop[0]->getBLReconFile();
+
+      if( pFile->good() )
+      {
+        Bool is16bit  = g_bitDepthLayer[CHANNEL_TYPE_LUMA][0] > 8 || g_bitDepthLayer[CHANNEL_TYPE_CHROMA][0] > 8;
+        UInt uiWidth  = pBLPic->getPicYuvRec()->getWidth(COMPONENT_Y);
+        UInt uiHeight = pBLPic->getPicYuvRec()->getHeight(COMPONENT_Y);
+
+        Int len = uiWidth * (is16bit ? 2 : 1);
+        UChar *buf = new UChar[len];
+
+        UInt64 uiPos = (UInt64) m_apcSlicePilot->getPOC() * uiWidth * uiHeight * 3 / 2;
+        if( is16bit )
+        {
+            uiPos <<= 1;
+        }
+
+        pFile->seekg((UInt)uiPos, ios::beg );
+
+        // read Y component
+        Pel* pPel = pBLPic->getPicYuvRec()->getAddr(COMPONENT_Y);
+        UInt uiStride = pBLPic->getPicYuvRec()->getStride(COMPONENT_Y);
+        for( Int i = 0; i < uiHeight; i++ )
+        {
+          pFile->read(reinterpret_cast<Char*>(buf), len);
+
+          if( !is16bit )
+          {
+            for (Int x = 0; x < uiWidth; x++)
+            {
+              pPel[x] = buf[x];
+            }
+          }
+          else
+          {
+            for (Int x = 0; x < uiWidth; x++)
+            {
+              pPel[x] = (buf[2*x+1] << 8) | buf[2*x];
+            }
+          }
+     
+          pPel += uiStride;
+        }
+
+        len >>= 1;
+        uiWidth >>= 1;
+        uiHeight >>= 1;
+
+        // read Cb component
+        pPel = pBLPic->getPicYuvRec()->getAddr(COMPONENT_Cb);
+        uiStride = pBLPic->getPicYuvRec()->getStride(COMPONENT_Cb);
+        for( Int i = 0; i < uiHeight; i++ )
+        {
+          pFile->read(reinterpret_cast<Char*>(buf), len);
+
+          if( !is16bit )
+          {
+            for( Int x = 0; x < uiWidth; x++ )
+            {
+              pPel[x] = buf[x];
+            }
+          }
+          else
+          {
+            for( Int x = 0; x < uiWidth; x++ )
+            {
+              pPel[x] = (buf[2*x+1] << 8) | buf[2*x];
+            }
+          }
+     
+          pPel += uiStride;
+        }
+
+        // read Cr component
+        pPel = pBLPic->getPicYuvRec()->getAddr(COMPONENT_Cr);
+        uiStride = pBLPic->getPicYuvRec()->getStride(COMPONENT_Cr);
+        for( Int i = 0; i < uiHeight; i++ )
+        {
+          pFile->read(reinterpret_cast<Char*>(buf), len);
+
+          if( !is16bit )
+          {
+            for( Int x = 0; x < uiWidth; x++ )
+            {
+              pPel[x] = buf[x];
+            }
+          }
+          else
+          {
+            for( Int x = 0; x < uiWidth; x++ )
+            {
+              pPel[x] = (buf[2*x+1] << 8) | buf[2*x];
+            }
+          }
+     
+          pPel += uiStride;
+        }
+
+        delete[] buf;
+      }
+    }
+#endif
+
+#if NO_OUTPUT_OF_PRIOR_PICS
+    if ( m_layerId == 0 && m_apcSlicePilot->getRapPicFlag() && getNoClrasOutputFlag() )
+    {
+      for (UInt i = 0; i < m_apcSlicePilot->getVPS()->getMaxLayers(); i++)
+      {
+        m_ppcTDecTop[i]->setLayerInitializedFlag(false);
+        m_ppcTDecTop[i]->setFirstPicInLayerDecodedFlag(false);
+      }
+    }
+#endif
+#if R0071_IRAP_EOS_CROSS_LAYER_IMPACTS
+    xCheckLayerReset();
+    xSetLayerInitializedFlag();
+#endif
+    // Buffer initialize for prediction.
+    m_cPrediction.initTempBuff(m_apcSlicePilot->getSPS()->getChromaFormatIdc());
+#if ALIGNED_BUMPING
+    m_apcSlicePilot->checkLeadingPictureRestrictions(m_cListPic);
+#else
+    m_apcSlicePilot->applyReferencePictureSet(m_cListPic, m_apcSlicePilot->getRPS());
+#endif
+    //  Get a new picture buffer
+    xGetNewPicBuffer (m_apcSlicePilot, m_pcPic);
+
+#if POC_RESET_IDC_DECODER
+    m_pcPic->setCurrAuFlag( true );
+#if POC_RESET_RESTRICTIONS
+    if( m_pcPic->getLayerId() > 0 && m_apcSlicePilot->isIDR() && !m_nonBaseIdrPresentFlag )
+    {
+      // IDR picture with nuh_layer_id > 0 present
+      m_nonBaseIdrPresentFlag = true;
+      m_nonBaseIdrType = (m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_W_RADL);
+    }
+    else
+    {
+      if( m_apcSlicePilot->getNalUnitType() != NAL_UNIT_CODED_SLICE_IDR_W_RADL )
+      {
+        // Picture with nal_unit_type not equal IDR_W_RADL present
+        m_picNonIdrWithRadlPresentFlag = true;
+      }
+      if( m_apcSlicePilot->getNalUnitType() != NAL_UNIT_CODED_SLICE_IDR_N_LP )
+      {
+        // Picture with nal_unit_type not equal IDR_N_LP present
+        m_picNonIdrNoLpPresentFlag = true;
+      }
+    }
+    if( !m_checkPocRestrictionsForCurrAu )  // Will be true for the first slice/picture of the AU
+    {
+      m_checkPocRestrictionsForCurrAu = true;
+      m_pocResetIdcOrCurrAu = m_apcSlicePilot->getPocResetIdc();
+      if( m_pcPic->getLayerId() == 0 )
+      {
+        // Base layer picture is present
+        m_baseLayerPicPresentFlag = true;
+        if( m_apcSlicePilot->isIRAP() )
+        {
+          // Base layer picture is IRAP
+          m_baseLayerIrapFlag = true;
+        }
+        if( m_apcSlicePilot->isIDR() )
+        {
+          // Base layer picture is IDR
+          m_baseLayerIdrFlag = true;
+        }
+        else
+        {
+          if( m_apcSlicePilot->getVPS()->getBaseLayerInternalFlag())
+          {
+            /* When the picture with nuh_layer_id equal to 0 in an access unit is not an IDR picture 
+            and vps_base_layer_internal_flag is equal to 1, the value of poc_reset_idc shall not be equal to 2 
+            for any picture in the access unit. */
+            assert( m_apcSlicePilot->getPocResetIdc() != 2 );
+          }
+        }
+      }
+    }
+    else
+    {
+      // The value of poc_reset_idc of all coded pictures that are present in the bitstream in an access unit shall be the same.
+      assert( m_pocResetIdcOrCurrAu == m_apcSlicePilot->getPocResetIdc() );
+
+      /* When the picture in an access unit with nuh_layer_id equal to 0 is an IRAP picture and vps_base_layer_internal_flag is equal to 1 
+      and there is at least one other picture in the same access unit that is not an IRAP picture, 
+      the value of poc_reset_idc shall be equal to 1 or 2 for all pictures in the access unit. */
+      if( m_baseLayerPicPresentFlag && m_baseLayerIrapFlag && !m_apcSlicePilot->isIRAP() && m_apcSlicePilot->getVPS()->getBaseLayerInternalFlag() )
+      {
+        assert( m_apcSlicePilot->getPocResetIdc() == 1 || m_apcSlicePilot->getPocResetIdc() == 2 );
+      }
+
+      /* When the picture with nuh_layer_id equal to 0 in an access unit is an IDR picture and 
+      vps_base_layer_internal_flag is equal to 1 and there is at least one non-IDR picture in the same access unit, 
+      the value of poc_reset_idc shall be equal to 2 for all pictures in the access unit. */
+      if( m_baseLayerPicPresentFlag && m_baseLayerIdrFlag && !m_apcSlicePilot->isIDR() && m_apcSlicePilot->getVPS()->getBaseLayerInternalFlag() )
+      {
+        assert( m_apcSlicePilot->getPocResetIdc() == 2 );
+      }
+
+      /* When there is at least one picture that has nuh_layer_id greater than 0 and that is an IDR picture 
+      with a particular value of nal_unit_type in an access unit and there is at least one other coded picture 
+      that is present in the bitstream in the same access unit with a different value of nal_unit_type, 
+      the value of poc_reset_idc shall be equal to 1 or 2 for all pictures in the access unit. */
+      if( m_nonBaseIdrPresentFlag && (
+            ( m_nonBaseIdrType == 1 && m_picNonIdrWithRadlPresentFlag ) ||
+            ( m_nonBaseIdrType == 0 && m_picNonIdrNoLpPresentFlag )
+        ))
+      {
+        assert( m_apcSlicePilot->getPocResetIdc() == 1 || m_apcSlicePilot->getPocResetIdc() == 2 );
+      }
+    }
+#endif
+#endif
+
+    Bool isField = false;
+    Bool isTff = false;
+    
+    if(!m_SEIs.empty())
+    {
+      // Check if any new Picture Timing SEI has arrived
+      SEIMessages pictureTimingSEIs = extractSeisByType (m_SEIs, SEI::PICTURE_TIMING);
+      if (pictureTimingSEIs.size()>0)
+      {
+        SEIPictureTiming* pictureTiming = (SEIPictureTiming*) *(pictureTimingSEIs.begin());
+        isField = (pictureTiming->m_picStruct == 1) || (pictureTiming->m_picStruct == 2);
+        isTff =  (pictureTiming->m_picStruct == 1);
+      }
+
+#if R0226_CONSTRAINT_TMVP_SEI
+      // Check if any new temporal motion vector prediction constraints SEI has arrived
+      SEIMessages seiTMVPConstrainsList = extractSeisByType (m_SEIs, SEI::TMVP_CONSTRAINTS);
+      if (seiTMVPConstrainsList.size() > 0)
+      {
+        assert ( m_pcPic->getTLayer() == 0 );  //this SEI can present only for AU with Tid equal to 0
+        SEITMVPConstrains* tmvpConstraintSEI = (SEITMVPConstrains*) *(seiTMVPConstrainsList.begin());
+        if ( tmvpConstraintSEI->prev_pics_not_used_flag == 1 )
+        {
+          //update all pics in the DPB such that they cannot be used for TMPV ref
+          TComList<TComPic*>::iterator  iterRefPic = m_cListPic.begin();  
+          while( iterRefPic != m_cListPic.end() )
+          {
+            TComPic *refPic = *iterRefPic;
+            if( ( refPic->getLayerId() == m_pcPic->getLayerId() ) && refPic->getReconMark() )
+            {
+              for(Int i = refPic->getNumAllocatedSlice()-1; i >= 0; i--)
+              {
+                TComSlice *refSlice = refPic->getSlice(i);
+                refSlice->setAvailableForTMVPRefFlag( false );
+              }
+            }
+            iterRefPic++;
+          }
+        }
+      }
+#endif
+    }
+    
+    //Set Field/Frame coding mode
+    m_pcPic->setField(isField);
+    m_pcPic->setTopField(isTff);
+
+    // transfer any SEI messages that have been received to the picture
+    m_pcPic->setSEIs(m_SEIs);
+    m_SEIs.clear();
+
+    // Recursive structure
+    m_cCuDecoder.create ( g_uiMaxCUDepth, g_uiMaxCUWidth, g_uiMaxCUHeight, m_apcSlicePilot->getSPS()->getChromaFormatIdc() );
+#if SVC_EXTENSION
+    m_cCuDecoder.init   ( m_ppcTDecTop,&m_cEntropyDecoder, &m_cTrQuant, &m_cPrediction, curLayerId );
+#else
+    m_cCuDecoder.init   ( &m_cEntropyDecoder, &m_cTrQuant, &m_cPrediction );
+#endif
+    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 = m_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;
+
+  m_pcPic->getPicSym()->initTiles(pcSlice->getPPS());
+  m_pcPic->getPicSym()->initCtuTsRsAddrMaps();
+
+  // When decoding the slice header, the stored start and end addresses were actually RS addresses, not TS addresses.
+  // Now, having set up the maps, convert them to the correct form.
+  pcSlice->setSliceSegmentCurStartCtuTsAddr( m_pcPic->getPicSym()->getCtuRsToTsAddrMap(pcSlice->getSliceSegmentCurStartCtuTsAddr()) );
+  pcSlice->setSliceSegmentCurEndCtuTsAddr( m_pcPic->getPicSym()->getCtuRsToTsAddrMap(pcSlice->getSliceSegmentCurEndCtuTsAddr()) );
+  if(!pcSlice->getDependentSliceSegmentFlag())
+  {
+    pcSlice->setSliceCurStartCtuTsAddr(m_pcPic->getPicSym()->getCtuRsToTsAddrMap(pcSlice->getSliceCurStartCtuTsAddr()));
+    pcSlice->setSliceCurEndCtuTsAddr(m_pcPic->getPicSym()->getCtuRsToTsAddrMap(pcSlice->getSliceCurEndCtuTsAddr()));
+  }
+
+  if (m_bFirstSliceInPicture)
+  {
+    if(m_pcPic->getNumAllocatedSlice() != 1)
+    {
+      m_pcPic->clearSliceBuffer();
+    }
+  }
+  else
+  {
+    m_pcPic->allocateNewSlice();
+  }
+  assert(m_pcPic->getNumAllocatedSlice() == (m_uiSliceIdx + 1));
+  m_apcSlicePilot = m_pcPic->getPicSym()->getSlice(m_uiSliceIdx);
+  m_pcPic->getPicSym()->setSlice(pcSlice, m_uiSliceIdx);
+
+  m_pcPic->setTLayer(nalu.m_temporalId);
+
+#if SVC_EXTENSION
+  m_pcPic->setLayerId(nalu.m_layerId);
+  pcSlice->setLayerId(nalu.m_layerId);
+  pcSlice->setPic(m_pcPic);
+#endif
+
+  if (!pcSlice->getDependentSliceSegmentFlag())
+  {
+    pcSlice->checkCRA(pcSlice->getRPS(), m_pocCRA, m_associatedIRAPType, m_cListPic );
+    // Set reference list
+#if SVC_EXTENSION
+    if (m_layerId == 0)
+#endif
+    pcSlice->setRefPicList( m_cListPic, true );
+
+#if SVC_EXTENSION
+    // Create upsampling reference layer pictures for all possible dependent layers and do it only once for the first slice. 
+    // Other slices might choose which reference pictures to be used for inter-layer prediction
+    if( m_layerId > 0 && m_uiSliceIdx == 0 )
+    {      
+#if M0040_ADAPTIVE_RESOLUTION_CHANGE
+      if( !pcSlice->getVPS()->getSingleLayerForNonIrapFlag() || ( pcSlice->getVPS()->getSingleLayerForNonIrapFlag() && pcSlice->isIRAP() ) )
+#endif
+      for( Int i = 0; i < pcSlice->getNumILRRefIdx(); i++ )
+      {
+        UInt refLayerIdc = i;
+        UInt refLayerId = pcSlice->getVPS()->getRefLayerId(m_layerId, refLayerIdc);
+#if AVC_BASE
+#if VPS_AVC_BL_FLAG_REMOVAL
+        if( refLayerId == 0 && m_parameterSetManagerDecoder.getActiveVPS()->getNonHEVCBaseLayerFlag() )
+#else
+        if( refLayerId == 0 && m_parameterSetManagerDecoder.getActiveVPS()->getAvcBaseLayerFlag() )
+#endif
+        {          
+          TComPic* pic = *m_ppcTDecTop[0]->getListPic()->begin();
+
+          if( pic )
+          {
+            pcSlice->setBaseColPic ( refLayerIdc, pic );
+          }
+          else
+          {
+            continue;
+          }
+        }
+        else
+        {
+#if VPS_EXTN_DIRECT_REF_LAYERS
+          TDecTop *pcTDecTop = (TDecTop *)getRefLayerDec( refLayerIdc );
+#else
+          TDecTop *pcTDecTop = (TDecTop *)getLayerDec( m_layerId-1 );
+#endif
+          TComList<TComPic*> *cListPic = pcTDecTop->getListPic();
+          if( !pcSlice->setBaseColPic ( *cListPic, refLayerIdc ) )
+          {
+            continue;
+          }
+        }
+#else
+#if VPS_EXTN_DIRECT_REF_LAYERS
+        TDecTop *pcTDecTop = (TDecTop *)getRefLayerDec( refLayerIdc );
+#else
+        TDecTop *pcTDecTop = (TDecTop *)getLayerDec( m_layerId-1 );
+#endif
+        TComList<TComPic*> *cListPic = pcTDecTop->getListPic();
+        pcSlice->setBaseColPic ( *cListPic, refLayerIdc );
+#endif
+
+#if MOVE_SCALED_OFFSET_TO_PPS
+#if O0098_SCALED_REF_LAYER_ID
+        const Window &scalEL = pcSlice->getPPS()->getScaledRefLayerWindowForLayer(refLayerId);
+#else
+        const Window &scalEL = pcSlice->getPPS()->getScaledRefLayerWindow(refLayerIdc);
+#endif
+#else
+#if O0098_SCALED_REF_LAYER_ID
+        const Window &scalEL = pcSlice->getSPS()->getScaledRefLayerWindowForLayer(refLayerId);
+#else
+        const Window &scalEL = pcSlice->getSPS()->getScaledRefLayerWindow(refLayerIdc);
+#endif
+#endif
+
+#if REF_REGION_OFFSET
+        const Window &windowRL = pcSlice->getPPS()->getRefLayerWindowForLayer(pcSlice->getVPS()->getRefLayerId(m_layerId, refLayerIdc));
+        Int widthBL   = pcSlice->getBaseColPic(refLayerIdc)->getPicYuvRec()->getWidth(COMPONENT_Y) - windowRL.getWindowLeftOffset() - windowRL.getWindowRightOffset();
+        Int heightBL  = pcSlice->getBaseColPic(refLayerIdc)->getPicYuvRec()->getHeight(COMPONENT_Y) - windowRL.getWindowTopOffset() - windowRL.getWindowBottomOffset();
+#else
+        Int widthBL   = pcSlice->getBaseColPic(refLayerIdc)->getPicYuvRec()->getWidth(COMPONENT_Y);
+        Int heightBL  = pcSlice->getBaseColPic(refLayerIdc)->getPicYuvRec()->getHeight(COMPONENT_Y);
+#if Q0200_CONFORMANCE_BL_SIZE
+        Int chromaFormatIdc = pcSlice->getBaseColPic(refLayerIdc)->getSlice(0)->getChromaFormatIdc();
+        const Window &confBL = pcSlice->getBaseColPic(refLayerIdc)->getConformanceWindow(); 
+        widthBL  -= ( confBL.getWindowLeftOffset() + confBL.getWindowRightOffset() ) * TComSPS::getWinUnitX( chromaFormatIdc );
+        heightBL -= ( confBL.getWindowTopOffset() + confBL.getWindowBottomOffset() ) * TComSPS::getWinUnitY( chromaFormatIdc );
+#endif
+#endif
+        Int widthEL   = m_pcPic->getPicYuvRec()->getWidth(COMPONENT_Y)  - scalEL.getWindowLeftOffset() - scalEL.getWindowRightOffset();
+        Int heightEL  = m_pcPic->getPicYuvRec()->getHeight(COMPONENT_Y) - scalEL.getWindowTopOffset()  - scalEL.getWindowBottomOffset();
+
+#if RESAMPLING_FIX
+#if REF_REGION_OFFSET
+        // conformance check: the values of RefLayerRegionWidthInSamplesY, RefLayerRegionHeightInSamplesY, ScaledRefRegionWidthInSamplesY and ScaledRefRegionHeightInSamplesY shall be greater than 0
+        assert(widthEL > 0 && heightEL > 0 && widthBL > 0 && widthEL > 0);
+
+        // conformance check: ScaledRefRegionWidthInSamplesY shall be greater or equal to RefLayerRegionWidthInSamplesY and ScaledRefRegionHeightInSamplesY shall be greater or equal to RefLayerRegionHeightInSamplesY
+        assert(widthEL >= widthBL && heightEL >= heightBL);
+
+#if R0209_GENERIC_PHASE
+        // conformance check: when ScaledRefRegionWidthInSamplesY is equal to RefLayerRegionWidthInSamplesY, PhaseHorY shall be equal to 0, when ScaledRefRegionWidthInSamplesC is equal to RefLayerRegionWidthInSamplesC, PhaseHorC shall be equal to 0, when ScaledRefRegionHeightInSamplesY is equal to RefLayerRegionHeightInSamplesY, PhaseVerY shall be equal to 0, and when ScaledRefRegionHeightInSamplesC is equal to RefLayerRegionHeightInSamplesC, PhaseVerC shall be equal to 0.
+        Bool phaseSetPresentFlag;
+        Int phaseHorLuma, phaseVerLuma, phaseHorChroma, phaseVerChroma;
+        pcSlice->getPPS()->getResamplingPhase( refLayerId, phaseSetPresentFlag, phaseHorLuma, phaseVerLuma, phaseHorChroma, phaseVerChroma );
+
+        assert( ( (widthEL  != widthBL)  || (phaseHorLuma == 0 && phaseHorChroma == 0) )
+             && ( (heightEL != heightBL) || (phaseVerLuma == 0 && phaseVerChroma == 0) ) );
+#endif
+#endif
+#endif
+
+        g_mvScalingFactor[refLayerIdc][0] = widthEL  == widthBL  ? 4096 : Clip3(-4096, 4095, ((widthEL  << 8) + (widthBL  >> 1)) / widthBL);
+        g_mvScalingFactor[refLayerIdc][1] = heightEL == heightBL ? 4096 : Clip3(-4096, 4095, ((heightEL << 8) + (heightBL >> 1)) / heightBL);
+
+        g_posScalingFactor[refLayerIdc][0] = ((widthBL  << 16) + (widthEL  >> 1)) / widthEL;
+        g_posScalingFactor[refLayerIdc][1] = ((heightBL << 16) + (heightEL >> 1)) / heightEL;
+
+#if Q0048_CGS_3D_ASYMLUT 
+        TComPicYuv* pBaseColRec = pcSlice->getBaseColPic(refLayerIdc)->getPicYuvRec();
+        if( pcSlice->getPPS()->getCGSFlag() 
+#if R0150_CGS_SIGNAL_CONSTRAINTS
+          && m_c3DAsymLUTPPS.isRefLayer( pcSlice->getVPS()->getRefLayerId(m_layerId, refLayerIdc) )
+#endif
+          )
+        {
+#if R0150_CGS_SIGNAL_CONSTRAINTS
+          assert( pcSlice->getBaseColPic( refLayerIdc )->getSlice( 0 )->getBitDepthY() == m_c3DAsymLUTPPS.getInputBitDepthY() );
+          assert( pcSlice->getBaseColPic( refLayerIdc )->getSlice( 0 )->getBitDepthC() == m_c3DAsymLUTPPS.getInputBitDepthC() );
+          assert( pcSlice->getBitDepthY() >= m_c3DAsymLUTPPS.getOutputBitDepthY() );
+          assert( pcSlice->getBitDepthY() >= m_c3DAsymLUTPPS.getOutputBitDepthC() );
+#endif
+          if(!m_pColorMappedPic)
+          {
+            initAsymLut(pcSlice->getBaseColPic(refLayerIdc)->getSlice(0));
+          }
+          m_c3DAsymLUTPPS.colorMapping( pcSlice->getBaseColPic(refLayerIdc)->getPicYuvRec(),  m_pColorMappedPic );
+          pBaseColRec = m_pColorMappedPic;
+        }
+#endif
+#if SVC_EXTENSION
+        if( m_pcPic->isSpatialEnhLayer(refLayerIdc) )
+        {
+          // check for the sample prediction picture type
+          if( pcSlice->getVPS()->isSamplePredictionType( pcSlice->getVPS()->getLayerIdxInVps(m_layerId), pcSlice->getVPS()->getLayerIdxInVps(refLayerId) ) )
+          {
+#if O0215_PHASE_ALIGNMENT_REMOVAL
+            m_cPrediction.upsampleBasePic( pcSlice, refLayerIdc, m_pcPic->getFullPelBaseRec(refLayerIdc), pBaseColRec, m_pcPic->getPicYuvRec());
+#else
+#if O0215_PHASE_ALIGNMENT
+#if O0194_JOINT_US_BITSHIFT
+#if Q0048_CGS_3D_ASYMLUT 
+            m_cPrediction.upsampleBasePic( pcSlice, refLayerIdc, m_pcPic->getFullPelBaseRec(refLayerIdc), pBaseColRec, m_pcPic->getPicYuvRec(), pcSlice->getVPS()->getPhaseAlignFlag() );
+#else
+            m_cPrediction.upsampleBasePic( pcSlice, refLayerIdc, m_pcPic->getFullPelBaseRec(refLayerIdc), pcSlice->getBaseColPic(refLayerIdc)->getPicYuvRec(), m_pcPic->getPicYuvRec(), pcSlice->getVPS()->getPhaseAlignFlag() );
+#endif
+#else
+#if Q0048_CGS_3D_ASYMLUT 
+#if MOVE_SCALED_OFFSET_TO_PPS
+          m_cPrediction.upsampleBasePic( refLayerIdc, m_pcPic->getFullPelBaseRec(refLayerIdc), pBaseColRec, m_pcPic->getPicYuvRec(), pcSlice->getPPS()->getScaledRefLayerWindow(refLayerIdc), pcSlice->getVPS()->getPhaseAlignFlag() );
+#else
+          m_cPrediction.upsampleBasePic( refLayerIdc, m_pcPic->getFullPelBaseRec(refLayerIdc), pBaseColRec, m_pcPic->getPicYuvRec(), pcSlice->getSPS()->getScaledRefLayerWindow(refLayerIdc), pcSlice->getVPS()->getPhaseAlignFlag() );
+#endif
+#else
+          m_cPrediction.upsampleBasePic( refLayerIdc, m_pcPic->getFullPelBaseRec(refLayerIdc), pcSlice->getBaseColPic(refLayerIdc)->getPicYuvRec(), m_pcPic->getPicYuvRec(), scalEL, pcSlice->getVPS()->getPhaseAlignFlag() );
+#endif
+#endif
+#else
+#if O0194_JOINT_US_BITSHIFT
+#if Q0048_CGS_3D_ASYMLUT 
+#if REF_REGION_OFFSET
+          m_cPrediction.upsampleBasePic( pcSlice, refLayerIdc, m_pcPic->getFullPelBaseRec(refLayerIdc), pBaseColRec, m_pcPic->getPicYuvRec(), scalEL, altRL );
+#else
+          m_cPrediction.upsampleBasePic( pcSlice, refLayerIdc, m_pcPic->getFullPelBaseRec(refLayerIdc), pBaseColRec, m_pcPic->getPicYuvRec(), scalEL );
+#endif
+#else
+          m_cPrediction.upsampleBasePic( pcSlice, refLayerIdc, m_pcPic->getFullPelBaseRec(refLayerIdc), pcSlice->getBaseColPic(refLayerIdc)->getPicYuvRec(), m_pcPic->getPicYuvRec(), scalEL );
+#endif
+#else
+#if Q0048_CGS_3D_ASYMLUT 
+            m_cPrediction.upsampleBasePic( refLayerIdc, m_pcPic->getFullPelBaseRec(refLayerIdc), pBaseColRec, m_pcPic->getPicYuvRec(), scalEL );
+#else
+            m_cPrediction.upsampleBasePic( refLayerIdc, m_pcPic->getFullPelBaseRec(refLayerIdc), pcSlice->getBaseColPic(refLayerIdc)->getPicYuvRec(), m_pcPic->getPicYuvRec(), scalEL );
+#endif
+#endif
+#endif
+#endif
+          }
+        }
+        else
+        {
+          m_pcPic->setFullPelBaseRec( refLayerIdc, pcSlice->getBaseColPic(refLayerIdc)->getPicYuvRec() );
+        }
+        pcSlice->setFullPelBaseRec ( refLayerIdc, m_pcPic->getFullPelBaseRec(refLayerIdc) );
+#endif //SVC_EXTENSION
+      }
+    }
+
+    if( m_layerId > 0 && pcSlice->getActiveNumILRRefIdx() )
+    {
+      for( Int i = 0; i < pcSlice->getActiveNumILRRefIdx(); i++ )
+      {
+        UInt refLayerIdc = pcSlice->getInterLayerPredLayerIdc(i);
+#if AVC_BASE
+#if VPS_AVC_BL_FLAG_REMOVAL
+        if( pcSlice->getVPS()->getRefLayerId( m_layerId, refLayerIdc ) == 0 && m_parameterSetManagerDecoder.getActiveVPS()->getNonHEVCBaseLayerFlag() )
+#else
+        if( pcSlice->getVPS()->getRefLayerId( m_layerId, refLayerIdc ) == 0 && m_parameterSetManagerDecoder.getActiveVPS()->getAvcBaseLayerFlag() )
+#endif
+        {
+          pcSlice->setBaseColPic ( refLayerIdc, *m_ppcTDecTop[0]->getListPic()->begin() );
+        }
+        else
+        {
+#if VPS_EXTN_DIRECT_REF_LAYERS
+          TDecTop *pcTDecTop = (TDecTop *)getRefLayerDec( refLayerIdc );
+#else
+          TDecTop *pcTDecTop = (TDecTop *)getLayerDec( m_layerId-1 );
+#endif
+          TComList<TComPic*> *cListPic = pcTDecTop->getListPic();
+          pcSlice->setBaseColPic ( *cListPic, refLayerIdc );
+        }
+#else
+#if VPS_EXTN_DIRECT_REF_LAYERS
+        TDecTop *pcTDecTop = (TDecTop *)getRefLayerDec( refLayerIdc );
+#else
+        TDecTop *pcTDecTop = (TDecTop *)getLayerDec( m_layerId-1 );
+#endif
+        TComList<TComPic*> *cListPic = pcTDecTop->getListPic();
+        pcSlice->setBaseColPic ( *cListPic, refLayerIdc );
+#endif
+
+        pcSlice->setFullPelBaseRec ( refLayerIdc, m_pcPic->getFullPelBaseRec(refLayerIdc) );
+      }
+
+      pcSlice->setILRPic( m_cIlpPic );
+
+#if REF_IDX_MFM
+      pcSlice->setRefPicList( m_cListPic, false, m_cIlpPic);
+    }
+#if M0040_ADAPTIVE_RESOLUTION_CHANGE
+    else if ( m_layerId > 0 )
+    {
+      pcSlice->setRefPicList( m_cListPic, false, NULL);
+    }
+#endif
+#if MFM_ENCCONSTRAINT
+    if( pcSlice->getMFMEnabledFlag() )
+    {
+      TComPic* refPic = pcSlice->getRefPic( pcSlice->getSliceType() == B_SLICE ? ( RefPicList )( 1 - pcSlice->getColFromL0Flag() ) : REF_PIC_LIST_0 , pcSlice->getColRefIdx() );
+
+      assert( refPic );
+
+      Int refLayerId = refPic->getLayerId();
+
+      if( refLayerId != pcSlice->getLayerId() )
+      {
+        TComPic* pColBasePic = pcSlice->getBaseColPic( *m_ppcTDecTop[refLayerId]->getListPic() );
+        assert( pColBasePic->checkSameRefInfo() == true );
+      }
+    }
+#endif
+#endif
+    
+    if( m_layerId > 0 && pcSlice->getVPS()->getCrossLayerIrapAlignFlag() )
+    {
+#if M0040_ADAPTIVE_RESOLUTION_CHANGE
+      if( !pcSlice->getVPS()->getSingleLayerForNonIrapFlag() || ( pcSlice->getVPS()->getSingleLayerForNonIrapFlag() && pcSlice->isIRAP() ) )
+#endif
+      for(Int dependentLayerIdx = 0; dependentLayerIdx < pcSlice->getVPS()->getNumDirectRefLayers(m_layerId); dependentLayerIdx++)
+      {
+        TComList<TComPic*> *cListPic = getRefLayerDec( dependentLayerIdx )->getListPic();
+        TComPic* refpicLayer = pcSlice->getRefPic(*cListPic, pcSlice->getPOC() );
+        if(refpicLayer && pcSlice->isIRAP())
+        {                 
+          assert(pcSlice->getNalUnitType() == refpicLayer->getSlice(0)->getNalUnitType());
+        }
+      }
+    }
+    
+    if( m_layerId > 0 && !pcSlice->isIntra() && pcSlice->getEnableTMVPFlag() )
+    {
+      TComPic* refPic = pcSlice->getRefPic(RefPicList(1 - pcSlice->getColFromL0Flag()), pcSlice->getColRefIdx());
+
+      assert( refPic );
+#if R0226_SLICE_TMVP
+      assert ( refPic->getPicSym()->getSlice(0)->getAvailableForTMVPRefFlag() == true );
+#endif
+
+      // It is a requirement of bitstream conformance when the collocated picture, used for temporal motion vector prediction, is an inter-layer reference picture, 
+      // VpsInterLayerMotionPredictionEnabled[ LayerIdxInVps[ currLayerId ] ][ LayerIdxInVps[ rLId ] ] shall be equal to 1, where rLId is set equal to nuh_layer_id of the inter-layer picture.
+      if( refPic->isILR(pcSlice->getLayerId()) )
+      {
+        assert( pcSlice->getVPS()->isMotionPredictionType( pcSlice->getVPS()->getLayerIdxInVps(m_layerId), refPic->getLayerIdx() ) );
+      }
+    }
+#endif //SVC_EXTENSION
+    
+    // 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();
+  }
+
+  m_pcPic->setCurrSliceIdx(m_uiSliceIdx);
+  if(pcSlice->getSPS()->getScalingListFlag())
+  {
+    pcSlice->setScalingList ( pcSlice->getSPS()->getScalingList()  );
+
+#if SCALINGLIST_INFERRING
+    if( pcSlice->getPPS()->getScalingListPresentFlag() || pcSlice->getPPS()->getInferScalingListFlag() )
+#else
+    if(pcSlice->getPPS()->getScalingListPresentFlag())
+#endif
+    {
+      pcSlice->setScalingList ( pcSlice->getPPS()->getScalingList()  );
+    }
+#if SCALINGLIST_INFERRING
+    if( m_layerId == 0 || ( m_layerId > 0 && !pcSlice->getPPS()->getInferScalingListFlag() && !pcSlice->getSPS()->getInferScalingListFlag() ) )
+#endif
+    if(!pcSlice->getPPS()->getScalingListPresentFlag() && !pcSlice->getSPS()->getScalingListPresentFlag())
+    {
+      pcSlice->setDefaultScalingList();
+    }
+    m_cTrQuant.setScalingListDec(pcSlice->getScalingList(), pcSlice->getSPS()->getChromaFormatIdc());
+    m_cTrQuant.setUseScalingList(true);
+  }
+  else
+  {
+    m_cTrQuant.setFlatScalingList(pcSlice->getSPS()->getChromaFormatIdc());
+    m_cTrQuant.setUseScalingList(false);
+  }
+
+  //  Decode a picture
+  m_cGopDecoder.decompressSlice(nalu.m_Bitstream, m_pcPic);
+
+#if P0297_VPS_POC_LSB_ALIGNED_FLAG
+  setFirstPicInLayerDecodedFlag(true);
+#endif
+#if R0071_IRAP_EOS_CROSS_LAYER_IMPACTS
+  m_lastPicHasEos = false;
+#endif
+
+  m_bFirstSliceInPicture = false;
+  m_uiSliceIdx++;
+
+  return false;
+}
+
+Void TDecTop::xDecodeVPS()
+{
+  TComVPS* vps = new TComVPS();
+
+  m_cEntropyDecoder.decodeVPS( vps );
+  m_parameterSetManagerDecoder.storePrefetchedVPS(vps);
+#if R0235_SMALLEST_LAYER_ID
+  checkValueOfTargetOutputLayerSetIdx(vps);
+#endif
+}
+
+#if SVC_EXTENSION
+Void TDecTop::xDecodeSPS()
+{
+  TComSPS* sps = new TComSPS();
+#if O0043_BEST_EFFORT_DECODING
+  sps->setForceDecodeBitDepth(m_forceDecodeBitDepth);
+#endif
+  sps->setLayerId(m_layerId);
+#if SPS_DPB_PARAMS
+  m_cEntropyDecoder.decodeSPS( sps ); // it should be removed after macro clean up
+#else
+  m_cEntropyDecoder.decodeSPS( sps, &m_parameterSetManagerDecoder );
+#endif
+  m_parameterSetManagerDecoder.storePrefetchedSPS(sps);
+#if !REPN_FORMAT_IN_VPS   // ILRP can only be initialized at activation  
+  if(m_numLayer>0)
+  {
+    xInitILRP(sps);
+  }
+#endif
+}
+
+Void TDecTop::xDecodePPS(
+#if Q0048_CGS_3D_ASYMLUT
+  TCom3DAsymLUT * pc3DAsymLUT
+#endif
+  )
+{
+  TComPPS* pps = new TComPPS();
+
+#if SCALINGLIST_INFERRING
+  pps->setLayerId( m_layerId );
+#endif
+
+  m_cEntropyDecoder.decodePPS( pps 
+#if Q0048_CGS_3D_ASYMLUT
+    , pc3DAsymLUT , m_layerId 
+#endif
+    );
+  m_parameterSetManagerDecoder.storePrefetchedPPS( pps );
+}
+#else
+Void TDecTop::xDecodeSPS()
+{
+  TComSPS* sps = new TComSPS();
+#if O0043_BEST_EFFORT_DECODING
+  sps->setForceDecodeBitDepth(m_forceDecodeBitDepth);
+#endif
+  m_cEntropyDecoder.decodeSPS( sps );
+  m_parameterSetManagerDecoder.storePrefetchedSPS(sps);
+}
+
+Void TDecTop::xDecodePPS()
+{
+  TComPPS* pps = new TComPPS();
+  m_cEntropyDecoder.decodePPS( pps );
+  m_parameterSetManagerDecoder.storePrefetchedPPS( pps );
+}
+#endif //SVC_EXTENSION
+
+Void TDecTop::xDecodeSEI( TComInputBitstream* bs, const NalUnitType nalUnitType )
+{
+#if SVC_EXTENSION
+  if(nalUnitType == NAL_UNIT_SUFFIX_SEI)
+  {
+    if (m_prevSliceSkipped) // No need to decode SEI messages of a skipped access unit
+    {
+      return;
+    }
+#if LAYERS_NOT_PRESENT_SEI
+    m_seiReader.parseSEImessage( bs, m_pcPic->getSEIs(), nalUnitType, m_parameterSetManagerDecoder.getActiveVPS(), m_parameterSetManagerDecoder.getActiveSPS(), m_pDecodedSEIOutputStream  );
+#else
+    m_seiReader.parseSEImessage( bs, m_pcPic->getSEIs(), nalUnitType, m_parameterSetManagerDecoder.getActiveSPS(), m_pDecodedSEIOutputStream  );
+#endif
+  }
+  else
+  {
+#if LAYERS_NOT_PRESENT_SEI
+    m_seiReader.parseSEImessage( bs, m_SEIs, nalUnitType, m_parameterSetManagerDecoder.getActiveVPS(), m_parameterSetManagerDecoder.getActiveSPS(), m_pDecodedSEIOutputStream  );
+#else
+    m_seiReader.parseSEImessage( bs, m_SEIs, nalUnitType, m_parameterSetManagerDecoder.getActiveSPS(), m_pDecodedSEIOutputStream  );
+#endif
+    SEIMessages activeParamSets = getSeisByType(m_SEIs, SEI::ACTIVE_PARAMETER_SETS);
+    if (activeParamSets.size()>0)
+    {
+      SEIActiveParameterSets *seiAps = (SEIActiveParameterSets*)(*activeParamSets.begin());
+#if !R0247_SEI_ACTIVE
+      m_parameterSetManagerDecoder.applyPrefetchedPS();
+      assert(seiAps->activeSeqParameterSetId.size()>0);
+      if( !m_parameterSetManagerDecoder.activateSPSWithSEI( seiAps->activeSeqParameterSetId[0] ) )
+      {
+        printf ("Warning SPS activation with Active parameter set SEI failed");
+      }
+#else
+      getLayerDec(0)->m_parameterSetManagerDecoder.applyPrefetchedPS();
+      assert(seiAps->activeSeqParameterSetId.size()>0);
+      if( !getLayerDec(0)->m_parameterSetManagerDecoder.activateSPSWithSEI( seiAps->activeSeqParameterSetId[0] ) )
+      {
+        printf ("Warning SPS activation with Active parameter set SEI failed");
+      }
+      for (Int c=1 ; c <= seiAps->numSpsIdsMinus1; c++)
+      {
+        Int layerIdx = seiAps->layerSpsIdx[c];
+        getLayerDec(layerIdx)->m_parameterSetManagerDecoder.applyPrefetchedPS();
+        if( !getLayerDec(layerIdx)->m_parameterSetManagerDecoder.activateSPSWithSEI( seiAps->activeSeqParameterSetId[layerIdx] ) )
+        {
+          printf ("Warning SPS activation with Active parameter set SEI failed");
+        }
+      }
+#endif
+    }
+  }
+#else
+  if(nalUnitType == NAL_UNIT_SUFFIX_SEI)
+  {
+#if LAYERS_NOT_PRESENT_SEI
+    m_seiReader.parseSEImessage( bs, m_pcPic->getSEIs(), nalUnitType, m_parameterSetManagerDecoder.getActiveVPS(), m_parameterSetManagerDecoder.getActiveSPS(), m_pDecodedSEIOutputStream  );
+#else
+    m_seiReader.parseSEImessage( bs, m_pcPic->getSEIs(), nalUnitType, m_parameterSetManagerDecoder.getActiveSPS(), m_pDecodedSEIOutputStream );
+
+#endif
+  }
+  else
+  {
+#if LAYERS_NOT_PRESENT_SEI
+    m_seiReader.parseSEImessage( bs, m_SEIs, nalUnitType, m_parameterSetManagerDecoder.getActiveVPS(), m_parameterSetManagerDecoder.getActiveSPS(), m_pDecodedSEIOutputStream  );
+#else
+    m_seiReader.parseSEImessage( bs, m_SEIs, nalUnitType, m_parameterSetManagerDecoder.getActiveSPS(), m_pDecodedSEIOutputStream );
+#endif
+    SEIMessages activeParamSets = getSeisByType(m_SEIs, SEI::ACTIVE_PARAMETER_SETS);
+    if (activeParamSets.size()>0)
+    {
+      SEIActiveParameterSets *seiAps = (SEIActiveParameterSets*)(*activeParamSets.begin());
+      m_parameterSetManagerDecoder.applyPrefetchedPS();
+      assert(seiAps->activeSeqParameterSetId.size()>0);
+      if (! m_parameterSetManagerDecoder.activateSPSWithSEI(seiAps->activeSeqParameterSetId[0] ))
+      {
+        printf ("Warning SPS activation with Active parameter set SEI failed");
+      }
+    }
+  }
+#endif
+}
+
+#if SVC_EXTENSION
+Bool TDecTop::decode(InputNALUnit& nalu, Int& iSkipFrame, Int& iPOCLastDisplay, UInt& curLayerId, Bool& bNewPOC)
+#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);
+
+#if O0137_MAX_LAYERID
+  // ignore any NAL units with nuh_layer_id == 63
+  if (nalu.m_layerId == 63 )
+  {  
+    return false;
+  }
+#endif
+  switch (nalu.m_nalUnitType)
+  {
+    case NAL_UNIT_VPS:
+#if SVC_EXTENSION
+      assert( nalu.m_layerId == 0 ); // Non-conforming bitstream. The value of nuh_layer_id of VPS NAL unit shall be equal to 0.
+#endif
+      xDecodeVPS();
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+      TComCodingStatistics::IncrementStatisticEP(STATS__BYTE_ALIGNMENT_BITS,nalu.m_Bitstream->readByteAlignment(),0);
+#endif
+#if Q0177_EOS_CHECKS
+      m_isLastNALWasEos = false;
+#endif
+#if AVC_BASE
+#if VPS_AVC_BL_FLAG_REMOVAL
+      if( m_parameterSetManagerDecoder.getPrefetchedVPS(0)->getNonHEVCBaseLayerFlag() )
+#else
+      if( m_parameterSetManagerDecoder.getPrefetchedVPS(0)->getAvcBaseLayerFlag() )
+#endif
+      {
+        if( !m_ppcTDecTop[0]->getBLReconFile()->good() )
+        {
+          printf( "Base layer YUV input reading error\n" );
+          exit(EXIT_FAILURE);
+        }        
+      }
+      else
+      {
+        TComList<TComPic*> *cListPic = m_ppcTDecTop[0]->getListPic();
+        cListPic->clear();
+      }
+#endif
+#if R0235_SMALLEST_LAYER_ID
+      xDeriveSmallestLayerId(m_parameterSetManagerDecoder.getPrefetchedVPS(0));
+#endif
+      return false;
+
+    case NAL_UNIT_SPS:
+      xDecodeSPS();
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+      TComCodingStatistics::IncrementStatisticEP(STATS__BYTE_ALIGNMENT_BITS,nalu.m_Bitstream->readByteAlignment(),0);
+#endif
+      return false;
+
+    case NAL_UNIT_PPS:
+      xDecodePPS(
+#if Q0048_CGS_3D_ASYMLUT
+        &m_c3DAsymLUTPPS
+#endif
+        );
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+      TComCodingStatistics::IncrementStatisticEP(STATS__BYTE_ALIGNMENT_BITS,nalu.m_Bitstream->readByteAlignment(),0);
+#endif
+      return false;
+
+    case NAL_UNIT_PREFIX_SEI:
+    case NAL_UNIT_SUFFIX_SEI:
+#if Q0177_EOS_CHECKS
+      if ( nalu.m_nalUnitType == NAL_UNIT_SUFFIX_SEI )
+      {
+        assert( m_isLastNALWasEos == false );
+      }
+#endif
+      xDecodeSEI( nalu.m_Bitstream, nalu.m_nalUnitType );
+      return false;
+
+    case NAL_UNIT_CODED_SLICE_TRAIL_R:
+    case NAL_UNIT_CODED_SLICE_TRAIL_N:
+    case NAL_UNIT_CODED_SLICE_TSA_R:
+    case NAL_UNIT_CODED_SLICE_TSA_N:
+    case NAL_UNIT_CODED_SLICE_STSA_R:
+    case NAL_UNIT_CODED_SLICE_STSA_N:
+    case NAL_UNIT_CODED_SLICE_BLA_W_LP:
+    case NAL_UNIT_CODED_SLICE_BLA_W_RADL:
+    case NAL_UNIT_CODED_SLICE_BLA_N_LP:
+    case NAL_UNIT_CODED_SLICE_IDR_W_RADL:
+    case NAL_UNIT_CODED_SLICE_IDR_N_LP:
+    case NAL_UNIT_CODED_SLICE_CRA:
+    case NAL_UNIT_CODED_SLICE_RADL_N:
+    case NAL_UNIT_CODED_SLICE_RADL_R:
+    case NAL_UNIT_CODED_SLICE_RASL_N:
+    case NAL_UNIT_CODED_SLICE_RASL_R:
+#if Q0177_EOS_CHECKS
+      if (nalu.m_nalUnitType == NAL_UNIT_CODED_SLICE_TRAIL_R || nalu.m_nalUnitType == NAL_UNIT_CODED_SLICE_TRAIL_N ||
+          nalu.m_nalUnitType == NAL_UNIT_CODED_SLICE_TSA_R || nalu.m_nalUnitType == NAL_UNIT_CODED_SLICE_TSA_N ||
+          nalu.m_nalUnitType == NAL_UNIT_CODED_SLICE_STSA_R || nalu.m_nalUnitType == NAL_UNIT_CODED_SLICE_STSA_N ||
+          nalu.m_nalUnitType == NAL_UNIT_CODED_SLICE_RADL_R || nalu.m_nalUnitType == NAL_UNIT_CODED_SLICE_RADL_N ||
+          nalu.m_nalUnitType == NAL_UNIT_CODED_SLICE_RASL_R || nalu.m_nalUnitType == NAL_UNIT_CODED_SLICE_RASL_N )
+      {
+        assert( m_isLastNALWasEos == false );
+      }
+      else
+      {
+        m_isLastNALWasEos = false;
+      }
+#endif
+#if SVC_EXTENSION
+      return xDecodeSlice(nalu, iSkipFrame, iPOCLastDisplay, curLayerId, bNewPOC);
+#else
+      return xDecodeSlice(nalu, iSkipFrame, iPOCLastDisplay);
+#endif
+      break;
+
+    case NAL_UNIT_EOS:
+#if Q0177_EOS_CHECKS
+      assert( m_isLastNALWasEos == false );
+#if !R0071_IRAP_EOS_CROSS_LAYER_IMPACTS
+      //Check layer id of the nalu. if it is not 0, give a warning message and just return without doing anything.
+      if (nalu.m_layerId > 0)
+      {
+        printf( "\nThis bitstream has EOS with non-zero layer id.\n" );
+        return false;
+      }
+#endif
+      m_isLastNALWasEos = true;
+#if R0071_IRAP_EOS_CROSS_LAYER_IMPACTS
+      m_lastPicHasEos = true;
+#endif
+#endif
+      m_associatedIRAPType = NAL_UNIT_INVALID;
+      m_pocCRA = 0;
+      m_pocRandomAccess = MAX_INT;
+      m_prevPOC = MAX_INT;
+      m_prevSliceSkipped = false;
+      m_skippedPOC = 0;
+      return false;
+
+    case NAL_UNIT_ACCESS_UNIT_DELIMITER:
+      // TODO: process AU delimiter
+      return false;
+
+    case NAL_UNIT_EOB:
+#if P0130_EOB
+      //Check layer id of the nalu. if it is not 0, give a warning message.
+      if (nalu.m_layerId > 0)
+      {
+        printf( "\n\nThis bitstream is ended with EOB NALU that has layer id greater than 0\n" );
+      }
+#endif
+      return false;
+
+    case NAL_UNIT_FILLER_DATA:
+#if Q0177_EOS_CHECKS
+      assert( m_isLastNALWasEos == false );
+#endif
+      return false;
+
+    case NAL_UNIT_RESERVED_VCL_N10:
+    case NAL_UNIT_RESERVED_VCL_R11:
+    case NAL_UNIT_RESERVED_VCL_N12:
+    case NAL_UNIT_RESERVED_VCL_R13:
+    case NAL_UNIT_RESERVED_VCL_N14:
+    case NAL_UNIT_RESERVED_VCL_R15:
+
+    case NAL_UNIT_RESERVED_IRAP_VCL22:
+    case NAL_UNIT_RESERVED_IRAP_VCL23:
+
+    case NAL_UNIT_RESERVED_VCL24:
+    case NAL_UNIT_RESERVED_VCL25:
+    case NAL_UNIT_RESERVED_VCL26:
+    case NAL_UNIT_RESERVED_VCL27:
+    case NAL_UNIT_RESERVED_VCL28:
+    case NAL_UNIT_RESERVED_VCL29:
+    case NAL_UNIT_RESERVED_VCL30:
+    case NAL_UNIT_RESERVED_VCL31:
+
+    case NAL_UNIT_RESERVED_NVCL41:
+    case NAL_UNIT_RESERVED_NVCL42:
+    case NAL_UNIT_RESERVED_NVCL43:
+    case NAL_UNIT_RESERVED_NVCL44:
+    case NAL_UNIT_RESERVED_NVCL45:
+    case NAL_UNIT_RESERVED_NVCL46:
+    case NAL_UNIT_RESERVED_NVCL47:
+    case NAL_UNIT_UNSPECIFIED_48:
+    case NAL_UNIT_UNSPECIFIED_49:
+    case NAL_UNIT_UNSPECIFIED_50:
+    case NAL_UNIT_UNSPECIFIED_51:
+    case NAL_UNIT_UNSPECIFIED_52:
+    case NAL_UNIT_UNSPECIFIED_53:
+    case NAL_UNIT_UNSPECIFIED_54:
+    case NAL_UNIT_UNSPECIFIED_55:
+    case NAL_UNIT_UNSPECIFIED_56:
+    case NAL_UNIT_UNSPECIFIED_57:
+    case NAL_UNIT_UNSPECIFIED_58:
+    case NAL_UNIT_UNSPECIFIED_59:
+    case NAL_UNIT_UNSPECIFIED_60:
+    case NAL_UNIT_UNSPECIFIED_61:
+    case NAL_UNIT_UNSPECIFIED_62:
+    case NAL_UNIT_UNSPECIFIED_63:
+
+    default:
+      assert (0);
+      break;
+  }
+
+  return false;
+}
+
+/** Function for checking if picture should be skipped because of association with a previous BLA picture
+ * \param iPOCLastDisplay POC of last picture displayed
+ * \returns true if the picture should be skipped
+ * This function skips all TFD pictures that follow a BLA picture
+ * in decoding order and precede it in output order.
+ */
+Bool TDecTop::isSkipPictureForBLA(Int& iPOCLastDisplay)
+{
+  if ((m_associatedIRAPType == NAL_UNIT_CODED_SLICE_BLA_N_LP || m_associatedIRAPType == NAL_UNIT_CODED_SLICE_BLA_W_LP || m_associatedIRAPType == NAL_UNIT_CODED_SLICE_BLA_W_RADL) &&
+       m_apcSlicePilot->getPOC() < m_pocCRA && (m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_RASL_R || m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_RASL_N))
+  {
+    iPOCLastDisplay++;
+    return true;
+  }
+  return false;
+}
+
+/** Function for checking if picture should be skipped because of random access
+ * \param iSkipFrame skip frame counter
+ * \param iPOCLastDisplay POC of last picture displayed
+ * \returns true if the picture shold be skipped in the random access.
+ * This function checks the skipping of pictures in the case of -s option random access.
+ * All pictures prior to the random access point indicated by the counter iSkipFrame are skipped.
+ * It also checks the type of Nal unit type at the random access point.
+ * If the random access point is CRA/CRANT/BLA/BLANT, TFD pictures with POC less than the POC of the random access point are skipped.
+ * If the random access point is IDR all pictures after the random access point are decoded.
+ * If the random access point is none of the above, a warning is issues, and decoding of pictures with POC
+ * equal to or greater than the random access point POC is attempted. For non IDR/CRA/BLA random
+ * access point there is no guarantee that the decoder will not crash.
+ */
+Bool TDecTop::isRandomAccessSkipPicture(Int& iSkipFrame,  Int& iPOCLastDisplay)
+{
+  if (iSkipFrame)
+  {
+    iSkipFrame--;   // decrement the counter
+    return true;
+  }
+  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 SVC_EXTENSION
+#if !REPN_FORMAT_IN_VPS
+Void TDecTop::xInitILRP(TComSPS *pcSPS)
+#else
+Void TDecTop::xInitILRP(TComSlice *slice)
+#endif
+{
+#if REPN_FORMAT_IN_VPS
+  TComSPS* pcSPS = slice->getSPS();
+  Int bitDepthY   = slice->getBitDepthY();
+  Int bitDepthC   = slice->getBitDepthC();
+  Int picWidth    = slice->getPicWidthInLumaSamples();
+  Int picHeight   = slice->getPicHeightInLumaSamples();
+#endif
+  if(m_layerId>0)
+  {
+#if REPN_FORMAT_IN_VPS
+    g_bitDepth[CHANNEL_TYPE_LUMA]     = bitDepthY;
+    g_bitDepth[CHANNEL_TYPE_CHROMA]   = bitDepthC;
+#else
+    g_bitDepth[CHANNEL_TYPE_LUMA]     = pcSPS->getBitDepthY();
+    g_bitDepth[CHANNEL_TYPE_CHROMA]   = pcSPS->getBitDepthC();
+#endif
+    g_uiMaxCUWidth  = pcSPS->getMaxCUWidth();
+    g_uiMaxCUHeight = pcSPS->getMaxCUHeight();
+    g_uiMaxCUDepth  = pcSPS->getMaxCUDepth();
+    g_uiAddCUDepth  = max (0, pcSPS->getLog2MinCodingBlockSize() - (Int)pcSPS->getQuadtreeTULog2MinSize() );
+
+    Int  numReorderPics[MAX_TLAYER];
+#if R0156_CONF_WINDOW_IN_REP_FORMAT
+    Window &conformanceWindow = slice->getConformanceWindow();
+#else
+    Window &conformanceWindow = pcSPS->getConformanceWindow();
+#endif
+    Window defaultDisplayWindow = pcSPS->getVuiParametersPresentFlag() ? pcSPS->getVuiParameters()->getDefaultDisplayWindow() : Window();
+
+    for( Int temporalLayer=0; temporalLayer < MAX_TLAYER; temporalLayer++) 
+    {
+#if USE_DPB_SIZE_TABLE
+      if( getCommonDecoderParams()->getTargetOutputLayerSetIdx() == 0 )
+      {
+        assert( this->getLayerId() == 0 );
+        numReorderPics[temporalLayer] = pcSPS->getNumReorderPics(temporalLayer);
+      }
+      else
+      {
+        TComVPS *vps = slice->getVPS();
+        // SHM decoders will use DPB size table in the VPS to determine the number of reorder pictures.
+        numReorderPics[temporalLayer] = vps->getMaxVpsNumReorderPics( getCommonDecoderParams()->getTargetOutputLayerSetIdx() , temporalLayer);
+      }
+#else
+      numReorderPics[temporalLayer] = pcSPS->getNumReorderPics(temporalLayer);
+#endif
+    }
+
+    if (m_cIlpPic[0] == NULL)
+    {
+      for (Int j=0; j < m_numDirectRefLayers; j++)
+      {
+
+        m_cIlpPic[j] = new  TComPic;
+
+#if AUXILIARY_PICTURES
+#if REPN_FORMAT_IN_VPS
+        m_cIlpPic[j]->create(picWidth, picHeight, slice->getChromaFormatIdc(), g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth, conformanceWindow, defaultDisplayWindow, numReorderPics, pcSPS, true);
+#else
+        m_cIlpPic[j]->create(pcSPS->getPicWidthInLumaSamples(), pcSPS->getPicHeightInLumaSamples(), pcSPS->getChromaFormatIdc(), g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth, conformanceWindow, defaultDisplayWindow, numReorderPics, pcSPS, true);
+#endif
+#else
+#if REPN_FORMAT_IN_VPS
+        m_cIlpPic[j]->create(picWidth, picHeight, g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth, conformanceWindow, defaultDisplayWindow, numReorderPics, pcSPS, true);
+#else
+        m_cIlpPic[j]->create(pcSPS->getPicWidthInLumaSamples(), pcSPS->getPicHeightInLumaSamples(), g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth, conformanceWindow, defaultDisplayWindow, numReorderPics, pcSPS, true);
+#endif
+#endif
+        for (Int i=0; i<m_cIlpPic[j]->getPicSym()->getNumberOfCtusInFrame(); i++)
+        {
+          m_cIlpPic[j]->getPicSym()->getCtu(i)->initCtu(m_cIlpPic[j], i);
+        }
+      }
+    }
+  }
+}
+
+#if VPS_EXTN_DIRECT_REF_LAYERS
+TDecTop* TDecTop::getRefLayerDec( UInt refLayerIdx )
+{
+  TComVPS* vps = m_parameterSetManagerDecoder.getActiveVPS();
+  if( vps->getNumDirectRefLayers( m_layerId ) <= 0 )
+  {
+    return (TDecTop *)getLayerDec( 0 );
+  }
+  
+  return (TDecTop *)getLayerDec( vps->getRefLayerId( m_layerId, refLayerIdx ) );
+}
+#endif
+
+#if VPS_EXTN_DIRECT_REF_LAYERS
+Void TDecTop::setRefLayerParams( TComVPS* vps )
+{
+  for(UInt layerIdx = 0; layerIdx < m_numLayer; layerIdx++)
+  {
+    TDecTop *decTop = (TDecTop *)getLayerDec(vps->getLayerIdInNuh(layerIdx));
+    decTop->setNumSamplePredRefLayers(0);
+    decTop->setNumMotionPredRefLayers(0);
+    decTop->setNumDirectRefLayers(0);
+
+    for(Int j = 0; j < layerIdx; j++)
+    {
+      if (vps->getDirectDependencyFlag(layerIdx, j))
+      {
+        decTop->setRefLayerId(decTop->getNumDirectRefLayers(), vps->getLayerIdInNuh(layerIdx));
+        decTop->setNumDirectRefLayers(decTop->getNumDirectRefLayers() + 1);
+
+        Int samplePredEnabledFlag = (vps->getDirectDependencyType(layerIdx, j) + 1) & 1;
+        decTop->setNumSamplePredRefLayers(decTop->getNumSamplePredRefLayers() + samplePredEnabledFlag);
+
+        Int motionPredEnabledFlag = ((vps->getDirectDependencyType(layerIdx, j) + 1) & 2) >> 1;
+        decTop->setNumMotionPredRefLayers(decTop->getNumMotionPredRefLayers() + motionPredEnabledFlag);
+      }
+    }
+  }
+}
+#endif
+
+#if EARLY_REF_PIC_MARKING
+Void TDecTop::earlyPicMarking(Int maxTemporalLayer, std::vector<Int>& targetDecLayerIdSet)
+{
+  UInt currTid = m_pcPic->getTLayer();
+  UInt highestTid = (maxTemporalLayer >= 0) ? maxTemporalLayer : (m_pcPic->getSlice(0)->getSPS()->getMaxTLayers() - 1);
+  UInt latestDecLayerId = m_layerId;
+  UInt numTargetDecLayers = 0;
+  Int targetDecLayerIdList[MAX_LAYERS];
+  UInt latestDecIdx = 0;
+  TComSlice* pcSlice = m_pcPic->getSlice(0);
+
+  if ( currTid != highestTid )  // Marking  process is only applicaple for highest decoded TLayer
+  {
+    return;
+  }
+
+  // currPic must be marked as "used for reference" and must be a sub-layer non-reference picture
+  if ( !((pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_TRAIL_N  ||
+          pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_TSA_N    ||
+          pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_STSA_N   ||
+          pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_RADL_N   ||
+          pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_RASL_N   ||
+          pcSlice->getNalUnitType() == NAL_UNIT_RESERVED_VCL_N10     ||
+          pcSlice->getNalUnitType() == NAL_UNIT_RESERVED_VCL_N12     ||
+          pcSlice->getNalUnitType() == NAL_UNIT_RESERVED_VCL_N14) && pcSlice->isReferenced()))
+  {
+    return;
+  }
+
+  if ( targetDecLayerIdSet.size() == 0 ) // Cannot mark if we don't know the number of scalable layers
+  {
+    return;
+  }
+
+  for (std::vector<Int>::iterator it = targetDecLayerIdSet.begin(); it != targetDecLayerIdSet.end(); it++)
+  {
+    if ( latestDecLayerId == (*it) )
+    {
+      latestDecIdx = numTargetDecLayers;
+    }
+    targetDecLayerIdList[numTargetDecLayers++] = (*it);
+  }
+
+  Int remainingInterLayerReferencesFlag = 0;
+  for ( Int j = latestDecIdx + 1; j < numTargetDecLayers; j++ )
+  {
+    Int jLidx = pcSlice->getVPS()->getLayerIdxInVps(targetDecLayerIdList[j]);
+    if ( currTid <= pcSlice->getVPS()->getMaxTidIlRefPicsPlus1(pcSlice->getVPS()->getLayerIdxInVps(latestDecLayerId),jLidx) - 1 )
+    {
+      for ( Int k = 0; k < m_ppcTDecTop[targetDecLayerIdList[j]]->getNumDirectRefLayers(); k++ )
+      {
+        if ( latestDecIdx == m_ppcTDecTop[targetDecLayerIdList[j]]->getRefLayerId(k) )
+        {
+          remainingInterLayerReferencesFlag = 1;
+        }
+      }
+    }
+  }
+
+  if ( remainingInterLayerReferencesFlag == 0 )
+  {
+    pcSlice->setReferenced(false);
+  }
+}
+#endif
+
+#if OUTPUT_LAYER_SET_INDEX
+Void TDecTop::checkValueOfTargetOutputLayerSetIdx(TComVPS *vps)
+{
+  CommonDecoderParams* params = this->getCommonDecoderParams();
+
+#if !FIX_CONF_MODE
+  assert( params->getTargetLayerId() < vps->getMaxLayers() );
+#endif
+
+  if( params->getValueCheckedFlag() )
+  {
+    return; // Already checked
+  }
+
+  if( params->getTargetOutputLayerSetIdx() == -1 )  // Output layer set index not specified
+  {
+    if( params->getTargetLayerId() > vps->getMaxLayerId() )
+    {
+      printf( "Warning: specified target layerId %d is greater than max layerId %d. Target layerId is set equal to max layerId %d.\n", params->getTargetLayerId(), vps->getMaxLayerId(), vps->getMaxLayerId() );
+      params->setTargetLayerId( vps->getMaxLayerId() );
+    }
+
+    Bool layerSetMatchFound = false;
+    // Output layer set index not assigned.
+    // Based on the value of targetLayerId, check if any of the output layer matches
+    // Currently, the target layer ID in the encoder assumes that all the layers are decoded    
+    // Check if any of the output layer sets match this description
+    for(Int i = 0; i < vps->getNumOutputLayerSets(); i++)
+    {
+      Bool layerSetMatchFlag = false;
+      Int layerSetIdx = vps->getOutputLayerSetIdx( i );
+
+      for(Int j = 0; j < vps->getNumLayersInIdList( layerSetIdx ); j++)
+      {
+        if( vps->getLayerSetLayerIdList( layerSetIdx, j ) == params->getTargetLayerId() )
+        {
+          layerSetMatchFlag = true;
+          break;
+        }
+      }
+      
+      if( layerSetMatchFlag ) // Potential output layer set candidate found
+      {
+        // If target dec layer ID list is also included - check if they match
+        if( params->getTargetDecLayerIdSet() )
+        {
+          if( params->getTargetDecLayerIdSet()->size() )  
+          {
+            for(Int j = 0; j < vps->getNumLayersInIdList( layerSetIdx ); j++)
+            {
+              if( *(params->getTargetDecLayerIdSet()->begin() + j) != vps->getLayerIdInNuh(vps->getLayerSetLayerIdList( layerSetIdx, j )))
+              {
+                layerSetMatchFlag = false;
+              }
+            }
+          }
+        }
+        if( layerSetMatchFlag ) // The target dec layer ID list also matches, if present
+        {
+          // Match found
+          layerSetMatchFound = true;
+          params->setTargetOutputLayerSetIdx( i );
+          params->setValueCheckedFlag( true );
+          break;
+        }
+      }
+    }
+    assert( layerSetMatchFound ); // No output layer set matched the value of either targetLayerId or targetdeclayerIdlist
+  }   
+  else // Output layer set index is assigned - check if the values match
+  {
+    // Check if the target decoded layer is the highest layer in the list
+#if R0235_SMALLEST_LAYER_ID
+    assert( params->getTargetOutputLayerSetIdx() < vps->getNumOutputLayerSets() );
+#endif
+#if !CONFORMANCE_BITSTREAM_MODE
+    assert( params->getTargetOutputLayerSetIdx() < vps->getNumLayerSets() );
+#endif
+    Int layerSetIdx = vps->getOutputLayerSetIdx( params->getTargetOutputLayerSetIdx() );  // Index to the layer set
+#if !CONFORMANCE_BITSTREAM_MODE
+    assert( params->getTargetLayerId() == vps->getNumLayersInIdList( layerSetIdx ) - 1);
+#endif
+    
+#if !R0235_SMALLEST_LAYER_ID
+    Bool layerSetMatchFlag = true;
+    for(Int j = 0; j < vps->getNumLayersInIdList( layerSetIdx ); j++)
+    {
+      if( vps->getLayerSetLayerIdList( layerSetIdx, j ) != j )
+      {
+        layerSetMatchFlag = false;
+        break;
+      }
+    }
+
+    assert(layerSetMatchFlag);    // Signaled output layer set index does not match targetOutputLayerId.
+#endif
+    
+    // Check if the targetdeclayerIdlist matches the output layer set
+    if( params->getTargetDecLayerIdSet() )
+    {
+      if( params->getTargetDecLayerIdSet()->size() )  
+      {
+        for(Int i = 0; i < vps->getNumLayersInIdList( layerSetIdx ); i++)
+        {
+          assert( *(params->getTargetDecLayerIdSet()->begin() + i) == vps->getLayerIdInNuh(vps->getLayerSetLayerIdList( layerSetIdx, i )));
+        }
+      }
+    }
+    params->setValueCheckedFlag( true );
+
+  }
+#if FIX_CONF_MODE
+  // Set correct value of targetLayerId
+  Int targetOlsIdx = params->getTargetOutputLayerSetIdx();
+  Int targetLsIdx = vps->getOutputLayerSetIdx( targetOlsIdx );
+  params->setTargetLayerId( vps->getLayerSetLayerIdList( targetLsIdx, vps->getNumLayersInIdList(targetLsIdx)-1 ) );
+#endif
+#if FIX_NON_OUTPUT_LAYER
+  // Check if the current layer is an output layer
+  for(Int i = 0; i < vps->getNumLayersInIdList( targetLsIdx ); i++)
+  {
+    if( vps->getOutputLayerFlag( targetOlsIdx, i ) )
+    {
+      this->getLayerDec( vps->getLayerSetLayerIdList( targetLsIdx, i ) )->m_isOutputLayerFlag = true;
+    }
+  }
+#endif
+}
+#endif
+#if RESOLUTION_BASED_DPB
+Void TDecTop::assignSubDpbs(TComVPS *vps)
+{
+  if( m_subDpbIdx == -1 ) // Sub-DPB index is not already assigned
+  {
+    Int lsIdx = vps->getOutputLayerSetIdx( getCommonDecoderParams()->getTargetOutputLayerSetIdx() );
+
+    Int layerIdx = vps->findLayerIdxInLayerSet( lsIdx, getLayerId() );
+    assert( layerIdx != -1 ); // Current layer should be found in the layer set.
+
+    // Copy from the active VPS based on the layer ID.
+    m_subDpbIdx = vps->getSubDpbAssigned( lsIdx, layerIdx );
+  }
+}
+#endif
+#if POC_RESET_IDC_DECODER
+Void TDecTop::markAllPicsAsNoCurrAu(TComVPS *vps)
+{
+  for(Int i = 0; i < MAX_LAYERS; i++)
+  {
+    TComList<TComPic*>* listPic = this->getLayerDec(vps->getLayerIdInNuh(i))->getListPic();
+    TComList<TComPic*>::iterator  iterPic = listPic->begin();
+    while ( iterPic != listPic->end() )
+    {
+      TComPic *pcPic = *(iterPic);
+      pcPic->setCurrAuFlag( false );
+      iterPic++;
+    }
+  }
+}
+#endif
+#if Q0048_CGS_3D_ASYMLUT
+Void TDecTop::initAsymLut(TComSlice *pcSlice)
+{
+  if(m_layerId>0)
+  {
+    if(!m_pColorMappedPic)
+    {
+      Int picWidth    = pcSlice->getPicWidthInLumaSamples();
+      Int picHeight   = pcSlice->getPicHeightInLumaSamples();
+      m_pColorMappedPic = new TComPicYuv;
+      m_pColorMappedPic->create( picWidth, picHeight, pcSlice->getChromaFormatIdc()/*CHROMA_420*/, g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth, NULL );
+    }
+  }
+}
+#endif
+#if POC_RESET_RESTRICTIONS
+Void TDecTop::resetPocRestrictionCheckParameters()
+{
+  TDecTop::m_checkPocRestrictionsForCurrAu       = false;
+  TDecTop::m_pocResetIdcOrCurrAu                 = -1;
+  TDecTop::m_baseLayerIdrFlag                    = false;
+  TDecTop::m_baseLayerPicPresentFlag             = false;
+  TDecTop::m_baseLayerIrapFlag                   = false;
+  TDecTop::m_nonBaseIdrPresentFlag               = false;
+  TDecTop::m_nonBaseIdrType                      = -1;
+  TDecTop::m_picNonIdrWithRadlPresentFlag        = false;
+  TDecTop::m_picNonIdrNoLpPresentFlag            = false;
+}
+#endif
+
+#if R0071_IRAP_EOS_CROSS_LAYER_IMPACTS
+Void TDecTop::xCheckLayerReset()
+{
+#if R0235_SMALLEST_LAYER_ID
+  if (m_apcSlicePilot->isIRAP() && m_layerId > m_smallestLayerId)
+#else
+  if (m_apcSlicePilot->isIRAP() && m_layerId > 0)
+#endif
+  {
+    Bool layerResetFlag;
+    UInt dolLayerId;
+    if (m_lastPicHasEos)
+    {
+      layerResetFlag = true;
+      dolLayerId = m_layerId;
+    }
+    else if ((m_apcSlicePilot->isCRA() && m_apcSlicePilot->getHandleCraAsBlaFlag()) ||
+      (m_apcSlicePilot->isIDR() && m_apcSlicePilot->getCrossLayerBLAFlag()) || m_apcSlicePilot->isBLA())
+    {
+      layerResetFlag = true;
+      dolLayerId = m_layerId;
+    }
+    else
+    {
+      layerResetFlag = false;
+    }
+
+    if (layerResetFlag)
+    {
+      for (Int i = 0; i < m_apcSlicePilot->getVPS()->getNumPredictedLayers(dolLayerId); i++)
+      {
+        UInt iLayerId = m_apcSlicePilot->getVPS()->getPredictedLayerId(dolLayerId, i);
+        m_ppcTDecTop[iLayerId]->m_layerInitializedFlag = false;
+        m_ppcTDecTop[iLayerId]->m_firstPicInLayerDecodedFlag = false;
+      }
+
+      for (TComList<TComPic*>::iterator i = m_cListPic.begin(); i != m_cListPic.end(); i++)
+      {
+        if ((*i)->getPOC() != m_apcSlicePilot->getPOC())
+        {
+          (*i)->getSlice(0)->setReferenced(false);
+        }
+      }
+
+      for (UInt i = 0; i < m_apcSlicePilot->getVPS()->getNumPredictedLayers(dolLayerId); i++)
+      {
+        UInt predLId = m_apcSlicePilot->getVPS()->getPredictedLayerId(dolLayerId, i);
+        for (TComList<TComPic*>::iterator pic = m_ppcTDecTop[predLId]->getListPic()->begin(); pic != m_ppcTDecTop[predLId]->getListPic()->end(); pic++)
+        {
+          if ((*pic)->getSlice(0)->getPOC() != m_apcSlicePilot->getPOC())
+          {
+            (*pic)->getSlice(0)->setReferenced(false);
+          }
+        }
+      }
+    }
+  }
+}
+
+Void TDecTop::xSetLayerInitializedFlag()
+{
+  if (m_apcSlicePilot->isIRAP() && m_apcSlicePilot->getNoRaslOutputFlag())
+  {
+    if (m_layerId == 0)
+    {
+      m_ppcTDecTop[m_layerId]->setLayerInitializedFlag(true);
+    }
+    else if (!m_ppcTDecTop[m_layerId]->getLayerInitializedFlag() && m_apcSlicePilot->getVPS()->getNumDirectRefLayers(m_layerId) == 0)
+    {
+      m_ppcTDecTop[m_layerId]->setLayerInitializedFlag(true);
+    }
+    else if (!m_ppcTDecTop[m_layerId]->getLayerInitializedFlag())
+    {
+      Bool refLayersInitialized = true;
+      for (UInt j = 0; j < m_apcSlicePilot->getVPS()->getNumDirectRefLayers(m_layerId); j++)
+      {
+        UInt refLayerId = m_apcSlicePilot->getVPS()->getRefLayerId(m_layerId, j);
+        if (!m_ppcTDecTop[refLayerId]->getLayerInitializedFlag())
+        {
+          refLayersInitialized = false;
+        }
+      }
+      if (refLayersInitialized)
+      {
+        m_ppcTDecTop[m_layerId]->setLayerInitializedFlag(true);
+      }
+    }
+  }
+}
+#endif
+
+#if R0235_SMALLEST_LAYER_ID
+Void TDecTop::xDeriveSmallestLayerId(TComVPS* vps)
+{
+  UInt smallestLayerId;
+  Int  targetOlsIdx = m_commonDecoderParams->getTargetOutputLayerSetIdx();
+  assert( targetOlsIdx >= 0 );
+
+  UInt targetDecLayerSetIdx = vps->getOutputLayerSetIdx(targetOlsIdx);
+  UInt lsIdx = targetDecLayerSetIdx;
+  UInt targetDecLayerIdList[MAX_LAYERS] = {0};
+
+  for (UInt i = 0, j = 0; i < vps->getNumLayersInIdList(lsIdx); i++)
+  {
+    if (vps->getNecessaryLayerFlag(targetOlsIdx, i))
+    {
+      targetDecLayerIdList[j++] = vps->getLayerSetLayerIdList(lsIdx, i);
+    }
+  }
+
+  if (targetDecLayerSetIdx <= vps->getVpsNumLayerSetsMinus1())
+  {
+    smallestLayerId = 0;
+  }
+  else if (vps->getNumLayersInIdList(targetDecLayerSetIdx) == 1)
+  {
+    smallestLayerId = 0;
+  }
+  else
+  {
+    smallestLayerId = targetDecLayerIdList[0];
+  }
+
+  for( UInt layerId = 0; layerId < MAX_VPS_LAYER_IDX_PLUS1; layerId++ )
+  {
+    m_ppcTDecTop[layerId]->m_smallestLayerId = smallestLayerId;
+  }
+}
+#endif
+
+Void TDecTop::xSetSpatialEnhLayerFlag(TComSlice* slice, TComPic* pic)
+{
+  for(UInt i = 0; i < slice->getVPS()->getNumDirectRefLayers( m_layerId ); i++ )
+  {
+    const Window scalEL = slice->getPPS()->getScaledRefLayerWindowForLayer(slice->getVPS()->getRefLayerId(m_layerId, i));
+    const Window refEL = slice->getPPS()->getRefLayerWindowForLayer(slice->getVPS()->getRefLayerId(m_layerId, i));
+    Bool equalOffsets = scalEL.hasEqualOffset(refEL);
+    Bool zeroPhase = slice->getPPS()->hasZeroResamplingPhase(slice->getVPS()->getRefLayerId(m_layerId, i));
+
+    TDecTop *pcTDecTopBase = (TDecTop *)getRefLayerDec( i );
+    //TComPic*                      pcPic = *(pcTDecTopBase->getListPic()->begin()); 
+    TComPicYuv* pcPicYuvRecBase = (*(pcTDecTopBase->getListPic()->begin()))->getPicYuvRec(); 
+
+    UInt refLayerId = slice->getVPS()->getRefLayerId(m_layerId, i);
+    Bool sameBitDepths = ( g_bitDepthLayer[CHANNEL_TYPE_LUMA][m_layerId] == g_bitDepthLayer[CHANNEL_TYPE_LUMA][refLayerId] ) && ( g_bitDepthLayer[CHANNEL_TYPE_CHROMA][m_layerId] == g_bitDepthLayer[CHANNEL_TYPE_CHROMA][refLayerId] );
+
+    if( pcPicYuvRecBase->getWidth(COMPONENT_Y) == slice->getPicWidthInLumaSamples() && pcPicYuvRecBase->getHeight(COMPONENT_Y) == slice->getPicHeightInLumaSamples() && equalOffsets && zeroPhase )
+    {
+      pic->setEqualPictureSizeAndOffsetFlag( i, true );
+    }
+
+    if( !pic->equalPictureSizeAndOffsetFlag(i) || !sameBitDepths 
+#if Q0048_CGS_3D_ASYMLUT
+      || slice->getPPS()->getCGSFlag() > 0
+#endif
+#if LAYER_CTB
+      || pcTDecTopBase->getActiveSPS()->getMaxCUWidth() != m_ppcTDecTop[m_layerId]->getActiveSPS()->getMaxCUWidth() || pcTDecTopBase->getActiveSPS()->getMaxCUHeight() != m_ppcTDecTop[m_layerId]->getActiveSPS()->getMaxCUHeight() || pcTDecTopBase->getActiveSPS()->getMaxCUDepth() != m_ppcTDecTop[m_layerId]->getActiveSPS()->getMaxCUDepth()
+#endif
+      )
+    {
+      pic->setSpatialEnhLayerFlag( i, true );
+
+      //only for scalable extension
+      assert( slice->getVPS()->getScalabilityMask( SCALABILITY_ID ) == true );
+    }
+  }
+}
+
+#endif //SVC_EXTENSION
+
+
+//! \}
Index: /tags/SHM-9.0/source/Lib/TLibDecoder/TDecTop.h
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibDecoder/TDecTop.h	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibDecoder/TDecTop.h	(revision 1088)
@@ -0,0 +1,360 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TDecTop.h
+    \brief    decoder class (header)
+*/
+
+#ifndef __TDECTOP__
+#define __TDECTOP__
+
+#include "TLibCommon/CommonDef.h"
+#include "TLibCommon/TComList.h"
+#include "TLibCommon/TComPicYuv.h"
+#include "TLibCommon/TComPic.h"
+#include "TLibCommon/TComTrQuant.h"
+#include "TLibCommon/SEI.h"
+#if Q0048_CGS_3D_ASYMLUT
+#include "TLibCommon/TCom3DAsymLUT.h"
+#endif
+
+#include "TDecGop.h"
+#include "TDecEntropy.h"
+#include "TDecSbac.h"
+#include "TDecCAVLC.h"
+#include "SEIread.h"
+
+struct InputNALUnit;
+
+//! \ingroup TLibDecoder
+//! \{
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// decoder class
+class TDecTop
+{
+private:
+  Int                     m_iMaxRefPicNum;
+
+  NalUnitType             m_associatedIRAPType; ///< NAL unit type of the associated IRAP picture
+  Int                     m_pocCRA;            ///< POC number of the latest CRA picture
+  Int                     m_pocRandomAccess;   ///< POC number of the random access point (the first IDR or CRA picture)
+
+  TComList<TComPic*>      m_cListPic;         //  Dynamic buffer
+  ParameterSetManagerDecoder m_parameterSetManagerDecoder;  // storage for parameter sets
+  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;
+#if Q0048_CGS_3D_ASYMLUT
+  TCom3DAsymLUT           m_c3DAsymLUTPPS;
+  TComPicYuv*             m_pColorMappedPic;
+#endif
+  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;
+#if !SVC_EXTENSION
+  Int                     m_prevPOC;
+#endif
+  Bool                    m_bFirstSliceInPicture;
+#if !SVC_EXTENSION
+  Bool                    m_bFirstSliceInSequence;
+#endif
+  Bool                    m_prevSliceSkipped;
+  Int                     m_skippedPOC;
+  Bool                    m_bFirstSliceInBitstream;
+  Int                     m_lastPOCNoOutputPriorPics;
+  Bool                    m_isNoOutputPriorPics;
+  Bool                    m_craNoRaslOutputFlag;    //value of variable NoRaslOutputFlag of the last CRA pic
+#if O0043_BEST_EFFORT_DECODING
+  UInt                    m_forceDecodeBitDepth;
+#endif
+  std::ostream           *m_pDecodedSEIOutputStream;
+
+#if SVC_EXTENSION
+#if Q0177_EOS_CHECKS
+  Bool                    m_isLastNALWasEos;
+#endif
+#if R0071_IRAP_EOS_CROSS_LAYER_IMPACTS
+  Bool                    m_lastPicHasEos;
+#endif
+  static UInt             m_prevPOC;        // POC of the previous slice
+  static UInt             m_uiPrevLayerId;  // LayerId of the previous slice
+  static Bool             m_bFirstSliceInSequence;
+  UInt                    m_layerId;      
+  UInt                    m_numLayer;
+  TDecTop**               m_ppcTDecTop;
+#if R0235_SMALLEST_LAYER_ID
+  UInt                    m_smallestLayerId;
+#endif
+#if P0297_VPS_POC_LSB_ALIGNED_FLAG
+  Bool                    m_pocResettingFlag;
+  Bool                    m_pocDecrementedInDPBFlag;
+#endif
+#if AVC_BASE
+  fstream*                m_pBLReconFile;
+#if !REPN_FORMAT_IN_VPS
+  Int                     m_iBLSourceWidth;
+  Int                     m_iBLSourceHeight;
+#endif
+#endif
+#if VPS_EXTN_DIRECT_REF_LAYERS
+  Int                     m_numDirectRefLayers;
+  Int                     m_refLayerId[MAX_VPS_LAYER_IDX_PLUS1];
+  Int                     m_numSamplePredRefLayers;
+  Int                     m_numMotionPredRefLayers;
+#endif
+  TComPic*                m_cIlpPic[MAX_NUM_REF];                    ///<  Inter layer Prediction picture =  upsampled picture
+#endif 
+#if OUTPUT_LAYER_SET_INDEX
+  CommonDecoderParams*    m_commonDecoderParams;
+#endif
+#if NO_CLRAS_OUTPUT_FLAG  
+  Bool                    m_noClrasOutputFlag;
+  Bool                    m_layerInitializedFlag;
+  Bool                    m_firstPicInLayerDecodedFlag;
+#endif
+#if POC_RESET_IDC_DECODER
+  Int                     m_parseIdc;
+  Int                     m_lastPocPeriodId;
+  Int                     m_prevPicOrderCnt;
+#endif
+#if RESOLUTION_BASED_DPB
+  Int                     m_subDpbIdx;     // Index to the sub-DPB that the layer belongs to.
+                                           // When new VPS is activated, this should be re-initialized to -1
+#endif
+#if CONFORMANCE_BITSTREAM_MODE
+  Bool m_confModeFlag;
+  std::vector<TComPic>   m_confListPic;         //  Dynamic buffer for storing pictures for conformance purposes
+#endif
+#if FIX_NON_OUTPUT_LAYER
+  Bool m_isOutputLayerFlag;
+#endif
+public:
+#if POC_RESET_RESTRICTIONS
+  static Bool                    m_checkPocRestrictionsForCurrAu;
+  static Int                     m_pocResetIdcOrCurrAu;
+  static Bool                    m_baseLayerIdrFlag;
+  static Bool                    m_baseLayerPicPresentFlag;
+  static Bool                    m_baseLayerIrapFlag;
+  static Bool                    m_nonBaseIdrPresentFlag;
+  static Int                     m_nonBaseIdrType;
+  static Bool                    m_picNonIdrWithRadlPresentFlag;
+  static Bool                    m_picNonIdrNoLpPresentFlag;
+#endif
+#if POC_RESET_VALUE_RESTRICTION
+  static Int                     m_crossLayerPocResetPeriodId;
+  static Int                     m_crossLayerPocResetIdc;
+#endif
+
+  TDecTop();
+  virtual ~TDecTop();
+
+  Void  create  ();
+  Void  destroy ();
+
+  Void setDecodedPictureHashSEIEnabled(Int enabled) { m_cGopDecoder.setDecodedPictureHashSEIEnabled(enabled); }
+#if Q0074_COLOUR_REMAPPING_SEI
+  void setColourRemappingInfoSEIEnabled(Bool enabled)  { m_cGopDecoder.setColourRemappingInfoSEIEnabled(enabled); }
+#endif
+
+  Void  init();
+#if SVC_EXTENSION
+  Bool  decode(InputNALUnit& nalu, Int& iSkipFrame, Int& iPOCLastDisplay, UInt& curLayerId, Bool& bNewPOC);
+#else
+  Bool  decode(InputNALUnit& nalu, Int& iSkipFrame, Int& iPOCLastDisplay);
+#endif
+  
+  Void  deletePicBuffer();
+
+  
+  TComSPS* getActiveSPS() { return m_parameterSetManagerDecoder.getActiveSPS(); }
+
+
+  Void  executeLoopFilters(Int& poc, TComList<TComPic*>*& rpcListPic);
+  Void  checkNoOutputPriorPics (TComList<TComPic*>* rpcListPic);
+
+  Bool  getNoOutputPriorPicsFlag () { return m_isNoOutputPriorPics; }
+  Void  setNoOutputPriorPicsFlag (Bool val) { m_isNoOutputPriorPics = val; }
+  Void  setFirstSliceInPicture (bool val)  { m_bFirstSliceInPicture = val; }
+  Bool  getFirstSliceInSequence ()         { return m_bFirstSliceInSequence; }
+  Void  setFirstSliceInSequence (bool val) { m_bFirstSliceInSequence = val; }
+#if O0043_BEST_EFFORT_DECODING
+  Void  setForceDecodeBitDepth(UInt bitDepth) { m_forceDecodeBitDepth = bitDepth; }
+#endif
+  Void  setDecodedSEIMessageOutputStream(std::ostream *pOpStream) { m_pDecodedSEIOutputStream = pOpStream; }
+
+#if SVC_EXTENSION
+#if EARLY_REF_PIC_MARKING
+  Void earlyPicMarking(Int maxTemporalLayer, std::vector<Int>& targetDecLayerIdList);
+#endif
+#if POC_RESET_IDC_DECODER
+  Int       getParseIdc                     ()                              { return m_parseIdc;               }
+  Void      setParseIdc                     (Int x)                         { m_parseIdc = x;                  }
+  Void      markAllPicsAsNoCurrAu           (TComVPS *vps);
+
+  Int       getLastPocPeriodId              ()                              { return m_lastPocPeriodId;        }
+  Void      setLastPocPeriodId              (Int x)                         { m_lastPocPeriodId = x;           }
+
+  Int       getPrevPicOrderCnt              ()                              { return m_prevPicOrderCnt;        }
+  Void      setPrevPicOrderCnt              (Int const x)                   { m_prevPicOrderCnt = x;           }
+#endif
+  UInt      getLayerId                      ()                              { return m_layerId;                }
+  Void      setLayerId                      (UInt layer)                    { m_layerId = layer;               }
+  UInt      getNumLayer                     ()                              { return m_numLayer;               }
+  Void      setNumLayer                     (UInt uiNum)                    { m_numLayer = uiNum;              }
+  TComList<TComPic*>*  getListPic           ()                              { return &m_cListPic;              }
+  Void      setLayerDec                     (TDecTop **p)                   { m_ppcTDecTop = p;                }
+  TDecTop*  getLayerDec                     (UInt layerId)                  { return m_ppcTDecTop[layerId];    }
+#if R0235_SMALLEST_LAYER_ID
+  Void      xDeriveSmallestLayerId(TComVPS* vps);
+#endif
+#if VPS_EXTN_DIRECT_REF_LAYERS
+  TDecTop*  getRefLayerDec                  (UInt refLayerIdx);
+  Int       getNumDirectRefLayers           ()                              { return m_numDirectRefLayers;      }
+  Void      setNumDirectRefLayers           (Int num)                       { m_numDirectRefLayers = num;       }
+
+  Int       getRefLayerId                   (Int i)                         { return m_refLayerId[i];           }
+  Void      setRefLayerId                   (Int i, Int refLayerId)         { m_refLayerId[i] = refLayerId;     }
+
+  Int       getNumSamplePredRefLayers       ()                              { return m_numSamplePredRefLayers;  }
+  Void      setNumSamplePredRefLayers       (Int num)                       { m_numSamplePredRefLayers = num;   }
+
+  Int       getNumMotionPredRefLayers       ()                              { return m_numMotionPredRefLayers;  }
+  Void      setNumMotionPredRefLayers       (Int num)                       { m_numMotionPredRefLayers = num;   }
+
+  Void      setRefLayerParams( TComVPS* vps );
+#endif
+#if AVC_BASE
+  Void      setBLReconFile( fstream* pFile ) { m_pBLReconFile = pFile; }
+  fstream*  getBLReconFile() { return m_pBLReconFile; }
+#if !REPN_FORMAT_IN_VPS
+  Void      setBLsize( Int iWidth, Int iHeight ) { m_iBLSourceWidth = iWidth; m_iBLSourceHeight = iHeight; }
+  Int       getBLWidth() { return  m_iBLSourceWidth; }
+  Int       getBLHeight() { return  m_iBLSourceHeight; }
+#endif
+#endif
+#if REPN_FORMAT_IN_VPS
+  Void      xInitILRP(TComSlice *slice);
+#else
+  Void      xInitILRP(TComSPS *pcSPS);
+#endif
+#if OUTPUT_LAYER_SET_INDEX
+  CommonDecoderParams*    getCommonDecoderParams() { return m_commonDecoderParams; }
+  Void                    setCommonDecoderParams(CommonDecoderParams* x) { m_commonDecoderParams = x; }
+  Void      checkValueOfTargetOutputLayerSetIdx(TComVPS *vps);
+#endif
+#if SCALINGLIST_INFERRING
+  ParameterSetManagerDecoder* getParameterSetManager() { return &m_parameterSetManagerDecoder; }
+#endif
+#if RESOLUTION_BASED_DPB
+  Void setSubDpbIdx(Int idx)    { m_subDpbIdx = idx; }
+  Int  getSubDpbIdx()           { return m_subDpbIdx; }
+  Void assignSubDpbs(TComVPS *vps);
+#endif
+#if CONFORMANCE_BITSTREAM_MODE
+  std::vector<TComPic>* getConfListPic() {return &m_confListPic; }
+  // std::string const getDecodedYuvLayerFileName(Int layerId) { return m_decodedYuvLayerFileName[layerId]; }
+  Bool const getConfModeFlag() { return m_confModeFlag; }
+  Void setConfModeFlag(Bool x) { m_confModeFlag = x; }
+#endif
+#endif //SVC_EXTENSION
+
+protected:
+  Void  xGetNewPicBuffer  (TComSlice* pcSlice, TComPic*& rpcPic);
+  Void  xCreateLostPicture (Int iLostPOC);
+
+  Void      xActivateParameterSets();
+#if SVC_EXTENSION
+#if POC_RESET_FLAG
+  Bool      xDecodeSlice(InputNALUnit &nalu, Int &iSkipFrame, Int &iPOCLastDisplay, UInt& curLayerId, Bool& bNewPOC);
+#else
+  Bool      xDecodeSlice(InputNALUnit &nalu, Int &iSkipFrame, Int iPOCLastDisplay, UInt& curLayerId, Bool& bNewPOC);
+#endif
+  Void      xSetSpatialEnhLayerFlag(TComSlice* slice, TComPic* pic);
+#else
+  Bool      xDecodeSlice(InputNALUnit &nalu, Int &iSkipFrame, Int iPOCLastDisplay);
+#endif
+  Void      xDecodeVPS();
+  Void      xDecodeSPS();
+  Void      xDecodePPS(
+#if Q0048_CGS_3D_ASYMLUT
+    TCom3DAsymLUT * pc3DAsymLUT
+#endif
+    );
+  Void      xDecodeSEI( TComInputBitstream* bs, const NalUnitType nalUnitType );
+
+#if NO_CLRAS_OUTPUT_FLAG
+  Int  getNoClrasOutputFlag()                { return m_noClrasOutputFlag;}
+  Void setNoClrasOutputFlag(Bool x)          { m_noClrasOutputFlag = x;   }
+  Int  getLayerInitializedFlag()             { return m_layerInitializedFlag;}
+  Void setLayerInitializedFlag(Bool x)       { m_layerInitializedFlag = x;   }
+  Int  getFirstPicInLayerDecodedFlag()       { return m_firstPicInLayerDecodedFlag;}
+  Void setFirstPicInLayerDecodedFlag(Bool x) { m_firstPicInLayerDecodedFlag = x;   }
+#endif
+#if Q0048_CGS_3D_ASYMLUT
+  Void initAsymLut(TComSlice *pcSlice);
+#endif
+#if POC_RESET_RESTRICTIONS
+  Void resetPocRestrictionCheckParameters();
+#endif
+#if R0071_IRAP_EOS_CROSS_LAYER_IMPACTS
+  Void xCheckLayerReset();
+  Void xSetNoRaslOutputFlag();
+  Void xSetLayerInitializedFlag();
+#endif
+};// END CLASS DEFINITION TDecTop
+
+
+//! \}
+
+#endif // __TDECTOP__
+
Index: /tags/SHM-9.0/source/Lib/TLibEncoder/AnnexBwrite.h
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibEncoder/AnnexBwrite.h	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibEncoder/AnnexBwrite.h	(revision 1088)
@@ -0,0 +1,91 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#pragma once
+
+#ifndef __ANNEXBWRITE__
+#define __ANNEXBWRITE__
+
+#include <ostream>
+#include "TLibCommon/AccessUnit.h"
+#include "NALwrite.h"
+
+//! \ingroup TLibEncoder
+//! \{
+
+/**
+ * write all NALunits in au to bytestream out in a manner satisfying
+ * AnnexB of AVC.  NALunits are written in the order they are found in au.
+ * the zero_byte word is appended to:
+ *  - the initial startcode in the access unit,
+ *  - any SPS/PPS nal units
+ */
+static std::vector<UInt> writeAnnexB(std::ostream& out, const AccessUnit& au)
+{
+  std::vector<UInt> annexBsizes;
+
+  for (AccessUnit::const_iterator it = au.begin(); it != au.end(); it++)
+  {
+    const NALUnitEBSP& nalu = **it;
+    UInt size = 0; /* size of annexB unit in bytes */
+
+    static const Char start_code_prefix[] = {0,0,0,1};
+    if (it == au.begin() || nalu.m_nalUnitType == NAL_UNIT_VPS || nalu.m_nalUnitType == NAL_UNIT_SPS || nalu.m_nalUnitType == NAL_UNIT_PPS)
+    {
+      /* From AVC, When any of the following conditions are fulfilled, the
+       * zero_byte syntax element shall be present:
+       *  - the nal_unit_type within the nal_unit() is equal to 7 (sequence
+       *    parameter set) or 8 (picture parameter set),
+       *  - the byte stream NAL unit syntax structure contains the first NAL
+       *    unit of an access unit in decoding order, as specified by subclause
+       *    7.4.1.2.3.
+       */
+      out.write(start_code_prefix, 4);
+      size += 4;
+    }
+    else
+    {
+      out.write(start_code_prefix+1, 3);
+      size += 3;
+    }
+    out << nalu.m_nalUnitData.str();
+    size += UInt(nalu.m_nalUnitData.str().size());
+
+    annexBsizes.push_back(size);
+  }
+
+  return annexBsizes;
+}
+//! \}
+
+#endif
Index: /tags/SHM-9.0/source/Lib/TLibEncoder/NALwrite.cpp
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibEncoder/NALwrite.cpp	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibEncoder/NALwrite.cpp	(revision 1088)
@@ -0,0 +1,127 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include <vector>
+#include <algorithm>
+#include <ostream>
+
+#include "TLibCommon/NAL.h"
+#include "TLibCommon/TComBitStream.h"
+#include "NALwrite.h"
+
+using namespace std;
+
+//! \ingroup TLibEncoder
+//! \{
+
+static const Char emulation_prevention_three_byte[] = {3};
+
+Void writeNalUnitHeader(ostream& out, OutputNALUnit& nalu)       // nal_unit_header()
+{
+TComOutputBitstream bsNALUHeader;
+
+  bsNALUHeader.write(0,1);                    // forbidden_zero_bit
+  bsNALUHeader.write(nalu.m_nalUnitType, 6);  // nal_unit_type
+#if SVC_EXTENSION
+  bsNALUHeader.write(nalu.m_layerId, 6); // reserved_one_5bits
+#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();
+
+  vector<uint8_t> outputBuffer;
+  outputBuffer.resize(rbsp.size()*2+1); //there can never be enough emulation_prevention_three_bytes to require this much space
+  std::size_t outputAmount = 0;
+  Int         zeroCount    = 0;
+  for (vector<uint8_t>::iterator it = rbsp.begin(); it != rbsp.end(); it++)
+  {
+    const uint8_t v=(*it);
+    if (zeroCount==2 && v<=3)
+    {
+      outputBuffer[outputAmount++]=emulation_prevention_three_byte[0];
+      zeroCount=0;
+    }
+    if (v==0) zeroCount++; else zeroCount=0;
+    outputBuffer[outputAmount++]=v;
+  }
+
+  /* 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 (zeroCount>0) outputBuffer[outputAmount++]=emulation_prevention_three_byte[0];
+  out.write((Char*)&(*outputBuffer.begin()), outputAmount);
+}
+
+/**
+ * Write rbsp_trailing_bits to bs causing it to become byte-aligned
+ */
+Void writeRBSPTrailingBits(TComOutputBitstream& bs)
+{
+  bs.write( 1, 1 );
+  bs.writeAlignZero();
+}
+
+//! \}
Index: /tags/SHM-9.0/source/Lib/TLibEncoder/NALwrite.h
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibEncoder/NALwrite.h	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibEncoder/NALwrite.h	(revision 1088)
@@ -0,0 +1,95 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#pragma once
+
+#ifndef __NALWRITE__
+#define __NALWRITE__
+
+#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 SVC_EXTENSION
+    UInt     layerId = 0,
+#endif
+    UInt reserved_zero_6bits = 0)
+#if SVC_EXTENSION
+  : NALUnit(nalUnitType, temporalID, layerId, reserved_zero_6bits)
+#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);
+}
+
+//! \}
+
+#endif
Index: /tags/SHM-9.0/source/Lib/TLibEncoder/SEIwrite.cpp
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibEncoder/SEIwrite.cpp	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibEncoder/SEIwrite.cpp	(revision 1088)
@@ -0,0 +1,1565 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "TLibCommon/TComBitCounter.h"
+#include "TLibCommon/TComBitStream.h"
+#include "TLibCommon/SEI.h"
+#include "TLibCommon/TComSlice.h"
+#include "TLibCommon/TComPicYuv.h"
+#include "SEIwrite.h"
+
+//! \ingroup TLibEncoder
+//! \{
+
+#if ENC_DEC_TRACE
+Void  xTraceSEIHeader()
+{
+  fprintf( g_hTrace, "=========== SEI message ===========\n");
+}
+
+Void  xTraceSEIMessageType(SEI::PayloadType payloadType)
+{
+  fprintf( g_hTrace, "=========== %s SEI message ===========\n", SEI::getSEIMessageString(payloadType));
+}
+#endif
+
+#if O0164_MULTI_LAYER_HRD
+#if VPS_VUI_BSP_HRD_PARAMS
+Void SEIWriter::xWriteSEIpayloadData(TComBitIf& bs, const SEI& sei, TComVPS *vps, TComSPS *sps, const SEIScalableNesting* nestingSeiPtr, const SEIBspNesting* bspNestingSeiPtr)
+#else
+Void SEIWriter::xWriteSEIpayloadData(TComBitIf& bs, const SEI& sei, TComVPS *vps, TComSPS *sps, const SEIScalableNesting& nestingSei, const SEIBspNesting& bspNestingSei)
+#endif
+#else
+Void SEIWriter::xWriteSEIpayloadData(TComBitIf& bs, const SEI& sei, TComSPS *sps)
+#endif
+{
+#if VPS_VUI_BSP_HRD_PARAMS
+  SEIScalableNesting nestingSei;
+  SEIBspNesting      bspNestingSei;
+  if( nestingSeiPtr )
+  {
+    nestingSei = *nestingSeiPtr;
+  }
+  if( bspNestingSeiPtr )
+  {
+    bspNestingSei = *bspNestingSeiPtr;
+  }
+#endif
+  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::DECODED_PICTURE_HASH:
+    xWriteSEIDecodedPictureHash(*static_cast<const SEIDecodedPictureHash*>(&sei));
+    break;
+#if VPS_VUI_BSP_HRD_PARAMS
+  case SEI::DECODING_UNIT_INFO:
+    xWriteSEIDecodingUnitInfo(*static_cast<const SEIDecodingUnitInfo*>(& sei), sps, nestingSeiPtr, bspNestingSeiPtr, vps);
+    break;
+  case SEI::BUFFERING_PERIOD:
+    xWriteSEIBufferingPeriod(*static_cast<const SEIBufferingPeriod*>(&sei), sps, nestingSeiPtr, bspNestingSeiPtr, vps);
+    break;
+  case SEI::PICTURE_TIMING:
+    xWriteSEIPictureTiming(*static_cast<const SEIPictureTiming*>(&sei), sps, nestingSeiPtr, bspNestingSeiPtr, vps);
+    break;
+#else
+  case SEI::DECODING_UNIT_INFO:
+    xWriteSEIDecodingUnitInfo(*static_cast<const SEIDecodingUnitInfo*>(& sei), sps);
+    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;
+#endif
+  case SEI::RECOVERY_POINT:
+    xWriteSEIRecoveryPoint(*static_cast<const SEIRecoveryPoint*>(&sei));
+    break;
+  case SEI::FRAME_PACKING:
+    xWriteSEIFramePacking(*static_cast<const SEIFramePacking*>(&sei));
+    break;
+  case SEI::SEGM_RECT_FRAME_PACKING:
+    xWriteSEISegmentedRectFramePacking(*static_cast<const SEISegmentedRectFramePacking*>(&sei));
+    break;
+  case SEI::DISPLAY_ORIENTATION:
+    xWriteSEIDisplayOrientation(*static_cast<const SEIDisplayOrientation*>(&sei));
+    break;
+  case SEI::TEMPORAL_LEVEL0_INDEX:
+    xWriteSEITemporalLevel0Index(*static_cast<const SEITemporalLevel0Index*>(&sei));
+    break;
+  case SEI::REGION_REFRESH_INFO:
+    xWriteSEIGradualDecodingRefreshInfo(*static_cast<const SEIGradualDecodingRefreshInfo*>(&sei));
+    break;
+  case SEI::NO_DISPLAY:
+    xWriteSEINoDisplay(*static_cast<const SEINoDisplay*>(&sei));
+    break;
+  case SEI::TONE_MAPPING_INFO:
+    xWriteSEIToneMappingInfo(*static_cast<const SEIToneMappingInfo*>(&sei));
+    break;
+  case SEI::SOP_DESCRIPTION:
+    xWriteSEISOPDescription(*static_cast<const SEISOPDescription*>(&sei));
+    break;
+  case SEI::SCALABLE_NESTING:
+#if O0164_MULTI_LAYER_HRD
+    xWriteSEIScalableNesting(bs, *static_cast<const SEIScalableNesting*>(&sei), vps, sps);
+#else
+    xWriteSEIScalableNesting(bs, *static_cast<const SEIScalableNesting*>(&sei), sps);
+#endif
+    break;
+  case SEI::CHROMA_SAMPLING_FILTER_HINT:
+    xWriteSEIChromaSamplingFilterHint(*static_cast<const SEIChromaSamplingFilterHint*>(&sei)/*, sps*/);
+    break;
+  case SEI::TEMP_MOTION_CONSTRAINED_TILE_SETS:
+    xWriteSEITempMotionConstrainedTileSets(bs, *static_cast<const SEITempMotionConstrainedTileSets*>(&sei));
+    break;
+  case SEI::TIME_CODE:
+    xWriteSEITimeCode(*static_cast<const SEITimeCode*>(&sei));
+    break;
+  case SEI::KNEE_FUNCTION_INFO:
+    xWriteSEIKneeFunctionInfo(*static_cast<const SEIKneeFunctionInfo*>(&sei));
+    break;
+  case SEI::MASTERING_DISPLAY_COLOUR_VOLUME:
+    xWriteSEIMasteringDisplayColourVolume(*static_cast<const SEIMasteringDisplayColourVolume*>(&sei));
+    break;
+#if Q0074_COLOUR_REMAPPING_SEI
+  case SEI::COLOUR_REMAPPING_INFO:
+    xWriteSEIColourRemappingInfo(*static_cast<const SEIColourRemappingInfo*>(&sei));
+    break;
+#endif
+#if SVC_EXTENSION
+#if LAYERS_NOT_PRESENT_SEI
+  case SEI::LAYERS_NOT_PRESENT:
+    xWriteSEILayersNotPresent(*static_cast<const SEILayersNotPresent*>(&sei));
+    break;
+#endif
+#if N0383_IL_CONSTRAINED_TILE_SETS_SEI
+  case SEI::INTER_LAYER_CONSTRAINED_TILE_SETS:
+    xWriteSEIInterLayerConstrainedTileSets(*static_cast<const SEIInterLayerConstrainedTileSets*>(&sei));
+    break;
+#endif
+#if SUB_BITSTREAM_PROPERTY_SEI
+   case SEI::SUB_BITSTREAM_PROPERTY:
+     xWriteSEISubBitstreamProperty(*static_cast<const SEISubBitstreamProperty*>(&sei));
+     break;
+#endif
+#if O0164_MULTI_LAYER_HRD
+   case SEI::BSP_NESTING:
+     xWriteSEIBspNesting(bs, *static_cast<const SEIBspNesting*>(&sei), vps, sps, nestingSei);
+     break;
+   case SEI::BSP_INITIAL_ARRIVAL_TIME:
+     xWriteSEIBspInitialArrivalTime(*static_cast<const SEIBspInitialArrivalTime*>(&sei), vps, sps, nestingSei, bspNestingSei);
+     break;
+#if !REMOVE_BSP_HRD_SEI
+   case SEI::BSP_HRD:
+     xWriteSEIBspHrd(*static_cast<const SEIBspHrd*>(&sei), sps, nestingSei);
+     break;
+#endif
+#endif
+#if Q0078_ADD_LAYER_SETS
+   case SEI::OUTPUT_LAYER_SET_NESTING:
+     xWriteSEIOutputLayerSetNesting(bs, *static_cast<const SEIOutputLayerSetNesting*>(&sei), vps, sps);
+     break;
+   case SEI::VPS_REWRITING:
+     xWriteSEIVPSRewriting(*static_cast<const SEIVPSRewriting*>(&sei));
+     break;
+#endif
+#if Q0189_TMVP_CONSTRAINTS
+   case SEI::TMVP_CONSTRAINTS:
+     xWriteSEITMVPConstraints(*static_cast<const SEITMVPConstrains*>(&sei));
+     break;
+#endif
+#if Q0247_FRAME_FIELD_INFO
+   case SEI::FRAME_FIELD_INFO:
+     xWriteSEIFrameFieldInfo(*static_cast<const SEIFrameFieldInfo*>(&sei));
+     break;
+#endif
+#if P0123_ALPHA_CHANNEL_SEI
+   case SEI::ALPHA_CHANNEL_INFO:
+     xWriteSEIAlphaChannelInfo(*static_cast<const SEIAlphaChannelInfo*>(&sei));
+     break;
+#endif
+#if Q0096_OVERLAY_SEI
+   case SEI::OVERLAY_INFO:
+     xWriteSEIOverlayInfo(*static_cast<const SEIOverlayInfo*>(&sei));
+     break;
+#endif
+#endif //SVC_EXTENSION
+  default:
+    assert(!"Unhandled SEI message");
+    break;
+  }
+  xWriteByteAlign();
+}
+
+/**
+ * marshal a single SEI message sei, storing the marshalled representation
+ * in bitstream bs.
+ */
+#if O0164_MULTI_LAYER_HRD
+Void SEIWriter::writeSEImessage(TComBitIf& bs, const SEI& sei, TComVPS *vps, TComSPS *sps, const SEIScalableNesting* nestingSei, const SEIBspNesting* bspNestingSei)
+#else
+Void SEIWriter::writeSEImessage(TComBitIf& bs, const SEI& sei, TComSPS *sps)
+#endif
+{
+  /* 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
+#if O0164_MULTI_LAYER_HRD
+#if VPS_VUI_BSP_HRD_PARAMS
+  xWriteSEIpayloadData(bs_count, sei, vps, sps, nestingSei, bspNestingSei);
+#else
+  xWriteSEIpayloadData(bs_count, sei, vps, sps, *nestingSei, *bspNestingSei);
+#endif
+#else
+  xWriteSEIpayloadData(bs_count, sei, sps);
+#endif
+#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
+
+#if O0164_MULTI_LAYER_HRD
+#if VPS_VUI_BSP_HRD_PARAMS
+  xWriteSEIpayloadData(bs, sei, vps, sps, nestingSei, bspNestingSei);
+#else
+  xWriteSEIpayloadData(bs, sei, vps, sps, *nestingSei, *bspNestingSei);
+#endif
+#else
+  xWriteSEIpayloadData(bs, sei, sps);
+#endif
+}
+
+/**
+ * marshal a user_data_unregistered SEI message sei, storing the marshalled
+ * representation in bitstream bs.
+ */
+Void SEIWriter::xWriteSEIuserDataUnregistered(const SEIuserDataUnregistered &sei)
+{
+  for (UInt i = 0; i < ISO_IEC_11578_LEN; i++)
+  {
+    WRITE_CODE(sei.uuid_iso_iec_11578[i], 8 , "sei.uuid_iso_iec_11578[i]");
+  }
+
+  for (UInt i = 0; i < sei.userDataLength; i++)
+  {
+    WRITE_CODE(sei.userData[i], 8 , "user_data");
+  }
+}
+
+/**
+ * marshal a decoded picture hash SEI message, storing the marshalled
+ * representation in bitstream bs.
+ */
+Void SEIWriter::xWriteSEIDecodedPictureHash(const SEIDecodedPictureHash& sei)
+{
+  const Char *traceString="\0";
+  switch (sei.method)
+  {
+    case SEIDecodedPictureHash::MD5: traceString="picture_md5"; break;
+    case SEIDecodedPictureHash::CRC: traceString="picture_crc"; break;
+    case SEIDecodedPictureHash::CHECKSUM: traceString="picture_checksum"; break;
+    default: assert(false); break;
+  }
+
+  if (traceString != 0) //use of this variable is needed to avoid a compiler error with G++ 4.6.1
+  {
+    WRITE_CODE(sei.method, 8, "hash_type");
+    for(UInt i=0; i<UInt(sei.m_digest.hash.size()); i++)
+    {
+      WRITE_CODE(sei.m_digest.hash[i], 8, traceString);
+    }
+  }
+}
+
+Void SEIWriter::xWriteSEIActiveParameterSets(const SEIActiveParameterSets& sei)
+{
+  WRITE_CODE(sei.activeVPSId,     4,         "active_video_parameter_set_id");
+  WRITE_FLAG(sei.m_selfContainedCvsFlag,     "self_contained_cvs_flag");
+  WRITE_FLAG(sei.m_noParameterSetUpdateFlag, "no_parameter_set_update_flag");
+  WRITE_UVLC(sei.numSpsIdsMinus1,            "num_sps_ids_minus1");
+
+  assert (sei.activeSeqParameterSetId.size() == (sei.numSpsIdsMinus1 + 1));
+
+  for (Int i = 0; i < sei.activeSeqParameterSetId.size(); i++)
+  {
+    WRITE_UVLC(sei.activeSeqParameterSetId[i], "active_seq_parameter_set_id"); 
+  }
+#if R0247_SEI_ACTIVE
+  for (Int i = 1; i < sei.activeSeqParameterSetId.size(); i++)
+  {
+    WRITE_UVLC(sei.layerSpsIdx[i], "layer_sps_idx"); 
+  }
+#endif
+}
+
+#if VPS_VUI_BSP_HRD_PARAMS
+Void SEIWriter::xWriteSEIDecodingUnitInfo(const SEIDecodingUnitInfo& sei, TComSPS *sps, const SEIScalableNesting* nestingSei, const SEIBspNesting* bspNestingSei, TComVPS *vps)
+#else
+Void SEIWriter::xWriteSEIDecodingUnitInfo(const SEIDecodingUnitInfo& sei, TComSPS *sps)
+#endif
+{
+#if VPS_VUI_BSP_HRD_PARAMS
+  TComHRD *hrd;
+  if( bspNestingSei )   // If DU info SEI contained inside a BSP nesting SEI message
+  {
+    assert( nestingSei );
+    Int psIdx = bspNestingSei->m_seiPartitioningSchemeIdx;
+    Int seiOlsIdx = bspNestingSei->m_seiOlsIdx;
+    Int maxTemporalId = nestingSei->m_nestingMaxTemporalIdPlus1[0] - 1;
+    Int maxValues = vps->getNumBspSchedulesMinus1(seiOlsIdx, psIdx, maxTemporalId) + 1;
+    std::vector<Int> hrdIdx(maxValues, 0);
+    std::vector<TComHRD *> hrdVec;
+    std::vector<Int> syntaxElemLen(maxValues, 0);
+    for(Int i = 0; i < maxValues; i++)
+    {
+      hrdIdx[i] = vps->getBspHrdIdx( seiOlsIdx, psIdx, maxTemporalId, i, bspNestingSei->m_bspIdx);
+      hrdVec.push_back(vps->getBspHrd(hrdIdx[i]));
+    
+      syntaxElemLen[i] = hrdVec[i]->getInitialCpbRemovalDelayLengthMinus1() + 1;
+      if ( !(hrdVec[i]->getNalHrdParametersPresentFlag() || hrdVec[i]->getVclHrdParametersPresentFlag()) )
+      {
+        assert( syntaxElemLen[i] == 24 ); // Default of value init_cpb_removal_delay_length_minus1 is 23
+      }
+      if( i > 0 )
+      {
+        assert( hrdVec[i]->getSubPicCpbParamsPresentFlag()    == hrdVec[i-1]->getSubPicCpbParamsPresentFlag() );
+        assert( hrdVec[i]->getSubPicCpbParamsInPicTimingSEIFlag()   == hrdVec[i-1]->getSubPicCpbParamsInPicTimingSEIFlag() );
+        assert( hrdVec[i]->getDpbOutputDelayDuLengthMinus1()  == hrdVec[i-1]->getDpbOutputDelayDuLengthMinus1() );
+        // To be done: Check CpbDpbDelaysPresentFlag
+      }
+    }
+    hrd = hrdVec[0];
+  }
+  else
+  {
+    TComVUI *vui = sps->getVuiParameters();
+    hrd = vui->getHrdParameters();
+  }
+
+  WRITE_UVLC(sei.m_decodingUnitIdx, "decoding_unit_idx");
+  if(hrd->getSubPicCpbParamsInPicTimingSEIFlag())
+  {
+    WRITE_CODE( sei.m_duSptCpbRemovalDelay, (hrd->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, hrd->getDpbOutputDelayDuLengthMinus1() + 1, "pic_spt_dpb_output_du_delay");
+  }
+#else
+  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");
+  }
+#endif
+}
+
+#if VPS_VUI_BSP_HRD_PARAMS
+Void SEIWriter::xWriteSEIBufferingPeriod(const SEIBufferingPeriod& sei, TComSPS *sps, const SEIScalableNesting* nestingSei, const SEIBspNesting* bspNestingSei, TComVPS *vps)
+#else
+Void SEIWriter::xWriteSEIBufferingPeriod(const SEIBufferingPeriod& sei, TComSPS *sps)
+#endif
+{
+  Int i, nalOrVcl;
+#if VPS_VUI_BSP_HRD_PARAMS
+  TComHRD *hrd;
+  if( bspNestingSei )   // If BP SEI contained inside a BSP nesting SEI message
+  {
+    assert( nestingSei );
+    Int psIdx = bspNestingSei->m_seiPartitioningSchemeIdx;
+    Int seiOlsIdx = bspNestingSei->m_seiOlsIdx;
+    Int maxTemporalId = nestingSei->m_nestingMaxTemporalIdPlus1[0] - 1;
+    Int maxValues = vps->getNumBspSchedulesMinus1(seiOlsIdx, psIdx, maxTemporalId) + 1;
+    std::vector<Int> hrdIdx(maxValues, 0);
+    std::vector<TComHRD *> hrdVec;
+    std::vector<Int> syntaxElemLen(maxValues, 0);
+    for(i = 0; i < maxValues; i++)
+    {
+      hrdIdx[i] = vps->getBspHrdIdx( seiOlsIdx, psIdx, maxTemporalId, i, bspNestingSei->m_bspIdx);
+      hrdVec.push_back(vps->getBspHrd(hrdIdx[i]));
+    
+      syntaxElemLen[i] = hrdVec[i]->getInitialCpbRemovalDelayLengthMinus1() + 1;
+      if ( !(hrdVec[i]->getNalHrdParametersPresentFlag() || hrdVec[i]->getVclHrdParametersPresentFlag()) )
+      {
+        assert( syntaxElemLen[i] == 24 ); // Default of value init_cpb_removal_delay_length_minus1 is 23
+      }
+      if( i > 0 )
+      {
+        assert( hrdVec[i]->getCpbRemovalDelayLengthMinus1()   == hrdVec[i-1]->getCpbRemovalDelayLengthMinus1() );
+        assert( hrdVec[i]->getDpbOutputDelayDuLengthMinus1()  == hrdVec[i-1]->getDpbOutputDelayDuLengthMinus1() );
+        assert( hrdVec[i]->getSubPicCpbParamsPresentFlag()    == hrdVec[i-1]->getSubPicCpbParamsPresentFlag() );
+      }
+    }
+    hrd = hrdVec[i];
+  }
+  else
+  {
+    TComVUI *vui = sps->getVuiParameters();
+    hrd = vui->getHrdParameters();
+  }
+  // To be done: When contained in an BSP HRD SEI message, the hrd structure is to be chosen differently.
+#else
+  TComVUI *vui = sps->getVuiParameters();
+  TComHRD *hrd = vui->getHrdParameters();
+#endif
+
+  WRITE_UVLC( sei.m_bpSeqParameterSetId, "bp_seq_parameter_set_id" );
+  if( !hrd->getSubPicCpbParamsPresentFlag() )
+  {
+    WRITE_FLAG( sei.m_rapCpbParamsPresentFlag, "irap_cpb_params_present_flag" );
+  }
+  if( sei.m_rapCpbParamsPresentFlag )
+  {
+    WRITE_CODE( sei.m_cpbDelayOffset, hrd->getCpbRemovalDelayLengthMinus1() + 1, "cpb_delay_offset" );
+    WRITE_CODE( sei.m_dpbDelayOffset, hrd->getDpbOutputDelayLengthMinus1()  + 1, "dpb_delay_offset" );
+  }
+  WRITE_FLAG( sei.m_concatenationFlag, "concatenation_flag");
+  WRITE_CODE( sei.m_auCpbRemovalDelayDelta - 1, ( hrd->getCpbRemovalDelayLengthMinus1() + 1 ), "au_cpb_removal_delay_delta_minus1" );
+  for( nalOrVcl = 0; nalOrVcl < 2; nalOrVcl ++ )
+  {
+    if( ( ( nalOrVcl == 0 ) && ( hrd->getNalHrdParametersPresentFlag() ) ) ||
+        ( ( nalOrVcl == 1 ) && ( hrd->getVclHrdParametersPresentFlag() ) ) )
+    {
+      for( i = 0; i < ( hrd->getCpbCntMinus1( 0 ) + 1 ); i ++ )
+      {
+        WRITE_CODE( sei.m_initialCpbRemovalDelay[i][nalOrVcl],( hrd->getInitialCpbRemovalDelayLengthMinus1() + 1 ) ,           "initial_cpb_removal_delay" );
+        WRITE_CODE( sei.m_initialCpbRemovalDelayOffset[i][nalOrVcl],( hrd->getInitialCpbRemovalDelayLengthMinus1() + 1 ),      "initial_cpb_removal_delay_offset" );
+        if( hrd->getSubPicCpbParamsPresentFlag() || sei.m_rapCpbParamsPresentFlag )
+        {
+          WRITE_CODE( sei.m_initialAltCpbRemovalDelay[i][nalOrVcl], ( hrd->getInitialCpbRemovalDelayLengthMinus1() + 1 ) ,     "initial_alt_cpb_removal_delay" );
+          WRITE_CODE( sei.m_initialAltCpbRemovalDelayOffset[i][nalOrVcl], ( hrd->getInitialCpbRemovalDelayLengthMinus1() + 1 ),"initial_alt_cpb_removal_delay_offset" );
+        }
+      }
+    }
+  }
+#if P0138_USE_ALT_CPB_PARAMS_FLAG
+  if (sei.m_useAltCpbParamsFlagPresent)
+  {
+    WRITE_FLAG( sei.m_useAltCpbParamsFlag, "use_alt_cpb_params_flag");
+  }
+#endif
+}
+#if VPS_VUI_BSP_HRD_PARAMS
+Void SEIWriter::xWriteSEIPictureTiming(const SEIPictureTiming& sei,  TComSPS *sps, const SEIScalableNesting* nestingSei, const SEIBspNesting* bspNestingSei, TComVPS *vps)
+#else
+Void SEIWriter::xWriteSEIPictureTiming(const SEIPictureTiming& sei,  TComSPS *sps)
+#endif
+{
+  Int i;
+#if VPS_VUI_BSP_HRD_PARAMS
+  TComHRD *hrd;    
+  TComVUI *vui = sps->getVuiParameters(); 
+  if( bspNestingSei )   // If BP SEI contained inside a BSP nesting SEI message
+  {
+    assert( nestingSei );
+    Int psIdx = bspNestingSei->m_seiPartitioningSchemeIdx;
+    Int seiOlsIdx = bspNestingSei->m_seiOlsIdx;
+    Int maxTemporalId = nestingSei->m_nestingMaxTemporalIdPlus1[0] - 1;
+    Int maxValues = vps->getNumBspSchedulesMinus1(seiOlsIdx, psIdx, maxTemporalId) + 1;
+    std::vector<Int> hrdIdx(maxValues, 0);
+    std::vector<TComHRD *> hrdVec;
+    std::vector<Int> syntaxElemLen(maxValues, 0);
+    for(i = 0; i < maxValues; i++)
+    {
+      hrdIdx[i] = vps->getBspHrdIdx( seiOlsIdx, psIdx, maxTemporalId, i, bspNestingSei->m_bspIdx);
+      hrdVec.push_back(vps->getBspHrd(hrdIdx[i]));
+    
+      syntaxElemLen[i] = hrdVec[i]->getInitialCpbRemovalDelayLengthMinus1() + 1;
+      if ( !(hrdVec[i]->getNalHrdParametersPresentFlag() || hrdVec[i]->getVclHrdParametersPresentFlag()) )
+      {
+        assert( syntaxElemLen[i] == 24 ); // Default of value init_cpb_removal_delay_length_minus1 is 23
+      }
+      if( i > 0 )
+      {
+        assert( hrdVec[i]->getSubPicCpbParamsPresentFlag()    == hrdVec[i-1]->getSubPicCpbParamsPresentFlag() );
+        assert( hrdVec[i]->getSubPicCpbParamsInPicTimingSEIFlag()   == hrdVec[i-1]->getSubPicCpbParamsInPicTimingSEIFlag() );
+        assert( hrdVec[i]->getCpbRemovalDelayLengthMinus1()  == hrdVec[i-1]->getCpbRemovalDelayLengthMinus1() );
+        assert( hrdVec[i]->getDpbOutputDelayLengthMinus1()  == hrdVec[i-1]->getDpbOutputDelayLengthMinus1() );
+        assert( hrdVec[i]->getDpbOutputDelayDuLengthMinus1()  == hrdVec[i-1]->getDpbOutputDelayDuLengthMinus1() );
+        assert( hrdVec[i]->getDuCpbRemovalDelayLengthMinus1()  == hrdVec[i-1]->getDuCpbRemovalDelayLengthMinus1() );
+        // To be done: Check CpbDpbDelaysPresentFlag
+      }
+    }
+    hrd = hrdVec[0];
+  }
+  else
+  {
+    hrd = vui->getHrdParameters();
+  }
+  // To be done: When contained in an BSP HRD SEI message, the hrd structure is to be chosen differently.
+#else
+  TComVUI *vui = sps->getVuiParameters();
+  TComHRD *hrd = vui->getHrdParameters();
+#endif
+
+  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" );
+        }
+      }
+    }
+  }
+}
+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"    );
+}
+Void SEIWriter::xWriteSEIFramePacking(const SEIFramePacking& sei)
+{
+  WRITE_UVLC( sei.m_arrangementId,                  "frame_packing_arrangement_id" );
+  WRITE_FLAG( sei.m_arrangementCancelFlag,          "frame_packing_arrangement_cancel_flag" );
+
+  if( sei.m_arrangementCancelFlag == 0 ) {
+    WRITE_CODE( sei.m_arrangementType, 7,           "frame_packing_arrangement_type" );
+
+    WRITE_FLAG( sei.m_quincunxSamplingFlag,         "quincunx_sampling_flag" );
+    WRITE_CODE( sei.m_contentInterpretationType, 6, "content_interpretation_type" );
+    WRITE_FLAG( sei.m_spatialFlippingFlag,          "spatial_flipping_flag" );
+    WRITE_FLAG( sei.m_frame0FlippedFlag,            "frame0_flipped_flag" );
+    WRITE_FLAG( sei.m_fieldViewsFlag,               "field_views_flag" );
+    WRITE_FLAG( sei.m_currentFrameIsFrame0Flag,     "current_frame_is_frame0_flag" );
+
+    WRITE_FLAG( sei.m_frame0SelfContainedFlag,      "frame0_self_contained_flag" );
+    WRITE_FLAG( sei.m_frame1SelfContainedFlag,      "frame1_self_contained_flag" );
+
+    if(sei.m_quincunxSamplingFlag == 0 && sei.m_arrangementType != 5)
+    {
+      WRITE_CODE( sei.m_frame0GridPositionX, 4,     "frame0_grid_position_x" );
+      WRITE_CODE( sei.m_frame0GridPositionY, 4,     "frame0_grid_position_y" );
+      WRITE_CODE( sei.m_frame1GridPositionX, 4,     "frame1_grid_position_x" );
+      WRITE_CODE( sei.m_frame1GridPositionY, 4,     "frame1_grid_position_y" );
+    }
+
+    WRITE_CODE( sei.m_arrangementReservedByte, 8,   "frame_packing_arrangement_reserved_byte" );
+    WRITE_FLAG( sei.m_arrangementPersistenceFlag,   "frame_packing_arrangement_persistence_flag" );
+  }
+
+  WRITE_FLAG( sei.m_upsampledAspectRatio,           "upsampled_aspect_ratio" );
+}
+
+Void SEIWriter::xWriteSEISegmentedRectFramePacking(const SEISegmentedRectFramePacking& sei)
+{
+  WRITE_FLAG( sei.m_arrangementCancelFlag,          "segmented_rect_frame_packing_arrangement_cancel_flag" );
+  if( sei.m_arrangementCancelFlag == 0 ) 
+  {
+    WRITE_CODE( sei.m_contentInterpretationType, 2, "segmented_rect_content_interpretation_type" );
+    WRITE_FLAG( sei.m_arrangementPersistenceFlag,   "segmented_rect_frame_packing_arrangement_persistence" );
+  }
+}
+
+Void SEIWriter::xWriteSEIToneMappingInfo(const SEIToneMappingInfo& sei)
+{
+  Int i;
+  WRITE_UVLC( sei.m_toneMapId,                    "tone_map_id" );
+  WRITE_FLAG( sei.m_toneMapCancelFlag,            "tone_map_cancel_flag" );
+  if( !sei.m_toneMapCancelFlag )
+  {
+    WRITE_FLAG( sei.m_toneMapPersistenceFlag,     "tone_map_persistence_flag" );
+    WRITE_CODE( sei.m_codedDataBitDepth,    8,    "coded_data_bit_depth" );
+    WRITE_CODE( sei.m_targetBitDepth,       8,    "target_bit_depth" );
+    WRITE_UVLC( sei.m_modelId,                    "model_id" );
+    switch(sei.m_modelId)
+    {
+    case 0:
+      {
+        WRITE_CODE( sei.m_minValue,  32,        "min_value" );
+        WRITE_CODE( sei.m_maxValue, 32,         "max_value" );
+        break;
+      }
+    case 1:
+      {
+        WRITE_CODE( sei.m_sigmoidMidpoint, 32,  "sigmoid_midpoint" );
+        WRITE_CODE( sei.m_sigmoidWidth,    32,  "sigmoid_width"    );
+        break;
+      }
+    case 2:
+      {
+        UInt num = 1u << sei.m_targetBitDepth;
+        for(i = 0; i < num; i++)
+        {
+          WRITE_CODE( sei.m_startOfCodedInterval[i], (( sei.m_codedDataBitDepth + 7 ) >> 3 ) << 3,  "start_of_coded_interval" );
+        }
+        break;
+      }
+    case 3:
+      {
+        WRITE_CODE( sei.m_numPivots, 16,          "num_pivots" );
+        for(i = 0; i < sei.m_numPivots; i++ )
+        {
+          WRITE_CODE( sei.m_codedPivotValue[i], (( sei.m_codedDataBitDepth + 7 ) >> 3 ) << 3,       "coded_pivot_value" );
+          WRITE_CODE( sei.m_targetPivotValue[i], (( sei.m_targetBitDepth + 7 ) >> 3 ) << 3,         "target_pivot_value");
+        }
+        break;
+      }
+    case 4:
+      {
+        WRITE_CODE( sei.m_cameraIsoSpeedIdc,    8,    "camera_iso_speed_idc" );
+        if( sei.m_cameraIsoSpeedIdc == 255) //Extended_ISO
+        {
+          WRITE_CODE( sei.m_cameraIsoSpeedValue,    32,    "camera_iso_speed_value" );
+        }
+        WRITE_CODE( sei.m_exposureIndexIdc,     8,    "exposure_index_idc" );
+        if( sei.m_exposureIndexIdc == 255) //Extended_ISO
+        {
+          WRITE_CODE( sei.m_exposureIndexValue,     32,    "exposure_index_value" );
+        }
+        WRITE_FLAG( sei.m_exposureCompensationValueSignFlag,           "exposure_compensation_value_sign_flag" );
+        WRITE_CODE( sei.m_exposureCompensationValueNumerator,     16,  "exposure_compensation_value_numerator" );
+        WRITE_CODE( sei.m_exposureCompensationValueDenomIdc,      16,  "exposure_compensation_value_denom_idc" );
+        WRITE_CODE( sei.m_refScreenLuminanceWhite,                32,  "ref_screen_luminance_white" );
+        WRITE_CODE( sei.m_extendedRangeWhiteLevel,                32,  "extended_range_white_level" );
+        WRITE_CODE( sei.m_nominalBlackLevelLumaCodeValue,         16,  "nominal_black_level_luma_code_value" );
+        WRITE_CODE( sei.m_nominalWhiteLevelLumaCodeValue,         16,  "nominal_white_level_luma_code_value" );
+        WRITE_CODE( sei.m_extendedWhiteLevelLumaCodeValue,        16,  "extended_white_level_luma_code_value" );
+        break;
+      }
+    default:
+      {
+        assert(!"Undefined SEIToneMapModelId");
+        break;
+      }
+    }//switch m_modelId
+  }//if(!sei.m_toneMapCancelFlag)
+}
+
+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" );
+  }
+}
+
+Void SEIWriter::xWriteSEITemporalLevel0Index(const SEITemporalLevel0Index &sei)
+{
+  WRITE_CODE( sei.tl0Idx, 8 , "tl0_idx" );
+  WRITE_CODE( sei.rapIdx, 8 , "rap_idx" );
+}
+
+Void SEIWriter::xWriteSEIGradualDecodingRefreshInfo(const SEIGradualDecodingRefreshInfo &sei)
+{
+  WRITE_FLAG( sei.m_gdrForegroundFlag, "gdr_foreground_flag");
+}
+
+Void SEIWriter::xWriteSEINoDisplay(const SEINoDisplay &sei)
+{
+}
+
+Void SEIWriter::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"               );
+    }
+  }
+}
+
+#if O0164_MULTI_LAYER_HRD
+Void SEIWriter::xWriteSEIScalableNesting(TComBitIf& bs, const SEIScalableNesting& sei, TComVPS *vps, TComSPS *sps)
+#else
+Void SEIWriter::xWriteSEIScalableNesting(TComBitIf& bs, const SEIScalableNesting& sei, TComSPS *sps)
+#endif
+{
+  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_minus1"        );
+    for (UInt i = (sei.m_defaultOpFlag ? 1 : 0); i <= sei.m_nestingNumOpsMinus1; i++)
+    {
+      WRITE_CODE( sei.m_nestingMaxTemporalIdPlus1[i], 3,  "nesting_max_temporal_id_plus1" );
+      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_plus1" );
+      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++)
+  {
+#if O0164_MULTI_LAYER_HRD
+    writeSEImessage(bs, *(*it), vps, sps, &sei);
+#else
+    writeSEImessage(bs, *(*it), sps);
+#endif
+  }
+}
+
+Void SEIWriter::xWriteSEITempMotionConstrainedTileSets(TComBitIf& bs, const SEITempMotionConstrainedTileSets& sei)
+{
+  //UInt code;
+  WRITE_FLAG((sei.m_mc_all_tiles_exact_sample_value_match_flag ? 1 : 0), "mc_all_tiles_exact_sample_value_match_flag"); 
+  WRITE_FLAG((sei.m_each_tile_one_tile_set_flag                ? 1 : 0), "each_tile_one_tile_set_flag"               );
+
+  if(!sei.m_each_tile_one_tile_set_flag)
+  {
+    WRITE_FLAG((sei.m_limited_tile_set_display_flag ? 1 : 0), "limited_tile_set_display_flag");
+    WRITE_UVLC((sei.getNumberOfTileSets() - 1),               "num_sets_in_message_minus1"   );
+
+    if(sei.getNumberOfTileSets() > 0)
+    {
+      for(Int i = 0; i < sei.getNumberOfTileSets(); i++)
+      {
+        WRITE_UVLC(sei.tileSetData(i).m_mcts_id, "mcts_id");
+
+        if(sei.m_limited_tile_set_display_flag)
+        { 
+          WRITE_FLAG((sei.tileSetData(i).m_display_tile_set_flag ? 1 : 0), "display_tile_set_flag");  
+        }
+
+        WRITE_UVLC((sei.tileSetData(i).getNumberOfTileRects() - 1), "num_tile_rects_in_set_minus1"); 
+        
+        for(Int j = 0; j < sei.tileSetData(i).getNumberOfTileRects(); j++)
+        {
+          WRITE_UVLC(sei.tileSetData(i).topLeftTileIndex    (j), "top_left_tile_index");  
+          WRITE_UVLC(sei.tileSetData(i).bottomRightTileIndex(j), "bottom_right_tile_index");  
+        }
+
+        if(!sei.m_mc_all_tiles_exact_sample_value_match_flag)
+        {
+          WRITE_FLAG((sei.tileSetData(i).m_exact_sample_value_match_flag ? 1 : 0), "exact_sample_value_match_flag");  
+        }
+
+        WRITE_FLAG((sei.tileSetData(i).m_mcts_tier_level_idc_present_flag ? 1 : 0), "mcts_tier_level_idc_present_flag");
+
+        if(sei.tileSetData(i).m_mcts_tier_level_idc_present_flag)
+        {
+          WRITE_FLAG((sei.tileSetData(i).m_mcts_tier_flag ? 1 : 0), "mcts_tier_flag");
+          WRITE_CODE( sei.tileSetData(i).m_mcts_level_idc, 8,       "mcts_level_idc"); 
+        }
+      }
+    }
+  }
+  else
+  {
+    WRITE_FLAG((sei.m_max_mcs_tier_level_idc_present_flag ? 1 : 0), "max_mcs_tier_level_idc_present_flag");
+
+    if(sei.m_max_mcs_tier_level_idc_present_flag)
+    {
+      WRITE_FLAG((sei.m_max_mcts_tier_flag ? 1 : 0), "max_mcts_tier_flag");  
+      WRITE_CODE( sei.m_max_mcts_level_idc, 8,       "max_mcts_level_idc"); 
+    }
+  }
+}
+
+Void SEIWriter::xWriteSEITimeCode(const SEITimeCode& sei)
+{
+  WRITE_CODE(sei.numClockTs, 2, "num_clock_ts");
+  for(Int i = 0; i < sei.numClockTs; i++)
+  {
+    const TComSEITimeSet &currentTimeSet = sei.timeSetArray[i];
+    WRITE_FLAG(currentTimeSet.clockTimeStampFlag, "clock_time_stamp_flag");
+    if(currentTimeSet.clockTimeStampFlag)
+    {
+      WRITE_FLAG(currentTimeSet.numUnitFieldBasedFlag, "units_field_based_flag");
+      WRITE_CODE(currentTimeSet.countingType, 5, "counting_type");
+      WRITE_FLAG(currentTimeSet.fullTimeStampFlag, "full_timestamp_flag");
+      WRITE_FLAG(currentTimeSet.discontinuityFlag, "discontinuity_flag");
+      WRITE_FLAG(currentTimeSet.cntDroppedFlag, "cnt_dropped_flag");
+      WRITE_CODE(currentTimeSet.numberOfFrames, 9, "n_frames");
+      if(currentTimeSet.fullTimeStampFlag)
+      {
+        WRITE_CODE(currentTimeSet.secondsValue, 6, "seconds_value");
+        WRITE_CODE(currentTimeSet.minutesValue, 6, "minutes_value");
+        WRITE_CODE(currentTimeSet.hoursValue, 5, "hours_value");
+      }
+      else
+      {
+        WRITE_FLAG(currentTimeSet.secondsFlag, "seconds_flag");
+        if(currentTimeSet.secondsFlag)
+        {
+          WRITE_CODE(currentTimeSet.secondsValue, 6, "seconds_value");
+          WRITE_FLAG(currentTimeSet.minutesFlag, "minutes_flag");
+          if(currentTimeSet.minutesFlag)
+          {
+            WRITE_CODE(currentTimeSet.minutesValue, 6, "minutes_value");
+            WRITE_FLAG(currentTimeSet.hoursFlag, "hours_flag");
+            if(currentTimeSet.hoursFlag)
+              WRITE_CODE(currentTimeSet.hoursValue, 5, "hours_value");
+          }
+        }
+      }
+      WRITE_CODE(currentTimeSet.timeOffsetLength, 5, "time_offset_length");
+      if(currentTimeSet.timeOffsetLength > 0)
+      {
+        if(currentTimeSet.timeOffsetValue >= 0)
+        {
+          WRITE_CODE((UInt)currentTimeSet.timeOffsetValue, currentTimeSet.timeOffsetLength, "time_offset_value");
+        }
+        else
+        {
+          //  Two's complement conversion
+          UInt offsetValue = ~(currentTimeSet.timeOffsetValue) + 1;
+          offsetValue |= (1 << (currentTimeSet.timeOffsetLength-1));
+          WRITE_CODE(offsetValue, currentTimeSet.timeOffsetLength, "time_offset_value");
+        }
+      }
+    }
+  }
+}
+
+Void SEIWriter::xWriteSEIChromaSamplingFilterHint(const SEIChromaSamplingFilterHint &sei/*, TComSPS* sps*/)
+{
+  WRITE_CODE(sei.m_verChromaFilterIdc, 8, "ver_chroma_filter_idc");
+  WRITE_CODE(sei.m_horChromaFilterIdc, 8, "hor_chroma_filter_idc");
+  WRITE_FLAG(sei.m_verFilteringProcessFlag, "ver_filtering_process_flag");
+  if(sei.m_verChromaFilterIdc == 1 || sei.m_horChromaFilterIdc == 1)
+  {
+    writeUserDefinedCoefficients(sei);
+  }
+}
+
+// write hardcoded chroma filter coefficients in the SEI messages
+Void SEIWriter::writeUserDefinedCoefficients(const SEIChromaSamplingFilterHint &sei)
+{
+  Int const iNumVerticalFilters = 3;
+  Int verticalTapLength_minus1[iNumVerticalFilters] = {5,3,3};
+  Int* userVerticalCoefficients[iNumVerticalFilters];
+  for(Int i = 0; i < iNumVerticalFilters; i ++)
+  {
+    userVerticalCoefficients[i] = (Int*)malloc( (verticalTapLength_minus1[i]+1) * sizeof(Int));
+  }
+  userVerticalCoefficients[0][0] = -3;
+  userVerticalCoefficients[0][1] = 13;
+  userVerticalCoefficients[0][2] = 31;
+  userVerticalCoefficients[0][3] = 23;
+  userVerticalCoefficients[0][4] = 3;
+  userVerticalCoefficients[0][5] = -3;
+
+  userVerticalCoefficients[1][0] = -1;
+  userVerticalCoefficients[1][1] = 25;
+  userVerticalCoefficients[1][2] = 247;
+  userVerticalCoefficients[1][3] = -15;
+
+  userVerticalCoefficients[2][0] = -20;
+  userVerticalCoefficients[2][1] = 186;
+  userVerticalCoefficients[2][2] = 100;
+  userVerticalCoefficients[2][3] = -10;
+  
+  Int const iNumHorizontalFilters = 1;
+  Int horizontalTapLength_minus1[iNumHorizontalFilters] = {3};
+  Int* userHorizontalCoefficients[iNumHorizontalFilters];
+  for(Int i = 0; i < iNumHorizontalFilters; i ++)
+  {
+    userHorizontalCoefficients[i] = (Int*)malloc( (horizontalTapLength_minus1[i]+1) * sizeof(Int));
+  }
+  userHorizontalCoefficients[0][0] = 1;
+  userHorizontalCoefficients[0][1] = 6;
+  userHorizontalCoefficients[0][2] = 1;
+
+  WRITE_UVLC(3, "target_format_idc");
+  if(sei.m_verChromaFilterIdc == 1)
+  {
+    WRITE_UVLC(iNumVerticalFilters, "num_vertical_filters");
+    if(iNumVerticalFilters > 0)
+    {
+      for(Int i = 0; i < iNumVerticalFilters; i ++)
+      {
+        WRITE_UVLC(verticalTapLength_minus1[i], "ver_tap_length_minus_1");
+        for(Int j = 0; j < verticalTapLength_minus1[i]; j ++)
+        {
+          WRITE_SVLC(userVerticalCoefficients[i][j], "ver_filter_coeff");
+        }
+      }
+    }
+  }
+  if(sei.m_horChromaFilterIdc == 1)
+  {
+    WRITE_UVLC(iNumHorizontalFilters, "num_horizontal_filters");
+    if(iNumHorizontalFilters > 0)
+    {
+      for(Int i = 0; i < iNumHorizontalFilters; i ++)
+      {
+        WRITE_UVLC(horizontalTapLength_minus1[i], "hor_tap_length_minus_1");
+        for(Int j = 0; j < horizontalTapLength_minus1[i]; j ++)
+        {
+          WRITE_SVLC(userHorizontalCoefficients[i][j], "hor_filter_coeff");
+        }
+      }
+    }
+  }
+}
+
+Void SEIWriter::xWriteSEIKneeFunctionInfo(const SEIKneeFunctionInfo &sei)
+{
+  WRITE_UVLC( sei.m_kneeId, "knee_function_id" );
+  WRITE_FLAG( sei.m_kneeCancelFlag, "knee_function_cancel_flag" ); 
+  if ( !sei.m_kneeCancelFlag )
+  {
+    WRITE_FLAG( sei.m_kneePersistenceFlag, "knee_function_persistence_flag" );
+    WRITE_CODE( (UInt)sei.m_kneeInputDrange , 32,  "input_d_range" );
+    WRITE_CODE( (UInt)sei.m_kneeInputDispLuminance, 32,  "input_disp_luminance" );
+    WRITE_CODE( (UInt)sei.m_kneeOutputDrange, 32,  "output_d_range" );
+    WRITE_CODE( (UInt)sei.m_kneeOutputDispLuminance, 32,  "output_disp_luminance" );
+    WRITE_UVLC( sei.m_kneeNumKneePointsMinus1, "num_knee_points_minus1" );
+    for(Int i = 0; i <= sei.m_kneeNumKneePointsMinus1; i++ )
+    {
+      WRITE_CODE( (UInt)sei.m_kneeInputKneePoint[i], 10,"input_knee_point" );
+      WRITE_CODE( (UInt)sei.m_kneeOutputKneePoint[i], 10, "output_knee_point" );
+    }
+  }
+}
+
+
+Void SEIWriter::xWriteSEIMasteringDisplayColourVolume(const SEIMasteringDisplayColourVolume& sei)
+{
+  WRITE_CODE( sei.values.primaries[0][0],  16,  "display_primaries_x[0]" );
+  WRITE_CODE( sei.values.primaries[0][1],  16,  "display_primaries_y[0]" );
+
+  WRITE_CODE( sei.values.primaries[1][0],  16,  "display_primaries_x[1]" );
+  WRITE_CODE( sei.values.primaries[1][1],  16,  "display_primaries_y[1]" );
+
+  WRITE_CODE( sei.values.primaries[2][0],  16,  "display_primaries_x[2]" );
+  WRITE_CODE( sei.values.primaries[2][1],  16,  "display_primaries_y[2]" );
+
+  WRITE_CODE( sei.values.whitePoint[0],    16,  "white_point_x" );
+  WRITE_CODE( sei.values.whitePoint[1],    16,  "white_point_y" );
+    
+  WRITE_CODE( sei.values.maxLuminance,     32,  "max_display_mastering_luminance" );
+  WRITE_CODE( sei.values.minLuminance,     32,  "min_display_mastering_luminance" );
+}
+
+
+Void SEIWriter::xWriteByteAlign()
+{
+  if( m_pcBitIf->getNumberOfWrittenBits() % 8 != 0)
+  {
+    WRITE_FLAG( 1, "payload_bit_equal_to_one" );
+    while( m_pcBitIf->getNumberOfWrittenBits() % 8 != 0 )
+    {
+      WRITE_FLAG( 0, "payload_bit_equal_to_zero" );
+    }
+  }
+}
+
+#if SVC_EXTENSION
+#if LAYERS_NOT_PRESENT_SEI
+Void SEIWriter::xWriteSEILayersNotPresent(const SEILayersNotPresent& sei)
+{
+  WRITE_UVLC( sei.m_activeVpsId,           "lp_sei_active_vps_id" );
+  for (UInt i = 0; i < sei.m_vpsMaxLayers; i++)
+  {
+    WRITE_FLAG( sei.m_layerNotPresentFlag[i], "layer_not_present_flag"   );
+  }  
+}
+#endif
+
+#if N0383_IL_CONSTRAINED_TILE_SETS_SEI
+Void SEIWriter::xWriteSEIInterLayerConstrainedTileSets(const SEIInterLayerConstrainedTileSets& sei)
+{
+  WRITE_FLAG( sei.m_ilAllTilesExactSampleValueMatchFlag,  "il_all_tiles_exact_sample_value_match_flag"   );
+  WRITE_FLAG( sei.m_ilOneTilePerTileSetFlag,              "il_one_tile_per_tile_set_flag"                );
+  if( !sei.m_ilOneTilePerTileSetFlag )
+  {
+    WRITE_UVLC( sei.m_ilNumSetsInMessageMinus1,             "il_num_sets_in_message_minus1"                );
+    if( sei.m_ilNumSetsInMessageMinus1 )
+    {
+      WRITE_FLAG( sei.m_skippedTileSetPresentFlag,            "skipped_tile_set_present_flag"                );
+    }
+    UInt numSignificantSets = sei.m_ilNumSetsInMessageMinus1 - (sei.m_skippedTileSetPresentFlag ? 1 : 0) + 1;
+    for( UInt i = 0; i < numSignificantSets; i++ )
+    {
+      WRITE_UVLC( sei.m_ilctsId[i],                           "ilcts_id"                                     );
+      WRITE_UVLC( sei.m_ilNumTileRectsInSetMinus1[i],         "il_num_tile_rects_in_set_minus1"              );
+      for( UInt j = 0; j <= sei.m_ilNumTileRectsInSetMinus1[i]; j++ )
+      {
+        WRITE_UVLC( sei.m_ilTopLeftTileIndex[i][j],             "il_top_left_tile_index"                       );
+        WRITE_UVLC( sei.m_ilBottomRightTileIndex[i][j],         "il_bottom_right_tile_index"                   );
+      }
+      WRITE_CODE( sei.m_ilcIdc[i], 2,                         "ilc_idc"                                      );
+      if( sei.m_ilAllTilesExactSampleValueMatchFlag )
+      {
+        WRITE_FLAG( sei.m_ilExactSampleValueMatchFlag[i],        "il_exact_sample_value_match_flag"            );
+      }
+    }
+  }
+  else
+  {
+    WRITE_CODE( sei.m_allTilesIlcIdc, 2,                    "all_tiles_ilc_idc"                          );
+  }
+}
+#endif
+#if SUB_BITSTREAM_PROPERTY_SEI
+Void SEIWriter::xWriteSEISubBitstreamProperty(const SEISubBitstreamProperty &sei)
+{
+  WRITE_CODE( sei.m_activeVpsId, 4, "active_vps_id" );
+  assert( sei.m_numAdditionalSubStreams >= 1 );
+  WRITE_UVLC( sei.m_numAdditionalSubStreams - 1, "num_additional_sub_streams_minus1" );
+
+  for( Int i = 0; i < sei.m_numAdditionalSubStreams; i++ )
+  {
+    WRITE_CODE( sei.m_subBitstreamMode[i],       2, "sub_bitstream_mode[i]"           );
+    WRITE_UVLC( sei.m_outputLayerSetIdxToVps[i],    "output_layer_set_idx_to_vps[i]"  );
+    WRITE_CODE( sei.m_highestSublayerId[i],      3, "highest_sub_layer_id[i]"         );
+    WRITE_CODE( sei.m_avgBitRate[i],            16, "avg_bit_rate[i]"                 );
+    WRITE_CODE( sei.m_maxBitRate[i],            16, "max_bit_rate[i]"                 );
+  }  
+}
+#endif
+
+#if Q0189_TMVP_CONSTRAINTS 
+Void SEIWriter::xWriteSEITMVPConstraints (const SEITMVPConstrains &sei)
+{
+  WRITE_UVLC( sei.prev_pics_not_used_flag ,    "prev_pics_not_used_flag"  );
+  WRITE_UVLC( sei.no_intra_layer_col_pic_flag ,    "no_intra_layer_col_pic_flag"  ); 
+}
+#endif
+
+#if Q0247_FRAME_FIELD_INFO
+Void SEIWriter::xWriteSEIFrameFieldInfo  (const SEIFrameFieldInfo &sei)
+{
+  WRITE_CODE( sei.m_ffinfo_picStruct , 4,             "ffinfo_pic_struct" );
+  WRITE_CODE( sei.m_ffinfo_sourceScanType, 2,         "ffinfo_source_scan_type" );
+  WRITE_FLAG( sei.m_ffinfo_duplicateFlag ? 1 : 0,     "ffinfo_duplicate_flag" );
+}
+#endif
+
+#if O0164_MULTI_LAYER_HRD
+Void SEIWriter::xWriteSEIBspNesting(TComBitIf& bs, const SEIBspNesting &sei, TComVPS *vps, TComSPS *sps, const SEIScalableNesting &nestingSei)
+{
+  WRITE_UVLC( sei.m_bspIdx, "bsp_idx" );
+
+  while ( m_pcBitIf->getNumberOfWrittenBits() % 8 != 0 )
+  {
+    WRITE_FLAG( 0, "bsp_nesting_zero_bit" );
+  }
+#if NESTING_SEI_EXTENSIBILITY
+  assert( sei.m_nestedSEIs.size() <= MAX_SEIS_IN_BSP_NESTING );
+  WRITE_UVLC( (UInt)sei.m_nestedSEIs.size(), "num_seis_in_bsp_minus1" );
+#endif
+  // write nested SEI messages
+  for (SEIMessages::const_iterator it = sei.m_nestedSEIs.begin(); it != sei.m_nestedSEIs.end(); it++)
+  {
+    writeSEImessage(bs, *(*it), vps, sps, &nestingSei, &sei);
+  }
+}
+
+Void SEIWriter::xWriteSEIBspInitialArrivalTime(const SEIBspInitialArrivalTime &sei, TComVPS *vps, TComSPS *sps, const SEIScalableNesting &nestingSei, const SEIBspNesting &bspNestingSei)
+{
+  assert(vps->getVpsVuiPresentFlag());
+
+#if VPS_VUI_BSP_HRD_PARAMS
+  Int psIdx = bspNestingSei.m_seiPartitioningSchemeIdx;
+  Int seiOlsIdx = bspNestingSei.m_seiOlsIdx;
+  Int maxTemporalId = nestingSei.m_nestingMaxTemporalIdPlus1[0] - 1;
+  Int maxValues = vps->getNumBspSchedulesMinus1(seiOlsIdx, psIdx, maxTemporalId) + 1;
+  std::vector<Int> hrdIdx(maxValues, 0);
+  std::vector<TComHRD *> hrdVec;
+  std::vector<Int> syntaxElemLen(maxValues, 0);
+  for(Int i = 0; i < maxValues; i++)
+  {
+    hrdIdx[i] = vps->getBspHrdIdx( seiOlsIdx, psIdx, maxTemporalId, i, bspNestingSei.m_bspIdx);
+    hrdVec.push_back(vps->getBspHrd(hrdIdx[i]));
+    
+    syntaxElemLen[i] = hrdVec[i]->getInitialCpbRemovalDelayLengthMinus1() + 1;
+    if ( !(hrdVec[i]->getNalHrdParametersPresentFlag() || hrdVec[i]->getVclHrdParametersPresentFlag()) )
+    {
+      assert( syntaxElemLen[i] == 24 ); // Default of value init_cpb_removal_delay_length_minus1 is 23
+    }
+    if( i > 0 )
+    {
+      assert( hrdVec[i]->getNalHrdParametersPresentFlag() == hrdVec[i-1]->getNalHrdParametersPresentFlag() );
+      assert( hrdVec[i]->getVclHrdParametersPresentFlag() == hrdVec[i-1]->getVclHrdParametersPresentFlag() );
+    }
+  }
+  if (hrdVec[0]->getNalHrdParametersPresentFlag())
+  {
+    for(UInt i = 0; i < maxValues; i++)
+    {
+      WRITE_CODE( sei.m_nalInitialArrivalDelay[i], syntaxElemLen[i], "nal_initial_arrival_delay[i]" );
+    }
+  }
+  if( hrdVec[0]->getVclHrdParametersPresentFlag() )
+  {
+    for(UInt i = 0; i < maxValues; i++)
+    {
+      WRITE_CODE( sei.m_vclInitialArrivalDelay[i], syntaxElemLen[i], "vcl_initial_arrival_delay[i]" );
+    }
+  }
+#else
+  UInt schedCombCnt = vps->getNumBspSchedCombinations(nestingSei.m_nestingOpIdx[0]);
+  UInt len;
+  UInt hrdIdx;
+
+  if (schedCombCnt > 0)
+  {
+    hrdIdx = vps->getBspCombHrdIdx(nestingSei.m_nestingOpIdx[0], 0, bspNestingSei.m_bspIdx);
+  }
+  else
+  {
+    hrdIdx = 0;
+  }
+
+  TComHRD *hrd = vps->getBspHrd(hrdIdx);
+
+  if (hrd->getNalHrdParametersPresentFlag() || hrd->getVclHrdParametersPresentFlag())
+  {
+    len = hrd->getInitialCpbRemovalDelayLengthMinus1() + 1;
+  }
+  else
+  {
+    len = 23 + 1;
+  }
+
+  if (hrd->getNalHrdParametersPresentFlag())
+  {
+    for(UInt i = 0; i < schedCombCnt; i++)
+    {
+      WRITE_CODE( sei.m_nalInitialArrivalDelay[i], len, "nal_initial_arrival_delay" );
+    }
+  }
+#if BSP_INIT_ARRIVAL_SEI
+  if( hrd->getVclHrdParametersPresentFlag() )
+#else
+  else
+#endif
+  {
+    for(UInt i = 0; i < schedCombCnt; i++)
+    {
+      WRITE_CODE( sei.m_vclInitialArrivalDelay[i], len, "vcl_initial_arrival_delay" );
+    }
+  }
+#endif
+}
+
+#if !REMOVE_BSP_HRD_SEI
+Void SEIWriter::xWriteSEIBspHrd(const SEIBspHrd &sei, TComSPS *sps, const SEIScalableNesting &nestingSei)
+{
+  WRITE_UVLC( sei.m_seiNumBspHrdParametersMinus1, "sei_num_bsp_hrd_parameters_minus1" );
+  for (UInt i = 0; i <= sei.m_seiNumBspHrdParametersMinus1; i++)
+  {
+    if (i > 0)
+    {
+      WRITE_FLAG( sei.m_seiBspCprmsPresentFlag[i], "sei_bsp_cprms_present_flag" );
+    }
+    xCodeHrdParameters(sei.hrd, i==0 ? 1 : sei.m_seiBspCprmsPresentFlag[i], nestingSei.m_nestingMaxTemporalIdPlus1[0]-1);
+  }
+  for (UInt h = 0; h <= nestingSei.m_nestingNumOpsMinus1; h++)
+  {
+    UInt lsIdx = nestingSei.m_nestingOpIdx[h];
+    WRITE_UVLC( sei.m_seiNumBitstreamPartitionsMinus1[lsIdx], "num_sei_bitstream_partitions_minus1[i]");
+    for (UInt i = 0; i <= sei.m_seiNumBitstreamPartitionsMinus1[lsIdx]; i++)
+    {
+#if HRD_BPB
+      UInt nl=0;
+      for (UInt j = 0; j < sei.m_vpsMaxLayers; j++)
+      {
+        if (sei.m_layerIdIncludedFlag[lsIdx][j])
+        {
+          nl++;
+        }
+      }
+      for (UInt j = 0; j < nl; j++)
+      {
+#else
+      for (UInt j = 0; j < sei.m_vpsMaxLayers; j++)
+      {
+        if (sei.m_layerIdIncludedFlag[lsIdx][j])
+        {
+#endif
+          WRITE_FLAG( sei.m_seiLayerInBspFlag[lsIdx][i][j], "sei_layer_in_bsp_flag[lsIdx][i][j]" );
+        }
+#if !HRD_BPB
+      }
+#endif
+    }
+    WRITE_UVLC( sei.m_seiNumBspSchedCombinationsMinus1[lsIdx], "sei_num_bsp_sched_combinations_minus1[i]");
+    for (UInt i = 0; i <= sei.m_seiNumBspSchedCombinationsMinus1[lsIdx]; i++)
+    {
+      for (UInt j = 0; j <= sei.m_seiNumBitstreamPartitionsMinus1[lsIdx]; j++)
+      {
+        WRITE_UVLC( sei.m_seiBspCombHrdIdx[lsIdx][i][j], "sei_bsp_comb_hrd_idx[lsIdx][i][j]");
+        WRITE_UVLC( sei.m_seiBspCombScheddx[lsIdx][i][j], "sei_bsp_comb_sched_idx[lsIdx][i][j]");
+      }
+    }
+  }
+}
+#endif
+
+Void SEIWriter::xCodeHrdParameters( 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");
+        }
+      }
+    }
+  }
+}
+
+#endif
+
+#if Q0078_ADD_LAYER_SETS
+
+Void SEIWriter::xWriteSEIOutputLayerSetNesting(TComBitIf& bs, const SEIOutputLayerSetNesting &sei, TComVPS *vps, TComSPS *sps)
+{
+  WRITE_FLAG(sei.m_olsFlag, "ols_flag");
+  WRITE_UVLC(sei.m_numOlsIndicesMinus1, "num_ols_indices_minus1");
+
+  for (Int i = 0; i <= sei.m_numOlsIndicesMinus1; i++)
+  {
+    WRITE_UVLC(sei.m_olsIdx[i], "ols_idx[i]");
+  }
+
+  while (m_pcBitIf->getNumberOfWrittenBits() % 8 != 0)
+  {
+    WRITE_FLAG(0, "ols_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), vps, sps);
+  }
+}
+
+Void SEIWriter::xWriteSEIVPSRewriting(const SEIVPSRewriting &sei)
+{
+  //sei.nalu->
+}
+
+#endif
+
+#if P0123_ALPHA_CHANNEL_SEI
+Void SEIWriter::xWriteSEIAlphaChannelInfo(const SEIAlphaChannelInfo &sei)
+{
+  WRITE_FLAG(sei.m_alphaChannelCancelFlag, "alpha_channel_cancel_flag");
+  if(!sei.m_alphaChannelCancelFlag)
+  {
+    WRITE_CODE(sei.m_alphaChannelUseIdc, 3, "alpha_channel_use_idc");
+    WRITE_CODE(sei.m_alphaChannelBitDepthMinus8, 3, "alpha_channel_bit_depth_minus8");
+    WRITE_CODE(sei.m_alphaTransparentValue, sei.m_alphaChannelBitDepthMinus8 + 9, "alpha_transparent_value");
+    WRITE_CODE(sei.m_alphaOpaqueValue, sei.m_alphaChannelBitDepthMinus8 + 9, "alpha_opaque_value");
+    WRITE_FLAG(sei.m_alphaChannelIncrFlag, "alpha_channel_incr_flag");
+    WRITE_FLAG(sei.m_alphaChannelClipFlag, "alpha_channel_clip_flag");
+    if(sei.m_alphaChannelClipFlag)
+    {
+      WRITE_FLAG(sei.m_alphaChannelClipTypeFlag, "alpha_channel_clip_type_flag");
+    }
+  }
+  xWriteByteAlign();
+}
+#endif
+
+#if Q0096_OVERLAY_SEI
+Void SEIWriter::xWriteSEIOverlayInfo(const SEIOverlayInfo &sei)
+{
+  Int i,j;
+  WRITE_FLAG( sei.m_overlayInfoCancelFlag, "overlay_info_cancel_flag" );
+  if ( !sei.m_overlayInfoCancelFlag )
+  {
+    WRITE_UVLC( sei.m_overlayContentAuxIdMinus128, "overlay_content_aux_id_minus128" );
+    WRITE_UVLC( sei.m_overlayLabelAuxIdMinus128, "overlay_label_aux_id_minus128" );
+    WRITE_UVLC( sei.m_overlayAlphaAuxIdMinus128, "overlay_alpha_aux_id_minus128" );
+    WRITE_UVLC( sei.m_overlayElementLabelValueLengthMinus8, "overlay_element_label_value_length_minus8" );
+    assert( sei.m_numOverlaysMinus1 < MAX_OVERLAYS );
+    WRITE_UVLC( sei.m_numOverlaysMinus1, "num_overlays_minus1" );
+    for (i=0 ; i<=sei.m_numOverlaysMinus1 ; i++)
+    {
+      WRITE_UVLC( sei.m_overlayIdx[i], "overlay_idx" );
+      WRITE_FLAG( sei.m_languageOverlayPresentFlag[i], "language_overlay_present_flag" );
+      WRITE_CODE( sei.m_overlayContentLayerId[i], 6, "overlay_content_layer_id");
+      WRITE_FLAG( sei.m_overlayLabelPresentFlag[i], "overlay_label_present_flag" );
+      if ( sei.m_overlayLabelPresentFlag[i] )
+      {
+        WRITE_CODE(  sei.m_overlayLabelLayerId[i], 6, "overlay_label_layer_id");
+      }
+      WRITE_FLAG( sei.m_overlayAlphaPresentFlag[i], "overlay_alpha_present_flag" );
+      if ( sei.m_overlayAlphaPresentFlag[i] )
+      {
+        WRITE_CODE( sei.m_overlayAlphaLayerId[i], 6, "overlay_alpha_layer_id");
+      }
+      if ( sei.m_overlayLabelPresentFlag[i] )
+      {
+        assert( sei.m_numOverlayElementsMinus1[i] < MAX_OVERLAY_ELEMENTS );
+        WRITE_UVLC( sei.m_numOverlayElementsMinus1[i], "num_overlay_elements_minus1");
+        for ( j=0 ; j<=sei.m_numOverlayElementsMinus1[i] ; j++ )
+        {
+          WRITE_CODE(sei.m_overlayElementLabelMin[i][j], sei.m_overlayElementLabelValueLengthMinus8 + 8, "overlay_element_label_min");
+          WRITE_CODE(sei.m_overlayElementLabelMax[i][j], sei.m_overlayElementLabelValueLengthMinus8 + 8, "overlay_element_label_max"); 
+        }
+      }
+    }
+
+
+    // byte alignment
+    while ( m_pcBitIf->getNumberOfWrittenBits() % 8 != 0 )
+    {
+      WRITE_FLAG( 0, "overlay_zero_bit" );
+    }
+
+    for ( i=0 ; i<=sei.m_numOverlaysMinus1 ; i++ )
+    {
+      if ( sei.m_languageOverlayPresentFlag[i] )
+      {
+        WRITE_STRING( sei.m_overlayLanguage[i], sei.m_overlayLanguageLength[i], "overlay_language" );    //WRITE_STRING adds zero-termination byte
+      }
+      WRITE_STRING( sei.m_overlayName[i], sei.m_overlayNameLength[i], "overlay_name" );
+      if ( sei.m_overlayLabelPresentFlag[i] )
+      {
+        for ( j=0 ; j<=sei.m_numOverlayElementsMinus1[i] ; j++)
+        {
+          WRITE_STRING( sei.m_overlayElementName[i][j], sei.m_overlayElementNameLength[i][j], "overlay_element_name" );
+        }
+      }
+    }
+    WRITE_FLAG( sei.m_overlayInfoPersistenceFlag, "overlay_info_persistence_flag" );
+  }
+}
+#endif
+
+#endif //SVC_EXTENSION
+
+#if Q0074_COLOUR_REMAPPING_SEI
+Void SEIWriter::xWriteSEIColourRemappingInfo(const SEIColourRemappingInfo& sei)
+{
+  WRITE_UVLC( sei.m_colourRemapId,                             "colour_remap_id" );
+  WRITE_FLAG( sei.m_colourRemapCancelFlag,                     "colour_remap_cancel_flag" );
+  if( !sei.m_colourRemapCancelFlag ) 
+  {
+    WRITE_FLAG( sei.m_colourRemapPersistenceFlag,              "colour_remap_persistence_flag" );
+    WRITE_FLAG( sei.m_colourRemapVideoSignalInfoPresentFlag,   "colour_remap_video_signal_info_present_flag" );
+    if ( sei.m_colourRemapVideoSignalInfoPresentFlag )
+    {
+      WRITE_FLAG( sei.m_colourRemapFullRangeFlag,              "colour_remap_full_range_flag" );
+      WRITE_CODE( sei.m_colourRemapPrimaries,               8, "colour_remap_primaries" );
+      WRITE_CODE( sei.m_colourRemapTransferFunction,        8, "colour_remap_transfer_function" );
+      WRITE_CODE( sei.m_colourRemapMatrixCoefficients,      8, "colour_remap_matrix_coefficients" );
+    }
+    WRITE_CODE( sei.m_colourRemapInputBitDepth,             8, "colour_remap_input_bit_depth" );
+    WRITE_CODE( sei.m_colourRemapBitDepth,                  8, "colour_remap_bit_depth" );
+    for( Int c=0 ; c<3 ; c++ )
+    {
+      WRITE_CODE( sei.m_preLutNumValMinus1[c],              8, "pre_lut_num_val_minus1[c]" );
+      if( sei.m_preLutNumValMinus1[c]>0 )
+        for( Int i=0 ; i<=sei.m_preLutNumValMinus1[c] ; i++ )
+        {
+          WRITE_CODE( sei.m_preLutCodedValue[c][i], (( sei.m_colourRemapInputBitDepth + 7 ) >> 3 ) << 3, "pre_lut_coded_value[c][i]" );
+          WRITE_CODE( sei.m_preLutTargetValue[c][i], (( sei.m_colourRemapBitDepth + 7 ) >> 3 ) << 3, "pre_lut_target_value[c][i]" );
+        }
+    }
+    WRITE_FLAG( sei.m_colourRemapMatrixPresentFlag,            "colour_remap_matrix_present_flag" );
+    if( sei.m_colourRemapMatrixPresentFlag )
+    {
+      WRITE_CODE( sei.m_log2MatrixDenom,                    4, "log2_matrix_denom" );
+      for( Int c=0 ; c<3 ; c++ )
+        for( Int i=0 ; i<3 ; i++ )
+          WRITE_SVLC( sei.m_colourRemapCoeffs[c][i],           "colour_remap_coeffs[c][i]" );
+    }
+
+    for( Int c=0 ; c<3 ; c++ )
+    {
+      WRITE_CODE( sei.m_postLutNumValMinus1[c],             8, "m_postLutNumValMinus1[c]" );
+      if( sei.m_postLutNumValMinus1[c]>0 )
+        for( Int i=0 ; i<=sei.m_postLutNumValMinus1[c] ; i++ )
+        {
+          WRITE_CODE( sei.m_postLutCodedValue[c][i], (( sei.m_colourRemapBitDepth + 7 ) >> 3 ) << 3, "post_lut_coded_value[c][i]" );       
+          WRITE_CODE( sei.m_postLutTargetValue[c][i], (( sei.m_colourRemapBitDepth + 7 ) >> 3 ) << 3, "post_lut_target_value[c][i]" );
+        }
+    }
+  }
+}
+#endif
+
+//! \}
Index: /tags/SHM-9.0/source/Lib/TLibEncoder/SEIwrite.h
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibEncoder/SEIwrite.h	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibEncoder/SEIwrite.h	(revision 1088)
@@ -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-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#pragma once
+
+#ifndef __SEIWRITE__
+#define __SEIWRITE__
+
+#include "SyntaxElementWriter.h"
+#include "TLibCommon/SEI.h"
+
+class TComBitIf;
+
+//! \ingroup TLibEncoder
+//! \{
+class SEIWriter:public SyntaxElementWriter
+{
+public:
+  SEIWriter() {};
+  virtual ~SEIWriter() {};
+
+#if O0164_MULTI_LAYER_HRD
+  Void writeSEImessage(TComBitIf& bs, const SEI& sei, TComVPS *vps, TComSPS *sps, const SEIScalableNesting* nestingSei=NULL, const SEIBspNesting* bspNestingSei=NULL);
+#else
+  Void writeSEImessage(TComBitIf& bs, const SEI& sei, TComSPS *sps);
+#endif
+
+protected:
+#if O0164_MULTI_LAYER_HRD
+#if VPS_VUI_BSP_HRD_PARAMS
+  Void xWriteSEIpayloadData(TComBitIf& bs, const SEI& sei, TComVPS *vps, TComSPS *sps, const SEIScalableNesting* nestingSei, const SEIBspNesting* bspNestingSei);
+#else
+  Void xWriteSEIpayloadData(TComBitIf& bs, const SEI& sei, TComVPS *vps, TComSPS *sps, const SEIScalableNesting& nestingSei, const SEIBspNesting& bspNestingSei);
+#endif
+#else
+  Void xWriteSEIpayloadData(TComBitIf& bs, const SEI& sei, TComSPS *sps);
+#endif
+  Void xWriteSEIuserDataUnregistered(const SEIuserDataUnregistered &sei);
+  Void xWriteSEIActiveParameterSets(const SEIActiveParameterSets& sei);
+  Void xWriteSEIDecodedPictureHash(const SEIDecodedPictureHash& sei);
+#if VPS_VUI_BSP_HRD_PARAMS
+  Void xWriteSEIDecodingUnitInfo(const SEIDecodingUnitInfo& sei, TComSPS *sps, const SEIScalableNesting* nestingSei, const SEIBspNesting* bspNestingSei, TComVPS *vps);
+  Void xWriteSEIBufferingPeriod(const SEIBufferingPeriod& sei, TComSPS *sps, const SEIScalableNesting* nestingSei, const SEIBspNesting* bspNestingSei, TComVPS *vps);
+  Void xWriteSEIPictureTiming(const SEIPictureTiming& sei, TComSPS *sps, const SEIScalableNesting* nestingSei, const SEIBspNesting* bspNestingSei, TComVPS *vps);
+#else
+  Void xWriteSEIDecodingUnitInfo(const SEIDecodingUnitInfo& sei, TComSPS *sps);
+  Void xWriteSEIBufferingPeriod(const SEIBufferingPeriod& sei, TComSPS *sps);
+  Void xWriteSEIPictureTiming(const SEIPictureTiming& sei, TComSPS *sps);
+#endif
+  TComSPS *m_pSPS;
+  Void xWriteSEIRecoveryPoint(const SEIRecoveryPoint& sei);
+  Void xWriteSEIFramePacking(const SEIFramePacking& sei);
+  Void xWriteSEISegmentedRectFramePacking(const SEISegmentedRectFramePacking& sei);
+  Void xWriteSEIDisplayOrientation(const SEIDisplayOrientation &sei);
+  Void xWriteSEITemporalLevel0Index(const SEITemporalLevel0Index &sei);
+  Void xWriteSEIGradualDecodingRefreshInfo(const SEIGradualDecodingRefreshInfo &sei);
+  Void xWriteSEINoDisplay(const SEINoDisplay &sei);
+  Void xWriteSEIToneMappingInfo(const SEIToneMappingInfo& sei);
+  Void xWriteSEISOPDescription(const SEISOPDescription& sei);
+#if O0164_MULTI_LAYER_HRD
+  Void xWriteSEIScalableNesting(TComBitIf& bs, const SEIScalableNesting& sei, TComVPS *vps, TComSPS *sps);
+#else
+  Void xWriteSEIScalableNesting(TComBitIf& bs, const SEIScalableNesting& sei, TComSPS *sps);
+#endif
+  Void xWriteSEITempMotionConstrainedTileSets(TComBitIf& bs, const SEITempMotionConstrainedTileSets& sei);
+  Void xWriteSEITimeCode(const SEITimeCode& sei);
+  Void xWriteSEIChromaSamplingFilterHint(const SEIChromaSamplingFilterHint& sei/*, TComSPS *sps*/);
+  Void writeUserDefinedCoefficients(const SEIChromaSamplingFilterHint& sei);
+  Void xWriteSEIKneeFunctionInfo(const SEIKneeFunctionInfo &sei);
+  Void xWriteSEIMasteringDisplayColourVolume( const SEIMasteringDisplayColourVolume& sei);
+  Void xWriteByteAlign();
+#if Q0074_COLOUR_REMAPPING_SEI
+  Void xWriteSEIColourRemappingInfo(const SEIColourRemappingInfo& sei);
+#endif
+#if SVC_EXTENSION
+#if LAYERS_NOT_PRESENT_SEI
+  Void xWriteSEILayersNotPresent(const SEILayersNotPresent& sei);
+#endif
+#if N0383_IL_CONSTRAINED_TILE_SETS_SEI
+  Void xWriteSEIInterLayerConstrainedTileSets(const SEIInterLayerConstrainedTileSets& sei);
+#endif
+#if SUB_BITSTREAM_PROPERTY_SEI
+  Void xWriteSEISubBitstreamProperty(const SEISubBitstreamProperty &sei);
+#endif
+#if Q0189_TMVP_CONSTRAINTS 
+Void xWriteSEITMVPConstraints (const SEITMVPConstrains &sei);
+#endif
+#if Q0247_FRAME_FIELD_INFO
+  Void xWriteSEIFrameFieldInfo  (const SEIFrameFieldInfo &sei);
+#endif
+#if O0164_MULTI_LAYER_HRD
+  Void xWriteSEIBspNesting(TComBitIf& bs, const SEIBspNesting &sei, TComVPS *vps, TComSPS *sps, const SEIScalableNesting &nestingSei);
+  Void xWriteSEIBspInitialArrivalTime(const SEIBspInitialArrivalTime &sei, TComVPS *vps, TComSPS *sps, const SEIScalableNesting &nestingSei, const SEIBspNesting &bspNestingSei);
+#if !REMOVE_BSP_HRD_SEI
+  Void xWriteSEIBspHrd(const SEIBspHrd &sei, TComSPS *sps, const SEIScalableNesting &nestingSei);
+#endif
+  Void xCodeHrdParameters( TComHRD *hrd, Bool commonInfPresentFlag, UInt maxNumSubLayersMinus1 );
+#endif
+#if Q0078_ADD_LAYER_SETS
+  Void xWriteSEIOutputLayerSetNesting(TComBitIf& bs, const SEIOutputLayerSetNesting &sei, TComVPS *vps, TComSPS *sps);
+  Void xWriteSEIVPSRewriting(const SEIVPSRewriting &sei);
+#endif
+#if P0123_ALPHA_CHANNEL_SEI
+  Void xWriteSEIAlphaChannelInfo(const SEIAlphaChannelInfo &sei);
+#endif
+#if Q0096_OVERLAY_SEI
+  Void xWriteSEIOverlayInfo(const SEIOverlayInfo &sei);
+#endif
+#endif //SVC_EXTENSION
+};
+
+//! \}
+
+#endif
Index: /tags/SHM-9.0/source/Lib/TLibEncoder/SyntaxElementWriter.cpp
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibEncoder/SyntaxElementWriter.cpp	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibEncoder/SyntaxElementWriter.cpp	(revision 1088)
@@ -0,0 +1,156 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     SyntaxElementWriter.cpp
+    \brief    CAVLC encoder class
+*/
+
+#include "TLibCommon/CommonDef.h"
+#include "SyntaxElementWriter.h"
+
+//! \ingroup TLibEncoder
+//! \{
+
+#if ENC_DEC_TRACE
+
+Void  SyntaxElementWriter::xWriteCodeTr (UInt value, UInt  length, const Char *pSymbolName)
+{
+  xWriteCode (value,length);
+  if( g_HLSTraceEnable )
+  {
+    fprintf( g_hTrace, "%8lld  ", g_nSymbolCounter++ );
+    if( length<10 )
+    {
+      fprintf( g_hTrace, "%-50s u(%d)  : %d\n", pSymbolName, length, value );
+    }
+    else
+    {
+      fprintf( g_hTrace, "%-50s u(%d) : %d\n", pSymbolName, length, value );
+    }
+  }
+}
+
+Void  SyntaxElementWriter::xWriteUvlcTr (UInt value, const Char *pSymbolName)
+{
+  xWriteUvlc (value);
+  if( g_HLSTraceEnable )
+  {
+    fprintf( g_hTrace, "%8lld  ", g_nSymbolCounter++ );
+    fprintf( g_hTrace, "%-50s ue(v) : %d\n", pSymbolName, value );
+  }
+}
+
+Void  SyntaxElementWriter::xWriteSvlcTr (Int value, const Char *pSymbolName)
+{
+  xWriteSvlc(value);
+  if( g_HLSTraceEnable )
+  {
+    fprintf( g_hTrace, "%8lld  ", g_nSymbolCounter++ );
+    fprintf( g_hTrace, "%-50s se(v) : %d\n", pSymbolName, value );
+  }
+}
+
+Void  SyntaxElementWriter::xWriteFlagTr(UInt value, const Char *pSymbolName)
+{
+  xWriteFlag(value);
+  if( g_HLSTraceEnable )
+  {
+    fprintf( g_hTrace, "%8lld  ", g_nSymbolCounter++ );
+    fprintf( g_hTrace, "%-50s u(1)  : %d\n", pSymbolName, value );
+  }
+}
+
+#if Q0096_OVERLAY_SEI
+Void  SyntaxElementWriter::xWriteStringTr( UChar* value, UInt length, const Char *pSymbolName)
+{
+  xWriteString(value, length);
+  if( g_HLSTraceEnable )
+  {
+    fprintf( g_hTrace, "%8lld  ", g_nSymbolCounter++ );
+    fprintf( g_hTrace, "%-50s st(v=%d)  : %s\n", pSymbolName, length, value ); 
+  }
+}
+#endif
+
+#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 );
+}
+
+#if Q0096_OVERLAY_SEI
+Void  SyntaxElementWriter::xWriteString( UChar* sCode, UInt uiLength)
+{
+  assert(m_pcBitIf->getNumberOfWrittenBits() % 8 == 0 );
+  for (Int i=0 ; i<uiLength; i++)
+  {
+    m_pcBitIf->write( sCode[i], 8 );
+  }
+  m_pcBitIf->write( 0, 8 ); //zero-termination byte
+}
+#endif
+
+//! \}
Index: /tags/SHM-9.0/source/Lib/TLibEncoder/SyntaxElementWriter.h
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibEncoder/SyntaxElementWriter.h	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibEncoder/SyntaxElementWriter.h	(revision 1088)
@@ -0,0 +1,109 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     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 )
+#if Q0096_OVERLAY_SEI
+#define WRITE_STRING( value, length, name)   xWriteStringTr( value, length, name )
+#endif
+
+#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 )
+#if Q0096_OVERLAY_SEI
+#define WRITE_STRING( value, length, name)   xWriteString( value, length )
+#endif
+
+#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 Q0096_OVERLAY_SEI
+  Void  xWriteString          ( UChar* sCode, UInt uiLength);
+#endif
+#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);
+#if Q0096_OVERLAY_SEI
+  Void  xWriteStringTr        ( UChar* value, UInt length, const Char *pSymbolName);
+#endif
+#endif
+
+  UInt  xConvertToUInt        ( Int iValue ) {  return ( iValue <= 0) ? -iValue<<1 : (iValue<<1)-1; }
+};
+
+//! \}
+
+#endif // !defined(__SYNTAXELEMENTWRITER__)
+
Index: /tags/SHM-9.0/source/Lib/TLibEncoder/TEnc3DAsymLUT.cpp
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibEncoder/TEnc3DAsymLUT.cpp	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibEncoder/TEnc3DAsymLUT.cpp	(revision 1088)
@@ -0,0 +1,1049 @@
+#include <cstdio>
+#include <cstdlib>
+#include <cstring>
+#include <cmath>
+#include <algorithm>
+
+#include "TEnc3DAsymLUT.h"
+
+#if Q0048_CGS_3D_ASYMLUT
+
+TEnc3DAsymLUT::TEnc3DAsymLUT()
+{
+  m_pColorInfo = NULL;
+  m_pColorInfoC = NULL;
+  m_pEncCuboid = NULL;
+
+  m_pBestEncCuboid = NULL;
+#if R0151_CGS_3D_ASYMLUT_IMPROVE
+  m_nAccuFrameBit = 0;
+  m_nAccuFrameCGSBit = 0;
+  m_nPrevFrameCGSPartNumLog2 = 0;
+#else
+  memset( m_nPrevFrameBit , 0 , sizeof( m_nPrevFrameBit ) );
+  memset( m_nPrevFrameCGSBit , 0 , sizeof( m_nPrevFrameCGSBit ) );
+  memset( m_nPrevFrameCGSPartNumLog2 , 0 , sizeof( m_nPrevFrameCGSPartNumLog2 ) );
+  memset( m_nPrevFrameOverWritePPS , 0 , sizeof( m_nPrevFrameOverWritePPS ) );
+#endif
+  m_dTotalFrameBit = 0;
+  m_nTotalCGSBit = 0;
+  m_nPPSBit = 0;
+  m_pDsOrigPic = NULL;
+#if R0179_ENC_OPT_3DLUT_SIZE
+  m_pMaxColorInfo = NULL;
+  m_pMaxColorInfoC = NULL;
+
+  
+  // fixed m_dDistFactor
+  Double dTmpFactor[3];   
+  dTmpFactor[I_SLICE] = 1.0;
+  dTmpFactor[P_SLICE] = 4./3.;
+  dTmpFactor[B_SLICE] = 1.5; 
+  for( Int iSliceType = 0; iSliceType < 3; iSliceType++) 
+  {
+    for(Int iLayer = 0; iLayer < MAX_TLAYER; iLayer++)
+    {
+      m_dDistFactor[iSliceType][iLayer] = dTmpFactor[iSliceType]*(Double)(1<<iLayer);      
+    }
+  }
+  // initialization with approximate number of bits to code the LUT
+  m_nNumLUTBits[0][0] = 200; // 1x1x1
+  m_nNumLUTBits[1][0] = 400; // 2x1x1  
+  m_nNumLUTBits[1][1] = 1500; // 2x2x2  
+  m_nNumLUTBits[2][0] = 800; // 4x1x1
+  m_nNumLUTBits[2][1] = 3200; // 4x2x2  
+  m_nNumLUTBits[2][2] = 8500; // 4x4x4  
+  m_nNumLUTBits[3][0] = 1200; // 8x1x1
+  m_nNumLUTBits[3][1] = 4500; // 8x2x2  
+  m_nNumLUTBits[3][2] = 10000; // 8x4x4  
+  m_nNumLUTBits[3][3] = 12000; // 8x8x8
+#endif
+}
+
+Void TEnc3DAsymLUT::create( Int nMaxOctantDepth , Int nInputBitDepth , Int nInputBitDepthC , Int nOutputBitDepth , Int nOutputBitDepthC , Int nMaxYPartNumLog2 )
+{
+  if( m_pColorInfo != NULL )
+  {
+    destroy();
+  }
+
+  TCom3DAsymLUT::create( nMaxOctantDepth , nInputBitDepth , nInputBitDepthC, nOutputBitDepth , nOutputBitDepthC, nMaxYPartNumLog2 
+#if R0151_CGS_3D_ASYMLUT_IMPROVE
+    , 1 << ( nInputBitDepthC - 1 ) , 1 << ( nInputBitDepthC - 1 )
+#endif
+    );
+  xAllocate3DArray( m_pColorInfo , xGetYSize() , xGetUSize() , xGetVSize() );
+  xAllocate3DArray( m_pColorInfoC , xGetYSize() , xGetUSize() , xGetVSize() );
+  xAllocate3DArray( m_pEncCuboid , xGetYSize() , xGetUSize() , xGetVSize() );
+  xAllocate3DArray( m_pBestEncCuboid , xGetYSize() , xGetUSize() , xGetVSize() );
+#if R0179_ENC_OPT_3DLUT_SIZE
+  xAllocate3DArray( m_pMaxColorInfo , xGetYSize() , xGetUSize() , xGetVSize() );
+  xAllocate3DArray( m_pMaxColorInfoC , xGetYSize() , xGetUSize() , xGetVSize() );
+
+  m_pEncCavlc = new TEncCavlc;
+  m_pBitstreamRedirect = new TComOutputBitstream;
+  m_pEncCavlc->setBitstream(m_pBitstreamRedirect);
+#endif
+}
+
+Void TEnc3DAsymLUT::destroy()
+{
+  xFree3DArray( m_pColorInfo );
+  xFree3DArray( m_pColorInfoC );
+  xFree3DArray( m_pEncCuboid );
+  xFree3DArray( m_pBestEncCuboid );
+#if R0179_ENC_OPT_3DLUT_SIZE
+  xFree3DArray( m_pMaxColorInfo );
+  xFree3DArray( m_pMaxColorInfoC );
+  delete m_pBitstreamRedirect;
+  delete m_pEncCavlc;
+#endif 
+  TCom3DAsymLUT::destroy();
+}
+
+TEnc3DAsymLUT::~TEnc3DAsymLUT()
+{
+  if( m_dTotalFrameBit != 0 )
+  {
+    printf( "\nTotal CGS bit: %d, %.2lf%%" , m_nTotalCGSBit , m_nTotalCGSBit * 100 / m_dTotalFrameBit );
+  }
+
+  destroy();
+}
+
+#if R0151_CGS_3D_ASYMLUT_IMPROVE
+Double TEnc3DAsymLUT::xxDeriveVertexPerColor( Double N , Double Ys , Double Yy , Double Yu , Double Yv , Double ys , Double us , Double vs , Double yy , Double yu , Double yv , Double uu , Double uv , Double vv , Double YY ,
+  Pel & rP0 , Pel & rP1 , Pel & rP3 , Pel & rP7 , Int nResQuantBit )
+{
+  Int nInitP0 = rP0;
+  Int nInitP1 = rP1;
+  Int nInitP3 = rP3;
+  Int nInitP7 = rP7;
+
+  const Int nOne = xGetNormCoeffOne();
+  Double dNorm = (N * yy * vv * uu - N * yy * uv * uv - N * yv * yv * uu - N * vv * yu * yu + 2 * N * yv * uv * yu - yy * vs * vs * uu + 2 * yy * vs * uv * us - yy * vv * us * us - 2 * vs * uv * yu * ys + uv * uv * ys * ys + vs * vs * yu * yu - 2 * yv * vs * us * yu + 2 * yv * vs * ys * uu - 2 * yv * uv * us * ys + 2 * vv * yu * ys * us - vv * uu * ys * ys + yv * yv * us * us);
+  if( N > 16 && dNorm != 0 )
+  {
+    Double dInitA = (-N * uu * yv * Yv + N * uu * Yy * vv - N * Yy * uv * uv + N * yv * uv * Yu - N * yu * Yu * vv + N * yu * uv * Yv + yu * us * Ys * vv - vs * ys * uv * Yu - yu * vs * us * Yv - yv * uv * us * Ys - yv * vs * us * Yu - yu * uv * vs * Ys - ys * us * uv * Yv + ys * us * Yu * vv + 2 * Yy * vs * uv * us + uu * yv * vs * Ys - uu * ys * Ys * vv + uu * vs * ys * Yv + ys * Ys * uv * uv - Yy * vv * us * us + yu * Yu * vs * vs + yv * Yv * us * us - uu * Yy * vs * vs) / dNorm;
+    Double dInitB = (N * yy * Yu * vv - N * yy * uv * Yv - N * Yu * yv * yv - N * yu * Yy * vv + N * uv * yv * Yy + N * yv * yu * Yv - yy * us * Ys * vv + yy * uv * vs * Ys - yy * Yu * vs * vs + yy * vs * us * Yv - uv * vs * ys * Yy - yv * yu * vs * Ys + yu * Yy * vs * vs + yu * ys * Ys * vv - uv * yv * ys * Ys + 2 * Yu * yv * vs * ys + us * ys * Yy * vv - vs * ys * yu * Yv + uv * ys * ys * Yv + us * Ys * yv * yv - Yu * ys * ys * vv - yv * ys * us * Yv - vs * us * yv * Yy) / dNorm;
+    Double dInitC = -(-N * yy * Yv * uu + N * yy * uv * Yu - N * yv * yu * Yu - N * uv * yu * Yy + N * Yv * yu * yu + N * yv * Yy * uu - yy * uv * us * Ys + yy * Yv * us * us + yy * vs * Ys * uu - yy * vs * us * Yu + yv * ys * us * Yu - vs * Ys * yu * yu - yv * ys * Ys * uu + vs * us * yu * Yy + vs * ys * yu * Yu - uv * Yu * ys * ys + Yv * uu * ys * ys - yv * Yy * us * us - 2 * Yv * yu * ys * us - vs * ys * Yy * uu + uv * us * ys * Yy + uv * yu * ys * Ys + yv * yu * us * Ys) / dNorm;
+    nInitP0 = ( Int )( dInitA * nOne + 0.5 ) >> nResQuantBit << nResQuantBit;
+    nInitP1 = ( Int )( dInitB * nOne + 0.5 ) >> nResQuantBit << nResQuantBit;
+    nInitP3 = ( Int )( dInitC * nOne + 0.5 ) >> nResQuantBit << nResQuantBit;
+  }
+
+  Int nMin = - ( 1 << ( m_nLUTBitDepth - 1 ) );
+  Int nMax = - nMin - ( 1 << nResQuantBit  );
+  Int nMask = ( 1 << nResQuantBit ) - 1;
+
+  Double dMinError = MAX_DOUBLE;
+  Int nTestRange = 2;
+  Int nStepSize = 1 << nResQuantBit;
+  for( Int i = - nTestRange ; i <= nTestRange ; i++ )
+  {
+    for( Int j = - nTestRange ; j <= nTestRange ; j++ )
+    {
+      for( Int k = - nTestRange ; k <= nTestRange ; k++ )
+      {
+        Int nTestP0 = Clip3( nMin , nMax , nInitP0 + i * nStepSize );
+        Int nTestP1 = Clip3( nMin , nMax , nInitP1 + j * nStepSize );
+        Int nTestP3 = Clip3( nMin , nMax , nInitP3 + k * nStepSize );
+        Double a = 1.0 * nTestP0 / nOne;
+        Double b = 1.0 * nTestP1 / nOne;
+        Double c = 1.0 * nTestP3 / nOne;
+        Double d = ( Ys - a * ys - b * us - c * vs ) / N;
+        nInitP7 = ( ( Int )d ) >> nResQuantBit << nResQuantBit;
+        for( Int m = 0 ; m < 2 ; m++ )
+        {
+          Int nTestP7 = Clip3( nMin , nMax , nInitP7 + m * nStepSize );
+          Double dError = xxCalEstDist( N , Ys , Yy , Yu , Yv , ys , us , vs , yy , yu , yv , uu , uv , vv , YY , a , b , c , nTestP7 );
+          if( dError < dMinError )
+          {
+            dMinError = dError;
+            rP0 = ( Pel )nTestP0;
+            rP1 = ( Pel )nTestP1;
+            rP3 = ( Pel )nTestP3;
+            rP7 = ( Pel )nTestP7;
+          }
+        }
+      }
+    }
+  }
+  assert( !( rP0 & nMask ) && !( rP1 & nMask ) && !( rP3 & nMask ) && !( rP7 & nMask ) );
+
+  return( dMinError );
+}
+#else
+Double TEnc3DAsymLUT::xxDeriveVertexPerColor( Double N , Double Ys , Double Yy , Double Yu , Double Yv , Double ys , Double us , Double vs , Double yy , Double yu , Double yv , Double uu , Double uv , Double vv , Double YY ,
+  Int y0 , Int u0 , Int v0 , Int nLengthY , Int nLengthUV ,
+  Pel & rP0 , Pel & rP1 , Pel & rP3 , Pel & rP7 , Int nResQuantBit )
+{
+  Int nInitP0 = rP0;
+  Int nInitP1 = rP1;
+  Int nInitP3 = rP3;
+  Int nInitP7 = rP7;
+
+  Double dNorm = (N * yy * vv * uu - N * yy * uv * uv - N * yv * yv * uu - N * vv * yu * yu + 2 * N * yv * uv * yu - yy * vs * vs * uu + 2 * yy * vs * uv * us - yy * vv * us * us - 2 * vs * uv * yu * ys + uv * uv * ys * ys + vs * vs * yu * yu - 2 * yv * vs * us * yu + 2 * yv * vs * ys * uu - 2 * yv * uv * us * ys + 2 * vv * yu * ys * us - vv * uu * ys * ys + yv * yv * us * us);
+  if( N > 16 && dNorm != 0 )
+  {
+    Double dInitA = (-N * uu * yv * Yv + N * uu * Yy * vv - N * Yy * uv * uv + N * yv * uv * Yu - N * yu * Yu * vv + N * yu * uv * Yv + yu * us * Ys * vv - vs * ys * uv * Yu - yu * vs * us * Yv - yv * uv * us * Ys - yv * vs * us * Yu - yu * uv * vs * Ys - ys * us * uv * Yv + ys * us * Yu * vv + 2 * Yy * vs * uv * us + uu * yv * vs * Ys - uu * ys * Ys * vv + uu * vs * ys * Yv + ys * Ys * uv * uv - Yy * vv * us * us + yu * Yu * vs * vs + yv * Yv * us * us - uu * Yy * vs * vs) / dNorm;
+    Double dInitB = (N * yy * Yu * vv - N * yy * uv * Yv - N * Yu * yv * yv - N * yu * Yy * vv + N * uv * yv * Yy + N * yv * yu * Yv - yy * us * Ys * vv + yy * uv * vs * Ys - yy * Yu * vs * vs + yy * vs * us * Yv - uv * vs * ys * Yy - yv * yu * vs * Ys + yu * Yy * vs * vs + yu * ys * Ys * vv - uv * yv * ys * Ys + 2 * Yu * yv * vs * ys + us * ys * Yy * vv - vs * ys * yu * Yv + uv * ys * ys * Yv + us * Ys * yv * yv - Yu * ys * ys * vv - yv * ys * us * Yv - vs * us * yv * Yy) / dNorm;
+    Double dInitC = -(-N * yy * Yv * uu + N * yy * uv * Yu - N * yv * yu * Yu - N * uv * yu * Yy + N * Yv * yu * yu + N * yv * Yy * uu - yy * uv * us * Ys + yy * Yv * us * us + yy * vs * Ys * uu - yy * vs * us * Yu + yv * ys * us * Yu - vs * Ys * yu * yu - yv * ys * Ys * uu + vs * us * yu * Yy + vs * ys * yu * Yu - uv * Yu * ys * ys + Yv * uu * ys * ys - yv * Yy * us * us - 2 * Yv * yu * ys * us - vs * ys * Yy * uu + uv * us * ys * Yy + uv * yu * ys * Ys + yv * yu * us * Ys) / dNorm;
+    Double dInitD = (-uu * yy * vs * Yv + uu * yy * Ys * vv + uu * vs * yv * Yy - uu * ys * Yy * vv + uu * ys * yv * Yv - uu * Ys * yv * yv + yy * vs * uv * Yu + yy * us * uv * Yv - yy * Ys * uv * uv - yy * us * Yu * vv + ys * yu * Yu * vv + vs * Yv * yu * yu + ys * Yy * uv * uv - us * yu * yv * Yv + us * yu * Yy * vv + 2 * Ys * yv * uv * yu - vs * uv * yu * Yy - vs * yv * yu * Yu - Ys * vv * yu * yu - us * uv * yv * Yy - ys * yv * uv * Yu - ys * yu * uv * Yv + us * Yu * yv * yv) / dNorm;
+    nInitP0 = xxCoeff2Vertex( dInitA , dInitB , dInitC , dInitD , y0 , u0 , v0 ) >> nResQuantBit  << nResQuantBit ; 
+    nInitP1 = xxCoeff2Vertex( dInitA , dInitB , dInitC , dInitD , y0 , u0 + nLengthUV , v0 ) >> nResQuantBit  << nResQuantBit ;
+    nInitP3 = xxCoeff2Vertex( dInitA , dInitB , dInitC , dInitD , y0 , u0 + nLengthUV , v0 + nLengthUV ) >> nResQuantBit  << nResQuantBit ;
+    nInitP7 = xxCoeff2Vertex( dInitA , dInitB , dInitC , dInitD , y0 + nLengthY , u0 + nLengthUV , v0 + nLengthUV ) >> nResQuantBit  << nResQuantBit ;
+  }
+
+  Int nMin = - ( 1 << ( m_nLUTBitDepth - 1 ) );
+  Int nMax = - nMin - ( 1 << nResQuantBit  );
+  Int nMask = ( 1 << nResQuantBit ) - 1;
+
+  Double dMinError = MAX_DOUBLE;
+  Int testRange = 2;
+  for( Int i = - testRange , nDeltaP01 = nInitP1 - nInitP0 - testRange * ( 1 << nResQuantBit  ) ; i <= testRange ; i++ , nDeltaP01 += ( 1 << nResQuantBit  ) )
+  {
+    for( Int j = - testRange , nDeltaP13 = nInitP3 - nInitP1 - testRange * ( 1 << nResQuantBit  ) ; j <= testRange ; j++ , nDeltaP13 += ( 1 << nResQuantBit  ) )
+    {
+      for( Int k = - testRange , nDeltaP37 = nInitP7 - nInitP3 - testRange * ( 1 << nResQuantBit  ) ; k <= testRange ; k++ , nDeltaP37 += ( 1 << nResQuantBit  ) )
+      {
+        Double a = 1.0 * nDeltaP37 / nLengthY;
+        Double b = 1.0 * nDeltaP01 / nLengthUV;
+        Double c = 1.0 * nDeltaP13 / nLengthUV;
+        Double d = ( Ys - a * ys - b * us - c * vs ) / N;
+        Int nP0 = xxCoeff2Vertex( a , b , c , d , y0 , u0 , v0 ) >> nResQuantBit  << nResQuantBit ;
+        nP0 = Clip3( nMin , nMax , nP0 );
+        Int nP1 = Clip3( nMin , nMax , nP0 + nDeltaP01 );
+        Int nP3 = Clip3( nMin , nMax , nP1 + nDeltaP13 );
+        Int nP7 = Clip3( nMin , nMax , nP3 + nDeltaP37 );
+        if ( nP0 & nMask )
+        {
+          nP0 -= ( nP0 & nMask );
+        }
+        if ( nP1 & nMask )
+        {
+          nP1 -= ( nP1 & nMask );
+        }
+        if ( nP3 & nMask )
+        {
+          nP3 -= ( nP3 & nMask );
+        }
+        if ( nP7 & nMask )
+        {
+          nP7 -= ( nP7 & nMask );
+        }
+        assert( !( nP0 & nMask ) && !( nP1 & nMask ) && !( nP3 & nMask ) && !( nP7 & nMask ) );
+        Double dError = xxCalEstDist( N , Ys , Yy , Yu , Yv , ys , us , vs , yy , yu , yv , uu , uv , vv , YY , y0 , u0 , v0 , nLengthY , nLengthUV , nP0 , nP1 , nP3 , nP7 );
+        if( dError < dMinError )
+        {
+          dMinError = dError;
+          rP0 = ( Pel )nP0;
+          rP1 = ( Pel )nP1;
+          rP3 = ( Pel )nP3;
+          rP7 = ( Pel )nP7;
+          assert( nMin <= rP0 && rP0 <= nMax && nMin <= rP1 && rP1 <= nMax  && nMin <= rP3 && rP3 <= nMax && nMin <= rP7 && rP7 <= nMax );
+        }
+      }
+    }
+  }
+
+  return( dMinError );
+}
+#endif
+
+#if R0151_CGS_3D_ASYMLUT_IMPROVE
+Double TEnc3DAsymLUT::estimateDistWithCur3DAsymLUT( TComPic * pCurPic , UInt refLayerIdc )
+{
+  xxCollectData( pCurPic , refLayerIdc );
+
+  Double dErrorLuma = 0 , dErrorChroma = 0;
+  Int nYSize = 1 << ( getCurOctantDepth() + getCurYPartNumLog2() );
+  Int nUVSize = 1 << getCurOctantDepth();
+  for( Int yIdx = 0 ; yIdx < nYSize ; yIdx++ )
+  {
+    for( Int uIdx = 0 ; uIdx < nUVSize ; uIdx++ )
+    {
+      for( Int vIdx = 0 ; vIdx < nUVSize ; vIdx++ )
+      {
+        SColorInfo & rCuboidColorInfo = m_pColorInfo[yIdx][uIdx][vIdx];
+        SColorInfo & rCuboidColorInfoC = m_pColorInfoC[yIdx][uIdx][vIdx];
+        SCuboid & rCuboid = xGetCuboid( yIdx , uIdx , vIdx );
+        if( rCuboidColorInfo.N > 0 )
+        {
+          dErrorLuma += xxCalEstDist( rCuboidColorInfo.N , rCuboidColorInfo.Ys , rCuboidColorInfo.Yy , rCuboidColorInfo.Yu , rCuboidColorInfo.Yv , rCuboidColorInfo.ys , rCuboidColorInfo.us , rCuboidColorInfo.vs , rCuboidColorInfo.yy , rCuboidColorInfo.yu , rCuboidColorInfo.yv , rCuboidColorInfo.uu , rCuboidColorInfo.uv , rCuboidColorInfo.vv , rCuboidColorInfo.YY ,
+            rCuboid.P[0].Y , rCuboid.P[1].Y , rCuboid.P[2].Y , rCuboid.P[3].Y );
+        }
+        if( rCuboidColorInfoC.N > 0 )
+        {
+          dErrorChroma += xxCalEstDist( rCuboidColorInfoC.N , rCuboidColorInfoC.Us , rCuboidColorInfoC.Uy , rCuboidColorInfoC.Uu , rCuboidColorInfoC.Uv , rCuboidColorInfoC.ys , rCuboidColorInfoC.us , rCuboidColorInfoC.vs , rCuboidColorInfoC.yy , rCuboidColorInfoC.yu , rCuboidColorInfoC.yv , rCuboidColorInfoC.uu , rCuboidColorInfoC.uv , rCuboidColorInfoC.vv , rCuboidColorInfoC.UU ,
+            rCuboid.P[0].U , rCuboid.P[1].U , rCuboid.P[2].U , rCuboid.P[3].U );
+          dErrorChroma += xxCalEstDist( rCuboidColorInfoC.N , rCuboidColorInfoC.Vs , rCuboidColorInfoC.Vy , rCuboidColorInfoC.Vu , rCuboidColorInfoC.Vv , rCuboidColorInfoC.ys , rCuboidColorInfoC.us , rCuboidColorInfoC.vs , rCuboidColorInfoC.yy , rCuboidColorInfoC.yu , rCuboidColorInfoC.yv , rCuboidColorInfoC.uu , rCuboidColorInfoC.uv , rCuboidColorInfoC.vv , rCuboidColorInfoC.VV ,
+            rCuboid.P[0].V , rCuboid.P[1].V , rCuboid.P[2].V , rCuboid.P[3].V );
+        }
+      }
+    }
+  }
+
+  return( dErrorLuma + dErrorChroma);
+}
+#else
+Double TEnc3DAsymLUT::estimateDistWithCur3DAsymLUT( TComPic * pCurPic , UInt refLayerIdc )
+{
+  xxCollectData( pCurPic , refLayerIdc );
+
+  Double dErrorLuma = 0 , dErrorChroma = 0;
+  Int nYSize = 1 << ( getCurOctantDepth() + getCurYPartNumLog2() );
+  Int nUVSize = 1 << getCurOctantDepth();
+  Int nLengthY = 1 << ( getInputBitDepthY() - getCurOctantDepth() - getCurYPartNumLog2() );
+  Int nLengthUV = 1 << ( getInputBitDepthC() - getCurOctantDepth() );
+  for( Int yIdx = 0 ; yIdx < nYSize ; yIdx++ )
+  {
+    for( Int uIdx = 0 ; uIdx < nUVSize ; uIdx++ )
+    {
+      for( Int vIdx = 0 ; vIdx < nUVSize ; vIdx++ )
+      {
+        SColorInfo & rCuboidColorInfo = m_pColorInfo[yIdx][uIdx][vIdx];
+        SColorInfo & rCuboidColorInfoC = m_pColorInfoC[yIdx][uIdx][vIdx];
+        SCuboid & rCuboid = xGetCuboid( yIdx , uIdx , vIdx );
+        Int y0 = yIdx << xGetYShift2Idx();
+        Int u0 = uIdx << xGetUShift2Idx();
+        Int v0 = vIdx << xGetVShift2Idx();
+        if( rCuboidColorInfo.N > 0 )
+        {
+          dErrorLuma += xxCalEstDist( rCuboidColorInfo.N , rCuboidColorInfo.Ys , rCuboidColorInfo.Yy , rCuboidColorInfo.Yu , rCuboidColorInfo.Yv , rCuboidColorInfo.ys , rCuboidColorInfo.us , rCuboidColorInfo.vs , rCuboidColorInfo.yy , rCuboidColorInfo.yu , rCuboidColorInfo.yv , rCuboidColorInfo.uu , rCuboidColorInfo.uv , rCuboidColorInfo.vv , rCuboidColorInfo.YY ,
+            y0 , u0 , v0 , nLengthY , nLengthUV , rCuboid.P[0].Y , rCuboid.P[1].Y , rCuboid.P[2].Y , rCuboid.P[3].Y );
+        }
+        if( rCuboidColorInfoC.N > 0 )
+        {
+          dErrorChroma += xxCalEstDist( rCuboidColorInfoC.N , rCuboidColorInfoC.Us , rCuboidColorInfoC.Uy , rCuboidColorInfoC.Uu , rCuboidColorInfoC.Uv , rCuboidColorInfoC.ys , rCuboidColorInfoC.us , rCuboidColorInfoC.vs , rCuboidColorInfoC.yy , rCuboidColorInfoC.yu , rCuboidColorInfoC.yv , rCuboidColorInfoC.uu , rCuboidColorInfoC.uv , rCuboidColorInfoC.vv , rCuboidColorInfoC.UU ,
+            y0 , u0 , v0 , nLengthY , nLengthUV , rCuboid.P[0].U , rCuboid.P[1].U , rCuboid.P[2].U , rCuboid.P[3].U );
+          dErrorChroma += xxCalEstDist( rCuboidColorInfoC.N , rCuboidColorInfoC.Vs , rCuboidColorInfoC.Vy , rCuboidColorInfoC.Vu , rCuboidColorInfoC.Vv , rCuboidColorInfoC.ys , rCuboidColorInfoC.us , rCuboidColorInfoC.vs , rCuboidColorInfoC.yy , rCuboidColorInfoC.yu , rCuboidColorInfoC.yv , rCuboidColorInfoC.uu , rCuboidColorInfoC.uv , rCuboidColorInfoC.vv , rCuboidColorInfoC.VV ,
+            y0 , u0 , v0 , nLengthY , nLengthUV , rCuboid.P[0].V , rCuboid.P[1].V , rCuboid.P[2].V , rCuboid.P[3].V );
+        }
+      }
+    }
+  }
+
+  return( dErrorLuma + dErrorChroma);
+}
+#endif
+
+#if R0151_CGS_3D_ASYMLUT_IMPROVE
+#if R0179_ENC_OPT_3DLUT_SIZE
+Double TEnc3DAsymLUT::derive3DAsymLUT( TComSlice * pSlice , TComPic * pCurPic , UInt refLayerIdc , TEncCfg * pCfg , Bool bSignalPPS , Bool bElRapSliceTypeB, Double dFrameLambda )
+{
+  m_nLUTBitDepth = pCfg->getCGSLUTBit();
+
+  Int nBestAdaptCThresholdU = 1 << ( getInputBitDepthC() - 1 );
+  Int nBestAdaptCThresholdV = 1 << ( getInputBitDepthC() - 1 );
+  Int nAdaptCThresholdU, nAdaptCThresholdV;
+
+  Int nTmpLutBits[MAX_Y_SIZE][MAX_C_SIZE] ;
+  memset(nTmpLutBits, 0, sizeof(nTmpLutBits)); 
+
+  SLUTSize sMaxLutSize;  
+
+  // collect stats for the most partitions 
+  Int nCurYPartNumLog2 = 0 , nCurOctantDepth = 0; 
+  Int nMaxPartNumLog2 = xGetMaxPartNumLog2();
+
+  xxMapPartNum2DepthYPart( nMaxPartNumLog2 , nCurOctantDepth , nCurYPartNumLog2 ); 
+  xUpdatePartitioning( nCurOctantDepth , nCurYPartNumLog2, nBestAdaptCThresholdU, nBestAdaptCThresholdV ); 
+  xxCollectData( pCurPic , refLayerIdc );
+  xxCopyColorInfo(m_pMaxColorInfo, m_pColorInfo, m_pMaxColorInfoC, m_pColorInfoC); 
+ 
+  sMaxLutSize.iCPartNumLog2 = nCurOctantDepth; 
+  sMaxLutSize.iYPartNumLog2 = nCurOctantDepth + nCurYPartNumLog2; 
+
+  m_pBitstreamRedirect->clear();
+
+  // find the best partition based on RD cost 
+  Int i; 
+  Double dMinCost, dCurCost;
+
+  Int iBestLUTSizeIdx = 0;   
+  Int nBestResQuanBit = 0;
+  Double dCurError, dMinError; 
+  Int iNumBitsCurSize; 
+  Int iNumBitsCurSizeSave = m_pEncCavlc->getNumberOfWrittenBits(); 
+  Double dDistFactor = getDistFactor(pSlice->getSliceType(), pSlice->getDepth());
+
+  // check all LUT sizes 
+  xxGetAllLutSizes(pSlice);  
+  if (m_nTotalLutSizes == 0) // return if no valid size is found, LUT will not be updated
+  {
+    nCurOctantDepth = sMaxLutSize.iCPartNumLog2;
+    nCurYPartNumLog2 = sMaxLutSize.iYPartNumLog2-nCurOctantDepth; 
+    xUpdatePartitioning( nCurOctantDepth , nCurYPartNumLog2, nBestAdaptCThresholdU, nBestAdaptCThresholdV ); 
+    return MAX_DOUBLE; 
+  }
+
+  dMinCost = MAX_DOUBLE; dMinError = MAX_DOUBLE;
+  for (i = 0; i < m_nTotalLutSizes; i++)
+  {
+    // add up the stats
+    nCurOctantDepth = m_sLutSizes[i].iCPartNumLog2;
+    nCurYPartNumLog2 = m_sLutSizes[i].iYPartNumLog2-nCurOctantDepth; 
+    xUpdatePartitioning( nCurOctantDepth , nCurYPartNumLog2, nBestAdaptCThresholdU, nBestAdaptCThresholdV ); 
+    xxConsolidateData( &m_sLutSizes[i], &sMaxLutSize );
+  
+    dCurError = xxDeriveVertexes(nBestResQuanBit, m_pEncCuboid);
+
+    setResQuantBit( nBestResQuanBit );
+    xSaveCuboids( m_pEncCuboid ); 
+    m_pEncCavlc->xCode3DAsymLUT( this ); 
+    iNumBitsCurSize = m_pEncCavlc->getNumberOfWrittenBits();
+    dCurCost = dCurError/dDistFactor + dFrameLambda*(Double)(iNumBitsCurSize-iNumBitsCurSizeSave);  
+    nTmpLutBits[m_sLutSizes[i].iYPartNumLog2][m_sLutSizes[i].iCPartNumLog2] = iNumBitsCurSize-iNumBitsCurSizeSave; // store LUT size 
+    iNumBitsCurSizeSave = iNumBitsCurSize;
+    if(dCurCost < dMinCost )
+    {
+      SCuboid *** tmp = m_pBestEncCuboid;
+      m_pBestEncCuboid = m_pEncCuboid;
+      m_pEncCuboid = tmp;
+      dMinCost = dCurCost; 
+      dMinError = dCurError;
+      iBestLUTSizeIdx = i; 
+    }
+  }
+
+  nCurOctantDepth = m_sLutSizes[iBestLUTSizeIdx].iCPartNumLog2;
+  nCurYPartNumLog2 = m_sLutSizes[iBestLUTSizeIdx].iYPartNumLog2-nCurOctantDepth; 
+
+  xUpdatePartitioning( nCurOctantDepth , nCurYPartNumLog2, nBestAdaptCThresholdU, nBestAdaptCThresholdV ); 
+
+  Bool bUseNewColorInfo = false; 
+  if( pCfg->getCGSAdaptChroma() && nCurOctantDepth <= 1 ) // if the best size found so far has depth = 0 or 1, then check AdaptC U/V thresholds
+  {
+    nAdaptCThresholdU = ( Int )( m_dSumU / m_nNChroma + 0.5 );
+    nAdaptCThresholdV = ( Int )( m_dSumV / m_nNChroma + 0.5 );
+    if( !(nAdaptCThresholdU == nBestAdaptCThresholdU && nAdaptCThresholdV == nBestAdaptCThresholdV ) ) 
+    {
+      nCurOctantDepth = 1;
+      if( nCurOctantDepth + nCurYPartNumLog2 > getMaxYPartNumLog2()+getMaxOctantDepth() )
+        nCurYPartNumLog2 = getMaxYPartNumLog2()+getMaxOctantDepth()-nCurOctantDepth; 
+      xUpdatePartitioning( nCurOctantDepth , nCurYPartNumLog2 , nAdaptCThresholdU , nAdaptCThresholdV );
+      xxCollectData( pCurPic , refLayerIdc );
+
+      dCurError = xxDeriveVertexes( nBestResQuanBit , m_pEncCuboid ) ;
+      setResQuantBit( nBestResQuanBit );
+      xSaveCuboids( m_pEncCuboid ); 
+      m_pEncCavlc->xCode3DAsymLUT( this ); 
+      iNumBitsCurSize = m_pEncCavlc->getNumberOfWrittenBits();
+      dCurCost = dCurError/dDistFactor + dFrameLambda*(Double)(iNumBitsCurSize-iNumBitsCurSizeSave);  
+      iNumBitsCurSizeSave = iNumBitsCurSize;
+      if(dCurCost < dMinCost )
+      {
+        SCuboid *** tmp = m_pBestEncCuboid;
+        m_pBestEncCuboid = m_pEncCuboid;
+        m_pEncCuboid = tmp;
+        dMinCost = dCurCost; 
+        dMinError = dCurError;
+        nBestAdaptCThresholdU = nAdaptCThresholdU;
+        nBestAdaptCThresholdV = nAdaptCThresholdV;
+        bUseNewColorInfo = true; 
+      }
+    }
+  }
+
+  xUpdatePartitioning( nCurOctantDepth , nCurYPartNumLog2, nBestAdaptCThresholdU, nBestAdaptCThresholdV ); 
+
+  // check res_quant_bits only for the best table size and best U/V threshold
+  if( !bUseNewColorInfo ) 
+    xxConsolidateData( &m_sLutSizes[iBestLUTSizeIdx], &sMaxLutSize );
+
+  //    xxCollectData( pCurPic , refLayerIdc );
+  for( Int nResQuanBit = 1 ; nResQuanBit < 4 ; nResQuanBit++ )
+  {
+    dCurError = xxDeriveVertexes( nResQuanBit , m_pEncCuboid );
+
+    setResQuantBit( nResQuanBit );
+    xSaveCuboids( m_pEncCuboid ); 
+    m_pEncCavlc->xCode3DAsymLUT( this ); 
+    iNumBitsCurSize = m_pEncCavlc->getNumberOfWrittenBits();
+    dCurCost = dCurError/dDistFactor + dFrameLambda*(Double)(iNumBitsCurSize-iNumBitsCurSizeSave);   
+
+    iNumBitsCurSizeSave = iNumBitsCurSize;
+    if(dCurCost < dMinCost)
+    {
+      nBestResQuanBit = nResQuanBit;
+      SCuboid *** tmp = m_pBestEncCuboid;
+      m_pBestEncCuboid = m_pEncCuboid;
+      m_pEncCuboid = tmp;
+      dMinCost = dCurCost; 
+      dMinError = dCurError;
+    }
+    else
+    {
+      break;
+    }
+  }
+    
+  setResQuantBit( nBestResQuanBit );
+  xSaveCuboids( m_pBestEncCuboid );
+
+  // update LUT size stats 
+  for(Int iLutSizeY = 0; iLutSizeY < MAX_Y_SIZE; iLutSizeY++)
+  {
+    for(Int iLutSizeC = 0; iLutSizeC < MAX_C_SIZE; iLutSizeC++) 
+    {
+      if(nTmpLutBits[iLutSizeY][iLutSizeC] != 0) 
+        m_nNumLUTBits[iLutSizeY][iLutSizeC] =  (m_nNumLUTBits[iLutSizeY][iLutSizeC] + nTmpLutBits[iLutSizeY][iLutSizeC]*3+2)>>2; // update with new stats
+    }
+  }
+
+  // return cost rather than error
+  return( dMinCost );
+}
+#endif 
+
+
+Double TEnc3DAsymLUT::derive3DAsymLUT( TComSlice * pSlice , TComPic * pCurPic , UInt refLayerIdc , TEncCfg * pCfg , Bool bSignalPPS , Bool bElRapSliceTypeB )
+{
+  m_nLUTBitDepth = pCfg->getCGSLUTBit();
+  Int nCurYPartNumLog2 = 0 , nCurOctantDepth = 0; 
+  xxDerivePartNumLog2( pSlice , pCfg , nCurOctantDepth , nCurYPartNumLog2 , bSignalPPS , bElRapSliceTypeB );
+
+  Int nBestResQuanBit = 0;
+  Int nBestAdaptCThresholdU = 1 << ( getInputBitDepthC() - 1 );
+  Int nBestAdaptCThresholdV = 1 << ( getInputBitDepthC() - 1 );
+  Int nBestOctantDepth = nCurOctantDepth;
+  Int nBestYPartNumLog2 = nCurYPartNumLog2;
+  Int nTargetLoop = 1 + ( pCfg->getCGSAdaptChroma() && ( nCurOctantDepth == 1 || ( nCurOctantDepth * 3 + nCurYPartNumLog2 ) >= 5 ) );
+  Double dMinError = MAX_DOUBLE;
+  for( Int nLoop = 0 ; nLoop < nTargetLoop ; nLoop++ )
+  {
+    Int nAdaptCThresholdU = 1 << ( getInputBitDepthC() - 1 );
+    Int nAdaptCThresholdV = 1 << ( getInputBitDepthC() - 1 );
+    if( nLoop > 0 )
+    {
+      nAdaptCThresholdU = ( Int )( m_dSumU / m_nNChroma + 0.5 );
+      nAdaptCThresholdV = ( Int )( m_dSumV / m_nNChroma + 0.5 );
+      if( nCurOctantDepth > 1 )
+      {
+        nCurOctantDepth = 1;
+        nCurYPartNumLog2 = 2;
+      }
+      if( nAdaptCThresholdU == nBestAdaptCThresholdU && nAdaptCThresholdV == nBestAdaptCThresholdV 
+        && nCurOctantDepth == nBestOctantDepth && nCurYPartNumLog2 == nBestYPartNumLog2 )
+        break;
+    }
+
+    xUpdatePartitioning( nCurOctantDepth , nCurYPartNumLog2 , nAdaptCThresholdU , nAdaptCThresholdV );
+    xxCollectData( pCurPic , refLayerIdc );
+    for( Int nResQuanBit = 0 ; nResQuanBit < 4 ; nResQuanBit++ )
+    {
+      Double dError = xxDeriveVertexes( nResQuanBit , m_pEncCuboid ) / ( 1 + ( nResQuanBit > 0 ) * 0.001 * ( pSlice->getDepth() + 1 ) );
+      if( dError <= dMinError )
+      {
+        nBestResQuanBit = nResQuanBit;
+        nBestAdaptCThresholdU = nAdaptCThresholdU;
+        nBestAdaptCThresholdV = nAdaptCThresholdV;
+        nBestOctantDepth = nCurOctantDepth;
+        nBestYPartNumLog2 = nCurYPartNumLog2;
+        SCuboid *** tmp = m_pBestEncCuboid;
+        m_pBestEncCuboid = m_pEncCuboid;
+        m_pEncCuboid = tmp;
+        dMinError = dError;
+      }
+      else
+      {
+        break;
+      }
+    }
+  }
+
+  setResQuantBit( nBestResQuanBit );
+  xUpdatePartitioning( nBestOctantDepth , nBestYPartNumLog2 , nBestAdaptCThresholdU , nBestAdaptCThresholdV );
+
+  xSaveCuboids( m_pBestEncCuboid );
+  return( dMinError );
+}
+#else
+Double TEnc3DAsymLUT::derive3DAsymLUT( TComSlice * pSlice , TComPic * pCurPic , UInt refLayerIdc , TEncCfg * pCfg , Bool bSignalPPS , Bool bElRapSliceTypeB )
+{
+  m_nLUTBitDepth = pCfg->getCGSLUTBit();
+  Int nCurYPartNumLog2 = 0 , nCurOctantDepth = 0; 
+  xxDerivePartNumLog2( pSlice , pCfg , nCurOctantDepth , nCurYPartNumLog2 , bSignalPPS , bElRapSliceTypeB );
+  xUpdatePartitioning( nCurOctantDepth , nCurYPartNumLog2 );
+  xxCollectData( pCurPic , refLayerIdc );
+  Int nBestResQuanBit = 0;
+  Double dError0 = xxDeriveVertexes( nBestResQuanBit , m_pBestEncCuboid );
+  Double dCurError = dError0;
+  Double dFactor = 1 + 0.001 * ( pSlice->getDepth() + 1 );
+  for( Int nResQuanBit = 1 ; nResQuanBit < 4 ; nResQuanBit++ )
+  {
+    Double dError = xxDeriveVertexes( nResQuanBit , m_pEncCuboid );
+    if( dError < dError0 * dFactor )
+    {
+      nBestResQuanBit = nResQuanBit;
+      SCuboid *** tmp = m_pBestEncCuboid;
+      m_pBestEncCuboid = m_pEncCuboid;
+      m_pEncCuboid = tmp;
+      dCurError = dError;
+    }
+    else
+    {
+      break;
+    }
+  }
+  setResQuantBit( nBestResQuanBit );
+  xSaveCuboids( m_pBestEncCuboid );
+  return( dCurError );
+}
+#endif
+
+Double TEnc3DAsymLUT::xxDeriveVertexes( Int nResQuanBit , SCuboid *** pCurCuboid )
+{
+  Double dErrorLuma = 0 , dErrorChroma = 0;
+  Int nYSize = 1 << ( getCurOctantDepth() + getCurYPartNumLog2() );
+  Int nUVSize = 1 << getCurOctantDepth();
+#if !R0151_CGS_3D_ASYMLUT_IMPROVE
+  Int nLengthY = 1 << ( getInputBitDepthY() - getCurOctantDepth() - getCurYPartNumLog2() );
+  Int nLengthUV = 1 << ( getInputBitDepthC() - getCurOctantDepth() );
+#endif
+  for( Int yIdx = 0 ; yIdx < nYSize ; yIdx++ )
+  {
+    for( Int uIdx = 0 ; uIdx < nUVSize ; uIdx++ )
+    {
+      for( Int vIdx = 0 ; vIdx < nUVSize ; vIdx++ )
+      {
+        SColorInfo & rCuboidColorInfo = m_pColorInfo[yIdx][uIdx][vIdx];
+        SColorInfo & rCuboidColorInfoC = m_pColorInfoC[yIdx][uIdx][vIdx];
+        SCuboid & rCuboid = pCurCuboid[yIdx][uIdx][vIdx];
+#if !R0151_CGS_3D_ASYMLUT_IMPROVE
+        Int y0 = yIdx << xGetYShift2Idx();
+        Int u0 = uIdx << xGetUShift2Idx();
+        Int v0 = vIdx << xGetVShift2Idx();
+#endif
+        for( Int idxVertex = 0 ; idxVertex < 4 ; idxVertex++ )
+        {
+          rCuboid.P[idxVertex] = xGetCuboidVertexPredAll( yIdx , uIdx , vIdx , idxVertex , pCurCuboid );
+        }
+
+        if( rCuboidColorInfo.N > 0 )
+        {
+          dErrorLuma += xxDeriveVertexPerColor( rCuboidColorInfo.N , rCuboidColorInfo.Ys , rCuboidColorInfo.Yy , rCuboidColorInfo.Yu , rCuboidColorInfo.Yv , rCuboidColorInfo.ys , rCuboidColorInfo.us , rCuboidColorInfo.vs , rCuboidColorInfo.yy , rCuboidColorInfo.yu , rCuboidColorInfo.yv , rCuboidColorInfo.uu , rCuboidColorInfo.uv , rCuboidColorInfo.vv , rCuboidColorInfo.YY ,
+#if !R0151_CGS_3D_ASYMLUT_IMPROVE
+            y0 , u0 , v0 , nLengthY , nLengthUV , 
+#endif
+            rCuboid.P[0].Y , rCuboid.P[1].Y , rCuboid.P[2].Y , rCuboid.P[3].Y , nResQuanBit );
+        }
+        if( rCuboidColorInfoC.N > 0 )
+        {
+          dErrorChroma += xxDeriveVertexPerColor( rCuboidColorInfoC.N , rCuboidColorInfoC.Us , rCuboidColorInfoC.Uy , rCuboidColorInfoC.Uu , rCuboidColorInfoC.Uv , rCuboidColorInfoC.ys , rCuboidColorInfoC.us , rCuboidColorInfoC.vs , rCuboidColorInfoC.yy , rCuboidColorInfoC.yu , rCuboidColorInfoC.yv , rCuboidColorInfoC.uu , rCuboidColorInfoC.uv , rCuboidColorInfoC.vv , rCuboidColorInfoC.UU ,
+#if !R0151_CGS_3D_ASYMLUT_IMPROVE
+            y0 , u0 , v0 , nLengthY , nLengthUV , 
+#endif
+            rCuboid.P[0].U , rCuboid.P[1].U , rCuboid.P[2].U , rCuboid.P[3].U , nResQuanBit );
+          dErrorChroma += xxDeriveVertexPerColor( rCuboidColorInfoC.N , rCuboidColorInfoC.Vs , rCuboidColorInfoC.Vy , rCuboidColorInfoC.Vu , rCuboidColorInfoC.Vv , rCuboidColorInfoC.ys , rCuboidColorInfoC.us , rCuboidColorInfoC.vs , rCuboidColorInfoC.yy , rCuboidColorInfoC.yu , rCuboidColorInfoC.yv , rCuboidColorInfoC.uu , rCuboidColorInfoC.uv , rCuboidColorInfoC.vv , rCuboidColorInfoC.VV ,
+#if !R0151_CGS_3D_ASYMLUT_IMPROVE
+            y0 , u0 , v0 , nLengthY , nLengthUV , 
+#endif
+            rCuboid.P[0].V , rCuboid.P[1].V , rCuboid.P[2].V , rCuboid.P[3].V , nResQuanBit );
+        }
+
+        if( nResQuanBit > 0 )
+        {
+          // check quantization
+          for( Int idxVertex = 0 ; idxVertex < 4 ; idxVertex++ )
+          {
+            SYUVP sPred = xGetCuboidVertexPredAll( yIdx , uIdx , vIdx , idxVertex , pCurCuboid );
+            assert( ( ( rCuboid.P[idxVertex].Y - sPred.Y ) >> nResQuanBit << nResQuanBit ) == rCuboid.P[idxVertex].Y - sPred.Y );
+            assert( ( ( rCuboid.P[idxVertex].U - sPred.U ) >> nResQuanBit << nResQuanBit ) == rCuboid.P[idxVertex].U - sPred.U );
+            assert( ( ( rCuboid.P[idxVertex].V - sPred.V ) >> nResQuanBit << nResQuanBit ) == rCuboid.P[idxVertex].V - sPred.V );
+          }
+        }
+      }
+    }
+  }
+
+  return( dErrorLuma + dErrorChroma );
+}
+
+Void TEnc3DAsymLUT::xxCollectData( TComPic * pCurPic , UInt refLayerIdc )
+{
+  Pel * pSrcY = m_pDsOrigPic->getAddr(COMPONENT_Y);
+  Pel * pSrcU = m_pDsOrigPic->getAddr(COMPONENT_Cb);
+  Pel * pSrcV = m_pDsOrigPic->getAddr(COMPONENT_Cr);
+  Int nStrideSrcY = m_pDsOrigPic->getStride(COMPONENT_Y);
+  Int nStrideSrcC = m_pDsOrigPic->getStride(COMPONENT_Cb);
+  TComPicYuv *pRecPic = pCurPic->getSlice(pCurPic->getCurrSliceIdx())->getBaseColPic(refLayerIdc)->getPicYuvRec();
+  Pel * pIRLY = pRecPic->getAddr(COMPONENT_Y);
+  Pel * pIRLU = pRecPic->getAddr(COMPONENT_Cb);
+  Pel * pIRLV = pRecPic->getAddr(COMPONENT_Cr);
+  Int nStrideILRY = pRecPic->getStride(COMPONENT_Y);
+  Int nStrideILRC = pRecPic->getStride(COMPONENT_Cb);
+#if R0179_ENC_OPT_3DLUT_SIZE
+  xReset3DArray( m_pColorInfo  , getMaxYSize() , getMaxCSize() , getMaxCSize() );
+  xReset3DArray( m_pColorInfoC , getMaxYSize() , getMaxCSize() , getMaxCSize() );
+#else
+  xReset3DArray( m_pColorInfo , xGetYSize() , xGetUSize() , xGetVSize() );
+  xReset3DArray( m_pColorInfoC , xGetYSize() , xGetUSize() , xGetVSize() );
+#endif
+
+  //alignment padding
+  pRecPic->setBorderExtension( false );
+  pRecPic->extendPicBorder();
+
+  TComSlice * pSlice = pCurPic->getSlice(pCurPic->getCurrSliceIdx());
+  UInt refLayerId = pSlice->getVPS()->getRefLayerId(pSlice->getLayerId(), refLayerIdc);
+#if MOVE_SCALED_OFFSET_TO_PPS
+  const Window &scalEL = pSlice->getPPS()->getScaledRefLayerWindowForLayer(refLayerId); 
+#else
+  const Window &scalEL = pSlice->getSPS()->getScaledRefLayerWindowForLayer(refLayerId); 
+#endif
+  TComPicYuv *pcRecPicBL = pSlice->getBaseColPic(refLayerIdc)->getPicYuvRec();
+  // borders of down-sampled picture
+  Int leftDS =  (scalEL.getWindowLeftOffset()*g_posScalingFactor[refLayerIdc][0]+(1<<15))>>16;
+  Int rightDS = pcRecPicBL->getWidth(COMPONENT_Y) - 1 + (((scalEL.getWindowRightOffset())*g_posScalingFactor[refLayerIdc][0]+(1<<15))>>16);
+  Int topDS = (((scalEL.getWindowTopOffset())*g_posScalingFactor[refLayerIdc][1]+(1<<15))>>16);
+  Int bottomDS = pcRecPicBL->getHeight(COMPONENT_Y) - 1 + (((scalEL.getWindowBottomOffset())*g_posScalingFactor[refLayerIdc][1]+(1<<15))>>16);
+  // overlapped region
+  Int left = max( 0 , leftDS );
+  Int right = min( pcRecPicBL->getWidth(COMPONENT_Y) - 1 , rightDS );
+  Int top = max( 0 , topDS );
+  Int bottom = min( pcRecPicBL->getHeight(COMPONENT_Y) - 1 , bottomDS );
+  // since we do data collection only for overlapped region, the border extension is good enough
+
+#if R0151_CGS_3D_ASYMLUT_IMPROVE
+  m_dSumU = m_dSumV = 0;
+  m_nNChroma = 0;
+#endif
+  for( Int i = top ; i <= bottom ; i++ )
+  {
+    Int iDS = i-topDS;
+    Int jDS = left-leftDS;
+    Int posSrcY = iDS * nStrideSrcY + jDS;
+    Int posIRLY = i * nStrideILRY + left;
+    Int posSrcUV = ( iDS >> 1 ) * nStrideSrcC + (jDS>>1);
+    Int posIRLUV = ( i >> 1 ) * nStrideILRC + (left>>1);
+    for( Int j = left ; j <= right ; j++ , posSrcY++ , posIRLY++ , posSrcUV += !( j & 0x01 ) , posIRLUV += !( j & 0x01 ) )
+    {
+      Int Y = pSrcY[posSrcY];
+      Int y = pIRLY[posIRLY];
+      Int U = pSrcU[posSrcUV];
+      Int u = pIRLU[posIRLUV];
+      Int V = pSrcV[posSrcUV];
+      Int v = pIRLV[posIRLUV];
+
+      // alignment
+      //filtering u, v for luma;
+      Int posIRLUVN =  posIRLUV + ((i&1)? nStrideILRC : -nStrideILRC);
+      if((j&1))
+      {
+        u = (pIRLU[posIRLUVN] + pIRLU[posIRLUVN+1] +(u + pIRLU[posIRLUV+1])*3 +4)>>3;
+        v = (pIRLV[posIRLUVN] + pIRLV[posIRLUVN+1] +(v + pIRLV[posIRLUV+1])*3 +4)>>3;
+      }
+      else
+      { 
+        u = (pIRLU[posIRLUVN] +u*3 +2)>>2;
+        v = (pIRLV[posIRLUVN] +v*3 +2)>>2;
+      }
+
+#if R0151_CGS_3D_ASYMLUT_IMPROVE
+      m_dSumU += u;
+      m_dSumV += v;
+      m_nNChroma++;
+#endif
+      SColorInfo sColorInfo;
+#if R0151_CGS_3D_ASYMLUT_IMPROVE
+      SColorInfo & rCuboidColorInfo = m_pColorInfo[xGetYIdx(y)][xGetUIdx(u)][xGetVIdx(v)];
+#else
+      SColorInfo & rCuboidColorInfo = m_pColorInfo[y>>xGetYShift2Idx()][u>>xGetUShift2Idx()][v>>xGetVShift2Idx()];
+#endif
+      memset(&sColorInfo, 0, sizeof(SColorInfo));
+      sColorInfo.Ys = Y;
+      sColorInfo.ys = y;
+      sColorInfo.us = u;
+      sColorInfo.vs = v;
+      sColorInfo.Yy = Y * y;
+      sColorInfo.Yu = Y * u;
+      sColorInfo.Yv = Y * v;
+      sColorInfo.yy = y * y;
+      sColorInfo.yu = y * u;
+      sColorInfo.yv = y * v;
+      sColorInfo.uu = u * u;
+      sColorInfo.uv = u * v;
+      sColorInfo.vv = v * v;
+      sColorInfo.YY = Y * Y;
+      sColorInfo.N  = 1;
+
+      rCuboidColorInfo += sColorInfo;
+
+      if(!((i&1) || (j&1)))
+      {
+        // alignment
+        y =  (pIRLY[posIRLY] + pIRLY[posIRLY+nStrideILRY] + 1)>>1;
+
+        u = pIRLU[posIRLUV];
+        v = pIRLV[posIRLUV];
+#if R0151_CGS_3D_ASYMLUT_IMPROVE
+        SColorInfo & rCuboidColorInfoC = m_pColorInfoC[xGetYIdx(y)][xGetUIdx(u)][xGetVIdx(v)];
+#else
+        SColorInfo & rCuboidColorInfoC = m_pColorInfoC[y>>xGetYShift2Idx()][u>>xGetUShift2Idx()][v>>xGetVShift2Idx()];
+#endif
+        sColorInfo.Us = U;
+        sColorInfo.Vs = V;
+        sColorInfo.ys = y;
+        sColorInfo.us = u;
+        sColorInfo.vs = v;
+
+        sColorInfo.Uy = U * y;
+        sColorInfo.Uu = U * u;
+        sColorInfo.Uv = U * v;
+        sColorInfo.Vy = V * y;
+        sColorInfo.Vu = V * u;
+        sColorInfo.Vv = V * v;
+        sColorInfo.yy = y * y;
+        sColorInfo.yu = y * u;
+        sColorInfo.yv = y * v;
+        sColorInfo.uu = u * u;
+        sColorInfo.uv = u * v;
+        sColorInfo.vv = v * v;
+        sColorInfo.UU = U * U;
+        sColorInfo.VV = V * V;
+        sColorInfo.N  = 1;
+
+        rCuboidColorInfoC += sColorInfo;
+      }
+    }
+  }
+}
+
+Void TEnc3DAsymLUT::xxDerivePartNumLog2( TComSlice * pSlice , TEncCfg * pcCfg , Int & rOctantDepth , Int & rYPartNumLog2 , Bool bSignalPPS , Bool bElRapSliceTypeB )
+{
+#if !R0151_CGS_3D_ASYMLUT_IMPROVE
+  Int nSliceType = pSlice->getSliceType();
+  // update slice type as what will be done later
+  if( pSlice->getActiveNumILRRefIdx() == 0 && pSlice->getNalUnitType() >= NAL_UNIT_CODED_SLICE_BLA_W_LP && pSlice->getNalUnitType() <= NAL_UNIT_CODED_SLICE_CRA )
+  {
+    nSliceType = I_SLICE;
+  }
+  else if( !bElRapSliceTypeB )
+  {
+    if( (pSlice->getNalUnitType() >= NAL_UNIT_CODED_SLICE_BLA_W_LP) &&
+      (pSlice->getNalUnitType() <= NAL_UNIT_CODED_SLICE_CRA) &&
+      pSlice->getSliceType() == B_SLICE )
+    {
+      nSliceType = P_SLICE;
+    }
+  }
+
+  const Int nSliceTempLevel = pSlice->getDepth();
+#endif
+  Int nPartNumLog2 = 4;
+  if( pSlice->getBaseColPic( pSlice->getInterLayerPredLayerIdc( 0 ) )->getSlice( 0 )->isIntra() )
+  {
+    nPartNumLog2 = xGetMaxPartNumLog2();
+  }
+#if R0151_CGS_3D_ASYMLUT_IMPROVE
+  if( m_nAccuFrameBit && pSlice->getPPS()->getCGSFlag() ) 
+  {
+    Double dBitCost = 1.0 * m_nAccuFrameCGSBit / m_nAccuFrameBit;
+    nPartNumLog2 = m_nPrevFrameCGSPartNumLog2;
+#else
+  if( m_nPrevFrameBit[nSliceType][nSliceTempLevel] && pSlice->getPPS()->getCGSFlag() ) 
+  {
+    Double dBitCost = 1.0 * m_nPrevFrameCGSBit[nSliceType][nSliceTempLevel] / m_nPrevFrameBit[nSliceType][nSliceTempLevel];
+    nPartNumLog2 = m_nPrevFrameCGSPartNumLog2[nSliceType][nSliceTempLevel];
+#endif
+    Double dBitCostT = 0.03;
+    if( dBitCost < dBitCostT / 6.0 )
+    {
+      nPartNumLog2++;
+    }
+    else if( dBitCost >= dBitCostT )
+    {
+      nPartNumLog2--;
+    }
+  }
+#if !R0151_CGS_3D_ASYMLUT_IMPROVE
+  else
+  {
+    nPartNumLog2 -= nSliceTempLevel;
+  }
+#endif
+  nPartNumLog2 = Clip3( 0 , xGetMaxPartNumLog2()  , nPartNumLog2 );
+  xxMapPartNum2DepthYPart( nPartNumLog2 , rOctantDepth , rYPartNumLog2 );
+}
+
+Void TEnc3DAsymLUT::xxMapPartNum2DepthYPart( Int nPartNumLog2 , Int & rOctantDepth , Int & rYPartNumLog2 )
+{
+  for( Int y = getMaxYPartNumLog2() ; y >= 0 ; y-- )
+  {
+    for( Int depth = ( nPartNumLog2 - y ) >> 1 ; depth >= 0 ; depth-- )
+    {
+      if( y + 3 * depth == nPartNumLog2 )
+      {
+        rOctantDepth = depth;
+        rYPartNumLog2 = y;
+        return;
+      }
+    }
+  }
+  rOctantDepth = min( getMaxOctantDepth() , nPartNumLog2 / 3 );
+  rYPartNumLog2 = min( getMaxYPartNumLog2() , nPartNumLog2 - 3 * rOctantDepth );
+}
+
+Void TEnc3DAsymLUT::updatePicCGSBits( TComSlice * pcSlice , Int nPPSBit )
+{
+#if !R0151_CGS_3D_ASYMLUT_IMPROVE
+  const Int nSliceType = pcSlice->getSliceType();
+  const Int nSliceTempLevel = pcSlice->getDepth();
+#endif
+  for( Int i = 0; i < pcSlice->getActiveNumILRRefIdx(); i++ )
+  {
+    UInt refLayerIdc = pcSlice->getInterLayerPredLayerIdc(i);
+#if R0151_CGS_3D_ASYMLUT_IMPROVE
+    m_nAccuFrameBit += pcSlice->getPic()->getFrameBit() + pcSlice->getBaseColPic(refLayerIdc)->getFrameBit();
+#else
+    m_nPrevFrameBit[nSliceType][nSliceTempLevel] = pcSlice->getPic()->getFrameBit() + pcSlice->getBaseColPic(refLayerIdc)->getFrameBit();
+#endif
+    m_dTotalFrameBit += pcSlice->getPic()->getFrameBit() + pcSlice->getBaseColPic(refLayerIdc)->getFrameBit();
+  }
+#if R0151_CGS_3D_ASYMLUT_IMPROVE
+  m_nAccuFrameCGSBit += nPPSBit;
+  m_nTotalCGSBit += nPPSBit;
+  m_nPrevFrameCGSPartNumLog2 = getCurOctantDepth() * 3 + getCurYPartNumLog2();
+#else
+  m_nPrevFrameOverWritePPS[nSliceType][nSliceTempLevel] = pcSlice->getCGSOverWritePPS();
+  m_nPrevFrameCGSBit[nSliceType][nSliceTempLevel] = nPPSBit;
+  m_nTotalCGSBit += nPPSBit;
+  m_nPrevFrameCGSPartNumLog2[nSliceType][nSliceTempLevel] = getCurOctantDepth() * 3 + getCurYPartNumLog2();
+#endif
+#if R0179_ENC_OPT_3DLUT_SIZE
+  Int nCurELFrameBit = pcSlice->getPic()->getFrameBit();
+  const Int nSliceType = pcSlice->getSliceType();
+  const Int nSliceTempLevel = pcSlice->getDepth();
+  m_nPrevELFrameBit[nSliceType][nSliceTempLevel] = m_nPrevELFrameBit[nSliceType][nSliceTempLevel] == 0 ? nCurELFrameBit:((m_nPrevELFrameBit[nSliceType][nSliceTempLevel]+nCurELFrameBit)>>1);
+#endif 
+}
+
+#if R0179_ENC_OPT_3DLUT_SIZE
+
+Void TEnc3DAsymLUT::xxGetAllLutSizes(TComSlice *pSlice)
+{
+  Int iMaxYPartNumLog2, iMaxCPartNumLog2; 
+  Int iCurYPartNumLog2, iCurCPartNumLog2; 
+  Int iMaxAddYPartNumLog2; 
+  Int iNumELFrameBits = m_nPrevELFrameBit[pSlice->getSliceType()][pSlice->getDepth()];
+
+  xxMapPartNum2DepthYPart( xGetMaxPartNumLog2() , iMaxCPartNumLog2 , iMaxYPartNumLog2 );
+  iMaxAddYPartNumLog2 = iMaxYPartNumLog2; 
+  iMaxYPartNumLog2 += iMaxCPartNumLog2; 
+
+  //m_sLutSizes[0].iYPartNumLog2 = iMaxYPartNumLog2; 
+  //m_sLutSizes[0].iCPartNumLog2 = iMaxCPartNumLog2; 
+  m_nTotalLutSizes = 0; 
+
+
+  for(iCurYPartNumLog2 = iMaxYPartNumLog2; iCurYPartNumLog2 >= 0; iCurYPartNumLog2--) 
+  {
+    for(iCurCPartNumLog2 = iMaxCPartNumLog2; iCurCPartNumLog2 >= 0; iCurCPartNumLog2--) 
+    {
+       // try more sizes
+      if(iCurCPartNumLog2 <= iCurYPartNumLog2  && 
+         (m_nNumLUTBits[iCurYPartNumLog2][iCurCPartNumLog2] < (iNumELFrameBits>>1)) && 
+         m_nTotalLutSizes < MAX_NUM_LUT_SIZES)
+      {
+        m_sLutSizes[m_nTotalLutSizes].iYPartNumLog2 = iCurYPartNumLog2; 
+        m_sLutSizes[m_nTotalLutSizes].iCPartNumLog2 = iCurCPartNumLog2; 
+        m_nTotalLutSizes ++; 
+      }
+    }
+  }
+
+}
+
+Void TEnc3DAsymLUT::xxCopyColorInfo( SColorInfo *** dst, SColorInfo *** src ,  SColorInfo *** dstC, SColorInfo *** srcC )
+{
+  Int yIdx, uIdx, vIdx; 
+
+  // copy from pColorInfo to pMaxColorInfo
+  for(yIdx = 0; yIdx < xGetYSize(); yIdx++)
+  {
+    for(uIdx = 0; uIdx < xGetUSize(); uIdx++)
+    {
+      for(vIdx = 0; vIdx < xGetVSize(); vIdx++)
+      {
+        dst [yIdx][uIdx][vIdx] = src [yIdx][uIdx][vIdx];
+        dstC[yIdx][uIdx][vIdx] = srcC[yIdx][uIdx][vIdx];
+      }
+    }
+  }
+}
+
+Void TEnc3DAsymLUT::xxAddColorInfo( Int yIdx, Int uIdx, Int vIdx, Int iYDiffLog2, Int iCDiffLog2 )
+{
+  SColorInfo & rCuboidColorInfo  = m_pColorInfo [yIdx][uIdx][vIdx];
+  SColorInfo & rCuboidColorInfoC = m_pColorInfoC[yIdx][uIdx][vIdx];
+  
+  for( Int i = 0; i < (1<<iYDiffLog2); i++)
+  {
+    for (Int j = 0; j < (1<<iCDiffLog2); j++)
+    {
+      for(Int k = 0; k < (1<<iCDiffLog2); k++)
+      {
+        rCuboidColorInfo  += m_pMaxColorInfo [(yIdx<<iYDiffLog2)+i][(uIdx<<iCDiffLog2)+j][(vIdx<<iCDiffLog2)+k];
+        rCuboidColorInfoC += m_pMaxColorInfoC[(yIdx<<iYDiffLog2)+i][(uIdx<<iCDiffLog2)+j][(vIdx<<iCDiffLog2)+k];
+      }
+    }
+  }
+}
+
+Void TEnc3DAsymLUT::xxConsolidateData( SLUTSize *pCurLUTSize, SLUTSize *pMaxLUTSize )
+{
+  Int yIdx, uIdx, vIdx; 
+  Int iYDiffLog2, iCDiffLog2;
+  Int nYSize = 1<< pMaxLUTSize->iYPartNumLog2;
+  Int nCSize = 1<< pMaxLUTSize->iCPartNumLog2;
+
+  iYDiffLog2 = pMaxLUTSize->iYPartNumLog2-pCurLUTSize->iYPartNumLog2;
+  iCDiffLog2 = pMaxLUTSize->iCPartNumLog2-pCurLUTSize->iCPartNumLog2;
+
+  //assert(pMaxLUTSize->iCPartNumLog2 >= pCurLUTSize->iCPartNumLog2 && pMaxLUTSize->iYPartNumLog2 >= pCurLUTSize->iYPartNumLog2); 
+  if (iYDiffLog2 == 0 && iCDiffLog2 == 0) // shouldn't have to do anything 
+  {
+    xxCopyColorInfo(m_pColorInfo, m_pMaxColorInfo, m_pColorInfoC, m_pMaxColorInfoC);
+    return; 
+  }
+
+  xReset3DArray( m_pColorInfo  ,  1<<pMaxLUTSize->iYPartNumLog2, 1<<pMaxLUTSize->iCPartNumLog2, 1<<pMaxLUTSize->iCPartNumLog2 );
+  xReset3DArray( m_pColorInfoC ,  1<<pMaxLUTSize->iYPartNumLog2, 1<<pMaxLUTSize->iCPartNumLog2, 1<<pMaxLUTSize->iCPartNumLog2 );
+
+  for(yIdx = 0; yIdx < nYSize; yIdx++)
+  {
+    for(uIdx = 0; uIdx < nCSize; uIdx++)
+    {
+      for(vIdx = 0; vIdx < nCSize; vIdx++)
+      {
+        const SColorInfo & rCuboidSrc   = m_pMaxColorInfo [yIdx][uIdx][vIdx];
+        const SColorInfo & rCuboidSrcC  = m_pMaxColorInfoC[yIdx][uIdx][vIdx];
+        
+        Int yIdx2, uIdx2, vIdx2; 
+        yIdx2 = yIdx>>iYDiffLog2; 
+        uIdx2 = uIdx>>iCDiffLog2;
+        vIdx2 = vIdx>>iCDiffLog2; 
+
+        m_pColorInfo [yIdx2][uIdx2][vIdx2] += rCuboidSrc;
+        m_pColorInfoC[yIdx2][uIdx2][vIdx2] += rCuboidSrcC;
+      }
+    }
+  }
+}
+
+Void TEnc3DAsymLUT::update3DAsymLUTParam( TEnc3DAsymLUT * pSrc )
+{
+  assert( pSrc->getMaxOctantDepth() == getMaxOctantDepth() && pSrc->getMaxYPartNumLog2() == getMaxYPartNumLog2() );
+  xUpdatePartitioning( pSrc->getCurOctantDepth() , pSrc->getCurYPartNumLog2() 
+#if R0151_CGS_3D_ASYMLUT_IMPROVE
+    , pSrc->getAdaptChromaThresholdU() , pSrc->getAdaptChromaThresholdV()
+#endif
+    );
+  setResQuantBit( pSrc->getResQuantBit() );
+}
+
+#endif 
+#endif
Index: /tags/SHM-9.0/source/Lib/TLibEncoder/TEnc3DAsymLUT.h
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibEncoder/TEnc3DAsymLUT.h	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibEncoder/TEnc3DAsymLUT.h	(revision 1088)
@@ -0,0 +1,200 @@
+
+#ifndef __TENC3DASYMLUT__
+#define __TENC3DASYMLUT__
+
+#include "../TLibCommon/TCom3DAsymLUT.h"
+#include "../TLibCommon/TComSlice.h"
+#include "../TLibCommon/CommonDef.h"
+#include "../TLibCommon/TComPic.h"
+#include "TEncCfg.h"
+#if R0179_ENC_OPT_3DLUT_SIZE
+#include "TEncCavlc.h"
+#define MAX_NUM_LUT_SIZES               10   // 4+3+2+1
+#define MAX_Y_SIZE                       4
+#define MAX_C_SIZE                       4
+#endif
+
+#if Q0048_CGS_3D_ASYMLUT
+
+typedef struct _ColorInfo
+{
+  Double YY , UU , VV;
+  Double Ys , Us , Vs;  // sum of enhancement
+  Double ys , us , vs;  // sum of base
+  Double Yy , Yu , Yv;  // product of enhancement and base
+  Double Uy , Uu , Uv;
+  Double Vy , Vu , Vv;
+  Double yy , yu , yv , uu , uv , vv; // product of base
+  Double N; // number of pixel
+
+public:
+  _ColorInfo & operator += ( const _ColorInfo & rColorInfo )
+  {
+    YY += rColorInfo.YY;
+    UU += rColorInfo.UU;
+    VV += rColorInfo.VV;
+    Ys += rColorInfo.Ys;
+    Us += rColorInfo.Us;
+    Vs += rColorInfo.Vs;
+    ys += rColorInfo.ys;
+    us += rColorInfo.us;
+    vs += rColorInfo.vs;
+    Yy += rColorInfo.Yy;
+    Yu += rColorInfo.Yu;
+    Yv += rColorInfo.Yv;
+    Uy += rColorInfo.Uy;
+    Uu += rColorInfo.Uu;
+    Uv += rColorInfo.Uv;
+    Vy += rColorInfo.Vy;
+    Vu += rColorInfo.Vu;
+    Vv += rColorInfo.Vv;
+    yy += rColorInfo.yy;
+    yu += rColorInfo.yu;
+    yv += rColorInfo.yv;
+    uu += rColorInfo.uu;
+    uv += rColorInfo.uv;
+    vv += rColorInfo.vv;
+    N  += rColorInfo.N; 
+    return *this;
+  }
+
+}SColorInfo;
+
+#if R0179_ENC_OPT_3DLUT_SIZE
+typedef struct _LUTSize 
+{
+  Int iYPartNumLog2; 
+  Int iCPartNumLog2; 
+} SLUTSize; 
+#endif 
+
+class TEnc3DAsymLUT : public TCom3DAsymLUT
+{
+public:
+  TEnc3DAsymLUT();
+  virtual ~TEnc3DAsymLUT();
+
+  virtual Void  create( Int nMaxOctantDepth , Int nInputBitDepth , Int nInputBitDepthC , Int nOutputBitDepth , Int nOutputBitDepthC , Int nMaxYPartNumLog2 );
+  virtual Void  destroy();
+  Double derive3DAsymLUT( TComSlice * pSlice , TComPic * pCurPic , UInt refLayerIdc , TEncCfg * pCfg , Bool bSignalPPS , Bool bElRapSliceTypeB );
+  Double estimateDistWithCur3DAsymLUT( TComPic * pCurPic , UInt refLayerIdc );
+#if R0179_ENC_OPT_3DLUT_SIZE
+  Double getDistFactor( Int iSliceType, Int iLayer) { return m_dDistFactor[iSliceType][iLayer];}
+  Double derive3DAsymLUT( TComSlice * pSlice , TComPic * pCurPic , UInt refLayerIdc , TEncCfg * pCfg , Bool bSignalPPS , Bool bElRapSliceTypeB, Double dFrameLambda );
+  Void   update3DAsymLUTParam( TEnc3DAsymLUT * pSrc );
+#endif
+
+  Void  updatePicCGSBits( TComSlice * pcSlice , Int nPPSBit );
+  Void  setPPSBit(Int n)  { m_nPPSBit = n;  }
+  Int   getPPSBit()       { return m_nPPSBit;}
+  Void  setDsOrigPic(TComPicYuv *pPicYuv) { m_pDsOrigPic = pPicYuv; };
+
+protected:
+  SColorInfo *** m_pColorInfo;
+  SColorInfo *** m_pColorInfoC;
+#if R0179_ENC_OPT_3DLUT_SIZE
+  SColorInfo *** m_pMaxColorInfo;
+  SColorInfo *** m_pMaxColorInfoC;
+#endif 
+  TComPicYuv* m_pDsOrigPic;
+  SCuboid *** m_pEncCuboid;
+  SCuboid *** m_pBestEncCuboid;
+#if R0151_CGS_3D_ASYMLUT_IMPROVE
+  Int   m_nAccuFrameBit;                  // base + enhancement layer
+  Int   m_nAccuFrameCGSBit;
+  Int   m_nPrevFrameCGSPartNumLog2;
+#else
+  Int   m_nPrevFrameBit[3][MAX_TLAYER];                  // base + enhancement layer
+  Int   m_nPrevFrameCGSBit[3][MAX_TLAYER];
+  Int   m_nPrevFrameCGSPartNumLog2[3][MAX_TLAYER];
+  Int   m_nPrevFrameOverWritePPS[3][MAX_TLAYER];
+#endif
+  Double m_dTotalFrameBit;
+  Int   m_nTotalCGSBit;
+  Int   m_nPPSBit;
+  Int   m_nLUTBitDepth;
+#if R0179_ENC_OPT_3DLUT_SIZE
+
+  Double m_dDistFactor[3][MAX_TLAYER];         
+  Int    m_nNumLUTBits[MAX_Y_SIZE][MAX_C_SIZE]; 
+  Int    m_nPrevELFrameBit[3][MAX_TLAYER];   
+
+
+  Int   m_nTotalLutSizes;
+  SLUTSize m_sLutSizes[MAX_NUM_LUT_SIZES];
+#endif 
+#if R0151_CGS_3D_ASYMLUT_IMPROVE
+  Double m_dSumU;
+  Double m_dSumV;
+  Int    m_nNChroma;
+#endif
+#if R0179_ENC_OPT_3DLUT_SIZE
+  TComOutputBitstream  *m_pBitstreamRedirect;
+  TEncCavlc *m_pEncCavlc;
+#endif 
+
+private:
+#if R0151_CGS_3D_ASYMLUT_IMPROVE
+  Double  xxDeriveVertexPerColor( Double N , Double Ys , Double Yy , Double Yu , Double Yv , Double ys , Double us , Double vs , Double yy , Double yu , Double yv , Double uu , Double uv , Double vv , Double YY ,
+    Pel & rP0 , Pel & rP1 , Pel & rP3 , Pel & rP7 , Int nResQuantBit );
+#else
+  Double  xxDeriveVertexPerColor( Double N , Double Ys , Double Yy , Double Yu , Double Yv , Double ys , Double us , Double vs , Double yy , Double yu , Double yv , Double uu , Double uv , Double vv , Double YY ,
+    Int y0 , Int u0 , Int v0 , Int nLengthY , Int nLengthUV ,
+    Pel & rP0 , Pel & rP1 , Pel & rP3 , Pel & rP7 , Int nResQuantBit );
+#endif
+  Void    xxDerivePartNumLog2( TComSlice * pSlice , TEncCfg * pcCfg , Int & rOctantDepth , Int & rYPartNumLog2 , Bool bSignalPPS , Bool bElRapSliceTypeB );
+  Void    xxMapPartNum2DepthYPart( Int nPartNumLog2 , Int & rOctantDepth , Int & rYPartNumLog2 );
+  Int     xxCoeff2Vertex( Double a , Double b , Double c , Double d , Int y , Int u , Int v ) { return ( ( Int )( a * y + b * u + c * v + d + 0.5 ) ); }
+  Void    xxCollectData( TComPic * pCurPic , UInt refLayerIdc );
+
+  Double  xxDeriveVertexes( Int nResQuantBit , SCuboid *** pCurCuboid );
+  inline Double  xxCalEstDist( Double N , Double Ys , Double Yy , Double Yu , Double Yv , Double ys , Double us , Double vs , Double yy , Double yu , Double yv , Double uu , Double uv , Double vv , Double YY ,
+    Int y0 , Int u0 , Int v0 , Int nLengthY , Int nLengthUV , Pel nP0 , Pel nP1 , Pel nP3 , Pel nP7 );
+  inline Double  xxCalEstDist( Double N , Double Ys , Double Yy , Double Yu , Double Yv , Double ys , Double us , Double vs , Double yy , Double yu , Double yv , Double uu , Double uv , Double vv , Double YY ,
+    Double a , Double b , Double c , Double d );
+#if R0151_CGS_3D_ASYMLUT_IMPROVE
+  inline Double  xxCalEstDist( Double N , Double Ys , Double Yy , Double Yu , Double Yv , Double ys , Double us , Double vs , Double yy , Double yu , Double yv , Double uu , Double uv , Double vv , Double YY ,
+    Pel nP0 , Pel nP1 , Pel nP3 , Pel nP7 );
+#endif
+#if R0179_ENC_OPT_3DLUT_SIZE
+  Void    xxConsolidateData( SLUTSize *pCurLUTSize, SLUTSize *pMaxLUTSize );
+  Void    xxGetAllLutSizes(TComSlice *pSlice);
+  Void    xxCopyColorInfo( SColorInfo *** dst, SColorInfo *** src ,  SColorInfo *** dstC, SColorInfo *** srcC ); 
+  Void    xxAddColorInfo( Int yIdx, Int uIdx, Int vIdx, Int iYDiffLog2, Int iCDiffLog2 );
+#endif 
+};
+
+Double TEnc3DAsymLUT::xxCalEstDist( Double N , Double Ys , Double Yy , Double Yu , Double Yv , Double ys , Double us , Double vs , Double yy , Double yu , Double yv , Double uu , Double uv , Double vv , Double YY ,
+  Int y0 , Int u0 , Int v0 , Int nLengthY , Int nLengthUV , Pel nP0 , Pel nP1 , Pel nP3 , Pel nP7 )
+{
+  Double a = 1.0 * ( nP7 - nP3 ) / nLengthY;
+  Double b = 1.0 * ( nP1 - nP0 ) / nLengthUV;
+  Double c = 1.0 * ( nP3 - nP1 ) / nLengthUV;
+  Double d = ( ( nP0 * nLengthUV + u0 * nP0 + ( v0 - u0 ) * nP1 - v0 * nP3 ) * nLengthY + y0 * nLengthUV * ( nP3 - nP7 ) ) / nLengthUV / nLengthY;
+  return( xxCalEstDist( N , Ys , Yy , Yu , Yv , ys , us , vs , yy , yu , yv , uu , uv , vv , YY , a , b , c , d ) );
+}
+
+Double TEnc3DAsymLUT::xxCalEstDist( Double N , Double Ys , Double Yy , Double Yu , Double Yv , Double ys , Double us , Double vs , Double yy , Double yu , Double yv , Double uu , Double uv , Double vv , Double YY ,
+  Double a , Double b , Double c , Double d )
+{
+  Double dError = N * d * d + 2 * b * c * uv + 2 * a * c * yv + 2 * a * b * yu - 2 * c * Yv - 2 * b * Yu - 2 * a * Yy + 2 * c * d * vs + 2 * b * d * us + 2 * a * d * ys + a * a * yy + c * c * vv + b * b * uu - 2 * d * Ys + YY;
+  return( dError );
+};
+
+#if R0151_CGS_3D_ASYMLUT_IMPROVE
+Double TEnc3DAsymLUT::xxCalEstDist( Double N , Double Ys , Double Yy , Double Yu , Double Yv , Double ys , Double us , Double vs , Double yy , Double yu , Double yv , Double uu , Double uv , Double vv , Double YY ,
+  Pel nP0 , Pel nP1 , Pel nP3 , Pel nP7 )
+{
+  const Int nOne = xGetNormCoeffOne();
+  Double a = 1.0 * nP0 / nOne;
+  Double b = 1.0 * nP1 / nOne;
+  Double c = 1.0 * nP3 / nOne;
+  Double d = nP7;
+  Double dError = N * d * d + 2 * b * c * uv + 2 * a * c * yv + 2 * a * b * yu - 2 * c * Yv - 2 * b * Yu - 2 * a * Yy + 2 * c * d * vs + 2 * b * d * us + 2 * a * d * ys + a * a * yy + c * c * vv + b * b * uu - 2 * d * Ys + YY;
+  return( dError );
+};
+#endif
+
+#endif
+
+#endif
Index: /tags/SHM-9.0/source/Lib/TLibEncoder/TEncAnalyze.cpp
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibEncoder/TEncAnalyze.cpp	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibEncoder/TEncAnalyze.cpp	(revision 1088)
@@ -0,0 +1,61 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TEncAnalyze.cpp
+    \brief    encoder analyzer class
+*/
+
+#include "TEncAnalyze.h"
+
+//! \ingroup TLibEncoder
+//! \{
+
+//////////////////////////////////////////////////////////////////////
+// Construction/Destruction
+//////////////////////////////////////////////////////////////////////
+
+#if SVC_EXTENSION
+TEncAnalyze             m_gcAnalyzeAll [MAX_LAYERS];
+TEncAnalyze             m_gcAnalyzeI [MAX_LAYERS];
+TEncAnalyze             m_gcAnalyzeP [MAX_LAYERS];
+TEncAnalyze             m_gcAnalyzeB [MAX_LAYERS];
+#else
+TEncAnalyze             m_gcAnalyzeAll;
+TEncAnalyze             m_gcAnalyzeI;
+TEncAnalyze             m_gcAnalyzeP;
+TEncAnalyze             m_gcAnalyzeB;
+#endif
+
+TEncAnalyze             m_gcAnalyzeAll_in;
+
+//! \}
Index: /tags/SHM-9.0/source/Lib/TLibEncoder/TEncAnalyze.h
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibEncoder/TEncAnalyze.h	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibEncoder/TEncAnalyze.h	(revision 1088)
@@ -0,0 +1,423 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TEncAnalyze.h
+    \brief    encoder analyzer class (header)
+*/
+
+#ifndef __TENCANALYZE__
+#define __TENCANALYZE__
+
+#if _MSC_VER > 1000
+#pragma once
+#endif // _MSC_VER > 1000
+
+#include <stdio.h>
+#include <memory.h>
+#include <assert.h>
+#include "TLibCommon/CommonDef.h"
+#include "TLibCommon/TComChromaFormat.h"
+#include "math.h"
+
+//! \ingroup TLibEncoder
+//! \{
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// encoder analyzer class
+class TEncAnalyze
+{
+private:
+  Double    m_dPSNRSum[MAX_NUM_COMPONENT];
+  Double    m_dAddBits;
+  UInt      m_uiNumPic;
+  Double    m_dFrmRate; //--CFG_KDY
+  Double    m_MSEyuvframe[MAX_NUM_COMPONENT]; // sum of MSEs
+
+public:
+  virtual ~TEncAnalyze()  {}
+  TEncAnalyze() { clear(); }
+
+  Void  addResult( Double psnr[MAX_NUM_COMPONENT], Double bits, const Double MSEyuvframe[MAX_NUM_COMPONENT])
+  {
+    m_dAddBits  += bits;
+    for(UInt i=0; i<MAX_NUM_COMPONENT; i++)
+    {
+      m_dPSNRSum[i] += psnr[i];
+      m_MSEyuvframe[i] += MSEyuvframe[i];
+    }
+
+    m_uiNumPic++;
+  }
+
+  Double  getPsnr(ComponentID compID) const { return  m_dPSNRSum[compID];  }
+  Double  getBits()                   const { return  m_dAddBits;   }
+  Void    setBits(Double numBits)     { m_dAddBits=numBits; }
+  UInt    getNumPic()                 const { return  m_uiNumPic;   }
+
+  Void    setFrmRate  (Double dFrameRate) { m_dFrmRate = dFrameRate; } //--CFG_KDY
+  Void    clear()
+  {
+    m_dAddBits = 0;
+    for(UInt i=0; i<MAX_NUM_COMPONENT; i++)
+    {
+      m_dPSNRSum[i] = 0;
+      m_MSEyuvframe[i] = 0;
+    }
+    m_uiNumPic = 0;
+  }
+
+
+  Void calculateCombinedValues(const ChromaFormat chFmt, Double &PSNRyuv, Double &MSEyuv)
+  {
+    MSEyuv    = 0;
+    Int scale = 0;
+
+    Int maximumBitDepth = g_bitDepth[0];
+    for (UInt channelTypeIndex = 1; channelTypeIndex < MAX_NUM_CHANNEL_TYPE; channelTypeIndex++)
+      if (g_bitDepth[channelTypeIndex] > maximumBitDepth)
+        maximumBitDepth = g_bitDepth[channelTypeIndex];
+
+    const UInt maxval                = 255 << (maximumBitDepth - 8);
+    const UInt numberValidComponents = getNumberValidComponents(chFmt);
+
+    for (UInt comp=0; comp<numberValidComponents; comp++)
+    {
+      const ComponentID compID        = ComponentID(comp);
+      const UInt        csx           = getComponentScaleX(compID, chFmt);
+      const UInt        csy           = getComponentScaleY(compID, chFmt);
+      const Int         scaleChan     = (4>>(csx+csy));
+      const UInt        bitDepthShift = 2 * (maximumBitDepth - g_bitDepth[toChannelType(compID)]); //*2 because this is a squared number
+
+      const Double      channelMSE    = (m_MSEyuvframe[compID] * Double(1 << bitDepthShift)) / Double(getNumPic());
+
+      scale  += scaleChan;
+      MSEyuv += scaleChan * channelMSE;
+    }
+
+    MSEyuv /= Double(scale);  // i.e. divide by 6 for 4:2:0, 8 for 4:2:2 etc.
+    PSNRyuv = (MSEyuv==0 ? 999.99 : 10*log10((maxval*maxval)/MSEyuv));
+  }
+
+#if SVC_EXTENSION
+  Void    printOut ( Char cDelim, const ChromaFormat chFmt, const Bool printMSEBasedSNR, const Bool printSequenceMSE, UInt layer )
+#else
+  Void    printOut ( Char cDelim, const ChromaFormat chFmt, const Bool printMSEBasedSNR, const Bool printSequenceMSE )
+#endif
+  {
+    Double dFps     =   m_dFrmRate; //--CFG_KDY
+    Double dScale   = dFps / 1000 / (Double)m_uiNumPic;
+
+    Double MSEBasedSNR[MAX_NUM_COMPONENT];
+    if (printMSEBasedSNR)
+    {
+      for (UInt componentIndex = 0; componentIndex < MAX_NUM_COMPONENT; componentIndex++)
+      {
+        const ComponentID compID = ComponentID(componentIndex);
+
+        if (getNumPic() == 0) MSEBasedSNR[compID] = 0 * dScale; // this is the same calculation that will be evaluated for any other statistic when there are no frames (it should result in NaN). We use it here so all the output is consistent.
+        else
+        {
+          //NOTE: this is not the true maximum value for any bitDepth other than 8. It comes from the original HM PSNR calculation
+          const UInt maxval = 255 << (g_bitDepth[toChannelType(compID)] - 8);
+          const Double MSE = m_MSEyuvframe[compID];
+
+          MSEBasedSNR[compID] = (MSE == 0) ? 999.99 : (10 * log10((maxval * maxval) / (MSE / (Double)getNumPic())));
+        }
+      }
+    }
+
+    switch (chFmt)
+    {
+      case CHROMA_400:
+        if (printMSEBasedSNR)
+        {
+#if SVC_EXTENSION
+          if( layer == 0 )
+          {
+#endif
+          printf( "         \tTotal Frames |   "   "Bitrate     "  "Y-PSNR" );
+
+          if (printSequenceMSE) printf( "    Y-MSE\n" );
+          else printf("\n");
+
+          //printf( "\t------------ "  " ----------"   " -------- "  " -------- "  " --------\n" );
+#if SVC_EXTENSION
+          }
+
+          printf( "Average:  L%d \t %8d    %c "          "%12.4lf  "    "%8.4lf",
+                 layer,
+
+#else
+          printf( "Average: \t %8d    %c "          "%12.4lf  "    "%8.4lf",
+#endif
+                 getNumPic(), cDelim,
+                 getBits() * dScale,
+                 getPsnr(COMPONENT_Y) / (Double)getNumPic() );
+
+          if (printSequenceMSE)
+          {
+            printf( "  %8.4lf\n", m_MSEyuvframe[COMPONENT_Y ] / (Double)getNumPic() );
+          }
+          else printf("\n");
+
+#if SVC_EXTENSION
+          printf( "From MSE:  L%d \t %8d    %c "          "%12.4lf  "    "%8.4lf\n",
+                 layer,
+#else
+          printf( "From MSE:\t %8d    %c "          "%12.4lf  "    "%8.4lf\n",
+#endif
+                 getNumPic(), cDelim,
+                 getBits() * dScale,
+                 MSEBasedSNR[COMPONENT_Y] );
+        }
+        else
+        {
+          printf( "\tTotal Frames |   "   "Bitrate     "  "Y-PSNR" );
+
+          if (printSequenceMSE) printf( "    Y-MSE\n" );
+          else printf("\n");
+
+          //printf( "\t------------ "  " ----------"   " -------- "  " -------- "  " --------\n" );
+#if SVC_EXTENSION
+          printf( "  L%d \t %8d    %c "          "%12.4lf  "    "%8.4lf",
+                 layer,
+#else
+          printf( "\t %8d    %c "          "%12.4lf  "    "%8.4lf",
+#endif
+                 getNumPic(), cDelim,
+                 getBits() * dScale,
+                 getPsnr(COMPONENT_Y) / (Double)getNumPic() );
+
+          if (printSequenceMSE)
+          {
+            printf( "  %8.4lf\n", m_MSEyuvframe[COMPONENT_Y ] / (Double)getNumPic() );
+          }
+          else printf("\n");
+        }
+        break;
+      case CHROMA_420:
+      case CHROMA_422:
+      case CHROMA_444:
+        {
+          Double PSNRyuv = MAX_DOUBLE;
+          Double MSEyuv  = MAX_DOUBLE;
+          
+          calculateCombinedValues(chFmt, PSNRyuv, MSEyuv);
+
+          if (printMSEBasedSNR)
+          {
+#if SVC_EXTENSION
+            if( layer == 0 )
+            {
+#endif
+            printf( "         \tTotal Frames |   "   "Bitrate     "  "Y-PSNR    "  "U-PSNR    "  "V-PSNR    "  "YUV-PSNR " );
+
+            if (printSequenceMSE) printf( " Y-MSE     "  "U-MSE     "  "V-MSE    "  "YUV-MSE \n" );
+            else printf("\n");
+
+            //printf( "\t------------ "  " ----------"   " -------- "  " -------- "  " --------\n" );
+#if SVC_EXTENSION
+            }
+            printf( "Average:  L%d \t %8d    %c "          "%12.4lf  "    "%8.4lf  "   "%8.4lf  "    "%8.4lf  "   "%8.4lf",
+                   layer,
+#else
+            printf( "Average: \t %8d    %c "          "%12.4lf  "    "%8.4lf  "   "%8.4lf  "    "%8.4lf  "   "%8.4lf",
+#endif
+                   getNumPic(), cDelim,
+                   getBits() * dScale,
+                   getPsnr(COMPONENT_Y) / (Double)getNumPic(),
+                   getPsnr(COMPONENT_Cb) / (Double)getNumPic(),
+                   getPsnr(COMPONENT_Cr) / (Double)getNumPic(),
+                   PSNRyuv );
+
+            if (printSequenceMSE)
+            {
+              printf( "  %8.4lf  "   "%8.4lf  "    "%8.4lf  "   "%8.4lf\n",
+                     m_MSEyuvframe[COMPONENT_Y ] / (Double)getNumPic(),
+                     m_MSEyuvframe[COMPONENT_Cb] / (Double)getNumPic(),
+                     m_MSEyuvframe[COMPONENT_Cr] / (Double)getNumPic(),
+                     MSEyuv );
+            }
+            else printf("\n");
+
+#if SVC_EXTENSION
+            printf( "From MSE:  L%d \t %8d    %c "          "%12.4lf  "    "%8.4lf  "   "%8.4lf  "    "%8.4lf  "   "%8.4lf\n",
+                   layer,
+#else
+            printf( "From MSE:\t %8d    %c "          "%12.4lf  "    "%8.4lf  "   "%8.4lf  "    "%8.4lf  "   "%8.4lf\n",
+#endif
+                   getNumPic(), cDelim,
+                   getBits() * dScale,
+                   MSEBasedSNR[COMPONENT_Y],
+                   MSEBasedSNR[COMPONENT_Cb],
+                   MSEBasedSNR[COMPONENT_Cr],
+                   PSNRyuv );
+          }
+          else
+          {
+#if SVC_EXTENSION
+            if( layer == 0 )
+            {
+#endif
+            printf( "\tTotal Frames |   "   "Bitrate     "  "Y-PSNR    "  "U-PSNR    "  "V-PSNR    "  "YUV-PSNR " );
+            
+            if (printSequenceMSE) printf( " Y-MSE     "  "U-MSE     "  "V-MSE    "  "YUV-MSE \n" );
+            else printf("\n");
+
+            //printf( "\t------------ "  " ----------"   " -------- "  " -------- "  " --------\n" );
+#if SVC_EXTENSION
+            }
+            printf( "  L%d \t %8d    %c "          "%12.4lf  "    "%8.4lf  "   "%8.4lf  "    "%8.4lf  "   "%8.4lf",
+                   layer,
+#else
+            printf( "\t %8d    %c "          "%12.4lf  "    "%8.4lf  "   "%8.4lf  "    "%8.4lf  "   "%8.4lf",
+#endif
+                   getNumPic(), cDelim,
+                   getBits() * dScale,
+                   getPsnr(COMPONENT_Y) / (Double)getNumPic(),
+                   getPsnr(COMPONENT_Cb) / (Double)getNumPic(),
+                   getPsnr(COMPONENT_Cr) / (Double)getNumPic(),
+                   PSNRyuv );
+
+            if (printSequenceMSE)
+            {
+              printf( "  %8.4lf  "   "%8.4lf  "    "%8.4lf  "   "%8.4lf\n",
+                     m_MSEyuvframe[COMPONENT_Y ] / (Double)getNumPic(),
+                     m_MSEyuvframe[COMPONENT_Cb] / (Double)getNumPic(),
+                     m_MSEyuvframe[COMPONENT_Cr] / (Double)getNumPic(),
+                     MSEyuv );
+            }
+            else printf("\n");
+          }
+        }
+        break;
+      default:
+        fprintf(stderr, "Unknown format during print out\n");
+        exit(1);
+        break;
+    }
+  }
+
+
+  Void    printSummary(const ChromaFormat chFmt, const Bool printSequenceMSE, Char ch='T')
+  {
+    FILE* pFile = NULL;
+
+    switch( ch )
+    {
+      case 'T':
+        pFile = fopen ("summaryTotal.txt", "at");
+        break;
+      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;
+    switch (chFmt)
+    {
+      case CHROMA_400:
+        fprintf(pFile, "%f\t %f\n",
+            getBits() * dScale,
+            getPsnr(COMPONENT_Y) / (Double)getNumPic() );
+        break;
+      case CHROMA_420:
+      case CHROMA_422:
+      case CHROMA_444:
+        {
+          Double PSNRyuv = MAX_DOUBLE;
+          Double MSEyuv  = MAX_DOUBLE;
+          
+          calculateCombinedValues(chFmt, PSNRyuv, MSEyuv);
+
+          fprintf(pFile, "%f\t %f\t %f\t %f\t %f",
+              getBits() * dScale,
+              getPsnr(COMPONENT_Y) / (Double)getNumPic(),
+              getPsnr(COMPONENT_Cb) / (Double)getNumPic(),
+              getPsnr(COMPONENT_Cr) / (Double)getNumPic(),
+              PSNRyuv );
+
+          if (printSequenceMSE)
+          {
+            fprintf(pFile, "\t %f\t %f\t %f\t %f\n",
+                m_MSEyuvframe[COMPONENT_Y ] / (Double)getNumPic(),
+                m_MSEyuvframe[COMPONENT_Cb] / (Double)getNumPic(),
+                m_MSEyuvframe[COMPONENT_Cr] / (Double)getNumPic(),
+                MSEyuv );
+          }
+          else fprintf(pFile, "\n");
+
+          break;
+        }
+
+      default:
+          fprintf(stderr, "Unknown format during print out\n");
+          exit(1);
+          break;
+    }
+
+    fclose(pFile);
+  }
+};
+
+#if SVC_EXTENSION
+extern TEncAnalyze             m_gcAnalyzeAll [MAX_LAYERS];
+extern TEncAnalyze             m_gcAnalyzeI [MAX_LAYERS];
+extern TEncAnalyze             m_gcAnalyzeP [MAX_LAYERS];
+extern TEncAnalyze             m_gcAnalyzeB [MAX_LAYERS];
+#else
+extern TEncAnalyze             m_gcAnalyzeAll;
+extern TEncAnalyze             m_gcAnalyzeI;
+extern TEncAnalyze             m_gcAnalyzeP;
+extern TEncAnalyze             m_gcAnalyzeB;
+#endif
+
+extern TEncAnalyze             m_gcAnalyzeAll_in;
+
+//! \}
+
+#endif // !defined(AFX_TENCANALYZE_H__C79BCAA2_6AC8_4175_A0FE_CF02F5829233__INCLUDED_)
Index: /tags/SHM-9.0/source/Lib/TLibEncoder/TEncBinCoder.h
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibEncoder/TEncBinCoder.h	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibEncoder/TEncBinCoder.h	(revision 1088)
@@ -0,0 +1,83 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TEncBinCoder.h
+    \brief    binary entropy encoder interface
+*/
+
+#ifndef __TENCBINCODER__
+#define __TENCBINCODER__
+
+#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         ( const 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 Void  align             ()                                          = 0;
+
+  virtual TEncBinCABAC*   getTEncBinCABAC   ()  { return 0; }
+  virtual const TEncBinCABAC*   getTEncBinCABAC   () const { return 0; }
+
+  virtual ~TEncBinIf() {}
+};
+
+//! \}
+
+#endif
+
Index: /tags/SHM-9.0/source/Lib/TLibEncoder/TEncBinCoderCABAC.cpp
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibEncoder/TEncBinCoderCABAC.cpp	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibEncoder/TEncBinCoderCABAC.cpp	(revision 1088)
@@ -0,0 +1,440 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TEncBinCoderCABAC.cpp
+    \brief    binary entropy encoder of CABAC
+*/
+
+#include "TEncBinCoderCABAC.h"
+#include "TLibCommon/TComRom.h"
+#include "TLibCommon/Debug.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;
+#if FAST_BIT_EST
+  m_fracBits         = 0;
+#endif
+}
+
+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( const TEncBinIf* pcTEncBinIf )
+{
+  const 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 )
+{
+  //{
+  //  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" )
+  //}
+
+#ifdef DEBUG_CABAC_BINS
+  const UInt startingRange = m_uiRange;
+#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;
+    testAndWriteOut();
+  }
+  else
+  {
+    rcCtxModel.updateMPS();
+
+    if ( m_uiRange < 256 )
+    {
+      m_uiLow <<= 1;
+      m_uiRange <<= 1;
+      m_bitsLeft--;
+      testAndWriteOut();
+    }
+  }
+
+#ifdef DEBUG_CABAC_BINS
+  if ((g_debugCounter + debugCabacBinWindow) >= debugCabacBinTargetLine)
+    std::cout << g_debugCounter << ": coding bin value " << binValue << ", range = [" << startingRange << "->" << m_uiRange << "]\n";
+
+  if (g_debugCounter >= debugCabacBinTargetLine)
+  {
+    Char breakPointThis;
+    breakPointThis = 7;
+  }
+  if (g_debugCounter >= (debugCabacBinTargetLine + debugCabacBinWindow)) exit(0);
+  g_debugCounter++;
+#endif
+}
+
+/**
+ * \brief Encode equiprobable bin
+ *
+ * \param binValue bin value
+ */
+Void TEncBinCABAC::encodeBinEP( UInt binValue )
+{
+  if (false)
+  {
+    DTRACE_CABAC_VL( g_nSymbolCounter++ )
+    DTRACE_CABAC_T( "\tEPsymbol=" )
+    DTRACE_CABAC_V( binValue )
+    DTRACE_CABAC_T( "\n" )
+  }
+
+  m_uiBinsCoded += m_binCountIncrement;
+
+  if (m_uiRange == 256)
+  {
+    encodeAlignedBinsEP(binValue, 1);
+    return;
+  }
+
+  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;
+
+  if (false)
+  {
+    for ( Int i = 0; i < numBins; i++ )
+    {
+      DTRACE_CABAC_VL( g_nSymbolCounter++ )
+      DTRACE_CABAC_T( "\tEPsymbol=" )
+      DTRACE_CABAC_V( ( binValues >> ( numBins - 1 - i ) ) & 1 )
+      DTRACE_CABAC_T( "\n" )
+    }
+  }
+
+  if (m_uiRange == 256)
+  {
+    encodeAlignedBinsEP(binValues, numBins);
+    return;
+  }
+
+  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();
+}
+
+Void TEncBinCABAC::align()
+{
+  m_uiRange = 256;
+}
+
+Void TEncBinCABAC::encodeAlignedBinsEP( UInt binValues, Int numBins )
+{
+  Int binsRemaining = numBins;
+
+  assert(m_uiRange == 256); //aligned encode only works when range = 256
+
+  while (binsRemaining > 0)
+  {
+    const UInt binsToCode = std::min<UInt>(binsRemaining, 8); //code bytes if able to take advantage of the system's byte-write function
+    const UInt binMask    = (1 << binsToCode) - 1;
+
+    const UInt newBins = (binValues >> (binsRemaining - binsToCode)) & binMask;
+
+    //The process of encoding an EP bin is the same as that of coding a normal
+    //bin where the symbol ranges for 1 and 0 are both half the range:
+    //
+    //  low = (low + range/2) << 1       (to encode a 1)
+    //  low =  low            << 1       (to encode a 0)
+    //
+    //  i.e.
+    //  low = (low + (bin * range/2)) << 1
+    //
+    //  which is equivalent to:
+    //
+    //  low = (low << 1) + (bin * range)
+    //
+    //  this can be generalised for multiple bins, producing the following expression:
+    //
+    m_uiLow = (m_uiLow << binsToCode) + (newBins << 8); //range is known to be 256
+
+    binsRemaining -= binsToCode;
+    m_bitsLeft    -= binsToCode;
+
+    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: /tags/SHM-9.0/source/Lib/TLibEncoder/TEncBinCoderCABAC.h
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibEncoder/TEncBinCoderCABAC.h	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibEncoder/TEncBinCoderCABAC.h	(revision 1088)
@@ -0,0 +1,108 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TEncBinCoderCABAC.h
+    \brief    binary entropy encoder of CABAC
+*/
+
+#ifndef __TENCBINCODERCABAC__
+#define __TENCBINCODERCABAC__
+
+#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         ( const 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                            );
+
+  Void  align             ();
+  Void  encodeAlignedBinsEP( UInt  binValues, Int numBins             );
+
+  TEncBinCABAC* getTEncBinCABAC()  { return this; }
+  const TEncBinCABAC* getTEncBinCABAC() const { 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: /tags/SHM-9.0/source/Lib/TLibEncoder/TEncBinCoderCABACCounter.cpp
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibEncoder/TEncBinCoderCABACCounter.cpp	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibEncoder/TEncBinCoderCABACCounter.cpp	(revision 1088)
@@ -0,0 +1,139 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TEncBinCoderCABAC.cpp
+    \brief    binary entropy encoder of CABAC
+*/
+
+#include "TEncBinCoderCABACCounter.h"
+#include "TLibCommon/TComRom.h"
+#include "TLibCommon/Debug.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 )
+{
+#ifdef DEBUG_ENCODER_SEARCH_BINS
+  const UInt64 startingFracBits = m_fracBits;
+#endif
+
+  m_uiBinsCoded += m_binCountIncrement;
+  m_fracBits += rcCtxModel.getEntropyBits( binValue );
+  rcCtxModel.update( binValue );
+
+#ifdef DEBUG_ENCODER_SEARCH_BINS
+  if ((g_debugCounter + debugEncoderSearchBinWindow) >= debugEncoderSearchBinTargetLine)
+    std::cout << g_debugCounter << ": coding bin value " << binValue << ", fracBits = [" << startingFracBits << "->" << m_fracBits << "]\n";
+
+  if (g_debugCounter >= debugEncoderSearchBinTargetLine)
+  {
+    Char breakPointThis;
+    breakPointThis = 7;
+  }
+  if (g_debugCounter >= (debugEncoderSearchBinTargetLine + debugEncoderSearchBinWindow)) exit(0);
+  g_debugCounter++;
+#endif
+}
+
+/**
+ * \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 );
+}
+
+Void TEncBinCABACCounter::align()
+{
+  m_fracBits = (m_fracBits + 32767) & (~32767);
+}
+
+//! \}
+#endif
+
Index: /tags/SHM-9.0/source/Lib/TLibEncoder/TEncBinCoderCABACCounter.h
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibEncoder/TEncBinCoderCABACCounter.h	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibEncoder/TEncBinCoderCABACCounter.h	(revision 1088)
@@ -0,0 +1,74 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TEncBinCoderCABAC.h
+    \brief    binary entropy encoder of CABAC
+*/
+
+#ifndef __TENCBINCODERCABACCOUNTER__
+#define __TENCBINCODERCABACCOUNTER__
+
+
+#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                            );
+
+  Void  align             ();
+
+private:
+};
+
+//! \}
+
+#endif
+
+#endif
+
Index: /tags/SHM-9.0/source/Lib/TLibEncoder/TEncCavlc.cpp
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibEncoder/TEncCavlc.cpp	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibEncoder/TEncCavlc.cpp	(revision 1088)
@@ -0,0 +1,3454 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TEncCavlc.cpp
+    \brief    CAVLC encoder class
+*/
+
+#include "../TLibCommon/CommonDef.h"
+#include "TEncCavlc.h"
+#include "SEIwrite.h"
+
+//! \ingroup TLibEncoder
+//! \{
+
+#if ENC_DEC_TRACE
+
+Void  xTraceSPSHeader (TComSPS *pSPS)
+{
+  fprintf( g_hTrace, "=========== Sequence Parameter Set ID: %d ===========\n", pSPS->getSPSId() );
+}
+
+Void  xTracePPSHeader (TComPPS *pPPS)
+{
+  fprintf( g_hTrace, "=========== Picture Parameter Set ID: %d ===========\n", pPPS->getPPSId() );
+}
+
+Void  xTraceSliceHeader (TComSlice *pSlice)
+{
+  fprintf( g_hTrace, "=========== Slice ===========\n");
+}
+
+#endif
+
+
+
+// ====================================================================================================================
+// Constructor / destructor / create / destroy
+// ====================================================================================================================
+
+TEncCavlc::TEncCavlc()
+{
+  m_pcBitIf           = NULL;
+}
+
+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 Q0048_CGS_3D_ASYMLUT
+  , TEnc3DAsymLUT * pc3DAsymLUT
+#endif
+  )
+{
+#if ENC_DEC_TRACE
+  xTracePPSHeader (pcPPS);
+#endif
+
+  const UInt numberValidComponents = getNumberValidComponents(pcPPS->getSPS()->getChromaFormatIdc());
+
+  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( COMPONENT_Cb<numberValidComponents ?  (pcPPS->getQpOffset(COMPONENT_Cb)) : 0, "pps_cb_qp_offset" );
+  WRITE_SVLC( COMPONENT_Cr<numberValidComponents ?  (pcPPS->getQpOffset(COMPONENT_Cr)) : 0, "pps_cr_qp_offset" );
+
+  assert(numberValidComponents <= 3); // if more than 3 components (eg 4:4:4:4), then additional offsets will have to go in extension area...
+
+  WRITE_FLAG( pcPPS->getSliceChromaQpFlag() ? 1 : 0,          "pps_slice_chroma_qp_offsets_present_flag" );
+
+  WRITE_FLAG( pcPPS->getUseWP() ? 1 : 0,  "weighted_pred_flag" );   // Use of Weighting Prediction (P_SLICE)
+  WRITE_FLAG( pcPPS->getWPBiPred() ? 1 : 0, "weighted_bipred_flag" );  // Use of Weighting Bi-Prediction (B_SLICE)
+  WRITE_FLAG( pcPPS->getTransquantBypassEnableFlag() ? 1 : 0, "transquant_bypass_enable_flag" );
+  WRITE_FLAG( pcPPS->getTilesEnabledFlag()             ? 1 : 0, "tiles_enabled_flag" );
+  WRITE_FLAG( pcPPS->getEntropyCodingSyncEnabledFlag() ? 1 : 0, "entropy_coding_sync_enabled_flag" );
+  if( pcPPS->getTilesEnabledFlag() )
+  {
+    WRITE_UVLC( pcPPS->getNumTileColumnsMinus1(),                                    "num_tile_columns_minus1" );
+    WRITE_UVLC( pcPPS->getNumTileRowsMinus1(),                                       "num_tile_rows_minus1" );
+    WRITE_FLAG( pcPPS->getTileUniformSpacingFlag(),                                  "uniform_spacing_flag" );
+    if( !pcPPS->getTileUniformSpacingFlag() )
+    {
+      for(UInt i=0; i<pcPPS->getNumTileColumnsMinus1(); i++)
+      {
+        WRITE_UVLC( pcPPS->getTileColumnWidth(i)-1,                                  "column_width_minus1" );
+      }
+      for(UInt i=0; i<pcPPS->getNumTileRowsMinus1(); i++)
+      {
+        WRITE_UVLC( pcPPS->getTileRowHeight(i)-1,                                    "row_height_minus1" );
+      }
+    }
+    if(pcPPS->getNumTileColumnsMinus1() !=0 || pcPPS->getNumTileRowsMinus1() !=0)
+    {
+      WRITE_FLAG( pcPPS->getLoopFilterAcrossTilesEnabledFlag()?1 : 0,          "loop_filter_across_tiles_enabled_flag");
+    }
+  }
+  WRITE_FLAG( pcPPS->getLoopFilterAcrossSlicesEnabledFlag()?1 : 0,        "loop_filter_across_slices_enabled_flag");
+  WRITE_FLAG( pcPPS->getDeblockingFilterControlPresentFlag()?1 : 0,       "deblocking_filter_control_present_flag");
+  if(pcPPS->getDeblockingFilterControlPresentFlag())
+  {
+    WRITE_FLAG( pcPPS->getDeblockingFilterOverrideEnabledFlag() ? 1 : 0,  "deblocking_filter_override_enabled_flag" );
+    WRITE_FLAG( pcPPS->getPicDisableDeblockingFilterFlag() ? 1 : 0,       "pps_disable_deblocking_filter_flag" );
+    if(!pcPPS->getPicDisableDeblockingFilterFlag())
+    {
+      WRITE_SVLC( pcPPS->getDeblockingFilterBetaOffsetDiv2(),             "pps_beta_offset_div2" );
+      WRITE_SVLC( pcPPS->getDeblockingFilterTcOffsetDiv2(),               "pps_tc_offset_div2" );
+    }
+  }
+  WRITE_FLAG( pcPPS->getScalingListPresentFlag() ? 1 : 0,                          "pps_scaling_list_data_present_flag" );
+  if( pcPPS->getScalingListPresentFlag() )
+  {
+    codeScalingList( m_pcSlice->getScalingList() );
+  }
+  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");
+
+  Bool pps_extension_present_flag=false;
+  Bool pps_extension_flags[NUM_PPS_EXTENSION_FLAGS]={false};
+
+  pps_extension_flags[PPS_EXT__REXT] = (
+             ( pcPPS->getUseTransformSkip() && (pcPPS->getTransformSkipLog2MaxSize() != 2))
+          || pcPPS->getUseCrossComponentPrediction()
+          || ( pcPPS->getChromaQpAdjTableSize() > 0 )
+          || ( pcPPS->getSaoOffsetBitShift(CHANNEL_TYPE_LUMA) !=0 ) || ( pcPPS->getSaoOffsetBitShift(CHANNEL_TYPE_CHROMA) !=0 )
+     )
+    ;
+
+  // Other PPS extension flags checked here.
+
+#if SVC_EXTENSION
+  pps_extension_flags[PPS_EXT__MLAYER] = pcPPS->getExtensionFlag() ? 1 : 0;
+#if Q0048_CGS_3D_ASYMLUT
+  UInt bits = 0;
+#endif
+#endif
+
+  for(Int i=0; i<NUM_PPS_EXTENSION_FLAGS; i++)
+  {
+    pps_extension_present_flag|=pps_extension_flags[i];
+  }
+
+  WRITE_FLAG( (pps_extension_present_flag?1:0), "pps_extension_present_flag" );
+
+  if (pps_extension_present_flag)
+  {
+    for(Int i=0; i<NUM_PPS_EXTENSION_FLAGS; i++)
+    {
+      WRITE_FLAG( pps_extension_flags[i]?1:0, "pps_extension_flag[]" );
+    }
+
+    for(Int i=0; i<NUM_PPS_EXTENSION_FLAGS; i++) // loop used so that the order is determined by the enum.
+    {
+      if (pps_extension_flags[i])
+      {
+        switch (PPSExtensionFlagIndex(i))
+        {
+          case PPS_EXT__REXT:
+
+            if (pcPPS->getUseTransformSkip())
+            {
+              WRITE_UVLC( pcPPS->getTransformSkipLog2MaxSize()-2,                 "log2_transform_skip_max_size_minus2");
+            }
+
+            WRITE_FLAG((pcPPS->getUseCrossComponentPrediction() ? 1 : 0),         "cross_component_prediction_flag" );
+
+            WRITE_FLAG(UInt(pcPPS->getChromaQpAdjTableSize() > 0),                "chroma_qp_adjustment_enabled_flag" );
+            if (pcPPS->getChromaQpAdjTableSize() > 0)
+            {
+              WRITE_UVLC(pcPPS->getMaxCuChromaQpAdjDepth(),                       "diff_cu_chroma_qp_adjustment_depth");
+              WRITE_UVLC(pcPPS->getChromaQpAdjTableSize() - 1,                    "chroma_qp_adjustment_table_size_minus1");
+              /* skip zero index */
+              for (Int chromaQpAdjustmentIndex = 1; chromaQpAdjustmentIndex <= pcPPS->getChromaQpAdjTableSize(); chromaQpAdjustmentIndex++)
+              {
+                WRITE_SVLC(pcPPS->getChromaQpAdjTableAt(chromaQpAdjustmentIndex).u.comp.CbOffset,     "cb_qp_adjustnemt[i]");
+                WRITE_SVLC(pcPPS->getChromaQpAdjTableAt(chromaQpAdjustmentIndex).u.comp.CrOffset,     "cr_qp_adjustnemt[i]");
+              }
+            }
+
+            WRITE_UVLC( pcPPS->getSaoOffsetBitShift(CHANNEL_TYPE_LUMA),           "sao_luma_bit_shift"   );
+            WRITE_UVLC( pcPPS->getSaoOffsetBitShift(CHANNEL_TYPE_CHROMA),         "sao_chroma_bit_shift" );
+            break;
+#if SVC_EXTENSION
+          case PPS_EXT__MLAYER:
+            WRITE_FLAG( pcPPS->getPocResetInfoPresentFlag() ? 1 : 0, "poc_reset_info_present_flag" );
+#if SCALINGLIST_INFERRING
+            WRITE_FLAG( pcPPS->getInferScalingListFlag() ? 1 : 0, "pps_infer_scaling_list_flag" );
+            if( pcPPS->getInferScalingListFlag() )
+            {
+              // The value of pps_scaling_list_ref_layer_id shall be in the range of 0 to 62, inclusive
+              assert( pcPPS->getScalingListRefLayerId() <= 62 );
+              WRITE_CODE( pcPPS->getScalingListRefLayerId(), 6, "pps_scaling_list_ref_layer_id" );
+            }
+#endif
+
+#if REF_REGION_OFFSET
+            WRITE_UVLC( pcPPS->getNumRefLayerLocationOffsets(),      "num_ref_loc_offsets" );
+            for(Int k = 0; k < pcPPS->getNumRefLayerLocationOffsets(); k++)
+            {
+              WRITE_CODE( pcPPS->getRefLocationOffsetLayerId(k), 6, "ref_loc_offset_layer_id" );
+              WRITE_FLAG( pcPPS->getScaledRefLayerOffsetPresentFlag(k) ? 1 : 0, "scaled_ref_layer_offset_prsent_flag" );
+              if (pcPPS->getScaledRefLayerOffsetPresentFlag(k))
+              {
+                Window scaledWindow = pcPPS->getScaledRefLayerWindow(k);
+                WRITE_SVLC( scaledWindow.getWindowLeftOffset()   >> 1, "scaled_ref_layer_left_offset" );
+                WRITE_SVLC( scaledWindow.getWindowTopOffset()    >> 1, "scaled_ref_layer_top_offset" );
+                WRITE_SVLC( scaledWindow.getWindowRightOffset()  >> 1, "scaled_ref_layer_right_offset" );
+                WRITE_SVLC( scaledWindow.getWindowBottomOffset() >> 1, "scaled_ref_layer_bottom_offset" );
+              }
+              WRITE_FLAG( pcPPS->getRefRegionOffsetPresentFlag(k) ? 1 : 0, "ref_region_offset_prsent_flag" );
+              if (pcPPS->getRefRegionOffsetPresentFlag(k))
+              {
+                Window refWindow = pcPPS->getRefLayerWindow(k);
+                WRITE_SVLC( refWindow.getWindowLeftOffset()   >> 1, "ref_region_left_offset" );
+                WRITE_SVLC( refWindow.getWindowTopOffset()    >> 1, "ref_region_top_offset" );
+                WRITE_SVLC( refWindow.getWindowRightOffset()  >> 1, "ref_region_right_offset" );
+                WRITE_SVLC( refWindow.getWindowBottomOffset() >> 1, "ref_region_bottom_offset" );
+              }
+#if R0209_GENERIC_PHASE
+              WRITE_FLAG( pcPPS->getResamplePhaseSetPresentFlag(k) ? 1 : 0, "resample_phase_set_present_flag" );
+              if (pcPPS->getResamplePhaseSetPresentFlag(k))
+              {
+                WRITE_UVLC( pcPPS->getPhaseHorLuma(k), "phase_hor_luma" );
+                WRITE_UVLC( pcPPS->getPhaseVerLuma(k), "phase_ver_luma" );
+                WRITE_UVLC( pcPPS->getPhaseHorChroma(k) + 8, "phase_hor_chroma_plus8" );
+                WRITE_UVLC( pcPPS->getPhaseVerChroma(k) + 8, "phase_ver_chroma_plus8" );
+              }
+#endif
+            }
+#else
+#if MOVE_SCALED_OFFSET_TO_PPS
+            WRITE_UVLC( pcPPS->getNumScaledRefLayerOffsets(),      "num_scaled_ref_layer_offsets" );
+            for(Int k = 0; k < pcPPS->getNumScaledRefLayerOffsets(); k++)
+            {
+              Window scaledWindow = pcPPS->getScaledRefLayerWindow(k);
+#if O0098_SCALED_REF_LAYER_ID
+              WRITE_CODE( pcPPS->getScaledRefLayerId(k), 6,          "scaled_ref_layer_id" );
+#endif
+              WRITE_SVLC( scaledWindow.getWindowLeftOffset()   >> 1, "scaled_ref_layer_left_offset" );
+              WRITE_SVLC( scaledWindow.getWindowTopOffset()    >> 1, "scaled_ref_layer_top_offset" );
+              WRITE_SVLC( scaledWindow.getWindowRightOffset()  >> 1, "scaled_ref_layer_right_offset" );
+              WRITE_SVLC( scaledWindow.getWindowBottomOffset() >> 1, "scaled_ref_layer_bottom_offset" );
+            }
+#endif
+#endif
+#if Q0048_CGS_3D_ASYMLUT
+            bits = getNumberOfWrittenBits();
+            WRITE_FLAG( pcPPS->getCGSFlag() , "colour_mapping_enabled_flag" );
+            if( pcPPS->getCGSFlag() )
+            {
+              assert( pc3DAsymLUT != NULL );
+              xCode3DAsymLUT( pc3DAsymLUT );
+            }
+            pc3DAsymLUT->setPPSBit( getNumberOfWrittenBits() - bits );
+#endif
+            break;
+#endif
+          default:
+            assert(pps_extension_flags[i]==false); // Should never get here with an active PPS extension flag.
+            break;
+        } // switch
+      } // if flag present
+    } // loop over PPS flags
+  } // pps_extension_present_flag is non-zero
+}
+
+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()  / TComSPS::getWinUnitX(pcSPS->getChromaFormatIdc()), "def_disp_win_left_offset");
+    WRITE_UVLC(defaultDisplayWindow.getWindowRightOffset() / TComSPS::getWinUnitX(pcSPS->getChromaFormatIdc()), "def_disp_win_right_offset");
+    WRITE_UVLC(defaultDisplayWindow.getWindowTopOffset()   / TComSPS::getWinUnitY(pcSPS->getChromaFormatIdc()), "def_disp_win_top_offset");
+    WRITE_UVLC(defaultDisplayWindow.getWindowBottomOffset()/ TComSPS::getWinUnitY(pcSPS->getChromaFormatIdc()), "def_disp_win_bottom_offset");
+  }
+  TimingInfo *timingInfo = pcVUI->getTimingInfo();
+  WRITE_FLAG(timingInfo->getTimingInfoPresentFlag(),          "vui_timing_info_present_flag");
+  if(timingInfo->getTimingInfoPresentFlag())
+  {
+    WRITE_CODE(timingInfo->getNumUnitsInTick(), 32,           "vui_num_units_in_tick");
+    WRITE_CODE(timingInfo->getTimeScale(),      32,           "vui_time_scale");
+    WRITE_FLAG(timingInfo->getPocProportionalToTimingFlag(),  "vui_poc_proportional_to_timing_flag");
+    if(timingInfo->getPocProportionalToTimingFlag())
+    {
+      WRITE_UVLC(timingInfo->getNumTicksPocDiffOneMinus1(),   "vui_num_ticks_poc_diff_one_minus1");
+    }
+    WRITE_FLAG(pcVUI->getHrdParametersPresentFlag(),              "hrd_parameters_present_flag");
+    if( pcVUI->getHrdParametersPresentFlag() )
+    {
+      codeHrdParameters(pcVUI->getHrdParameters(), 1, pcSPS->getMaxTLayers() - 1 );
+    }
+  }
+
+  WRITE_FLAG(pcVUI->getBitstreamRestrictionFlag(),              "bitstream_restriction_flag");
+  if (pcVUI->getBitstreamRestrictionFlag())
+  {
+    WRITE_FLAG(pcVUI->getTilesFixedStructureFlag(),             "tiles_fixed_structure_flag");
+    WRITE_FLAG(pcVUI->getMotionVectorsOverPicBoundariesFlag(),  "motion_vectors_over_pic_boundaries_flag");
+    WRITE_FLAG(pcVUI->getRestrictedRefPicListsFlag(),           "restricted_ref_pic_lists_flag");
+    WRITE_UVLC(pcVUI->getMinSpatialSegmentationIdc(),           "min_spatial_segmentation_idc");
+    WRITE_UVLC(pcVUI->getMaxBytesPerPicDenom(),                 "max_bytes_per_pic_denom");
+    WRITE_UVLC(pcVUI->getMaxBitsPerMinCuDenom(),                "max_bits_per_mincu_denom");
+    WRITE_UVLC(pcVUI->getLog2MaxMvLengthHorizontal(),           "log2_max_mv_length_horizontal");
+    WRITE_UVLC(pcVUI->getLog2MaxMvLengthVertical(),             "log2_max_mv_length_vertical");
+  }
+}
+
+Void TEncCavlc::codeHrdParameters( TComHRD *hrd, Bool commonInfPresentFlag, UInt maxNumSubLayersMinus1 )
+{
+  if( commonInfPresentFlag )
+  {
+    WRITE_FLAG( hrd->getNalHrdParametersPresentFlag() ? 1 : 0 ,  "nal_hrd_parameters_present_flag" );
+    WRITE_FLAG( hrd->getVclHrdParametersPresentFlag() ? 1 : 0 ,  "vcl_hrd_parameters_present_flag" );
+    if( hrd->getNalHrdParametersPresentFlag() || hrd->getVclHrdParametersPresentFlag() )
+    {
+      WRITE_FLAG( hrd->getSubPicCpbParamsPresentFlag() ? 1 : 0,  "sub_pic_cpb_params_present_flag" );
+      if( hrd->getSubPicCpbParamsPresentFlag() )
+      {
+        WRITE_CODE( hrd->getTickDivisorMinus2(), 8,              "tick_divisor_minus2" );
+        WRITE_CODE( hrd->getDuCpbRemovalDelayLengthMinus1(), 5,  "du_cpb_removal_delay_length_minus1" );
+        WRITE_FLAG( hrd->getSubPicCpbParamsInPicTimingSEIFlag() ? 1 : 0, "sub_pic_cpb_params_in_pic_timing_sei_flag" );
+        WRITE_CODE( hrd->getDpbOutputDelayDuLengthMinus1(), 5,   "dpb_output_delay_du_length_minus1"  );
+      }
+      WRITE_CODE( hrd->getBitRateScale(), 4,                     "bit_rate_scale" );
+      WRITE_CODE( hrd->getCpbSizeScale(), 4,                     "cpb_size_scale" );
+      if( hrd->getSubPicCpbParamsPresentFlag() )
+      {
+        WRITE_CODE( hrd->getDuCpbSizeScale(), 4,                "du_cpb_size_scale" );
+      }
+      WRITE_CODE( hrd->getInitialCpbRemovalDelayLengthMinus1(), 5, "initial_cpb_removal_delay_length_minus1" );
+      WRITE_CODE( hrd->getCpbRemovalDelayLengthMinus1(),        5, "au_cpb_removal_delay_length_minus1" );
+      WRITE_CODE( hrd->getDpbOutputDelayLengthMinus1(),         5, "dpb_output_delay_length_minus1" );
+    }
+  }
+  Int i, j, nalOrVcl;
+  for( i = 0; i <= maxNumSubLayersMinus1; i ++ )
+  {
+    WRITE_FLAG( hrd->getFixedPicRateFlag( i ) ? 1 : 0,          "fixed_pic_rate_general_flag");
+    if( !hrd->getFixedPicRateFlag( i ) )
+    {
+      WRITE_FLAG( hrd->getFixedPicRateWithinCvsFlag( i ) ? 1 : 0, "fixed_pic_rate_within_cvs_flag");
+    }
+    else
+    {
+      hrd->setFixedPicRateWithinCvsFlag( i, true );
+    }
+    if( hrd->getFixedPicRateWithinCvsFlag( i ) )
+    {
+      WRITE_UVLC( hrd->getPicDurationInTcMinus1( i ),           "elemental_duration_in_tc_minus1");
+    }
+    else
+    {
+      WRITE_FLAG( hrd->getLowDelayHrdFlag( i ) ? 1 : 0,           "low_delay_hrd_flag");
+    }
+    if (!hrd->getLowDelayHrdFlag( i ))
+    {
+      WRITE_UVLC( hrd->getCpbCntMinus1( i ),                      "cpb_cnt_minus1");
+    }
+
+    for( nalOrVcl = 0; nalOrVcl < 2; nalOrVcl ++ )
+    {
+      if( ( ( nalOrVcl == 0 ) && ( hrd->getNalHrdParametersPresentFlag() ) ) ||
+          ( ( nalOrVcl == 1 ) && ( hrd->getVclHrdParametersPresentFlag() ) ) )
+      {
+        for( j = 0; j <= ( hrd->getCpbCntMinus1( i ) ); j ++ )
+        {
+          WRITE_UVLC( hrd->getBitRateValueMinus1( i, j, nalOrVcl ), "bit_rate_value_minus1");
+          WRITE_UVLC( hrd->getCpbSizeValueMinus1( i, j, nalOrVcl ), "cpb_size_value_minus1");
+          if( hrd->getSubPicCpbParamsPresentFlag() )
+          {
+            WRITE_UVLC( hrd->getDuCpbSizeValueMinus1( i, j, nalOrVcl ), "cpb_size_du_value_minus1");
+            WRITE_UVLC( hrd->getDuBitRateValueMinus1( i, j, nalOrVcl ), "bit_rate_du_value_minus1");
+          }
+          WRITE_FLAG( hrd->getCbrFlag( i, j, nalOrVcl ) ? 1 : 0, "cbr_flag");
+        }
+      }
+    }
+  }
+}
+
+Void TEncCavlc::codeSPS( TComSPS* pcSPS )
+{
+#if SVC_EXTENSION
+  Bool V1CompatibleSPSFlag = !(pcSPS->getLayerId() != 0 && pcSPS->getNumDirectRefLayers() != 0);
+#endif
+
+  const ChromaFormat format                = pcSPS->getChromaFormatIdc();
+  const Bool         chromaEnabled         = isChromaEnabled(format);
+
+#if ENC_DEC_TRACE
+  xTraceSPSHeader (pcSPS);
+#endif
+  WRITE_CODE( pcSPS->getVPSId (),          4,       "sps_video_parameter_set_id" );
+#if SVC_EXTENSION
+  if(pcSPS->getLayerId() == 0)
+  {
+#endif
+  WRITE_CODE( pcSPS->getMaxTLayers() - 1,  3,       "sps_max_sub_layers_minus1" );
+#if SVC_EXTENSION
+  }
+  else
+  {
+    WRITE_CODE( V1CompatibleSPSFlag ? (pcSPS->getMaxTLayers() - 1) : 7,  3,       "sps_ext_or_max_sub_layers_minus1" );
+  }
+
+  if( V1CompatibleSPSFlag )
+  {
+#endif
+  WRITE_FLAG( pcSPS->getTemporalIdNestingFlag() ? 1 : 0,                             "sps_temporal_id_nesting_flag" );
+  codePTL(pcSPS->getPTL(), 1, pcSPS->getMaxTLayers() - 1);
+#if SVC_EXTENSION
+  }
+#endif
+  WRITE_UVLC( pcSPS->getSPSId (),                   "sps_seq_parameter_set_id" );
+#if SVC_EXTENSION
+  if( !V1CompatibleSPSFlag )
+  {
+    WRITE_FLAG( pcSPS->getUpdateRepFormatFlag(), "update_rep_format_flag" );
+  
+    if( pcSPS->getUpdateRepFormatFlag())
+    {
+      WRITE_CODE( pcSPS->getUpdateRepFormatIndex(), 8,   "sps_rep_format_idx");
+    }
+  }
+  else
+  {
+#endif
+  WRITE_UVLC( Int(pcSPS->getChromaFormatIdc ()),    "chroma_format_idc" );
+  if( format == CHROMA_444 )
+  {
+    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())
+  {
+#if REPN_FORMAT_IN_VPS
+    WRITE_UVLC( conf.getWindowLeftOffset(),   "conf_win_left_offset"   );
+    WRITE_UVLC( conf.getWindowRightOffset(),  "conf_win_right_offset"  );
+    WRITE_UVLC( conf.getWindowTopOffset(),    "conf_win_top_offset"    );
+    WRITE_UVLC( conf.getWindowBottomOffset(), "conf_win_bottom_offset" );
+#else
+    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" );
+#endif
+  }
+#if SVC_EXTENSION
+  }
+
+  if( V1CompatibleSPSFlag )
+  {
+#endif
+  WRITE_UVLC( pcSPS->getBitDepth(CHANNEL_TYPE_LUMA) - 8,                      "bit_depth_luma_minus8" );
+
+  WRITE_UVLC( chromaEnabled ? (pcSPS->getBitDepth(CHANNEL_TYPE_CHROMA) - 8):0,  "bit_depth_chroma_minus8" );
+#if SVC_EXTENSION
+  }
+#endif
+
+  WRITE_UVLC( pcSPS->getBitsForPOC()-4,                 "log2_max_pic_order_cnt_lsb_minus4" );
+
+#if SVC_EXTENSION
+  if( V1CompatibleSPSFlag )
+  {
+#endif
+  const Bool subLayerOrderingInfoPresentFlag = 1;
+  WRITE_FLAG(subLayerOrderingInfoPresentFlag,       "sps_sub_layer_ordering_info_present_flag");
+  for(UInt i=0; i <= pcSPS->getMaxTLayers()-1; i++)
+  {
+    WRITE_UVLC( pcSPS->getMaxDecPicBuffering(i) - 1,       "sps_max_dec_pic_buffering_minus1[i]" );
+    WRITE_UVLC( pcSPS->getNumReorderPics(i),               "sps_num_reorder_pics[i]" );
+    WRITE_UVLC( pcSPS->getMaxLatencyIncrease(i),           "sps_max_latency_increase_plus1[i]" );
+    if (!subLayerOrderingInfoPresentFlag)
+    {
+      break;
+    }
+  }
+#if SVC_EXTENSION
+  }
+#endif
+  assert( pcSPS->getMaxCUWidth() == pcSPS->getMaxCUHeight() );
+
+  WRITE_UVLC( pcSPS->getLog2MinCodingBlockSize() - 3,                                "log2_min_coding_block_size_minus3" );
+  WRITE_UVLC( pcSPS->getLog2DiffMaxMinCodingBlockSize(),                             "log2_diff_max_min_coding_block_size" );
+  WRITE_UVLC( pcSPS->getQuadtreeTULog2MinSize() - 2,                                 "log2_min_transform_block_size_minus2" );
+  WRITE_UVLC( pcSPS->getQuadtreeTULog2MaxSize() - pcSPS->getQuadtreeTULog2MinSize(), "log2_diff_max_min_transform_block_size" );
+  WRITE_UVLC( pcSPS->getQuadtreeTUMaxDepthInter() - 1,                               "max_transform_hierarchy_depth_inter" );
+  WRITE_UVLC( pcSPS->getQuadtreeTUMaxDepthIntra() - 1,                               "max_transform_hierarchy_depth_intra" );
+  WRITE_FLAG( pcSPS->getScalingListFlag() ? 1 : 0,                                   "scaling_list_enabled_flag" );
+  if(pcSPS->getScalingListFlag())
+  {
+#if SCALINGLIST_INFERRING
+    if( !V1CompatibleSPSFlag )
+    {
+      WRITE_FLAG( pcSPS->getInferScalingListFlag() ? 1 : 0, "sps_infer_scaling_list_flag" );
+    }
+
+    if( pcSPS->getInferScalingListFlag() )
+    {
+      // The value of pps_scaling_list_ref_layer_id shall be in the range of 0 to 62, inclusive
+      assert( pcSPS->getScalingListRefLayerId() <= 62 );
+
+      WRITE_CODE( pcSPS->getScalingListRefLayerId(), 6, "sps_scaling_list_ref_layer_id" );
+    }
+    else
+    {
+#endif
+    WRITE_FLAG( pcSPS->getScalingListPresentFlag() ? 1 : 0,                          "sps_scaling_list_data_present_flag" );
+    if(pcSPS->getScalingListPresentFlag())
+    {
+      codeScalingList( m_pcSlice->getScalingList() );
+    }
+#if SCALINGLIST_INFERRING
+    }
+#endif
+  }
+  WRITE_FLAG( pcSPS->getUseAMP() ? 1 : 0,                                            "amp_enabled_flag" );
+  WRITE_FLAG( pcSPS->getUseSAO() ? 1 : 0,                                            "sample_adaptive_offset_enabled_flag");
+
+  WRITE_FLAG( pcSPS->getUsePCM() ? 1 : 0,                                            "pcm_enabled_flag");
+  if( pcSPS->getUsePCM() )
+  {
+    WRITE_CODE( pcSPS->getPCMBitDepth(CHANNEL_TYPE_LUMA) - 1, 4,                            "pcm_sample_bit_depth_luma_minus1" );
+    WRITE_CODE( chromaEnabled ? (pcSPS->getPCMBitDepth(CHANNEL_TYPE_CHROMA) - 1) : 0, 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);
+  }
+
+  Bool sps_extension_present_flag=false;
+  Bool sps_extension_flags[NUM_SPS_EXTENSION_FLAGS]={false};
+
+  sps_extension_flags[SPS_EXT__REXT] = (
+          pcSPS->getUseResidualRotation()
+       || pcSPS->getUseSingleSignificanceMapContext()
+       || pcSPS->getUseResidualDPCM(RDPCM_SIGNAL_IMPLICIT)
+       || pcSPS->getUseResidualDPCM(RDPCM_SIGNAL_EXPLICIT)
+       || pcSPS->getUseExtendedPrecision()
+       || pcSPS->getDisableIntraReferenceSmoothing()
+       || pcSPS->getUseHighPrecisionPredictionWeighting()
+       || pcSPS->getUseGolombRiceParameterAdaptation()
+       || pcSPS->getAlignCABACBeforeBypass()
+    );
+
+  // Other SPS extension flags checked here.
+#if SVC_EXTENSION
+  sps_extension_flags[SPS_EXT__MLAYER] = pcSPS->getExtensionFlag() ? 1 : 0;
+#endif
+
+  for(Int i=0; i<NUM_SPS_EXTENSION_FLAGS; i++)
+  {
+    sps_extension_present_flag|=sps_extension_flags[i];
+  }
+
+  WRITE_FLAG( (sps_extension_present_flag?1:0), "sps_extension_present_flag" );
+
+  if (sps_extension_present_flag)
+  {
+    for(Int i=0; i<NUM_SPS_EXTENSION_FLAGS; i++)
+    {
+      WRITE_FLAG( sps_extension_flags[i]?1:0, "sps_extension_flag[]" );
+    }
+
+    for(Int i=0; i<NUM_SPS_EXTENSION_FLAGS; i++) // loop used so that the order is determined by the enum.
+    {
+      if (sps_extension_flags[i])
+      {
+        switch (SPSExtensionFlagIndex(i))
+        {
+          case SPS_EXT__REXT:
+
+            WRITE_FLAG( (pcSPS->getUseResidualRotation() ? 1 : 0),                  "transform_skip_rotation_enabled_flag");
+            WRITE_FLAG( (pcSPS->getUseSingleSignificanceMapContext() ? 1 : 0),      "transform_skip_context_enabled_flag");
+            WRITE_FLAG( (pcSPS->getUseResidualDPCM(RDPCM_SIGNAL_IMPLICIT) ? 1 : 0), "residual_dpcm_implicit_enabled_flag" );
+            WRITE_FLAG( (pcSPS->getUseResidualDPCM(RDPCM_SIGNAL_EXPLICIT) ? 1 : 0), "residual_dpcm_explicit_enabled_flag" );
+            WRITE_FLAG( (pcSPS->getUseExtendedPrecision() ? 1 : 0),                 "extended_precision_processing_flag" );
+            WRITE_FLAG( (pcSPS->getDisableIntraReferenceSmoothing() ? 1 : 0),       "intra_smoothing_disabled_flag" );
+            WRITE_FLAG( (pcSPS->getUseHighPrecisionPredictionWeighting() ? 1 : 0),  "high_precision_prediction_weighting_flag" );
+            WRITE_FLAG( (pcSPS->getUseGolombRiceParameterAdaptation() ? 1 : 0),     "golomb_rice_parameter_adaptation_flag" );
+            WRITE_FLAG( (pcSPS->getAlignCABACBeforeBypass() ? 1 : 0),               "cabac_bypass_alignment_enabled_flag" );
+            break;
+#if SVC_EXTENSION
+          case SPS_EXT__MLAYER:
+            codeSPSExtension( pcSPS ); //it is sps_multilayer_extension
+            break;
+#endif
+          default:
+            assert(sps_extension_flags[i]==false); // Should never get here with an active SPS extension flag.
+            break;
+        }
+      }
+    }
+  }
+}
+
+Void TEncCavlc::codeVPS( TComVPS* pcVPS )
+{
+#if !P0125_REVERT_VPS_EXTN_OFFSET_TO_RESERVED
+#if VPS_EXTN_OFFSET_CALC
+  UInt numBytesInVps = this->m_pcBitIf->getNumberOfWrittenBits();
+#endif
+#endif
+#if !P0307_REMOVE_VPS_VUI_OFFSET
+#if VPS_VUI_OFFSET
+   m_vpsVuiCounter = this->m_pcBitIf->getNumberOfWrittenBits();
+#endif
+#endif
+  WRITE_CODE( pcVPS->getVPSId(),                    4,        "vps_video_parameter_set_id" );
+#if VPS_RESERVED_FLAGS
+  WRITE_FLAG( pcVPS->getBaseLayerInternalFlag(),              "vps_base_layer_internal_flag");
+  WRITE_FLAG( pcVPS->getBaseLayerAvailableFlag(),             "vps_base_layer_available_flag");
+#else
+  WRITE_CODE( 3,                                    2,        "vps_reserved_three_2bits" );
+#endif
+#if SVC_EXTENSION
+  WRITE_CODE( pcVPS->getMaxLayers() - 1,            6,        "vps_max_layers_minus1" );
+  assert( pcVPS->getBaseLayerInternalFlag() || pcVPS->getMaxLayers() > 1 );
+#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 !P0125_REVERT_VPS_EXTN_OFFSET_TO_RESERVED
+#if VPS_EXTN_OFFSET
+  WRITE_CODE( pcVPS->getExtensionOffset(),         16,        "vps_extension_offset" );
+#else
+  WRITE_CODE( 0xffff,                              16,        "vps_reserved_ffff_16bits" );
+#endif
+#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;
+    }
+  }
+
+#if SVC_EXTENSION
+  assert( pcVPS->getNumHrdParameters() <= MAX_VPS_LAYER_SETS_PLUS1 );
+  assert( pcVPS->getMaxLayerId() < MAX_VPS_LAYER_IDX_PLUS1 );
+#if !VPS_EXTN_OP_LAYER_SETS     // num layer sets set in TAppEncTop.cpp
+  pcVPS->setNumLayerSets(1);
+#endif
+  WRITE_CODE( pcVPS->getMaxLayerId(), 6,                       "vps_max_layer_id" );
+#if Q0078_ADD_LAYER_SETS
+  WRITE_UVLC(pcVPS->getVpsNumLayerSetsMinus1(),                "vps_num_layer_sets_minus1");
+  for (UInt opsIdx = 1; opsIdx <= pcVPS->getVpsNumLayerSetsMinus1(); opsIdx++)
+#else
+  WRITE_UVLC( pcVPS->getNumLayerSets() - 1,                 "vps_num_layer_sets_minus1" );
+  for (UInt opsIdx = 1; opsIdx <= (pcVPS->getNumLayerSets() - 1); opsIdx++)
+#endif
+  {
+    // Operation point set
+    for( UInt i = 0; i <= pcVPS->getMaxLayerId(); i ++ )
+#else
+  assert( pcVPS->getNumHrdParameters() <= MAX_VPS_NUM_HRD_PARAMETERS );
+  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 ++ )
+#endif
+    {
+#if !VPS_EXTN_OP_LAYER_SETS     // layer Id include flag set in TAppEncTop.cpp
+      // 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]" );
+    }
+  }
+#if !FIX_LAYER_ID_INIT  // It was still called because NECESSARY_FLAG does not exist and is by default "false"
+#if !NECESSARY_FLAG   // Already called once in TAppEncTop.cpp
+#if DERIVE_LAYER_ID_LIST_VARIABLES
+  pcVPS->deriveLayerIdListVariables();
+#endif
+#endif
+#endif
+  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 SVC_EXTENSION
+  // When MaxLayersMinus1 is greater than 0, vps_extension_flag shall be equal to 1.
+  if( pcVPS->getMaxLayers() > 1 )
+  {
+    assert( pcVPS->getVpsExtensionFlag() == true );
+  }
+
+  WRITE_FLAG( pcVPS->getVpsExtensionFlag() ? 1 : 0,                     "vps_extension_flag" );
+
+  if( pcVPS->getVpsExtensionFlag() )
+  {
+    while ( m_pcBitIf->getNumberOfWrittenBits() % 8 != 0 )
+    {
+      WRITE_FLAG(1,                  "vps_extension_alignment_bit_equal_to_one");
+    }
+#if !P0125_REVERT_VPS_EXTN_OFFSET_TO_RESERVED
+#if VPS_EXTN_OFFSET_CALC
+    Int vpsExntOffsetValueInBits = this->m_pcBitIf->getNumberOfWrittenBits() - numBytesInVps + 16; // 2 bytes for NUH
+    assert( vpsExntOffsetValueInBits % 8 == 0 );
+    pcVPS->setExtensionOffset( vpsExntOffsetValueInBits >> 3 );
+#endif
+#endif
+    codeVPSExtension(pcVPS);
+    WRITE_FLAG( 0,                     "vps_extension2_flag" );   // Flag value of 1 reserved
+  }
+#else
+  WRITE_FLAG( 0,                     "vps_extension_flag" );
+#endif  
+  //future extensions here..
+  
+  return;
+}
+
+Void TEncCavlc::codeSliceHeader         ( TComSlice* pcSlice )
+{
+#if ENC_DEC_TRACE
+  xTraceSliceHeader (pcSlice);
+#endif
+
+  const ChromaFormat format                = pcSlice->getSPS()->getChromaFormatIdc();
+  const UInt         numberValidComponents = getNumberValidComponents(format);
+  const Bool         chromaEnabled         = isChromaEnabled(format);
+
+  //calculate number of bits required for slice address
+  Int maxSliceSegmentAddress = pcSlice->getPic()->getNumberOfCtusInFrame();
+  Int bitsSliceSegmentAddress = 0;
+  while(maxSliceSegmentAddress>(1<<bitsSliceSegmentAddress))
+  {
+    bitsSliceSegmentAddress++;
+  }
+  const Int ctuTsAddress = pcSlice->getSliceSegmentCurStartCtuTsAddr();
+
+  //write slice address
+  const Int sliceSegmentRsAddress = pcSlice->getPic()->getPicSym()->getCtuTsToRsAddrMap(ctuTsAddress);
+
+  WRITE_FLAG( sliceSegmentRsAddress==0, "first_slice_segment_in_pic_flag" );
+  if ( pcSlice->getRapPicFlag() )
+  {
+    WRITE_FLAG( pcSlice->getNoOutputPriorPicsFlag() ? 1 : 0, "no_output_of_prior_pics_flag" );
+  }
+  WRITE_UVLC( pcSlice->getPPS()->getPPSId(), "slice_pic_parameter_set_id" );
+  if ( pcSlice->getPPS()->getDependentSliceSegmentsEnabledFlag() && (sliceSegmentRsAddress!=0) )
+  {
+    WRITE_FLAG( pcSlice->getDependentSliceSegmentFlag() ? 1 : 0, "dependent_slice_segment_flag" );
+  }
+  if(sliceSegmentRsAddress>0)
+  {
+    WRITE_CODE( sliceSegmentRsAddress, bitsSliceSegmentAddress, "slice_segment_address" );
+  }
+  if ( !pcSlice->getDependentSliceSegmentFlag() )
+  {
+#if SVC_EXTENSION
+#if POC_RESET_FLAG
+    Int iBits = 0;
+    if( pcSlice->getPPS()->getNumExtraSliceHeaderBits() > iBits )
+    {
+      WRITE_FLAG( pcSlice->getPocResetFlag(), "poc_reset_flag" );
+      iBits++;
+    }
+    if( pcSlice->getPPS()->getNumExtraSliceHeaderBits() > iBits )
+    {
+      assert(!!"discardable_flag");
+      WRITE_FLAG(pcSlice->getDiscardableFlag(), "discardable_flag");
+      iBits++;
+    }
+#if O0149_CROSS_LAYER_BLA_FLAG
+    if( pcSlice->getPPS()->getNumExtraSliceHeaderBits() > iBits )
+    {
+      assert(!!"cross_layer_bla_flag");
+      WRITE_FLAG(pcSlice->getCrossLayerBLAFlag(), "cross_layer_bla_flag");
+      iBits++;
+    }
+#endif
+    for ( ; iBits < pcSlice->getPPS()->getNumExtraSliceHeaderBits(); iBits++)
+    {
+      assert(!!"slice_reserved_undetermined_flag[]");
+      WRITE_FLAG(0, "slice_reserved_undetermined_flag[]");
+    }
+#else
+#if CROSS_LAYER_BLA_FLAG_FIX
+    Int iBits = 0;
+    if(pcSlice->getPPS()->getNumExtraSliceHeaderBits() > iBits)
+#else
+    if (pcSlice->getPPS()->getNumExtraSliceHeaderBits()>0)
+#endif
+    {
+      assert(!!"discardable_flag");
+#if NON_REF_NAL_TYPE_DISCARDABLE
+      if (pcSlice->getDiscardableFlag())
+      {
+        assert(pcSlice->getNalUnitType() != NAL_UNIT_CODED_SLICE_TRAIL_R &&
+          pcSlice->getNalUnitType() != NAL_UNIT_CODED_SLICE_TSA_R &&
+          pcSlice->getNalUnitType() != NAL_UNIT_CODED_SLICE_STSA_R &&
+          pcSlice->getNalUnitType() != NAL_UNIT_CODED_SLICE_RADL_R &&
+          pcSlice->getNalUnitType() != NAL_UNIT_CODED_SLICE_RASL_R);
+      }
+#endif
+      WRITE_FLAG(pcSlice->getDiscardableFlag(), "discardable_flag");
+#if CROSS_LAYER_BLA_FLAG_FIX
+      iBits++;
+#endif
+    }
+#if CROSS_LAYER_BLA_FLAG_FIX
+    if( pcSlice->getPPS()->getNumExtraSliceHeaderBits() > iBits )
+    {
+      assert(!!"cross_layer_bla_flag");
+      WRITE_FLAG(pcSlice->getCrossLayerBLAFlag(), "cross_layer_bla_flag");
+      iBits++;
+    }
+    for (; iBits < pcSlice->getPPS()->getNumExtraSliceHeaderBits(); iBits++)
+#else
+    for (Int i = 1; i < pcSlice->getPPS()->getNumExtraSliceHeaderBits(); i++)
+#endif
+    {
+      assert(!!"slice_reserved_undetermined_flag[]");
+      WRITE_FLAG(0, "slice_reserved_undetermined_flag[]");
+    }
+#endif
+#else //SVC_EXTENSION
+    for (Int i = 0; i < pcSlice->getPPS()->getNumExtraSliceHeaderBits(); i++)
+    {
+      assert(!!"slice_reserved_undetermined_flag[]");
+      WRITE_FLAG(0, "slice_reserved_undetermined_flag[]");
+    }
+#endif //SVC_EXTENSION
+
+    WRITE_UVLC( pcSlice->getSliceType(),       "slice_type" );
+
+    if( pcSlice->getPPS()->getOutputFlagPresentFlag() )
+    {
+      WRITE_FLAG( pcSlice->getPicOutputFlag() ? 1 : 0, "pic_output_flag" );
+    }
+
+#if N0065_LAYER_POC_ALIGNMENT
+#if O0062_POC_LSB_NOT_PRESENT_FLAG
+    if( (pcSlice->getLayerId() > 0 && !pcSlice->getVPS()->getPocLsbNotPresentFlag( pcSlice->getVPS()->getLayerIdxInVps(pcSlice->getLayerId())) ) || !pcSlice->getIdrPicFlag())
+#else
+    if( pcSlice->getLayerId() > 0 || !pcSlice->getIdrPicFlag() )
+#endif
+#else
+    if( !pcSlice->getIdrPicFlag() )
+#endif
+    {
+#if POC_RESET_FLAG
+      Int picOrderCntLSB;
+      if( !pcSlice->getPocResetFlag() )
+      {
+        picOrderCntLSB = (pcSlice->getPOC()-pcSlice->getLastIDR()+(1<<pcSlice->getSPS()->getBitsForPOC())) & ((1<<pcSlice->getSPS()->getBitsForPOC())-1);
+      }
+      else
+      {
+        picOrderCntLSB = (pcSlice->getPocValueBeforeReset()-pcSlice->getLastIDR()+(1<<pcSlice->getSPS()->getBitsForPOC())) & ((1<<pcSlice->getSPS()->getBitsForPOC())-1);
+      }
+#else
+#if POC_RESET_IDC_ENCODER
+      Int picOrderCntLSB;
+      if( pcSlice->getPocResetIdc() == 2 )  // i.e. the LSB is reset
+      {
+        picOrderCntLSB = pcSlice->getPicOrderCntLsb();  // This will be the LSB value w.r.t to the previous POC reset period.
+      }
+      else
+      {
+        picOrderCntLSB = (pcSlice->getPOC() + (1<<pcSlice->getSPS()->getBitsForPOC())) & ((1<<pcSlice->getSPS()->getBitsForPOC())-1);
+      }
+#else
+      Int picOrderCntLSB = (pcSlice->getPOC()-pcSlice->getLastIDR()+(1<<pcSlice->getSPS()->getBitsForPOC())) & ((1<<pcSlice->getSPS()->getBitsForPOC())-1);
+#endif
+#endif
+      WRITE_CODE( picOrderCntLSB, pcSlice->getSPS()->getBitsForPOC(), "pic_order_cnt_lsb");
+
+#if N0065_LAYER_POC_ALIGNMENT
+#if SHM_FIX7
+    }
+#endif
+      if( !pcSlice->getIdrPicFlag() )
+      {
+#endif
+      TComReferencePictureSet* rps = pcSlice->getRPS();
+
+      // check for bitstream restriction stating that:
+      // If the current picture is a BLA or CRA picture, the value of NumPocTotalCurr shall be equal to 0.
+      // Ideally this process should not be repeated for each slice in a picture
+#if SVC_EXTENSION
+      if( pcSlice->getLayerId() == 0 )
+#endif
+      if (pcSlice->isIRAP())
+      {
+        for (Int picIdx = 0; picIdx < rps->getNumberOfPictures(); picIdx++)
+        {
+          assert (!rps->getUsed(picIdx));
+        }
+      }
+
+      if(pcSlice->getRPSidx() < 0)
+      {
+        WRITE_FLAG( 0, "short_term_ref_pic_set_sps_flag");
+        codeShortTermRefPicSet(pcSlice->getSPS(), rps, true, pcSlice->getSPS()->getRPSList()->getNumberOfReferencePictureSets());
+      }
+      else
+      {
+        WRITE_FLAG( 1, "short_term_ref_pic_set_sps_flag");
+        Int numBits = 0;
+        while ((1 << numBits) < pcSlice->getSPS()->getRPSList()->getNumberOfReferencePictureSets())
+        {
+          numBits++;
+        }
+        if (numBits > 0)
+        {
+          WRITE_CODE( pcSlice->getRPSidx(), numBits, "short_term_ref_pic_set_idx" );
+        }
+      }
+      if(pcSlice->getSPS()->getLongTermRefsPresent())
+      {
+        Int numLtrpInSH = rps->getNumberOfLongtermPictures();
+        Int ltrpInSPS[MAX_NUM_REF_PICS];
+        Int numLtrpInSPS = 0;
+        UInt ltrpIndex;
+        Int counter = 0;
+        for(Int k = rps->getNumberOfPictures()-1; k > rps->getNumberOfPictures()-rps->getNumberOfLongtermPictures()-1; k--)
+        {
+          if (findMatchingLTRP(pcSlice, &ltrpIndex, rps->getPOC(k), rps->getUsed(k)))
+          {
+            ltrpInSPS[numLtrpInSPS] = ltrpIndex;
+            numLtrpInSPS++;
+          }
+          else
+          {
+            counter++;
+          }
+        }
+        numLtrpInSH -= numLtrpInSPS;
+
+        Int bitsForLtrpInSPS = 0;
+        while (pcSlice->getSPS()->getNumLongTermRefPicSPS() > (1 << bitsForLtrpInSPS))
+        {
+          bitsForLtrpInSPS++;
+        }
+        if (pcSlice->getSPS()->getNumLongTermRefPicSPS() > 0)
+        {
+          WRITE_UVLC( numLtrpInSPS, "num_long_term_sps");
+        }
+        WRITE_UVLC( numLtrpInSH, "num_long_term_pics");
+        // Note that the LSBs of the LT ref. pic. POCs must be sorted before.
+        // Not sorted here because LT ref indices will be used in setRefPicList()
+        Int prevDeltaMSB = 0, prevLSB = 0;
+        Int offset = rps->getNumberOfNegativePictures() + rps->getNumberOfPositivePictures();
+        for(Int i=rps->getNumberOfPictures()-1 ; i > offset-1; i--)
+        {
+          if (counter < numLtrpInSPS)
+          {
+            if (bitsForLtrpInSPS > 0)
+            {
+              WRITE_CODE( ltrpInSPS[counter], bitsForLtrpInSPS, "lt_idx_sps[i]");
+            }
+          }
+          else
+          {
+            WRITE_CODE( rps->getPocLSBLT(i), pcSlice->getSPS()->getBitsForPOC(), "poc_lsb_lt");
+            WRITE_FLAG( rps->getUsed(i), "used_by_curr_pic_lt_flag");
+          }
+          WRITE_FLAG( rps->getDeltaPocMSBPresentFlag(i), "delta_poc_msb_present_flag");
+
+          if(rps->getDeltaPocMSBPresentFlag(i))
+          {
+            Bool deltaFlag = false;
+            //  First LTRP from SPS                 ||  First LTRP from SH                              || curr LSB            != prev LSB
+            if( (i == rps->getNumberOfPictures()-1) || (i == rps->getNumberOfPictures()-1-numLtrpInSPS) || (rps->getPocLSBLT(i) != prevLSB) )
+            {
+              deltaFlag = true;
+            }
+            if(deltaFlag)
+            {
+              WRITE_UVLC( rps->getDeltaPocMSBCycleLT(i), "delta_poc_msb_cycle_lt[i]" );
+            }
+            else
+            {
+              Int differenceInDeltaMSB = rps->getDeltaPocMSBCycleLT(i) - prevDeltaMSB;
+              assert(differenceInDeltaMSB >= 0);
+              WRITE_UVLC( differenceInDeltaMSB, "delta_poc_msb_cycle_lt[i]" );
+            }
+            prevLSB = rps->getPocLSBLT(i);
+            prevDeltaMSB = rps->getDeltaPocMSBCycleLT(i);
+          }
+        }
+      }
+      if (pcSlice->getSPS()->getTMVPFlagsPresent())
+      {
+#if R0226_SLICE_TMVP
+        WRITE_FLAG( pcSlice->getEnableTMVPFlag() ? 1 : 0, "slice_temporal_mvp_enabled_flag" );
+#else
+        WRITE_FLAG( pcSlice->getEnableTMVPFlag() ? 1 : 0, "slice_temporal_mvp_enable_flag" );
+#endif
+      }
+#if N0065_LAYER_POC_ALIGNMENT && !SHM_FIX7
+      }
+#endif
+    }
+
+#if SVC_EXTENSION
+    if((pcSlice->getLayerId() > 0) && !(pcSlice->getVPS()->getIlpSshSignalingEnabledFlag()) && (pcSlice->getNumILRRefIdx() > 0) )
+    {
+      WRITE_FLAG(pcSlice->getInterLayerPredEnabledFlag(),"inter_layer_pred_enabled_flag");
+      if( pcSlice->getInterLayerPredEnabledFlag())
+      {
+        if(pcSlice->getNumILRRefIdx() > 1)
+        {
+          Int numBits = 1;
+          while ((1 << numBits) < pcSlice->getNumILRRefIdx())
+          {
+            numBits++;
+          }
+          if( !pcSlice->getVPS()->getMaxOneActiveRefLayerFlag()) 
+          {
+            WRITE_CODE(pcSlice->getActiveNumILRRefIdx() - 1, numBits,"num_inter_layer_ref_pics_minus1");
+          }       
+
+          if( pcSlice->getNumILRRefIdx() != pcSlice->getActiveNumILRRefIdx() )
+          {
+            for(Int i = 0; i < pcSlice->getActiveNumILRRefIdx(); i++ )
+            {
+              WRITE_CODE(pcSlice->getInterLayerPredLayerIdc(i),numBits,"inter_layer_pred_layer_idc[i]");   
+            }
+          }
+        }
+      }
+    }     
+#if P0312_VERT_PHASE_ADJ
+    for(Int i = 0; i < pcSlice->getActiveNumILRRefIdx(); i++ )
+    {
+      UInt refLayerIdc = pcSlice->getInterLayerPredLayerIdc(i);
+      if( pcSlice->getSPS()->getVertPhasePositionEnableFlag(refLayerIdc) )
+      {
+        WRITE_FLAG( pcSlice->getVertPhasePositionFlag(refLayerIdc), "vert_phase_position_flag" );
+      }
+    }
+#endif
+#endif //SVC_EXTENSION
+
+    if(pcSlice->getSPS()->getUseSAO())
+    {
+       WRITE_FLAG( pcSlice->getSaoEnabledFlag(CHANNEL_TYPE_LUMA), "slice_sao_luma_flag" );
+       if (chromaEnabled) WRITE_FLAG( pcSlice->getSaoEnabledFlag(CHANNEL_TYPE_CHROMA), "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 ( pcSlice->getSliceType() == B_SLICE )
+      {
+        WRITE_FLAG( pcSlice->getColFromL0Flag(), "collocated_from_l0_flag" );
+      }
+
+      if ( pcSlice->getSliceType() != I_SLICE &&
+        ((pcSlice->getColFromL0Flag()==1 && pcSlice->getNumRefIdx(REF_PIC_LIST_0)>1)||
+        (pcSlice->getColFromL0Flag()==0  && pcSlice->getNumRefIdx(REF_PIC_LIST_1)>1)))
+      {
+        WRITE_UVLC( pcSlice->getColRefIdx(), "collocated_ref_idx" );
+      }
+    }
+    if ( (pcSlice->getPPS()->getUseWP() && pcSlice->getSliceType()==P_SLICE) || (pcSlice->getPPS()->getWPBiPred() && pcSlice->getSliceType()==B_SLICE) )
+    {
+      xCodePredWeightTable( pcSlice );
+    }
+    assert(pcSlice->getMaxNumMergeCand()<=MRG_MAX_NUM_CANDS);
+    if (!pcSlice->isIntra())
+    {
+      WRITE_UVLC(MRG_MAX_NUM_CANDS - pcSlice->getMaxNumMergeCand(), "five_minus_max_num_merge_cand");
+    }
+    Int iCode = pcSlice->getSliceQp() - ( pcSlice->getPPS()->getPicInitQPMinus26() + 26 );
+    WRITE_SVLC( iCode, "slice_qp_delta" );
+    if (pcSlice->getPPS()->getSliceChromaQpFlag())
+    {
+      if (numberValidComponents > COMPONENT_Cb) { WRITE_SVLC( pcSlice->getSliceChromaQpDelta(COMPONENT_Cb), "slice_qp_delta_cb" ); }
+      if (numberValidComponents > COMPONENT_Cr) { WRITE_SVLC( pcSlice->getSliceChromaQpDelta(COMPONENT_Cr), "slice_qp_delta_cr" ); }
+      assert(numberValidComponents <= COMPONENT_Cr+1);
+    }
+
+    if (pcSlice->getPPS()->getChromaQpAdjTableSize() > 0)
+    {
+      WRITE_FLAG(pcSlice->getUseChromaQpAdj(), "slice_chroma_qp_adjustment_enabled_flag");
+    }
+
+    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() && (pcSlice->getSaoEnabledFlag(CHANNEL_TYPE_LUMA) || (chromaEnabled && pcSlice->getSaoEnabledFlag(CHANNEL_TYPE_CHROMA)));
+    Bool isDBFEnabled = (!pcSlice->getDeblockingFilterDisable());
+
+    if(pcSlice->getPPS()->getLoopFilterAcrossSlicesEnabledFlag() && ( isSAOEnabled || isDBFEnabled ))
+    {
+      WRITE_FLAG(pcSlice->getLFCrossSliceBoundaryFlag()?1:0, "slice_loop_filter_across_slices_enabled_flag");
+    }
+  }
+
+#if !POC_RESET_IDC_SIGNALLING   // Wrong place to put slice header extension
+  if(pcSlice->getPPS()->getSliceHeaderExtensionPresentFlag())
+  {
+    WRITE_UVLC(0,"slice_header_extension_length");
+  }
+#endif
+}
+
+Void TEncCavlc::codePTL( TComPTL* pcPTL, Bool profilePresentFlag, Int maxNumSubLayersMinus1)
+{
+  if(profilePresentFlag)
+  {
+    codeProfileTier(pcPTL->getGeneralPTL());    // general_...
+  }
+  WRITE_CODE( Int(pcPTL->getGeneralPTL()->getLevelIdc()), 8, "general_level_idc" );
+
+  for (Int i = 0; i < maxNumSubLayersMinus1; i++)
+  {
+#if MULTIPLE_PTL_SUPPORT
+    WRITE_FLAG( pcPTL->getSubLayerProfilePresentFlag(i), "sub_layer_profile_present_flag[i]" );
+#else
+    if(profilePresentFlag)
+    {
+      WRITE_FLAG( pcPTL->getSubLayerProfilePresentFlag(i), "sub_layer_profile_present_flag[i]" );
+    }
+#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 MULTIPLE_PTL_SUPPORT
+    if( pcPTL->getSubLayerProfilePresentFlag(i) )
+#else
+    if( profilePresentFlag && pcPTL->getSubLayerProfilePresentFlag(i) )
+#endif
+    {
+      codeProfileTier(pcPTL->getSubLayerPTL(i));  // sub_layer_...
+    }
+    if( pcPTL->getSubLayerLevelPresentFlag(i) )
+    {
+      WRITE_CODE( Int(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()==Level::HIGH, "XXX_tier_flag[]"    );
+#if MULTIPLE_PTL_SUPPORT
+  WRITE_CODE( (ptl->getProfileIdc() == Profile::SCALABLEMAIN || ptl->getProfileIdc() == Profile::SCALABLEMAIN10) ? 7 : Int(ptl->getProfileIdc()), 5 ,  "XXX_profile_idc[]"  );
+#else
+  WRITE_CODE( Int(ptl->getProfileIdc()), 5 ,  "XXX_profile_idc[]"  );
+#endif
+  for(Int j = 0; j < 32; j++)
+  {
+    WRITE_FLAG( ptl->getProfileCompatibilityFlag(j), "XXX_profile_compatibility_flag[][j]");
+  }
+
+  WRITE_FLAG(ptl->getProgressiveSourceFlag(),   "general_progressive_source_flag");
+  WRITE_FLAG(ptl->getInterlacedSourceFlag(),    "general_interlaced_source_flag");
+  WRITE_FLAG(ptl->getNonPackedConstraintFlag(), "general_non_packed_constraint_flag");
+  WRITE_FLAG(ptl->getFrameOnlyConstraintFlag(), "general_frame_only_constraint_flag");
+
+  if (ptl->getProfileIdc() == Profile::MAINREXT || ptl->getProfileIdc() == Profile::HIGHTHROUGHPUTREXT )
+  {
+    const UInt         bitDepthConstraint=ptl->getBitDepthConstraint();
+    WRITE_FLAG(bitDepthConstraint<=12, "general_max_12bit_constraint_flag");
+    WRITE_FLAG(bitDepthConstraint<=10, "general_max_10bit_constraint_flag");
+    WRITE_FLAG(bitDepthConstraint<= 8, "general_max_8bit_constraint_flag");
+    const ChromaFormat chromaFmtConstraint=ptl->getChromaFormatConstraint();
+    WRITE_FLAG(chromaFmtConstraint==CHROMA_422||chromaFmtConstraint==CHROMA_420||chromaFmtConstraint==CHROMA_400, "general_max_422chroma_constraint_flag");
+    WRITE_FLAG(chromaFmtConstraint==CHROMA_420||chromaFmtConstraint==CHROMA_400,                                  "general_max_420chroma_constraint_flag");
+    WRITE_FLAG(chromaFmtConstraint==CHROMA_400,                                                                   "general_max_monochrome_constraint_flag");
+    WRITE_FLAG(ptl->getIntraConstraintFlag(),        "general_intra_constraint_flag");
+    WRITE_FLAG(0,                                    "general_one_picture_only_constraint_flag");
+    WRITE_FLAG(ptl->getLowerBitRateConstraintFlag(), "general_lower_bit_rate_constraint_flag");
+#if MULTIPLE_PTL_SUPPORT
+    WRITE_CODE(0, 32,  "general_reserved_zero_34bits");  WRITE_CODE(0, 2,  "general_reserved_zero_34bits");
+  }
+  else if( ptl->getProfileIdc() == Profile::SCALABLEMAIN || ptl->getProfileIdc() == Profile::SCALABLEMAIN10 )      // at encoder side, scalable-main10 profile has a profile idc equal to 8, which is converted to 7 during signalling
+  {
+    WRITE_FLAG(true,   "general_max_12bit_constraint_flag");
+    WRITE_FLAG(true,   "general_max_10bit_constraint_flag");
+    WRITE_FLAG((ptl->getProfileIdc() == Profile::SCALABLEMAIN) ? true : false, "general_max_8bit_constraint_flag");
+    WRITE_FLAG(true,   "general_max_422chroma_constraint_flag");
+    WRITE_FLAG(true,   "general_max_420chroma_constraint_flag");
+    WRITE_FLAG(false,  "general_max_monochrome_constraint_flag");
+    WRITE_FLAG(false,  "general_intra_constraint_flag");
+    WRITE_FLAG(false,  "general_one_picture_only_constraint_flag");
+    WRITE_FLAG(true,   "general_lower_bit_rate_constraint_flag");
+    WRITE_CODE(0, 32,  "general_reserved_zero_34bits");  WRITE_CODE(0, 2,  "general_reserved_zero_34bits");
+  }
+  else
+  {
+    WRITE_CODE(0, 32,  "general_reserved_zero_43bits");  WRITE_CODE(0, 11,  "general_reserved_zero_43bits");
+  }
+
+  if( ( ptl->getProfileIdc() >= 1 && ptl->getProfileIdc() <= 5 ) || 
+      ptl->getProfileCompatibilityFlag(1) || ptl->getProfileCompatibilityFlag(2) || 
+      ptl->getProfileCompatibilityFlag(3) || ptl->getProfileCompatibilityFlag(4) || 
+      ptl->getProfileCompatibilityFlag(5)                                           )
+  {
+    WRITE_FLAG(false, "general_inbld_flag");
+  }
+  else
+  {
+    WRITE_FLAG(false, "general_reserved_zero_bit");
+  }
+#else
+    WRITE_CODE(0 , 16, "XXX_reserved_zero_35bits[0..15]");
+    WRITE_CODE(0 , 16, "XXX_reserved_zero_35bits[16..31]");
+    WRITE_CODE(0 ,  3, "XXX_reserved_zero_35bits[32..34]");
+  }
+  else
+  {
+    WRITE_CODE(0x0000 , 16, "XXX_reserved_zero_44bits[0..15]");
+    WRITE_CODE(0x0000 , 16, "XXX_reserved_zero_44bits[16..31]");
+    WRITE_CODE(0x000  , 12, "XXX_reserved_zero_44bits[32..43]");
+  }
+#endif
+}
+
+/**
+ - write tiles and 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 maxOffset = 0;
+  for(Int idx=0; idx<pSlice->getNumberOfSubstreamSizes(); idx++)
+  {
+    UInt offset=pSlice->getSubstreamSize(idx);
+    if ( offset > maxOffset )
+    {
+      maxOffset = offset;
+    }
+  }
+
+  // Determine number of bits "offsetLenMinus1+1" required for entry point information
+  UInt offsetLenMinus1 = 0;
+  while (maxOffset >= (1u << (offsetLenMinus1 + 1)))
+  {
+    offsetLenMinus1++;
+    assert(offsetLenMinus1 + 1 < 32);
+  }
+
+  WRITE_UVLC(pSlice->getNumberOfSubstreamSizes(), "num_entry_point_offsets");
+  if (pSlice->getNumberOfSubstreamSizes()>0)
+  {
+    WRITE_UVLC(offsetLenMinus1, "offset_len_minus1");
+
+    for (UInt idx=0; idx<pSlice->getNumberOfSubstreamSizes(); idx++)
+    {
+      WRITE_CODE(pSlice->getSubstreamSize(idx)-1, offsetLenMinus1+1, "entry_point_offset_minus1");
+    }
+  }
+}
+
+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);
+}
+
+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( TComTU &rTu, const ComponentID compID, const Bool lowestLevel )
+{
+  assert(0);
+}
+
+Void TEncCavlc::codeQtRootCbf( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  assert(0);
+}
+
+Void TEncCavlc::codeQtCbfZero( TComTU &rTu, const ChannelType chType )
+{
+  assert(0);
+}
+Void TEncCavlc::codeQtRootCbfZero( TComDataCU* pcCU )
+{
+  assert(0);
+}
+
+Void TEncCavlc::codeTransformSkipFlags (TComTU &rTu, ComponentID component )
+{
+  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::codeCrossComponentPrediction( TComTU& /*rTu*/, ComponentID /*compID*/ )
+{
+  assert(0);
+}
+
+Void TEncCavlc::codeDeltaQP( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  Int iDQp  = pcCU->getQP( uiAbsPartIdx ) - pcCU->getRefQP( uiAbsPartIdx );
+
+#if REPN_FORMAT_IN_VPS
+  Int qpBdOffsetY =  pcCU->getSlice()->getQpBDOffsetY();
+#else
+  Int qpBdOffsetY =  pcCU->getSlice()->getSPS()->getQpBDOffset(CHANNEL_TYPE_LUMA);
+#endif
+  iDQp = (iDQp + 78 + qpBdOffsetY + (qpBdOffsetY/2)) % (52 + qpBdOffsetY) - 26 - (qpBdOffsetY/2);
+
+  xWriteSvlc( iDQp );
+
+  return;
+}
+
+Void TEncCavlc::codeChromaQpAdjustment( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  assert(0);
+}
+
+Void TEncCavlc::codeCoeffNxN    ( TComTU &rTu, TCoeff* pcCoef, const ComponentID compID )
+{
+  assert(0);
+}
+
+Void TEncCavlc::estBit( estBitsSbacStruct* pcEstBitsCabac, Int width, Int height, ChannelType chType )
+{
+  // 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;
+  const ChromaFormat    format                = pcSlice->getPic()->getChromaFormat();
+  const UInt            numberValidComponents = getNumberValidComponents(format);
+  const Bool            bChroma               = isChromaEnabled(format);
+  const 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 );
+
+      // NOTE: wp[].uiLog2WeightDenom and wp[].bPresentFlag are actually per-channel-type settings.
+
+      for ( Int iRefIdx=0 ; iRefIdx<pcSlice->getNumRefIdx(eRefPicList) ; iRefIdx++ )
+      {
+        pcSlice->getWpScaling(eRefPicList, iRefIdx, wp);
+        if ( !bDenomCoded )
+        {
+          Int iDeltaDenom;
+          WRITE_UVLC( wp[COMPONENT_Y].uiLog2WeightDenom, "luma_log2_weight_denom" );     // ue(v): luma_log2_weight_denom
+
+          if( bChroma )
+          {
+            assert(wp[COMPONENT_Cb].uiLog2WeightDenom == wp[COMPONENT_Cr].uiLog2WeightDenom); // check the channel-type settings are consistent across components.
+            iDeltaDenom = (wp[COMPONENT_Cb].uiLog2WeightDenom - wp[COMPONENT_Y].uiLog2WeightDenom);
+            WRITE_SVLC( iDeltaDenom, "delta_chroma_log2_weight_denom" );       // se(v): delta_chroma_log2_weight_denom
+          }
+          bDenomCoded = true;
+        }
+        WRITE_FLAG( wp[COMPONENT_Y].bPresentFlag, "luma_weight_lX_flag" );               // u(1): luma_weight_lX_flag
+        uiTotalSignalledWeightFlags += wp[COMPONENT_Y].bPresentFlag;
+      }
+      if (bChroma)
+      {
+        for ( Int iRefIdx=0 ; iRefIdx<pcSlice->getNumRefIdx(eRefPicList) ; iRefIdx++ )
+        {
+          pcSlice->getWpScaling(eRefPicList, iRefIdx, wp);
+          assert(wp[COMPONENT_Cb].bPresentFlag == wp[COMPONENT_Cr].bPresentFlag); // check the channel-type settings are consistent across components.
+          WRITE_FLAG( wp[COMPONENT_Cb].bPresentFlag, "chroma_weight_lX_flag" );           // u(1): chroma_weight_lX_flag
+          uiTotalSignalledWeightFlags += 2*wp[COMPONENT_Cb].bPresentFlag;
+        }
+      }
+
+      for ( Int iRefIdx=0 ; iRefIdx<pcSlice->getNumRefIdx(eRefPicList) ; iRefIdx++ )
+      {
+        pcSlice->getWpScaling(eRefPicList, iRefIdx, wp);
+        if ( wp[COMPONENT_Y].bPresentFlag )
+        {
+          Int iDeltaWeight = (wp[COMPONENT_Y].iWeight - (1<<wp[COMPONENT_Y].uiLog2WeightDenom));
+          WRITE_SVLC( iDeltaWeight, "delta_luma_weight_lX" );                            // se(v): delta_luma_weight_lX
+          WRITE_SVLC( wp[COMPONENT_Y].iOffset, "luma_offset_lX" );                       // se(v): luma_offset_lX
+        }
+
+        if ( bChroma )
+        {
+          if ( wp[COMPONENT_Cb].bPresentFlag )
+          {
+            for ( Int j = COMPONENT_Cb ; j < numberValidComponents ; j++ )
+            {
+              assert(wp[COMPONENT_Cb].uiLog2WeightDenom == wp[COMPONENT_Cr].uiLog2WeightDenom);
+              Int iDeltaWeight = (wp[j].iWeight - (1<<wp[COMPONENT_Cb].uiLog2WeightDenom));
+              WRITE_SVLC( iDeltaWeight, "delta_chroma_weight_lX" );            // se(v): delta_chroma_weight_lX
+
+              Int range=pcSlice->getSPS()->getUseHighPrecisionPredictionWeighting() ? (1<<g_bitDepth[CHANNEL_TYPE_CHROMA])/2 : 128;
+              Int pred = ( range - ( ( range*wp[j].iWeight)>>(wp[j].uiLog2WeightDenom) ) );
+              Int iDeltaChroma = (wp[j].iOffset - pred);
+              WRITE_SVLC( iDeltaChroma, "delta_chroma_offset_lX" );            // se(v): delta_chroma_offset_lX
+            }
+          }
+        }
+      }
+    }
+    assert(uiTotalSignalledWeightFlags<=24);
+  }
+}
+
+/** code quantization matrix
+ *  \param scalingList quantization matrix information
+ */
+Void TEncCavlc::codeScalingList( TComScalingList* scalingList )
+{
+  UInt listId,sizeId;
+  Bool scalingListPredModeFlag;
+
+  //for each size
+  for(sizeId = 0; sizeId < SCALING_LIST_SIZE_NUM; sizeId++)
+  {
+    Int predListStep = (sizeId == SCALING_LIST_32x32? (SCALING_LIST_NUM/NUMBER_OF_PREDICTION_MODES) : 1); // if 32x32, skip over chroma entries.
+
+    for(listId = 0; listId < SCALING_LIST_NUM; listId+=predListStep)
+    {
+      scalingListPredModeFlag = scalingList->checkPredMode( sizeId, listId );
+      WRITE_FLAG( scalingListPredModeFlag, "scaling_list_pred_mode_flag" );
+      if(!scalingListPredModeFlag)// Copy Mode
+      {
+        if (sizeId == SCALING_LIST_32x32)
+        {
+          // adjust the code, to cope with the missing chroma entries
+          WRITE_UVLC( ((Int)listId - (Int)scalingList->getRefMatrixId (sizeId,listId)) / (SCALING_LIST_NUM/NUMBER_OF_PREDICTION_MODES), "scaling_list_pred_matrix_id_delta");
+        }
+        else
+        {
+          WRITE_UVLC( (Int)listId - (Int)scalingList->getRefMatrixId (sizeId,listId), "scaling_list_pred_matrix_id_delta");
+        }
+      }
+      else// DPCM Mode
+      {
+        xCodeScalingList(scalingList, sizeId, listId);
+      }
+    }
+  }
+  return;
+}
+/** code DPCM
+ * \param scalingList quantization matrix information
+ * \param sizeIdc size index
+ * \param listIdc list index
+ */
+Void TEncCavlc::xCodeScalingList(TComScalingList* scalingList, UInt sizeId, UInt listId)
+{
+  Int coefNum = min(MAX_MATRIX_COEF_NUM,(Int)g_scalingListSize[sizeId]);
+  UInt* scan  = g_scanOrder[SCAN_UNGROUPED][SCAN_DIAG][sizeId==0 ? 2 : 3][sizeId==0 ? 2 : 3];
+  Int nextCoef = SCALING_LIST_START_VALUE;
+  Int data;
+  Int *src = scalingList->getScalingListAddress(sizeId, listId);
+    if( sizeId > SCALING_LIST_8x8 )
+    {
+      WRITE_SVLC( scalingList->getScalingListDC(sizeId,listId) - 8, "scaling_list_dc_coef_minus8");
+      nextCoef = scalingList->getScalingListDC(sizeId,listId);
+    }
+    for(Int i=0;i<coefNum;i++)
+    {
+      data = src[scan[i]] - nextCoef;
+      nextCoef = src[scan[i]];
+      if(data > 127)
+      {
+        data = data - 256;
+      }
+      if(data < -128)
+      {
+        data = data + 256;
+      }
+
+      WRITE_SVLC( data,  "scaling_list_delta_coef");
+    }
+}
+Bool TEncCavlc::findMatchingLTRP ( TComSlice* pcSlice, UInt *ltrpsIndex, Int ltrpPOC, Bool usedFlag )
+{
+  // Bool state = true, state2 = false;
+  Int lsb = ltrpPOC & ((1<<pcSlice->getSPS()->getBitsForPOC())-1);
+  for (Int k = 0; k < pcSlice->getSPS()->getNumLongTermRefPicSPS(); k++)
+  {
+    if ( (lsb == pcSlice->getSPS()->getLtRefPicPocLsbSps(k)) && (usedFlag == pcSlice->getSPS()->getUsedByCurrPicLtSPSFlag(k)) )
+    {
+      *ltrpsIndex = k;
+      return true;
+    }
+  }
+  return false;
+}
+Bool TComScalingList::checkPredMode(UInt sizeId, UInt listId)
+{
+  Int predListStep = (sizeId == SCALING_LIST_32x32? (SCALING_LIST_NUM/NUMBER_OF_PREDICTION_MODES) : 1); // if 32x32, skip over chroma entries.
+
+  for(Int predListIdx = (Int)listId ; predListIdx >= 0; predListIdx-=predListStep)
+  {
+    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;
+}
+
+Void TEncCavlc::codeExplicitRdpcmMode( TComTU &rTu, const ComponentID compID )
+ {
+   assert(0);
+ }
+
+#if SVC_EXTENSION
+
+#if POC_RESET_IDC_SIGNALLING
+Void  TEncCavlc::codeSliceHeaderExtn( TComSlice* slice, Int shBitsWrittenTillNow )
+{
+  Int tmpBitsBeforeWriting = getNumberOfWrittenBits();
+  Int maxPocLsb = 1 << slice->getSPS()->getBitsForPOC();
+  if(slice->getPPS()->getSliceHeaderExtensionPresentFlag())
+  {
+    // Derive the value of PocMsbValRequiredFlag
+#if P0297_VPS_POC_LSB_ALIGNED_FLAG
+    slice->setPocMsbValRequiredFlag( (slice->getCraPicFlag() || slice->getBlaPicFlag())
+                                  && (!slice->getVPS()->getVpsPocLsbAlignedFlag() ||
+                                      (slice->getVPS()->getVpsPocLsbAlignedFlag() && slice->getVPS()->getNumDirectRefLayers(slice->getLayerId()) == 0))
+                                   );
+#else
+    slice->setPocMsbValRequiredFlag( slice->getCraPicFlag() || slice->getBlaPicFlag() );
+#endif
+
+    // Determine value of SH extension length.
+    Int shExtnLengthInBit = 0;
+    if (slice->getPPS()->getPocResetInfoPresentFlag())
+    {
+      shExtnLengthInBit += 2;
+    }
+    if (slice->getPocResetIdc() > 0)
+    {
+      shExtnLengthInBit += 6;
+    }
+    if (slice->getPocResetIdc() == 3)
+    {
+      shExtnLengthInBit += (slice->getSPS()->getBitsForPOC() + 1);
+    }
+
+
+#if P0297_VPS_POC_LSB_ALIGNED_FLAG
+    if (!slice->getPocMsbValRequiredFlag() && slice->getVPS()->getVpsPocLsbAlignedFlag())
+#else
+    if (!slice->getPocMsbValRequiredFlag() /* &&  vps_poc_lsb_aligned_flag */)
+#endif
+    {
+      shExtnLengthInBit++;
+    }
+    else
+    {
+      if( slice->getPocMsbValRequiredFlag() )
+      {
+        slice->setPocMsbValPresentFlag( true );
+      }
+      else
+      {
+        slice->setPocMsbValPresentFlag( false );
+      }
+    }
+
+#if P0297_VPS_POC_LSB_ALIGNED_FLAG
+    if (slice->getPocMsbNeeded())
+    {
+      slice->setPocMsbValPresentFlag(true);
+    }
+#endif
+
+    if (slice->getPocMsbValPresentFlag())
+    {
+      UInt lengthVal = 1;
+      UInt tempVal = (slice->getPocMsbVal() / maxPocLsb) + 1;
+      assert ( tempVal );
+      while( 1 != tempVal )
+      {
+        tempVal >>= 1;
+        lengthVal += 2;
+      }
+      shExtnLengthInBit += lengthVal;
+    }
+    Int shExtnAdditionalBits = 0;
+    if(shExtnLengthInBit % 8 != 0)
+    {
+      shExtnAdditionalBits = 8 - (shExtnLengthInBit % 8);
+    }
+    Int shExtnLength = (shExtnLengthInBit + shExtnAdditionalBits) / 8;
+    WRITE_UVLC( shExtnLength, "slice_header_extension_length" );
+
+    if(slice->getPPS()->getPocResetInfoPresentFlag())
+    {
+      WRITE_CODE( slice->getPocResetIdc(), 2,                                 "poc_reset_idc");
+    }
+    if(slice->getPocResetIdc() > 0)
+    {
+      WRITE_CODE( slice->getPocResetPeriodId(), 6,                            "poc_reset_period_id");
+    }
+    if(slice->getPocResetIdc() == 3) 
+    {
+      WRITE_FLAG( slice->getFullPocResetFlag() ? 1 : 0,                       "full_poc_reset_flag");
+      WRITE_CODE( slice->getPocLsbVal(), slice->getSPS()->getBitsForPOC(),  "poc_lsb_val");
+    }
+
+#if P0297_VPS_POC_LSB_ALIGNED_FLAG
+    if (!slice->getPocMsbValRequiredFlag() && slice->getVPS()->getVpsPocLsbAlignedFlag())
+#else
+    if (!slice->getPocMsbValRequiredFlag() /* &&  vps_poc_lsb_aligned_flag */)
+#endif
+    {
+#if P0297_VPS_POC_LSB_ALIGNED_FLAG
+      WRITE_FLAG( slice->getPocMsbValPresentFlag(),                           "poc_msb_cycle_val_present_flag" );
+#else
+      WRITE_FLAG( slice->getPocMsbValPresentFlag(),                           "poc_msb_val_present_flag" );
+#endif
+    }
+    if (slice->getPocMsbValPresentFlag())
+    {
+      assert(slice->getPocMsbVal() % maxPocLsb == 0);
+#if P0297_VPS_POC_LSB_ALIGNED_FLAG
+      WRITE_UVLC(slice->getPocMsbVal() / maxPocLsb, "poc_msb_cycle_val");
+#else
+      WRITE_UVLC(slice->getPocMsbVal() / maxPocLsb, "poc_msb_val");
+#endif
+    }
+    for (Int i = 0; i < shExtnAdditionalBits; i++)
+    {
+#if Q0146_SSH_EXT_DATA_BIT 
+      WRITE_FLAG( 1, "slice_segment_header_extension_data_bit");
+#else
+      WRITE_FLAG( 1, "slice_segment_header_extension_reserved_bit");
+#endif
+    }
+  }
+  shBitsWrittenTillNow += ( getNumberOfWrittenBits() - tmpBitsBeforeWriting );
+  
+  // Slice header byte_alignment() included in xAttachSliceDataToNalUnit
+}
+#endif
+
+Void TEncCavlc::codeVPSExtension (TComVPS *vps)
+{
+  // ... More syntax elements to be written here
+#if P0300_ALT_OUTPUT_LAYER_FLAG
+  Int NumOutputLayersInOutputLayerSet[MAX_VPS_LAYER_SETS_PLUS1];
+  Int OlsHighestOutputLayerId[MAX_VPS_LAYER_SETS_PLUS1];
+#endif
+#if LIST_OF_PTL
+  if( vps->getMaxLayers() > 1 && vps->getBaseLayerInternalFlag() )
+  {
+#if MULTIPLE_PTL_SUPPORT
+    codePTL( vps->getPTL(1), false, vps->getMaxTLayers() - 1 );
+#else
+    codePTL( vps->getPTLForExtn(1), false, vps->getMaxTLayers() - 1 );
+#endif
+  }
+#endif
+#if VPS_EXTN_MASK_AND_DIM_INFO
+  UInt i = 0, j = 0;
+#if !VPS_AVC_BL_FLAG_REMOVAL
+  WRITE_FLAG( vps->getAvcBaseLayerFlag(),              "avc_base_layer_flag" );
+#endif
+#if !P0307_REMOVE_VPS_VUI_OFFSET
+#if O0109_MOVE_VPS_VUI_FLAG
+  WRITE_FLAG( 1,                     "vps_vui_present_flag" );
+  vps->setVpsVuiPresentFlag(true);
+  if ( vps->getVpsVuiPresentFlag() ) 
+  {
+#if VPS_VUI_OFFSET
+    WRITE_CODE( vps->getVpsVuiOffset(  ), 16,             "vps_vui_offset" );
+#endif
+    WRITE_FLAG( vps->getSplittingFlag(),                 "splitting_flag" );
+  }
+#else
+#if VPS_VUI_OFFSET
+  WRITE_CODE( vps->getVpsVuiOffset(  ), 16,             "vps_vui_offset" );  
+#endif
+  WRITE_FLAG( vps->getSplittingFlag(),                 "splitting_flag" );
+#endif // O0109_MOVE_VPS_VUI_FLAG
+#endif
+  WRITE_FLAG( vps->getSplittingFlag(),                 "splitting_flag" );
+
+  for(i = 0; i < MAX_VPS_NUM_SCALABILITY_TYPES; i++)
+  {
+    WRITE_FLAG( vps->getScalabilityMask(i),            "scalability_mask[i]" );
+  }
+
+  for(j = 0; j < vps->getNumScalabilityTypes() - vps->getSplittingFlag(); j++)
+  {
+    WRITE_CODE( vps->getDimensionIdLen(j) - 1, 3,      "dimension_id_len_minus1[j]" );
+  }
+
+  // The value of dimBitOffset[ NumScalabilityTypes ] is set equal to 6.
+  if(vps->getSplittingFlag())
+  {
+    UInt splDimSum=0;
+    for(j = 0; j < vps->getNumScalabilityTypes(); j++)
+    {
+      splDimSum+=(vps->getDimensionIdLen(j));
+    }
+    assert(splDimSum<=6);
+  }
+
+  WRITE_FLAG( vps->getNuhLayerIdPresentFlag(),         "vps_nuh_layer_id_present_flag" );
+  for(i = 1; i < vps->getMaxLayers(); i++)
+  {
+    if( vps->getNuhLayerIdPresentFlag() )
+    {
+      WRITE_CODE( vps->getLayerIdInNuh(i),     6,      "layer_id_in_nuh[i]" );
+    }
+
+    if( !vps->getSplittingFlag() )
+    {
+      for(j = 0; j < vps->getNumScalabilityTypes(); j++)
+      {
+        UInt bits = vps->getDimensionIdLen(j);
+        WRITE_CODE( vps->getDimensionId(i, j),   bits,   "dimension_id[i][j]" );
+      }
+    }
+  }
+#endif
+#if VIEW_ID_RELATED_SIGNALING
+  // if ( pcVPS->getNumViews() > 1 )  
+  //   However, this is a bug in the text since, view_id_len_minus1 is needed to parse view_id_val. 
+  {
+#if O0109_VIEW_ID_LEN
+    WRITE_CODE( vps->getViewIdLen( ), 4, "view_id_len" );
+    assert ( vps->getNumViews() >= (1<<vps->getViewIdLen()) );
+#else
+    WRITE_CODE( vps->getViewIdLenMinus1( ), 4, "view_id_len_minus1" );
+#endif
+  }
+
+#if O0109_VIEW_ID_LEN
+  if ( vps->getViewIdLen() > 0 )
+  {
+#endif
+  for(  i = 0; i < vps->getNumViews(); i++ )
+  {
+#if O0109_VIEW_ID_LEN
+    WRITE_CODE( vps->getViewIdVal( i ), vps->getViewIdLen( ), "view_id_val[i]" );
+#else
+    WRITE_CODE( vps->getViewIdVal( i ), vps->getViewIdLenMinus1( ) + 1, "view_id_val[i]" );
+#endif
+  }
+#if O0109_VIEW_ID_LEN
+  }
+#endif
+#endif // VIEW_ID_RELATED_SIGNALING
+
+#if VPS_EXTN_DIRECT_REF_LAYERS
+  for( Int layerCtr = 1; layerCtr < vps->getMaxLayers(); layerCtr++)
+  {
+    for( Int refLayerCtr = 0; refLayerCtr < layerCtr; refLayerCtr++)
+    {
+      WRITE_FLAG(vps->getDirectDependencyFlag(layerCtr, refLayerCtr), "direct_dependency_flag[i][j]" );
+    }
+  }
+#endif
+#if MOVE_ADDN_LS_SIGNALLING
+#if Q0078_ADD_LAYER_SETS
+  if (vps->getNumIndependentLayers() > 1)
+  {
+    WRITE_UVLC( vps->getNumAddLayerSets(), "num_add_layer_sets" );
+    for (i = 0; i < vps->getNumAddLayerSets(); i++)
+    {
+      for (j = 1; j < vps->getNumIndependentLayers(); j++)
+      {
+        int len = 1;
+        while ((1 << len) < (vps->getNumLayersInTreePartition(j) + 1))
+        {
+          len++;
+        }
+        WRITE_CODE(vps->getHighestLayerIdxPlus1(i, j), len, "highest_layer_idx_plus1[i][j]");
+      }
+    }
+  }
+#endif
+#endif
+#if VPS_TSLAYERS
+    WRITE_FLAG( vps->getMaxTSLayersPresentFlag(), "vps_sub_layers_max_minus1_present_flag");
+    if (vps->getMaxTSLayersPresentFlag())
+    {
+        for( i = 0; i < vps->getMaxLayers(); i++)
+        {
+            WRITE_CODE(vps->getMaxTSLayersMinus1(i), 3, "sub_layers_vps_max_minus1[i]" );
+        }
+    }
+#endif
+   WRITE_FLAG( vps->getMaxTidRefPresentFlag(), "max_tid_ref_present_flag");
+   if (vps->getMaxTidRefPresentFlag())
+   {
+     for( i = 0; i < vps->getMaxLayers() - 1; i++)
+     {
+       for( j = i+1; j <= vps->getMaxLayers() - 1; j++)
+       {
+         if(vps->getDirectDependencyFlag(j, i))
+         {
+           WRITE_CODE(vps->getMaxTidIlRefPicsPlus1(i,j), 3, "max_tid_il_ref_pics_plus1[i][j]" );
+         }
+       }
+     }
+   }
+   WRITE_FLAG( vps->getIlpSshSignalingEnabledFlag(), "all_ref_layers_active_flag" );
+#if VPS_EXTN_PROFILE_INFO
+  // Profile-tier-level signalling
+#if !VPS_EXTN_UEV_CODING
+  WRITE_CODE( vps->getNumLayerSets() - 1   , 10, "vps_number_layer_sets_minus1" );     
+  WRITE_CODE( vps->getNumProfileTierLevel() - 1,  6, "vps_num_profile_tier_level_minus1"); 
+#else
+  WRITE_UVLC( vps->getNumProfileTierLevel() - 1, "vps_num_profile_tier_level_minus1"); 
+#if PER_LAYER_PTL
+  Int const numBitsForPtlIdx = vps->calculateLenOfSyntaxElement( vps->getNumProfileTierLevel() );
+#endif
+#endif
+#if LIST_OF_PTL
+#if MULTIPLE_PTL_SUPPORT
+  //Do something here to make sure the loop is correct to consider base layer internal stuff
+#else
+  assert( vps->getNumProfileTierLevel() == vps->getPTLForExtnPtr()->size());
+#endif
+  for(Int idx = vps->getBaseLayerInternalFlag() ? 2 : 1; idx < vps->getNumProfileTierLevel(); idx++)
+#else
+  for(Int idx = 1; idx <= vps->getNumProfileTierLevel() - 1; idx++)
+#endif
+  {
+#if MULTIPLE_PTL_SUPPORT
+    vps->setProfilePresentFlag(idx, true);
+#endif
+    WRITE_FLAG( vps->getProfilePresentFlag(idx),       "vps_profile_present_flag[i]" );
+#if !P0048_REMOVE_PROFILE_REF
+    if( !vps->getProfilePresentFlag(idx) )
+    {
+      WRITE_CODE( vps->getProfileLayerSetRef(idx) - 1, 6, "profile_ref_minus1[i]" );
+    }
+#endif
+#if MULTIPLE_PTL_SUPPORT
+    codePTL( vps->getPTL(idx), vps->getProfilePresentFlag(idx), vps->getMaxTLayers() - 1 );
+#else
+    codePTL( vps->getPTLForExtn(idx), vps->getProfilePresentFlag(idx), vps->getMaxTLayers() - 1 );
+#endif
+  }
+#endif
+
+
+#if !MOVE_ADDN_LS_SIGNALLING
+#if Q0078_ADD_LAYER_SETS
+  if (vps->getNumIndependentLayers() > 1)
+  {
+    WRITE_UVLC( vps->getNumAddLayerSets(), "num_add_layer_sets" );
+    for (i = 0; i < vps->getNumAddLayerSets(); i++)
+    {
+      for (j = 1; j < vps->getNumIndependentLayers(); j++)
+      {
+        int len = 1;
+        while ((1 << len) < (vps->getNumLayersInTreePartition(j) + 1))
+        {
+          len++;
+        }
+        WRITE_CODE(vps->getHighestLayerIdxPlus1(i, j), len, "highest_layer_idx_plus1[i][j]");
+      }
+    }
+  }
+#endif
+#endif
+
+#if !VPS_EXTN_UEV_CODING
+  Int numOutputLayerSets = vps->getNumOutputLayerSets() ;
+  WRITE_FLAG(  (numOutputLayerSets > vps->getNumLayerSets()), "more_output_layer_sets_than_default_flag" ); 
+  if(numOutputLayerSets > vps->getNumLayerSets())
+  {
+    WRITE_CODE( numOutputLayerSets - vps->getNumLayerSets(), 10, "num_add_output_layer_sets" );
+  }
+#else
+  Int numOutputLayerSets = vps->getNumOutputLayerSets();
+  Int numAddOutputLayerSets = numOutputLayerSets - (Int)vps->getNumLayerSets();
+
+  // The value of num_add_olss shall be in the range of 0 to 1023, inclusive.
+  assert( numAddOutputLayerSets >= 0 && numAddOutputLayerSets < 1024 );
+
+#if Q0165_NUM_ADD_OUTPUT_LAYER_SETS
+  if( vps->getNumLayerSets() > 1 )
+  {
+    WRITE_UVLC( numAddOutputLayerSets, "num_add_olss" );
+    WRITE_CODE( vps->getDefaultTargetOutputLayerIdc(), 2, "default_output_layer_idc" );
+  }
+#else
+  WRITE_UVLC( numOutputLayerSets - vps->getNumLayerSets(), "num_add_output_layer_sets" );
+#endif
+#endif
+
+#if !Q0165_NUM_ADD_OUTPUT_LAYER_SETS
+  if( numOutputLayerSets > 1 )
+  {
+#if P0295_DEFAULT_OUT_LAYER_IDC
+    WRITE_CODE( vps->getDefaultTargetOutputLayerIdc(), 2, "default_target_output_layer_idc" );   
+#else
+#if O0109_DEFAULT_ONE_OUT_LAYER_IDC
+    WRITE_CODE( vps->getDefaultOneTargetOutputLayerIdc(), 2, "default_one_target_output_layer_idc" );   
+#else
+    WRITE_FLAG( vps->getDefaultOneTargetOutputLayerFlag(), "default_one_target_output_layer_flag" );   
+#endif
+#endif
+  }
+#endif
+
+  for(i = 1; i < numOutputLayerSets; i++)
+  {
+    Int layerSetIdxForOutputLayerSet = vps->getOutputLayerSetIdx(i);
+#if VPS_FIX_TO_MATCH_SPEC
+    if( vps->getNumLayerSets() > 2 && i >= vps->getNumLayerSets() )
+#else
+    if( i > (vps->getNumLayerSets() - 1) )
+#endif
+    {
+      Int numBits = 1;
+      while ((1 << numBits) < (vps->getNumLayerSets() - 1))
+      {
+        numBits++;
+      }
+      WRITE_CODE( vps->getOutputLayerSetIdx(i) - 1, numBits, "layer_set_idx_for_ols_minus1"); 
+#if P0295_DEFAULT_OUT_LAYER_IDC
+    }
+#if Q0078_ADD_LAYER_SETS
+    if ( i > vps->getVpsNumLayerSetsMinus1() || vps->getDefaultTargetOutputLayerIdc() >= 2 ) //Instead of == 2, >= 2 is used to follow the agreement that value 3 should be interpreted as 2
+#else
+    if ( i > (vps->getNumLayerSets() - 1) || vps->getDefaultTargetOutputLayerIdc() >= 2 ) //Instead of == 2, >= 2 is used to follow the agreement that value 3 should be interpreted as 2
+#endif
+    {
+#endif
+#if NUM_OL_FLAGS
+      for(j = 0; j < vps->getNumLayersInIdList(layerSetIdxForOutputLayerSet) ; j++)
+#else
+      for(j = 0; j < vps->getNumLayersInIdList(lsIdx) - 1; j++)
+#endif
+      {
+        WRITE_FLAG( vps->getOutputLayerFlag(i,j), "output_layer_flag[i][j]");
+      }
+    }
+#if PER_LAYER_PTL
+    for(j = 0; j < vps->getNumLayersInIdList(layerSetIdxForOutputLayerSet) ; j++)
+    {
+#if VPS_FIX_TO_MATCH_SPEC
+      if( vps->getNecessaryLayerFlag(i, j) && (vps->getNumProfileTierLevel() - 1) > 0 )
+#else
+      if( vps->getNecessaryLayerFlag(i, j) )
+#endif
+      {
+        WRITE_CODE( vps->getProfileLevelTierIdx(i, j), numBitsForPtlIdx, "profile_level_tier_idx[i]" );
+      }
+    }
+#else
+    Int numBits = 1;
+    while ((1 << numBits) < (vps->getNumProfileTierLevel()))
+    {
+      numBits++;
+    }
+    WRITE_CODE( vps->getProfileLevelTierIdx(i), numBits, "profile_level_tier_idx[i]" );     
+#endif
+#if P0300_ALT_OUTPUT_LAYER_FLAG
+    NumOutputLayersInOutputLayerSet[i] = 0;
+    for (j = 0; j < vps->getNumLayersInIdList(layerSetIdxForOutputLayerSet); j++)
+    {
+      NumOutputLayersInOutputLayerSet[i] += vps->getOutputLayerFlag(i, j);
+      if (vps->getOutputLayerFlag(i, j))
+      {
+        OlsHighestOutputLayerId[i] = vps->getLayerSetLayerIdList(layerSetIdxForOutputLayerSet, j);
+      }
+    }
+    if (NumOutputLayersInOutputLayerSet[i] == 1 && vps->getNumDirectRefLayers(OlsHighestOutputLayerId[i]) > 0)
+    {
+      WRITE_FLAG(vps->getAltOuputLayerFlag(i), "alt_output_layer_flag[i]");
+    }
+
+#if Q0165_OUTPUT_LAYER_SET
+    assert( NumOutputLayersInOutputLayerSet[i]>0 );
+#endif
+
+#endif
+  }
+
+#if !P0300_ALT_OUTPUT_LAYER_FLAG
+#if O0153_ALT_OUTPUT_LAYER_FLAG
+  if( vps->getMaxLayers() > 1 )
+  {
+    WRITE_FLAG( vps->getAltOuputLayerFlag(), "alt_output_layer_flag" );   
+  }
+#endif
+#endif
+
+#if REPN_FORMAT_IN_VPS
+#if Q0195_REP_FORMAT_CLEANUP  
+  // The value of vps_num_rep_formats_minus1 shall be in the range of 0 to 255, inclusive.
+  assert( vps->getVpsNumRepFormats() > 0 && vps->getVpsNumRepFormats() <= 256 );
+  
+  WRITE_UVLC( vps->getVpsNumRepFormats() - 1, "vps_num_rep_formats_minus1" );
+
+  for(i = 0; i < vps->getVpsNumRepFormats(); i++)
+  {
+    // Write rep_format_structures
+    codeRepFormat( vps->getVpsRepFormat(i) );
+  }
+
+  if( vps->getVpsNumRepFormats() > 1 )
+  {
+    WRITE_FLAG( vps->getRepFormatIdxPresentFlag(), "rep_format_idx_present_flag"); 
+  }
+  else
+  {
+    // When not present, the value of rep_format_idx_present_flag is inferred to be equal to 0
+    assert( !vps->getRepFormatIdxPresentFlag() );
+  }
+
+  if( vps->getRepFormatIdxPresentFlag() )
+  {
+#if VPS_FIX_TO_MATCH_SPEC
+    for( i = vps->getBaseLayerInternalFlag() ? 1 : 0; i < vps->getMaxLayers(); i++ )
+#else
+    for(i = 1; i < vps->getMaxLayers(); i++)
+#endif
+    {
+      Int numBits = 1;
+      while ((1 << numBits) < (vps->getVpsNumRepFormats()))
+      {
+        numBits++;
+      }
+      WRITE_CODE( vps->getVpsRepFormatIdx(i), numBits, "vps_rep_format_idx[i]" );
+    }
+  }
+#else
+  WRITE_FLAG( vps->getRepFormatIdxPresentFlag(), "rep_format_idx_present_flag"); 
+
+  if( vps->getRepFormatIdxPresentFlag() )
+  {
+    // The value of vps_num_rep_formats_minus1 shall be in the range of 0 to 255, inclusive.
+    assert( vps->getVpsNumRepFormats() > 0 && vps->getVpsNumRepFormats() <= 256 );
+
+#if O0096_REP_FORMAT_INDEX
+#if !VPS_EXTN_UEV_CODING
+    WRITE_CODE( vps->getVpsNumRepFormats() - 1, 8, "vps_num_rep_formats_minus1" );
+#else
+    WRITE_UVLC( vps->getVpsNumRepFormats() - 1, "vps_num_rep_formats_minus1" );
+#endif
+#else
+    WRITE_CODE( vps->getVpsNumRepFormats() - 1, 4, "vps_num_rep_formats_minus1" );
+#endif
+  }
+  for(i = 0; i < vps->getVpsNumRepFormats(); i++)
+  {
+    // Read rep_format_structures
+    codeRepFormat( vps->getVpsRepFormat(i) );
+  }
+  
+  if( vps->getRepFormatIdxPresentFlag() )
+  {
+    for(i = 1; i < vps->getMaxLayers(); i++)
+    {
+      if( vps->getVpsNumRepFormats() > 1 )
+      {
+#if O0096_REP_FORMAT_INDEX
+#if !VPS_EXTN_UEV_CODING
+        WRITE_CODE( vps->getVpsRepFormatIdx(i), 8, "vps_rep_format_idx[i]" );
+#else
+        Int numBits = 1;
+        while ((1 << numBits) < (vps->getVpsNumRepFormats()))
+        {
+          numBits++;
+        }
+        WRITE_CODE( vps->getVpsRepFormatIdx(i), numBits, "vps_rep_format_idx[i]" );
+#endif
+#else
+        WRITE_CODE( vps->getVpsRepFormatIdx(i), 4, "vps_rep_format_idx[i]" );
+#endif
+      }
+    }
+  }
+#endif
+#endif
+
+  WRITE_FLAG(vps->getMaxOneActiveRefLayerFlag(), "max_one_active_ref_layer_flag");
+#if P0297_VPS_POC_LSB_ALIGNED_FLAG
+  WRITE_FLAG(vps->getVpsPocLsbAlignedFlag(), "vps_poc_lsb_aligned_flag");
+#endif
+#if O0062_POC_LSB_NOT_PRESENT_FLAG
+  for(i = 1; i< vps->getMaxLayers(); i++)
+  {
+    if( vps->getNumDirectRefLayers( vps->getLayerIdInNuh(i) ) == 0  )
+    {
+      WRITE_FLAG(vps->getPocLsbNotPresentFlag(i), "poc_lsb_not_present_flag[i]");
+    }
+  }
+#endif
+#if O0215_PHASE_ALIGNMENT
+  WRITE_FLAG(vps->getPhaseAlignFlag(), "cross_layer_phase_alignment_flag" );
+#endif
+#if !IRAP_ALIGN_FLAG_IN_VPS_VUI
+  WRITE_FLAG(vps->getCrossLayerIrapAlignFlag(), "cross_layer_irap_aligned_flag");
+#endif 
+#if VPS_DPB_SIZE_TABLE
+  codeVpsDpbSizeTable(vps);
+#endif
+#if VPS_EXTN_DIRECT_REF_LAYERS
+  WRITE_UVLC( vps->getDirectDepTypeLen()-2,                           "direct_dep_type_len_minus2");
+#if O0096_DEFAULT_DEPENDENCY_TYPE
+  WRITE_FLAG(vps->getDefaultDirectDependencyTypeFlag(), "default_direct_dependency_flag");
+  if (vps->getDefaultDirectDependencyTypeFlag())
+  {
+    WRITE_CODE( vps->getDefaultDirectDependencyType(), vps->getDirectDepTypeLen(), "default_direct_dependency_type" );
+  }
+  else
+  {
+#if VPS_FIX_TO_MATCH_SPEC
+    for( i = vps->getBaseLayerInternalFlag() ? 1 : 2; i < vps->getMaxLayers(); i++ )
+#else
+    for(i = 1; i < vps->getMaxLayers(); i++)
+#endif
+    {
+#if VPS_FIX_TO_MATCH_SPEC
+      for( j = vps->getBaseLayerInternalFlag() ? 0 : 1; j < i; j++ )
+#else
+      for(j = 0; j < i; j++)
+#endif
+      {
+        if (vps->getDirectDependencyFlag(i, j))
+        {
+          WRITE_CODE( vps->getDirectDependencyType(i, j), vps->getDirectDepTypeLen(), "direct_dependency_type[i][j]" );
+        }
+      }
+    }
+  }
+#else
+  for(i = 1; i < vps->getMaxLayers(); i++)
+  {
+    for(j = 0; j < i; j++)
+    {
+      if (vps->getDirectDependencyFlag(i, j))
+      {
+        WRITE_CODE( vps->getDirectDependencyType(i, j), vps->getDirectDepTypeLen(), "direct_dependency_type[i][j]" );
+      }
+    }
+  }
+#endif
+#endif
+
+#if !O0109_O0199_FLAGS_TO_VUI
+#if M0040_ADAPTIVE_RESOLUTION_CHANGE
+  WRITE_FLAG(vps->getSingleLayerForNonIrapFlag(), "single_layer_for_non_irap_flag" );
+#endif
+#if HIGHER_LAYER_IRAP_SKIP_FLAG
+  WRITE_FLAG(vps->getHigherLayerIrapSkipFlag(), "higher_layer_irap_skip_flag" );
+#endif
+#endif
+
+#if P0307_VPS_NON_VUI_EXTENSION
+  // The value of vps_non_vui_extension_length shall be in the range of 0 to 4096, inclusive.
+  assert( vps->getVpsNonVuiExtLength() >= 0 && vps->getVpsNonVuiExtLength() <= 4096 );
+
+  WRITE_UVLC( vps->getVpsNonVuiExtLength(), "vps_non_vui_extension_length" );
+#if P0307_VPS_NON_VUI_EXT_UPDATE
+  for (i = 1; i <= vps->getVpsNonVuiExtLength(); i++)
+  {
+    WRITE_CODE(1, 8, "vps_non_vui_extension_data_byte");
+  }
+#else
+  if ( vps->getVpsNonVuiExtLength() > 0 )
+  {
+    printf("\n\nUp to the current spec, the value of vps_non_vui_extension_length is supposed to be 0\n");
+  }
+#endif
+#endif
+
+#if !O0109_MOVE_VPS_VUI_FLAG
+  WRITE_FLAG( 1,                     "vps_vui_present_flag" );
+  if(1)   // Should be conditioned on the value of vps_vui_present_flag
+  {
+    while ( m_pcBitIf->getNumberOfWrittenBits() % 8 != 0 )
+    {
+      WRITE_FLAG(1,                  "vps_vui_alignment_bit_equal_to_one");
+    }
+#if VPS_VUI_OFFSET
+    Int vpsVuiOffsetValeInBits = this->m_pcBitIf->getNumberOfWrittenBits() - m_vpsVuiCounter + 16; // 2 bytes for NUH
+    assert( vpsVuiOffsetValeInBits % 8 == 0 );
+    vps->setVpsVuiOffset( vpsVuiOffsetValeInBits >> 3 );
+#endif
+    codeVPSVUI(vps);  
+  }
+#else
+#if P0307_REMOVE_VPS_VUI_OFFSET
+  vps->setVpsVuiPresentFlag(true);
+  WRITE_FLAG( vps->getVpsVuiPresentFlag() ? 1 : 0,                     "vps_vui_present_flag" );
+#endif
+  if(vps->getVpsVuiPresentFlag())   // Should be conditioned on the value of vps_vui_present_flag
+  {
+    while ( m_pcBitIf->getNumberOfWrittenBits() % 8 != 0 )
+    {
+      WRITE_FLAG(1,                  "vps_vui_alignment_bit_equal_to_one");
+    }
+#if !P0307_REMOVE_VPS_VUI_OFFSET
+#if VPS_VUI_OFFSET
+    Int vpsVuiOffsetValeInBits = this->m_pcBitIf->getNumberOfWrittenBits() - m_vpsVuiCounter + 16; // 2 bytes for NUH
+    assert( vpsVuiOffsetValeInBits % 8 == 0 );
+    vps->setVpsVuiOffset( vpsVuiOffsetValeInBits >> 3 );
+#endif
+#endif
+    codeVPSVUI(vps);  
+  }
+#endif // 0109_MOVE_VPS_FLAG
+}
+
+#if REPN_FORMAT_IN_VPS
+Void  TEncCavlc::codeRepFormat( RepFormat *repFormat )
+{
+#if REPN_FORMAT_CONTROL_FLAG
+  WRITE_CODE( repFormat->getPicWidthVpsInLumaSamples (), 16, "pic_width_vps_in_luma_samples" );    
+  WRITE_CODE( repFormat->getPicHeightVpsInLumaSamples(), 16, "pic_height_vps_in_luma_samples" );  
+  WRITE_FLAG( repFormat->getChromaAndBitDepthVpsPresentFlag(), "chroma_and_bit_depth_vps_present_flag" );
+
+  if( repFormat->getChromaAndBitDepthVpsPresentFlag() )
+  {
+    WRITE_CODE( repFormat->getChromaFormatVpsIdc(), 2, "chroma_format_vps_idc" );   
+
+    if( repFormat->getChromaFormatVpsIdc() == 3 )
+    {
+      WRITE_FLAG( repFormat->getSeparateColourPlaneVpsFlag(), "separate_colour_plane_vps_flag" );      
+    }
+
+    assert( repFormat->getBitDepthVpsLuma() >= 8 );
+    assert( repFormat->getBitDepthVpsChroma() >= 8 );
+    WRITE_CODE( repFormat->getBitDepthVpsLuma() - 8,   4, "bit_depth_vps_luma_minus8" );           
+    WRITE_CODE( repFormat->getBitDepthVpsChroma() - 8, 4, "bit_depth_vps_chroma_minus8" );
+  }
+#else 
+  WRITE_CODE( repFormat->getChromaFormatVpsIdc(), 2, "chroma_format_idc" );    
+  
+  if( repFormat->getChromaFormatVpsIdc() == 3 )
+  {
+    WRITE_FLAG( repFormat->getSeparateColourPlaneVpsFlag(), "separate_colour_plane_flag");      
+  }
+
+  WRITE_CODE ( repFormat->getPicWidthVpsInLumaSamples (), 16, "pic_width_in_luma_samples" );    
+  WRITE_CODE ( repFormat->getPicHeightVpsInLumaSamples(), 16, "pic_height_in_luma_samples" );    
+  
+  assert( repFormat->getBitDepthVpsLuma() >= 8 );
+  assert( repFormat->getBitDepthVpsChroma() >= 8 );
+  WRITE_CODE( repFormat->getBitDepthVpsLuma() - 8,   4, "bit_depth_luma_minus8" );           
+  WRITE_CODE( repFormat->getBitDepthVpsChroma() - 8, 4, "bit_depth_chroma_minus8" );
+#endif
+
+#if R0156_CONF_WINDOW_IN_REP_FORMAT
+  Window conf = repFormat->getConformanceWindowVps();
+
+  WRITE_FLAG( conf.getWindowEnabledFlag(),    "conformance_window_vps_flag" );
+  if (conf.getWindowEnabledFlag())
+  {
+    WRITE_UVLC( conf.getWindowLeftOffset(),   "conf_win_vps_left_offset"   );
+    WRITE_UVLC( conf.getWindowRightOffset(),  "conf_win_vps_right_offset"  );
+    WRITE_UVLC( conf.getWindowTopOffset(),    "conf_win_vps_top_offset"    );
+    WRITE_UVLC( conf.getWindowBottomOffset(), "conf_win_vps_bottom_offset" );
+  }
+#endif
+}
+#endif
+#if VPS_DPB_SIZE_TABLE
+Void TEncCavlc::codeVpsDpbSizeTable(TComVPS *vps)
+{
+#if !SUB_LAYERS_IN_LAYER_SET  // MaxSLInLayerSets calculated earlier in the encoder
+#if DPB_PARAMS_MAXTLAYERS
+#if BITRATE_PICRATE_SIGNALLING
+    Int * MaxSubLayersInLayerSetMinus1 = new Int[vps->getNumLayerSets()];
+    for(Int i = 0; i < vps->getNumLayerSets(); i++)
+#else
+    Int * MaxSubLayersInLayerSetMinus1 = new Int[vps->getNumOutputLayerSets()];
+    for(Int i = 1; i < vps->getNumOutputLayerSets(); i++)
+#endif
+    {
+        UInt maxSLMinus1 = 0;
+#if CHANGE_NUMSUBDPB_IDX
+        Int optLsIdx = vps->getOutputLayerSetIdx( i );
+#else
+        Int optLsIdx = i;
+#endif
+#if BITRATE_PICRATE_SIGNALLING
+        optLsIdx = i;
+#endif
+        for(Int k = 0; k < vps->getNumLayersInIdList(optLsIdx); k++ ) {
+            Int  lId = vps->getLayerSetLayerIdList(optLsIdx, k);
+            maxSLMinus1 = max(maxSLMinus1, vps->getMaxTSLayersMinus1(vps->getLayerIdxInVps(lId)));
+        }
+        MaxSubLayersInLayerSetMinus1[ i ] = maxSLMinus1;
+#if BITRATE_PICRATE_SIGNALLING
+        vps->setMaxSLayersInLayerSetMinus1(i,MaxSubLayersInLayerSetMinus1[ i ]);
+#endif
+    }
+#endif
+#endif
+    
+    
+  for(Int i = 1; i < vps->getNumOutputLayerSets(); i++)
+  {
+#if CHANGE_NUMSUBDPB_IDX
+    Int layerSetIdxForOutputLayerSet = vps->getOutputLayerSetIdx( i );
+#endif
+    WRITE_FLAG( vps->getSubLayerFlagInfoPresentFlag( i ), "sub_layer_flag_info_present_flag[i]");
+#if SUB_LAYERS_IN_LAYER_SET
+    for(Int j = 0; j <= vps->getMaxSLayersInLayerSetMinus1( layerSetIdxForOutputLayerSet ); j++)
+#else
+#if DPB_PARAMS_MAXTLAYERS
+#if BITRATE_PICRATE_SIGNALLING
+    for(Int j = 0; j <= MaxSubLayersInLayerSetMinus1[ vps->getOutputLayerSetIdx( i ) ]; j++)
+#else
+    for(Int j = 0; j <= MaxSubLayersInLayerSetMinus1[ i ]; j++)
+#endif
+#else
+    for(Int j = 0; j < vps->getMaxTLayers(); j++)
+#endif
+#endif
+    {
+      if( j > 0 && vps->getSubLayerFlagInfoPresentFlag(i) )
+      {
+        WRITE_FLAG( vps->getSubLayerDpbInfoPresentFlag( i, j), "sub_layer_dpb_info_present_flag[i]");  
+      }
+      if( vps->getSubLayerDpbInfoPresentFlag(i, j) )
+      {
+#if CHANGE_NUMSUBDPB_IDX
+#if RESOLUTION_BASED_DPB
+        for(Int k = 0; k < vps->getNumSubDpbs(layerSetIdxForOutputLayerSet); k++)
+#else
+        for(Int k = 0; k < vps->getNumLayersInIdList( layerSetIdxForOutputLayerSet ); k++)
+#endif
+#else
+        for(Int k = 0; k < vps->getNumSubDpbs(i); k++)
+#endif
+        {
+#if DPB_INTERNAL_BL_SIG
+#if VPS_FIX_TO_MATCH_SPEC
+        if( vps->getNecessaryLayerFlag(i, k) && (vps->getBaseLayerInternalFlag() || (vps->getLayerSetLayerIdList(layerSetIdxForOutputLayerSet, k) != 0)) )
+#else
+        if(vps->getBaseLayerInternalFlag()  || ( vps->getLayerSetLayerIdList(layerSetIdxForOutputLayerSet, k)   !=  0 ) )
+#endif
+#endif
+          WRITE_UVLC( vps->getMaxVpsDecPicBufferingMinus1( i, k, j ), "max_vps_dec_pic_buffering_minus1[i][k][j]" );
+        }
+        WRITE_UVLC( vps->getMaxVpsNumReorderPics( i, j), "max_vps_num_reorder_pics[i][j]" );              
+#if RESOLUTION_BASED_DPB
+        if( vps->getNumSubDpbs(layerSetIdxForOutputLayerSet) != vps->getNumLayersInIdList( layerSetIdxForOutputLayerSet ) )  // NumSubDpbs
+        {
+          for(Int k = 0; k < vps->getNumLayersInIdList( layerSetIdxForOutputLayerSet ); k++)
+          {
+            WRITE_UVLC( vps->getMaxVpsLayerDecPicBuffMinus1( i, k, j), "max_vps_layer_dec_pic_buff_minus1[i][k][j]" );
+          }
+        }
+#endif
+        WRITE_UVLC( vps->getMaxVpsLatencyIncreasePlus1( i, j), "max_vps_latency_increase_plus1[i][j]" );        
+      }
+    }
+  }
+
+#if !SUB_LAYERS_IN_LAYER_SET
+#if BITRATE_PICRATE_SIGNALLING
+  if( MaxSubLayersInLayerSetMinus1 )
+  {
+    delete [] MaxSubLayersInLayerSetMinus1;
+  }
+#endif
+#endif
+}
+#endif
+
+Void TEncCavlc::codeVPSVUI (TComVPS *vps)
+{
+  Int i,j;
+#if O0223_PICTURE_TYPES_ALIGN_FLAG
+  WRITE_FLAG(vps->getCrossLayerPictureTypeAlignFlag(), "cross_layer_pic_type_aligned_flag");
+  if (!vps->getCrossLayerPictureTypeAlignFlag())
+  {
+#endif 
+#if IRAP_ALIGN_FLAG_IN_VPS_VUI
+    WRITE_FLAG(vps->getCrossLayerIrapAlignFlag(), "cross_layer_irap_aligned_flag");
+#endif 
+#if O0223_PICTURE_TYPES_ALIGN_FLAG
+  }
+  else
+  {
+    vps->setCrossLayerIrapAlignFlag(vps->getVpsVuiPresentFlag()); // When not present, the value of cross_layer_irap_aligned_flag is inferred to be equal to vps_vui_present_flag
+  }
+#endif
+#if P0068_CROSS_LAYER_ALIGNED_IDR_ONLY_FOR_IRAP_FLAG
+  if(vps->getCrossLayerIrapAlignFlag())
+  {
+    WRITE_FLAG(vps->getCrossLayerAlignedIdrOnlyFlag(), "all_layers_idr_aligned_flag");
+  }
+#endif
+
+  WRITE_FLAG( vps->getBitRatePresentVpsFlag(),        "bit_rate_present_vps_flag" );
+  WRITE_FLAG( vps->getPicRatePresentVpsFlag(),        "pic_rate_present_vps_flag" );
+
+  if( vps->getBitRatePresentVpsFlag() || vps->getPicRatePresentVpsFlag() )
+  {
+#if Q0078_ADD_LAYER_SETS
+#if R0227_BR_PR_ADD_LAYER_SET
+#if SIGNALLING_BITRATE_PICRATE_FIX
+    for( i = vps->getBaseLayerInternalFlag() ? 0 : 1; i < vps->getNumLayerSets(); i++ )
+#else
+    for( i = 0; i < vps->getNumLayerSets(); i++ )
+#endif
+#else
+    for( i = 0; i <= vps->getVpsNumLayerSetsMinus1(); i++ )
+#endif
+#else
+    for( i = 0; i < vps->getNumLayerSets(); i++ )
+#endif
+    {
+#if BITRATE_PICRATE_SIGNALLING
+      for( j = 0; j <= vps->getMaxSLayersInLayerSetMinus1(i); j++ )
+#else
+      for( j = 0; j < vps->getMaxTLayers(); j++ )
+#endif
+      {
+        if( vps->getBitRatePresentVpsFlag() )
+        {
+          WRITE_FLAG( vps->getBitRatePresentFlag( i, j),        "bit_rate_present_flag[i][j]" );
+        }
+        if( vps->getPicRatePresentVpsFlag() )
+        {
+          WRITE_FLAG( vps->getPicRatePresentFlag( i, j),        "pic_rate_present_flag[i][j]" );
+        }
+        if( vps->getBitRatePresentFlag(i, j) )
+        {
+          WRITE_CODE( vps->getAvgBitRate( i, j ), 16, "avg_bit_rate[i][j]" );
+          WRITE_CODE( vps->getAvgBitRate( i, j ), 16, "max_bit_rate[i][j]" );
+        }
+        if( vps->getPicRatePresentFlag(i, j) )
+        {
+          WRITE_CODE( vps->getConstPicRateIdc( i, j), 2 , "constant_pic_rate_idc[i][j]" ); 
+          WRITE_CODE( vps->getConstPicRateIdc( i, j), 16, "avg_pic_rate[i][j]"          ); 
+        }
+      }
+    }
+  }
+#if VPS_VUI_VIDEO_SIGNAL_MOVE
+  WRITE_FLAG( vps->getVideoSigPresentVpsFlag(), "video_signal_info_idx_present_flag" );
+  if (vps->getVideoSigPresentVpsFlag())
+  {
+    WRITE_CODE(vps->getNumVideoSignalInfo()-1, 4, "vps_num_video_signal_info_minus1" );
+  }
+
+  for(i = 0; i < vps->getNumVideoSignalInfo(); i++)
+  {
+    WRITE_CODE(vps->getVideoVPSFormat(i), 3, "video_vps_format" );
+    WRITE_FLAG(vps->getVideoFullRangeVpsFlag(i), "video_full_range_vps_flag" );
+    WRITE_CODE(vps->getColorPrimaries(i), 8, "color_primaries_vps" );
+    WRITE_CODE(vps->getTransCharacter(i), 8, "transfer_characteristics_vps" );
+    WRITE_CODE(vps->getMaxtrixCoeff(i), 8, "matrix_coeffs_vps" );
+  }
+
+  if (vps->getVideoSigPresentVpsFlag() && vps->getNumVideoSignalInfo() > 1 )
+  {
+#if VPS_VUI_VST_PARAMS
+    for(i = vps->getBaseLayerInternalFlag() ? 0 : 1; i < vps->getMaxLayers(); i++)
+    {
+      WRITE_CODE( vps->getVideoSignalInfoIdx(i), 4, "vps_video_signal_info_idx" );
+    }
+#else
+    for (i=1; i < vps->getMaxLayers(); i++)
+      WRITE_CODE(vps->getVideoSignalInfoIdx(i), 4, "vps_video_signal_info_idx" );
+#endif
+  }
+#endif 
+#if VPS_VUI_TILES_NOT_IN_USE__FLAG
+  UInt layerIdx;
+  WRITE_FLAG( vps->getTilesNotInUseFlag() ? 1 : 0 , "tiles_not_in_use_flag" );
+  if (!vps->getTilesNotInUseFlag())
+  {
+#if VPS_FIX_TO_MATCH_SPEC
+    for( i = vps->getBaseLayerInternalFlag() ? 0 : 1; i < vps->getMaxLayers(); i++ )
+#else
+    for(i = 0; i < vps->getMaxLayers(); i++)
+#endif
+    {
+      WRITE_FLAG( vps->getTilesInUseFlag(i) ? 1 : 0 , "tiles_in_use_flag[ i ]" );
+      if (vps->getTilesInUseFlag(i))
+      {
+        WRITE_FLAG( vps->getLoopFilterNotAcrossTilesFlag(i) ? 1 : 0 , "loop_filter_not_across_tiles_flag[ i ]" );
+      }
+    }
+#endif
+
+#if VPS_FIX_TO_MATCH_SPEC
+    for( i = vps->getBaseLayerInternalFlag() ? 1 : 2; i < vps->getMaxLayers(); i++ )
+#else
+    for(i = 1; i < vps->getMaxLayers(); i++)
+#endif
+    {
+      for(j = 0; j < vps->getNumDirectRefLayers(vps->getLayerIdInNuh(i)); j++)
+      {
+#if VPS_VUI_TILES_NOT_IN_USE__FLAG
+        layerIdx = vps->getLayerIdxInVps(vps->getRefLayerId(vps->getLayerIdInNuh(i), j));
+        if (vps->getTilesInUseFlag(i) && vps->getTilesInUseFlag(layerIdx)) {
+          WRITE_FLAG( vps->getTileBoundariesAlignedFlag(i,j) ? 1 : 0 , "tile_boundaries_aligned_flag[i][j]" );
+        }
+#else
+        WRITE_FLAG( vps->getTileBoundariesAlignedFlag(i,j) ? 1 : 0 , "tile_boundaries_aligned_flag[i][j]" );
+#endif
+      }
+    }  
+#if VPS_VUI_TILES_NOT_IN_USE__FLAG
+  }
+#endif
+#if VPS_VUI_WPP_NOT_IN_USE__FLAG
+  WRITE_FLAG( vps->getWppNotInUseFlag() ? 1 : 0 , "wpp_not_in_use_flag" );
+  if (!vps->getWppNotInUseFlag())
+  {
+#if VPS_FIX_TO_MATCH_SPEC
+    for( i = vps->getBaseLayerInternalFlag() ? 0 : 1; i < vps->getMaxLayers(); i++ )
+#else
+    for(i = 0; i < vps->getMaxLayers(); i++)
+#endif
+    {
+      WRITE_FLAG( vps->getWppInUseFlag(i) ? 1 : 0 , "wpp_in_use_flag[ i ]" );
+    }
+  }
+#endif
+
+#if O0109_O0199_FLAGS_TO_VUI
+#if M0040_ADAPTIVE_RESOLUTION_CHANGE
+  WRITE_FLAG(vps->getSingleLayerForNonIrapFlag(), "single_layer_for_non_irap_flag" );
+#endif
+#if HIGHER_LAYER_IRAP_SKIP_FLAG
+  // When single_layer_for_non_irap_flag is equal to 0, higher_layer_irap_skip_flag shall be equal to 0
+  if( !vps->getSingleLayerForNonIrapFlag() )
+  {
+    assert( !vps->getHigherLayerIrapSkipFlag() );
+  }
+
+  WRITE_FLAG(vps->getHigherLayerIrapSkipFlag(), "higher_layer_irap_skip_flag" );
+#endif
+#endif
+#if P0312_VERT_PHASE_ADJ
+  WRITE_FLAG( vps->getVpsVuiVertPhaseInUseFlag(), "vps_vui_vert_phase_in_use_flag" );
+#endif
+#if N0160_VUI_EXT_ILP_REF
+  WRITE_FLAG( vps->getIlpRestrictedRefLayersFlag() ? 1 : 0 , "ilp_restricted_ref_layers_flag" );    
+  if( vps->getIlpRestrictedRefLayersFlag())
+  {
+    for(i = 1; i < vps->getMaxLayers(); i++)
+    {
+      for(j = 0; j < vps->getNumDirectRefLayers(vps->getLayerIdInNuh(i)); j++)
+      {
+#if VPS_FIX_TO_MATCH_SPEC
+        if (vps->getBaseLayerInternalFlag() || vps->getRefLayerId(vps->getLayerIdInNuh(i), j))
+        {
+#endif
+          WRITE_UVLC(vps->getMinSpatialSegmentOffsetPlus1( i, j),    "min_spatial_segment_offset_plus1[i][j]");
+
+          if( vps->getMinSpatialSegmentOffsetPlus1(i,j ) > 0 ) 
+          {  
+            WRITE_FLAG( vps->getCtuBasedOffsetEnabledFlag( i, j) ? 1 : 0 , "ctu_based_offset_enabled_flag[i][j]" );    
+
+            if(vps->getCtuBasedOffsetEnabledFlag(i,j))  
+            {
+              WRITE_UVLC(vps->getMinHorizontalCtuOffsetPlus1( i, j),    "min_horizontal_ctu_offset_plus1[i][j]");            
+            }
+          }
+#if VPS_FIX_TO_MATCH_SPEC
+        }
+#endif
+      }  
+    }
+  }
+#endif 
+#if VPS_VUI_VIDEO_SIGNAL
+#if VPS_VUI_VIDEO_SIGNAL_MOVE
+#else 
+    WRITE_FLAG( vps->getVideoSigPresentVpsFlag(), "video_signal_info_idx_present_flag" );
+    if (vps->getVideoSigPresentVpsFlag())
+    {
+        WRITE_CODE(vps->getNumVideoSignalInfo()-1, 4, "vps_num_video_signal_info_minus1" );
+    }
+    
+    for(i = 0; i < vps->getNumVideoSignalInfo(); i++)
+    {
+        WRITE_CODE(vps->getVideoVPSFormat(i), 3, "video_vps_format" );
+        WRITE_FLAG(vps->getVideoFullRangeVpsFlag(i), "video_full_range_vps_flag" );
+        WRITE_CODE(vps->getColorPrimaries(i), 8, "color_primaries_vps" );
+        WRITE_CODE(vps->getTransCharacter(i), 8, "transfer_characteristics_vps" );
+        WRITE_CODE(vps->getMaxtrixCoeff(i), 8, "matrix_coeffs_vps" );
+    }
+    
+    if (vps->getVideoSigPresentVpsFlag() && vps->getNumVideoSignalInfo() > 1 )
+    {
+        for (i=1; i < vps->getMaxLayers(); i++)
+            WRITE_CODE(vps->getVideoSignalInfoIdx(i), 4, "vps_video_signal_info_idx" );
+    }
+#endif 
+#endif
+#if O0164_MULTI_LAYER_HRD
+    WRITE_FLAG(vps->getVpsVuiBspHrdPresentFlag(), "vps_vui_bsp_hrd_present_flag" );
+    if (vps->getVpsVuiBspHrdPresentFlag())
+    {
+#if VPS_VUI_BSP_HRD_PARAMS
+      codeVpsVuiBspHrdParams(vps);
+#else
+      WRITE_UVLC( vps->getVpsNumBspHrdParametersMinus1(), "vps_num_bsp_hrd_parameters_minus1" );
+      for( i = 0; i <= vps->getVpsNumBspHrdParametersMinus1(); i++ )
+      {
+        if( i > 0 )
+        {
+          WRITE_FLAG( vps->getBspCprmsPresentFlag(i), "bsp_cprms_present_flag[i]" );
+        }
+        codeHrdParameters(vps->getBspHrd(i), i==0 ? 1 : vps->getBspCprmsPresentFlag(i), vps->getMaxTLayers()-1);
+      }
+#if Q0078_ADD_LAYER_SETS
+      for( UInt h = 1; h <= vps->getVpsNumLayerSetsMinus1(); h++ )
+#else
+      for( UInt h = 1; h <= (vps->getNumLayerSets()-1); h++ )
+#endif
+      {
+        WRITE_UVLC( vps->getNumBitstreamPartitions(h), "num_bitstream_partitions[i]");
+        for( i = 0; i < vps->getNumBitstreamPartitions(h); i++ )
+        {
+          for( j = 0; j <= (vps->getMaxLayers()-1); j++ )
+          {
+            if (vps->getLayerIdIncludedFlag(h, j))
+            {
+              WRITE_FLAG( vps->getLayerInBspFlag(h, i, j), "layer_in_bsp_flag[h][i][j]" );
+            }
+          }
+        }
+        if (vps->getNumBitstreamPartitions(h))
+        {
+#if Q0182_MULTI_LAYER_HRD_UPDATE
+          WRITE_UVLC(vps->getNumBspSchedCombinations(h) - 1, "num_bsp_sched_combinations_minus1[h]");
+#else
+          WRITE_UVLC( vps->getNumBspSchedCombinations(h), "num_bsp_sched_combinations[h]");
+#endif
+          for( i = 0; i < vps->getNumBspSchedCombinations(h); i++ )
+          {
+            for( j = 0; j < vps->getNumBitstreamPartitions(h); j++ )
+            {
+              WRITE_UVLC( vps->getBspCombHrdIdx(h, i, j), "bsp_comb_hrd_idx[h][i][j]");
+              WRITE_UVLC( vps->getBspCombSchedIdx(h, i, j), "bsp_comb_sched_idx[h][i][j]");
+            }
+          }
+        }
+      }
+#endif
+    }
+#endif
+#if P0182_VPS_VUI_PS_FLAG
+    for(i = 1; i < vps->getMaxLayers(); i++)
+    {
+      if( vps->getNumRefLayers(vps->getLayerIdInNuh(i)) == 0 ) 
+      {
+        WRITE_FLAG(vps->getBaseLayerPSCompatibilityFlag(i), "base_layer_parameter_set_compatibility_flag" );
+      }
+    }
+#endif
+}
+
+Void TEncCavlc::codeSPSExtension( TComSPS* pcSPS )
+{
+  // more syntax elements to be written here
+
+  // Vertical MV component restriction is not used in SHVC CTC
+  WRITE_FLAG( 0, "inter_view_mv_vert_constraint_flag" );
+
+#if !MOVE_SCALED_OFFSET_TO_PPS
+  if( pcSPS->getLayerId() > 0 )
+  {
+    WRITE_UVLC( pcSPS->getNumScaledRefLayerOffsets(),      "num_scaled_ref_layer_offsets" );
+    for(Int i = 0; i < pcSPS->getNumScaledRefLayerOffsets(); i++)
+    {
+      Window scaledWindow = pcSPS->getScaledRefLayerWindow(i);
+#if O0098_SCALED_REF_LAYER_ID
+      WRITE_CODE( pcSPS->getScaledRefLayerId(i), 6,          "scaled_ref_layer_id" );
+#endif
+      WRITE_SVLC( scaledWindow.getWindowLeftOffset()   >> 1, "scaled_ref_layer_left_offset" );
+      WRITE_SVLC( scaledWindow.getWindowTopOffset()    >> 1, "scaled_ref_layer_top_offset" );
+      WRITE_SVLC( scaledWindow.getWindowRightOffset()  >> 1, "scaled_ref_layer_right_offset" );
+      WRITE_SVLC( scaledWindow.getWindowBottomOffset() >> 1, "scaled_ref_layer_bottom_offset" );
+#if P0312_VERT_PHASE_ADJ
+      WRITE_FLAG( scaledWindow.getVertPhasePositionEnableFlag(), "vert_phase_position_enable_flag" ); 
+#endif
+    }
+  }
+#endif
+}
+#endif //SVC_EXTENSION
+
+#if Q0048_CGS_3D_ASYMLUT
+Void TEncCavlc::xCode3DAsymLUT( TCom3DAsymLUT * pc3DAsymLUT )
+{
+#if R0150_CGS_SIGNAL_CONSTRAINTS
+  UInt uiNumRefLayers = ( UInt )pc3DAsymLUT->getRefLayerNum();
+  WRITE_UVLC( uiNumRefLayers - 1 , "num_cm_ref_layers_minus1" );
+  for( UInt i = 0 ; i < uiNumRefLayers ; i++ )
+  {
+    WRITE_CODE( pc3DAsymLUT->getRefLayerId( i ) , 6 , "cm_ref_layer_id" );
+  }
+#endif
+  assert( pc3DAsymLUT->getCurOctantDepth() < 4 );
+  WRITE_CODE( pc3DAsymLUT->getCurOctantDepth() , 2 , "cm_octant_depth" );
+  assert( pc3DAsymLUT->getCurYPartNumLog2() < 4 );
+  WRITE_CODE( pc3DAsymLUT->getCurYPartNumLog2() , 2 , "cm_y_part_num_log2" );
+  assert( pc3DAsymLUT->getInputBitDepthY() < 16 );
+#if R0150_CGS_SIGNAL_CONSTRAINTS
+  WRITE_UVLC( pc3DAsymLUT->getInputBitDepthY() - 8 , "cm_input_luma_bit_depth_minus8" );
+  WRITE_UVLC( pc3DAsymLUT->getInputBitDepthC() - 8 , "cm_input_chroma_bit_depth_minus8" );
+  WRITE_UVLC( pc3DAsymLUT->getOutputBitDepthY() - 8 , "cm_output_luma_bit_depth_minus8" );
+  WRITE_UVLC( pc3DAsymLUT->getOutputBitDepthC() - 8 , "cm_output_chroma_bit_depth_minus8" );
+#else
+  WRITE_CODE( pc3DAsymLUT->getInputBitDepthY() - 8 , 3 , "cm_input_bit_depth_minus8" );
+  WRITE_SVLC(pc3DAsymLUT->getInputBitDepthC()-pc3DAsymLUT->getInputBitDepthY(), "cm_input_bit_depth_chroma delta");
+  assert( pc3DAsymLUT->getOutputBitDepthY() < 16 );
+  WRITE_CODE( pc3DAsymLUT->getOutputBitDepthY() - 8 , 3 , "cm_output_bit_depth_minus8" );
+  WRITE_SVLC(pc3DAsymLUT->getOutputBitDepthC()-pc3DAsymLUT->getOutputBitDepthY(), "cm_output_bit_depth_chroma_delta");
+#endif
+  assert( pc3DAsymLUT->getResQuantBit() < 4 );
+  WRITE_CODE( pc3DAsymLUT->getResQuantBit() , 2 , "cm_res_quant_bit" );
+#if R0300_CGS_RES_COEFF_CODING
+  xFindDeltaBits( pc3DAsymLUT );
+  assert(pc3DAsymLUT->getDeltaBits() >=1 && pc3DAsymLUT->getDeltaBits() <= 4);
+  WRITE_CODE( pc3DAsymLUT->getDeltaBits()-1 , 2 , "cm_delta_bit" );
+#endif 
+#if R0151_CGS_3D_ASYMLUT_IMPROVE
+  if( pc3DAsymLUT->getCurOctantDepth() == 1 )
+  {
+    WRITE_SVLC( pc3DAsymLUT->getAdaptChromaThresholdU() - ( 1 << ( pc3DAsymLUT->getInputBitDepthC() - 1 ) ) , "cm_adapt_threshold_u_delta" );
+    WRITE_SVLC( pc3DAsymLUT->getAdaptChromaThresholdV() - ( 1 << ( pc3DAsymLUT->getInputBitDepthC() - 1 ) ) , "cm_adapt_threshold_v_delta" );
+  }
+#endif
+
+#if R0164_CGS_LUT_BUGFIX_CHECK
+  pc3DAsymLUT->xInitCuboids();
+#endif
+  xCode3DAsymLUTOctant( pc3DAsymLUT , 0 , 0 , 0 , 0 , 1 << pc3DAsymLUT->getCurOctantDepth() );
+#if R0164_CGS_LUT_BUGFIX_CHECK
+  xCuboidsFilledCheck( false );
+  pc3DAsymLUT->display( false );
+#endif
+}
+
+Void TEncCavlc::xCode3DAsymLUTOctant( TCom3DAsymLUT * pc3DAsymLUT , Int nDepth , Int yIdx , Int uIdx , Int vIdx , Int nLength )
+{
+  UInt uiOctantSplit = nDepth < pc3DAsymLUT->getCurOctantDepth();
+  if( nDepth < pc3DAsymLUT->getCurOctantDepth() )
+    WRITE_FLAG( uiOctantSplit , "split_octant_flag" );
+  Int nYPartNum = 1 << pc3DAsymLUT->getCurYPartNumLog2();
+  if( uiOctantSplit )
+  {
+    Int nHalfLength = nLength >> 1;
+    for( Int l = 0 ; l < 2 ; l++ )
+    {
+      for( Int m = 0 ; m < 2 ; m++ )
+      {
+        for( Int n = 0 ; n < 2 ; n++ )
+        {
+          xCode3DAsymLUTOctant( pc3DAsymLUT , nDepth + 1 , yIdx + l * nHalfLength * nYPartNum , uIdx + m * nHalfLength , vIdx + n * nHalfLength , nHalfLength );
+        }
+      }
+    }
+  }
+  else
+  {
+#if R0300_CGS_RES_COEFF_CODING
+    Int nFLCbits = pc3DAsymLUT->getMappingShift()-pc3DAsymLUT->getResQuantBit()-pc3DAsymLUT->getDeltaBits() ; 
+    nFLCbits = nFLCbits >= 0 ? nFLCbits : 0;
+#endif
+    for( Int l = 0 ; l < nYPartNum ; l++ )
+    {
+#if R0164_CGS_LUT_BUGFIX      
+      Int shift = pc3DAsymLUT->getCurOctantDepth() - nDepth ;
+#endif
+      for( Int nVertexIdx = 0 ; nVertexIdx < 4 ; nVertexIdx++ )
+      {
+#if R0164_CGS_LUT_BUGFIX 
+        SYUVP sRes = pc3DAsymLUT->getCuboidVertexResTree( yIdx + (l<<shift) , uIdx , vIdx , nVertexIdx );
+#else
+        SYUVP sRes = pc3DAsymLUT->getCuboidVertexResTree( yIdx + l , uIdx , vIdx , nVertexIdx );
+#endif
+        UInt uiCodeVertex = sRes.Y != 0 || sRes.U != 0 || sRes.V != 0;
+        WRITE_FLAG( uiCodeVertex , "coded_vertex_flag" );
+        if( uiCodeVertex )
+        {
+#if R0151_CGS_3D_ASYMLUT_IMPROVE
+#if R0300_CGS_RES_COEFF_CODING
+          xWriteParam( sRes.Y, nFLCbits );
+          xWriteParam( sRes.U, nFLCbits );
+          xWriteParam( sRes.V, nFLCbits );
+#else
+          xWriteParam( sRes.Y );
+          xWriteParam( sRes.U );
+          xWriteParam( sRes.V );
+#endif
+#else
+          WRITE_SVLC( sRes.Y , "resY" );
+          WRITE_SVLC( sRes.U , "resU" );
+          WRITE_SVLC( sRes.V , "resV" );
+#endif
+        }
+      }
+#if R0164_CGS_LUT_BUGFIX_CHECK
+      pc3DAsymLUT->xSetExplicit( yIdx + (l<<shift) , uIdx , vIdx );
+#endif
+    }
+  }
+}
+
+#if R0151_CGS_3D_ASYMLUT_IMPROVE
+#if R0300_CGS_RES_COEFF_CODING
+Void TEncCavlc::xWriteParam( Int param, UInt rParam)
+#else
+Void TEncCavlc::xWriteParam( Int param)
+#endif
+{
+#if !R0300_CGS_RES_COEFF_CODING
+  const UInt rParam = 7;
+#endif
+  Int codeNumber = abs(param);
+  WRITE_UVLC(codeNumber / (1 << rParam), "quotient");
+  WRITE_CODE((codeNumber % (1 << rParam)), rParam, "remainder");
+  if (abs(param))
+    WRITE_FLAG( param <0, "sign");
+}
+#endif
+
+#if R0300_CGS_RES_COEFF_CODING
+Void TEncCavlc::xFindDeltaBits( TCom3DAsymLUT * pc3DAsymLUT )
+{
+  Int nDeltaBits; 
+  Int nBestDeltaBits = -1; 
+  Int nBestBits = MAX_INT; 
+  for( nDeltaBits = 1; nDeltaBits < 5; nDeltaBits++)
+  {
+    Int nCurBits = 0;
+    xTally3DAsymLUTOctantBits( pc3DAsymLUT , 0 , 0 , 0 , 0 , 1 << pc3DAsymLUT->getCurOctantDepth(), nDeltaBits, nCurBits );
+    //printf("%d, %d, %d\n", nDeltaBits, nCurBits, nBestBits); 
+    if(nCurBits < nBestBits)
+    {
+      nBestDeltaBits = nDeltaBits; 
+      nBestBits = nCurBits;
+    }
+  }
+
+  assert(nBestDeltaBits >=1 && nBestDeltaBits < 5);
+  pc3DAsymLUT->setDeltaBits(nBestDeltaBits); 
+}
+
+Void TEncCavlc::xTally3DAsymLUTOctantBits( TCom3DAsymLUT * pc3DAsymLUT , Int nDepth , Int yIdx , Int uIdx , Int vIdx , Int nLength, Int nDeltaBits, Int& nCurBits )
+{
+  UInt uiOctantSplit = nDepth < pc3DAsymLUT->getCurOctantDepth();
+  if( nDepth < pc3DAsymLUT->getCurOctantDepth() )
+    nCurBits ++; 
+  Int nYPartNum = 1 << pc3DAsymLUT->getCurYPartNumLog2();
+  if( uiOctantSplit )
+  {
+    Int nHalfLength = nLength >> 1;
+    for( Int l = 0 ; l < 2 ; l++ )
+    {
+      for( Int m = 0 ; m < 2 ; m++ )
+      {
+        for( Int n = 0 ; n < 2 ; n++ )
+        {
+          xTally3DAsymLUTOctantBits( pc3DAsymLUT , nDepth + 1 , yIdx + l * nHalfLength * nYPartNum , uIdx + m * nHalfLength , vIdx + n * nHalfLength , nHalfLength, nDeltaBits, nCurBits );
+        }
+      }
+    }
+  }
+  else
+  {
+    Int nFLCbits = pc3DAsymLUT->getMappingShift()-pc3DAsymLUT->getResQuantBit()-nDeltaBits ; 
+    nFLCbits = nFLCbits >= 0 ? nFLCbits:0;
+    //printf("nFLCbits = %d\n", nFLCbits);
+
+    for( Int l = 0 ; l < nYPartNum ; l++ )
+    {
+      for( Int nVertexIdx = 0 ; nVertexIdx < 4 ; nVertexIdx++ )
+      {
+        SYUVP sRes = pc3DAsymLUT->getCuboidVertexResTree( yIdx + l , uIdx , vIdx , nVertexIdx );
+
+        UInt uiCodeVertex = sRes.Y != 0 || sRes.U != 0 || sRes.V != 0;
+        nCurBits++;
+        if( uiCodeVertex )
+        {
+          xCheckParamBits( sRes.Y, nFLCbits, nCurBits );
+          xCheckParamBits( sRes.U, nFLCbits, nCurBits );
+          xCheckParamBits( sRes.V, nFLCbits, nCurBits );
+        }
+      }
+    }
+  }
+}
+
+Void TEncCavlc::xCheckParamBits( Int param, Int rParam, Int &nBits)
+{
+  Int codeNumber = abs(param);
+  Int codeQuotient = codeNumber >> rParam;
+  Int qLen; 
+
+  UInt uiLength = 1;
+  UInt uiTemp = ++codeQuotient;
+    
+  while( 1 != uiTemp )
+  {
+    uiTemp >>= 1;
+    uiLength += 2;
+  }
+
+  qLen  = (uiLength >> 1);
+  qLen += ((uiLength+1) >> 1);
+
+  nBits += qLen; 
+  nBits += rParam; 
+  if (abs(param))
+    nBits++; 
+}
+#endif
+#if VPS_VUI_BSP_HRD_PARAMS
+Void TEncCavlc::codeVpsVuiBspHrdParams(TComVPS * const vps)
+{
+  WRITE_UVLC( vps->getVpsNumAddHrdParams(), "vps_num_add_hrd_params" );
+  for( Int i = vps->getNumHrdParameters(), j = 0; i < vps->getNumHrdParameters() + vps->getVpsNumAddHrdParams(); i++, j++ ) // j = i - vps->getNumHrdParameters()
+  {
+    if( i > 0 )
+    {
+      WRITE_FLAG( vps->getCprmsAddPresentFlag(j), "cprms_add_present_flag[i]" );
+    }
+    WRITE_UVLC( vps->getNumSubLayerHrdMinus1(j), "num_sub_layer_hrd_minus1[i]" );
+    codeHrdParameters(vps->getBspHrd(j), i == 0 ? true : vps->getCprmsAddPresentFlag(j), vps->getNumSubLayerHrdMinus1(j));
+  }
+
+#if VPS_FIX_TO_MATCH_SPEC
+  if( vps->getNumHrdParameters() + vps->getVpsNumAddHrdParams() > 0 )
+  {
+#endif
+  for( Int h = 1; h < vps->getNumOutputLayerSets(); h++ )
+  {
+    Int lsIdx = vps->getOutputLayerSetIdx( h );
+    WRITE_UVLC( vps->getNumSignalledPartitioningSchemes(h), "num_signalled_partitioning_schemes[h]");
+
+#if VPS_FIX_TO_MATCH_SPEC
+    for( Int j = 1; j < vps->getNumSignalledPartitioningSchemes(h) + 1; j++ )
+#else
+    for( Int j = 0; j < vps->getNumSignalledPartitioningSchemes(h); j++ )
+#endif
+    {
+      WRITE_UVLC( vps->getNumPartitionsInSchemeMinus1(h, j), "num_partitions_in_scheme_minus1[h][j]" );
+      for( Int k = 0; k <= vps->getNumPartitionsInSchemeMinus1(h, j); k++ )
+      {
+        for( Int r = 0; r < vps->getNumLayersInIdList( lsIdx ); r++ )
+        {
+          WRITE_FLAG( vps->getLayerIncludedInPartitionFlag(h, j, k, r), "layer_included_in_partition_flag[h][j][k][r]" );
+        }
+      }
+    }
+
+    for( Int i = 0; i < vps->getNumSignalledPartitioningSchemes(h) + 1; i++ )
+    {
+      for( Int t = 0; t <= vps->getMaxSLayersInLayerSetMinus1(lsIdx); t++ )
+      {
+        WRITE_UVLC(vps->getNumBspSchedulesMinus1(h, i, t), "num_bsp_schedules_minus1[h][i][t]");
+
+        for( Int j = 0; j <= vps->getNumBspSchedulesMinus1(h, i, t); j++ )
+        {
+#if VPS_FIX_TO_MATCH_SPEC
+          for (Int k = 0; k <= vps->getNumPartitionsInSchemeMinus1(h, i); k++)
+#else
+          for( Int k = 0; k < vps->getNumPartitionsInSchemeMinus1(h, i); k++ )
+#endif
+          {
+#if VPS_FIX_TO_MATCH_SPEC
+            if (vps->getNumHrdParameters() + vps->getVpsNumAddHrdParams() > 1)
+            {
+              Int numBits = 1;
+              while ((1 << numBits) < (vps->getNumHrdParameters() + vps->getVpsNumAddHrdParams()))
+              {
+                numBits++;
+              }
+              WRITE_CODE(vps->getBspHrdIdx(h, i, t, j, k), numBits, "bsp_comb_hrd_idx[h][i][t][j][k]");
+            }
+#else
+            WRITE_UVLC( vps->getBspHrdIdx(h, i, t, j, k),   "bsp_comb_hrd_idx[h][i][t][j][k]");
+#endif
+            WRITE_UVLC( vps->getBspSchedIdx(h, i, t, j, k), "bsp_comb_sched_idx[h][i][t][j][k]");
+          }
+        }
+      }
+    }
+  }
+#if VPS_FIX_TO_MATCH_SPEC
+  }
+#endif
+}
+#endif
+#endif
+//! \}
Index: /tags/SHM-9.0/source/Lib/TLibEncoder/TEncCavlc.h
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibEncoder/TEncCavlc.h	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibEncoder/TEncCavlc.h	(revision 1088)
@@ -0,0 +1,200 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TEncCavlc.h
+    \brief    CAVLC encoder class (header)
+*/
+
+#ifndef __TENCCAVLC__
+#define __TENCCAVLC__
+
+#if _MSC_VER > 1000
+#pragma once
+#endif // _MSC_VER > 1000
+
+#include "TLibCommon/CommonDef.h"
+#include "TLibCommon/TComBitStream.h"
+#include "TLibCommon/TComRom.h"
+#include "TEncEntropy.h"
+#include "SyntaxElementWriter.h"
+#if Q0048_CGS_3D_ASYMLUT
+#include "../TLibCommon/TCom3DAsymLUT.h"
+#include "TEnc3DAsymLUT.h"
+#endif
+
+//! \ingroup TLibEncoder
+//! \{
+
+class TEncTop;
+#if Q0048_CGS_3D_ASYMLUT
+class TCom3DAsymLUT;
+#endif
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// CAVLC encoder class
+class TEncCavlc : public SyntaxElementWriter, public TEncEntropyIf
+{
+public:
+  TEncCavlc();
+  virtual ~TEncCavlc();
+
+protected:
+  TComSlice*    m_pcSlice;
+
+  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(); }
+  UInt  getNumberOfWrittenBits()                { return  m_pcBitIf->getNumberOfWrittenBits();  }
+  Void  codeVPS                 ( TComVPS* pcVPS );
+  Void  codeVUI                 ( TComVUI *pcVUI, TComSPS* pcSPS );
+  Void  codeSPS                 ( TComSPS* pcSPS );
+  Void  codePPS                 ( TComPPS* pcPPS 
+#if Q0048_CGS_3D_ASYMLUT
+    , TEnc3DAsymLUT * pc3DAsymLUT
+#endif
+    );
+  Void  codeSliceHeader         ( TComSlice* pcSlice );
+  Void  codePTL                 ( TComPTL* pcPTL, Bool profilePresentFlag, Int maxNumSubLayersMinus1);
+  Void  codeProfileTier         ( ProfileTierLevel* ptl );
+  Void  codeHrdParameters       ( TComHRD *hrd, Bool commonInfPresentFlag, UInt maxNumSubLayersMinus1 );
+  Void  codeTilesWPPEntryPoint( TComSlice* pSlice );
+  Void  codeTerminatingBit      ( UInt uilsLast );
+  Void  codeSliceFinish         ();
+
+  Void codeMVPIdx ( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList );
+#if SVC_EXTENSION
+  Void codeSAOBlkParam(SAOBlkParam& saoBlkParam, UInt* saoMaxOffsetQVal, Bool* sliceEnabled, Bool leftMergeAvail, Bool aboveMergeAvail, Bool onlyEstMergeInfo = false){printf("only supported in CABAC"); assert(0); exit(-1);}
+#else
+  Void codeSAOBlkParam(SAOBlkParam& saoBlkParam, Bool* sliceEnabled, Bool leftMergeAvail, Bool aboveMergeAvail, Bool onlyEstMergeInfo = false){printf("only supported in CABAC"); assert(0); exit(-1);}
+#endif
+  Void codeCUTransquantBypassFlag( TComDataCU* pcCU, UInt uiAbsPartIdx );
+  Void codeSkipFlag      ( TComDataCU* pcCU, UInt uiAbsPartIdx );
+  Void codeMergeFlag     ( TComDataCU* pcCU, UInt uiAbsPartIdx );
+  Void codeMergeIndex    ( TComDataCU* pcCU, UInt uiAbsPartIdx );
+
+  Void codeAlfCtrlFlag   ( ComponentID component, UInt code ) {printf("Not supported\n"); assert(0);}
+  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         ( TComTU &rTu, const ComponentID compID, const Bool lowestLevel );
+  Void codeQtRootCbf     ( TComDataCU* pcCU, UInt uiAbsPartIdx );
+  Void codeQtCbfZero     ( TComTU &rTu, const ChannelType chType );
+  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 codeCrossComponentPrediction( TComTU &rTu, ComponentID compID );
+
+  Void codeDeltaQP       ( TComDataCU* pcCU, UInt uiAbsPartIdx );
+  Void codeChromaQpAdjustment( TComDataCU* pcCU, UInt uiAbsPartIdx );
+
+  Void codeCoeffNxN      ( TComTU &rTu, TCoeff* pcCoef, const ComponentID compID );
+  Void codeTransformSkipFlags ( TComTU &rTu, ComponentID component );
+
+  Void estBit            ( estBitsSbacStruct* pcEstBitsSbac, Int width, Int height, ChannelType chType );
+
+  Void xCodePredWeightTable          ( TComSlice* pcSlice );
+
+  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 );
+
+  Void codeExplicitRdpcmMode( TComTU &rTu, const ComponentID compID );
+
+#if SVC_EXTENSION
+#if POC_RESET_IDC_SIGNALLING
+  Void  codeSliceHeaderExtn( TComSlice* slice, Int shBitsWrittenTillNow );
+#endif
+  Void codeSPSExtension        ( TComSPS* pcSPS );
+  Void codeVPSExtension        ( TComVPS* pcVPS );
+  Void codeVPSVUI              ( TComVPS *vps   );
+#if REPN_FORMAT_IN_VPS
+  Void  codeRepFormat          ( RepFormat *repFormat );
+#endif
+#if VPS_DPB_SIZE_TABLE
+  Void  codeVpsDpbSizeTable    (TComVPS *vps);
+#endif
+#if VPS_VUI_BSP_HRD_PARAMS
+  Void  codeVpsVuiBspHrdParams  (TComVPS * const);
+#endif
+#if Q0048_CGS_3D_ASYMLUT
+#if R0179_ENC_OPT_3DLUT_SIZE
+public:
+  Void xCode3DAsymLUT( TCom3DAsymLUT * pc3DAsymLUT );
+protected:
+  Void xCode3DAsymLUTOctant( TCom3DAsymLUT * pc3DAsymLUT , Int nDepth , Int yIdx , Int uIdx , Int vIdx , Int nLength );
+#else
+protected:
+  Void xCode3DAsymLUT( TCom3DAsymLUT * pc3DAsymLUT );
+  Void xCode3DAsymLUTOctant( TCom3DAsymLUT * pc3DAsymLUT , Int nDepth , Int yIdx , Int uIdx , Int vIdx , Int nLength );
+#endif
+#if R0151_CGS_3D_ASYMLUT_IMPROVE
+#if R0300_CGS_RES_COEFF_CODING
+  Void xWriteParam( Int param, UInt nFLCBits);
+  Void xCheckParamBits( Int param, Int nFLCBits, Int & nCurBits);
+  Void xTally3DAsymLUTOctantBits( TCom3DAsymLUT * pc3DAsymLUT , Int nDepth , Int yIdx , Int uIdx , Int vIdx , Int nLength, Int nDeltaBits, Int &nCurBits); 
+  Void xFindDeltaBits( TCom3DAsymLUT * pc3DAsymLUT );
+#else
+  Void xWriteParam( Int param);
+#endif
+#endif
+#endif
+#endif //SVC_EXTENSION
+
+};
+
+//! \}
+
+#endif // !defined(AFX_TENCCAVLC_H__EE8A0B30_945B_4169_B290_24D3AD52296F__INCLUDED_)
+
Index: /tags/SHM-9.0/source/Lib/TLibEncoder/TEncCfg.h
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibEncoder/TEncCfg.h	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibEncoder/TEncCfg.h	(revision 1088)
@@ -0,0 +1,1270 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TEncCfg.h
+    \brief    encoder configuration class (header)
+*/
+
+#ifndef __TENCCFG__
+#define __TENCCFG__
+
+#if _MSC_VER > 1000
+#pragma once
+#endif // _MSC_VER > 1000
+
+#include "TLibCommon/CommonDef.h"
+#include "TLibCommon/TComSlice.h"
+#include <assert.h>
+
+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];
+  Bool m_isEncoded;
+  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)
+  , m_isEncoded(false)
+  {
+    ::memset( m_referencePics, 0, sizeof(m_referencePics) );
+    ::memset( m_usedByCurrPic, 0, sizeof(m_usedByCurrPic) );
+    ::memset( m_refIdc,        0, sizeof(m_refIdc) );
+  }
+};
+
+std::istringstream &operator>>(std::istringstream &in, GOPEntry &entry);     //input
+//! \ingroup TLibEncoder
+//! \{
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// encoder configuration class
+class TEncCfg
+{
+protected:
+  //==== File I/O ========
+  Int       m_iFrameRate;
+  Int       m_FrameSkip;
+  Int       m_iSourceWidth;
+  Int       m_iSourceHeight;
+  Window    m_conformanceWindow;
+  Int       m_framesToBeEncoded;
+  Double    m_adLambdaModifier[ MAX_TLAYER ];
+
+  Bool      m_printMSEBasedSequencePSNR;
+  Bool      m_printFrameMSE;
+  Bool      m_printSequenceMSE;
+  Bool      m_cabacZeroWordPaddingEnabled;
+
+  /* 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;
+  UInt              m_bitDepthConstraintValue;
+  ChromaFormat      m_chromaFormatConstraintValue;
+  Bool              m_intraConstraintFlag;
+  Bool              m_lowerBitRateConstraintFlag;
+
+  //====== Coding Structure ========
+  UInt      m_uiIntraPeriod;
+  UInt      m_uiDecodingRefreshType;            ///< the type of decoding refresh employed for the random access.
+  Int       m_iGOPSize;
+  GOPEntry  m_GOPList[MAX_GOP];
+  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_saoCtuBoundary;
+
+  //====== 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_maxCUChromaQpAdjustmentDepth;
+
+  Int       m_chromaCbQpOffset;                 //  Chroma Cb QP Offset (0:default)
+  Int       m_chromaCrQpOffset;                 //  Chroma Cr Qp Offset (0:default)
+  ChromaFormat m_chromaFormatIDC;
+
+#if ADAPTIVE_QP_SELECTION
+  Bool      m_bUseAdaptQpSelect;
+#endif
+  Bool      m_useExtendedPrecision;
+  Bool      m_useHighPrecisionPredictionWeighting;
+  Bool      m_bUseAdaptiveQP;
+  Int       m_iQPAdaptationRange;
+
+  //====== Tool list ========
+  Bool      m_bUseASR;
+  Bool      m_bUseHADME;
+  Bool      m_useRDOQ;
+  Bool      m_useRDOQTS;
+  UInt      m_rdPenalty;
+  Bool      m_bUseFastEnc;
+  Bool      m_bUseEarlyCU;
+  Bool      m_useFastDecisionForMerge;
+  Bool      m_bUseCbfFastMode;
+  Bool      m_useEarlySkipDetection;
+  Bool      m_useCrossComponentPrediction;
+  Bool      m_reconBasedCrossCPredictionEstimate;
+  UInt      m_saoOffsetBitShift[MAX_NUM_CHANNEL_TYPE];
+  Bool      m_useTransformSkip;
+  Bool      m_useTransformSkipFast;
+  UInt      m_transformSkipLog2MaxSize;
+  Bool      m_useResidualRotation;
+  Bool      m_useSingleSignificanceMapContext;
+  Bool      m_useGolombRiceParameterAdaptation;
+  Bool      m_alignCABACBeforeBypass;
+  Bool      m_useResidualDPCM[NUMBER_OF_RDPCM_SIGNALLING_MODES];
+  Int*      m_aidQP;
+  UInt      m_uiDeltaQpRD;
+
+  Bool      m_bUseConstrainedIntraPred;
+  Bool      m_usePCM;
+  UInt      m_pcmLog2MaxSize;
+  UInt      m_uiPCMLog2MinSize;
+  //====== Slice ========
+  SliceConstraint m_sliceMode;
+  Int       m_sliceArgument;
+  //====== Dependent Slice ========
+  SliceConstraint m_sliceSegmentMode;
+  Int       m_sliceSegmentArgument;
+  Bool      m_bLFCrossSliceBoundaryFlag;
+
+  Bool      m_bPCMInputBitDepthFlag;
+  UInt      m_uiPCMBitDepthLuma;
+  UInt      m_uiPCMBitDepthChroma;
+  Bool      m_bPCMFilterDisableFlag;
+  Bool      m_disableIntraReferenceSmoothing;
+  Bool      m_loopFilterAcrossTilesEnabledFlag;
+  Bool      m_tileUniformSpacingFlag;
+  Int       m_iNumColumnsMinus1;
+  Int       m_iNumRowsMinus1;
+  std::vector<Int> m_tileColumnWidth;
+  std::vector<Int> m_tileRowHeight;
+
+  Int       m_iWaveFrontSynchro;
+  Int       m_iWaveFrontSubstreams;
+
+  Int       m_decodedPictureHashSEIEnabled;              ///< Checksum(3)/CRC(2)/MD5(1)/disable(0) acting on decoded picture hash SEI message
+  Int       m_bufferingPeriodSEIEnabled;
+  Int       m_pictureTimingSEIEnabled;
+  Int       m_recoveryPointSEIEnabled;
+  Bool      m_toneMappingInfoSEIEnabled;
+  Int       m_toneMapId;
+  Bool      m_toneMapCancelFlag;
+  Bool      m_toneMapPersistenceFlag;
+  Int       m_codedDataBitDepth;
+  Int       m_targetBitDepth;
+  Int       m_modelId;
+  Int       m_minValue;
+  Int       m_maxValue;
+  Int       m_sigmoidMidpoint;
+  Int       m_sigmoidWidth;
+  Int       m_numPivots;
+  Int       m_cameraIsoSpeedIdc;
+  Int       m_cameraIsoSpeedValue;
+  Int       m_exposureIndexIdc;
+  Int       m_exposureIndexValue;
+  Int       m_exposureCompensationValueSignFlag;
+  Int       m_exposureCompensationValueNumerator;
+  Int       m_exposureCompensationValueDenomIdc;
+  Int       m_refScreenLuminanceWhite;
+  Int       m_extendedRangeWhiteLevel;
+  Int       m_nominalBlackLevelLumaCodeValue;
+  Int       m_nominalWhiteLevelLumaCodeValue;
+  Int       m_extendedWhiteLevelLumaCodeValue;
+  Int*      m_startOfCodedInterval;
+  Int*      m_codedPivotValue;
+  Int*      m_targetPivotValue;
+  Int       m_framePackingSEIEnabled;
+  Int       m_framePackingSEIType;
+  Int       m_framePackingSEIId;
+  Int       m_framePackingSEIQuincunx;
+  Int       m_framePackingSEIInterpretation;
+  Int       m_segmentedRectFramePackingSEIEnabled;
+  Bool      m_segmentedRectFramePackingSEICancel;
+  Int       m_segmentedRectFramePackingSEIType;
+  Bool      m_segmentedRectFramePackingSEIPersistence;
+  Int       m_displayOrientationSEIAngle;
+  Int       m_temporalLevel0IndexSEIEnabled;
+  Int       m_gradualDecodingRefreshInfoEnabled;
+  Int       m_noDisplaySEITLayer;
+  Int       m_decodingUnitInfoSEIEnabled;
+  Int       m_SOPDescriptionSEIEnabled;
+  Int       m_scalableNestingSEIEnabled;
+  Bool      m_tmctsSEIEnabled;
+  Bool      m_timeCodeSEIEnabled;
+  Int       m_timeCodeSEINumTs;
+  TComSEITimeSet   m_timeSetArray[MAX_TIMECODE_SEI_SETS];
+  Bool      m_kneeSEIEnabled;
+  Int       m_kneeSEIId;
+  Bool      m_kneeSEICancelFlag;
+  Bool      m_kneeSEIPersistenceFlag;
+  Int       m_kneeSEIInputDrange;
+  Int       m_kneeSEIInputDispLuminance;
+  Int       m_kneeSEIOutputDrange;
+  Int       m_kneeSEIOutputDispLuminance;
+  Int       m_kneeSEINumKneePointsMinus1;
+  Int*      m_kneeSEIInputKneePoint;
+  Int*      m_kneeSEIOutputKneePoint;
+  TComSEIMasteringDisplay m_masteringDisplay;
+  //====== 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
+  ScalingListMode m_useScalingListId;            ///< Using quantization matrix i.e. 0=off, 1=default, 2=file.
+  Char*     m_scalingListFile;          ///< quantization matrix file name
+  Int       m_TMVPModeId;
+  Int       m_signHideFlag;
+  Bool      m_RCEnableRateControl;
+  Int       m_RCTargetBitrate;
+  Int       m_RCKeepHierarchicalBit;
+  Bool      m_RCLCULevelRC;
+  Bool      m_RCUseLCUSeparateModel;
+  Int       m_RCInitialQP;
+  Bool      m_RCForceIntraQP;
+  Bool      m_TransquantBypassEnableFlag;                     ///< transquant_bypass_enable_flag setting in PPS.
+  Bool      m_CUTransquantBypassFlagForce;                    ///< if transquant_bypass_enable_flag, then, if true, all CU transquant bypass flags will be set to true.
+
+  CostMode  m_costMode;                                       ///< The cost function to use, primarily when considering lossless coding.
+#if SVC_EXTENSION
+  static TComVPS  m_cVPS;
+#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
+  Bool      m_chromaSamplingFilterHintEnabled;                ///< Signals whether chroma sampling filter hint data is present
+  Int       m_chromaSamplingHorFilterIdc;                     ///< Specifies the Index of filter to use
+  Int       m_chromaSamplingVerFilterIdc;                     ///< Specifies the Index of filter to use
+  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 SVC_EXTENSION
+  UInt      m_layerId;   
+  UInt      m_numLayer;
+  Int       m_elRapSliceBEnabled;
+#if M0040_ADAPTIVE_RESOLUTION_CHANGE
+  Int       m_adaptiveResolutionChange;
+#endif
+#if R0071_IRAP_EOS_CROSS_LAYER_IMPACTS
+  int       m_layerSwitchOffBegin;
+  int       m_layerSwitchOffEnd;
+#endif
+#if O0153_ALT_OUTPUT_LAYER_FLAG
+  Bool      m_altOutputLayerFlag;
+#endif
+#if HIGHER_LAYER_IRAP_SKIP_FLAG
+  Int       m_skipPictureAtArcSwitch;
+#endif
+#if O0149_CROSS_LAYER_BLA_FLAG
+  Bool      m_crossLayerBLAFlag;
+#endif
+#if VPS_EXTN_DIRECT_REF_LAYERS
+  Int       m_numDirectRefLayers;
+  Int       m_refLayerId[MAX_VPS_LAYER_IDX_PLUS1];
+
+  Int       m_numActiveRefLayers;
+  Int       m_predLayerIdx[MAX_VPS_LAYER_IDX_PLUS1];
+  Int       m_numSamplePredRefLayers;
+  Int       m_samplePredRefLayerId[MAX_VPS_LAYER_IDX_PLUS1];
+  Int       m_numMotionPredRefLayers;
+  Int       m_motionPredRefLayerId[MAX_VPS_LAYER_IDX_PLUS1];
+  Bool      m_samplePredEnabledFlag[MAX_VPS_LAYER_IDX_PLUS1];
+  Bool      m_motionPredEnabledFlag[MAX_VPS_LAYER_IDX_PLUS1];
+#endif
+  Int       m_maxTidIlRefPicsPlus1;
+#if FAST_INTRA_SHVC
+  Bool      m_useFastIntraScalable;
+#endif
+#if LAYERS_NOT_PRESENT_SEI
+  Int       m_layersNotPresentSEIEnabled;
+#endif
+#if N0383_IL_CONSTRAINED_TILE_SETS_SEI
+  Bool      m_interLayerConstrainedTileSetsSEIEnabled;
+  UInt      m_ilNumSetsInMessage;
+  Bool      m_skippedTileSetPresentFlag;
+  UInt      m_topLeftTileIndex[1024];
+  UInt      m_bottomRightTileIndex[1024];
+  UInt      m_ilcIdc[1024];
+#endif
+#if Q0048_CGS_3D_ASYMLUT
+  Int       m_nCGSFlag;
+  Int       m_nCGSMaxOctantDepth;
+  Int       m_nCGSMaxYPartNumLog2;
+  Int       m_nCGSLUTBit;
+#if R0151_CGS_3D_ASYMLUT_IMPROVE
+  Int       m_nCGSAdaptiveChroma;
+#endif
+#if R0179_ENC_OPT_3DLUT_SIZE
+  Int       m_nCGSLutSizeRDO;
+#endif
+#endif
+#if P0123_ALPHA_CHANNEL_SEI
+  Bool      m_alphaSEIEnabled;
+  Bool      m_alphaCancelFlag;
+  Int       m_alphaUseIdc;
+  Int       m_alphaBitDepthMinus8;
+  Int       m_alphaTransparentValue;
+  Int       m_alphaOpaqueValue;
+  Bool      m_alphaIncrementFlag;
+  Int       m_alphaClipFlag;
+  Int       m_alphaClipTypeFlag;
+#endif
+#if Q0096_OVERLAY_SEI
+  Bool                                m_overlaySEIEnabled;
+  Bool                                m_overlayInfoCancelFlag;
+  UInt                                m_overlayContentAuxIdMinus128;
+  UInt                                m_overlayLabelAuxIdMinus128;
+  UInt                                m_overlayAlphaAuxIdMinus128;
+  UInt                                m_overlayElementLabelValueLengthMinus8;
+  UInt                                m_numOverlaysMinus1;
+  std::vector<UInt>                   m_overlayIdx;  
+  std::vector<Bool>                   m_overlayLanguagePresentFlag;
+  std::vector<UInt>                   m_overlayContentLayerId;
+  std::vector<Bool>                   m_overlayLabelPresentFlag;
+  std::vector<UInt>                   m_overlayLabelLayerId;
+  std::vector<Bool>                   m_overlayAlphaPresentFlag;
+  std::vector<UInt>                   m_overlayAlphaLayerId;
+  std::vector<UInt>                   m_numOverlayElementsMinus1;
+  std::vector< std::vector<UInt> >    m_overlayElementLabelMin;
+  std::vector< std::vector<UInt> >    m_overlayElementLabelMax;
+  std::vector<string>                 m_overlayLanguage;  
+  std::vector<string>                 m_overlayName;  
+  std::vector< std::vector<string> >  m_overlayElementName;  
+  Bool                                m_overlayInfoPersistenceFlag;
+#endif
+#if Q0189_TMVP_CONSTRAINTS
+  Int       m_TMVPConstraintsSEIEnabled;
+#endif
+#endif //SVC_EXTENSION
+#if Q0074_COLOUR_REMAPPING_SEI
+  Char*     m_colourRemapSEIFile;          ///< SEI Colour Remapping File (initialized from external file)
+  Int       m_colourRemapSEIId;
+  Bool      m_colourRemapSEICancelFlag;
+  Bool      m_colourRemapSEIPersistenceFlag;
+  Bool      m_colourRemapSEIVideoSignalInfoPresentFlag;
+  Bool      m_colourRemapSEIFullRangeFlag;
+  Int       m_colourRemapSEIPrimaries;
+  Int       m_colourRemapSEITransferFunction;
+  Int       m_colourRemapSEIMatrixCoefficients;
+  Int       m_colourRemapSEIInputBitDepth;
+  Int       m_colourRemapSEIBitDepth;
+  Int       m_colourRemapSEIPreLutNumValMinus1[3];
+  Int*      m_colourRemapSEIPreLutCodedValue[3];
+  Int*      m_colourRemapSEIPreLutTargetValue[3];
+  Bool      m_colourRemapSEIMatrixPresentFlag;
+  Int       m_colourRemapSEILog2MatrixDenom;
+  Int       m_colourRemapSEICoeffs[3][3];
+  Int       m_colourRemapSEIPostLutNumValMinus1[3];
+  Int*      m_colourRemapSEIPostLutCodedValue[3];
+  Int*      m_colourRemapSEIPostLutTargetValue[3];
+#endif
+
+public:
+  TEncCfg()
+  : m_tileColumnWidth()
+  , m_tileRowHeight()
+#if Q0074_COLOUR_REMAPPING_SEI
+  , m_colourRemapSEIFile(NULL)
+#endif
+  {}
+
+  virtual ~TEncCfg()
+  {}
+
+  Void setProfile(Profile::Name profile) { m_profile = profile; }
+  Void setLevel(Level::Tier tier, Level::Name level) { m_levelTier = tier; m_level = level; }
+
+  Void      setFrameRate                    ( Int   i )      { m_iFrameRate = i; }
+  Void      setFrameSkip                    ( UInt i ) { m_FrameSkip = i; }
+  Void      setSourceWidth                  ( Int   i )      { m_iSourceWidth = i; }
+  Void      setSourceHeight                 ( Int   i )      { m_iSourceHeight = i; }
+
+  Window   &getConformanceWindow()                           { return m_conformanceWindow; }
+#if P0312_VERT_PHASE_ADJ && !R0209_GENERIC_PHASE
+  Void      setConformanceWindow (Int confLeft, Int confRight, Int confTop, Int confBottom ) { m_conformanceWindow.setWindow (confLeft, confRight, confTop, confBottom, false); }
+#else
+  Void      setConformanceWindow (Int confLeft, Int confRight, Int confTop, Int confBottom ) { m_conformanceWindow.setWindow (confLeft, confRight, confTop, confBottom); }
+#endif
+
+  Void      setFramesToBeEncoded            ( Int   i )      { m_framesToBeEncoded = i; }
+
+  Bool      getPrintMSEBasedSequencePSNR    ()         const { return m_printMSEBasedSequencePSNR;  }
+  Void      setPrintMSEBasedSequencePSNR    (Bool value)     { m_printMSEBasedSequencePSNR = value; }
+
+  Bool      getPrintFrameMSE                ()         const { return m_printFrameMSE;              }
+  Void      setPrintFrameMSE                (Bool value)     { m_printFrameMSE = value;             }
+
+  Bool      getPrintSequenceMSE             ()         const { return m_printSequenceMSE;           }
+  Void      setPrintSequenceMSE             (Bool value)     { m_printSequenceMSE = value;          }
+
+  Bool      getCabacZeroWordPaddingEnabled()           const { return m_cabacZeroWordPaddingEnabled;  }
+  Void      setCabacZeroWordPaddingEnabled(Bool value)       { m_cabacZeroWordPaddingEnabled = value; }
+
+  //====== 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; }
+  Void      setGopList                      ( GOPEntry*  GOPList ) {  for ( Int i = 0; i < MAX_GOP; i++ ) m_GOPList[i] = GOPList[i]; }
+  Void      setExtraRPSs                    ( Int   i )      { m_extraRPSs = i; }
+  GOPEntry  getGOPEntry                     ( Int   i )      { return m_GOPList[i]; }
+  Void      setEncodedFlag                  ( Int  i, Bool value )  { m_GOPList[i].m_isEncoded = value; }
+  Void      setMaxDecPicBuffering           ( UInt u, UInt tlayer ) { m_maxDecPicBuffering[tlayer] = u;    }
+  Void      setNumReorderPics               ( Int  i, UInt tlayer ) { m_numReorderPics[tlayer] = i;    }
+
+  Void      setQP                           ( Int   i )      { m_iQP = i; }
+
+  Void      setPad                          ( Int*  iPad                   )      { for ( Int i = 0; i < 2; i++ ) m_aiPad[i] = iPad[i]; }
+
+  Int       getMaxRefPicNum                 ()                              { return m_iMaxRefPicNum;           }
+  Void      setMaxRefPicNum                 ( Int iMaxRefPicNum )           { m_iMaxRefPicNum = iMaxRefPicNum;  }
+
+  Int       getMaxTempLayer                 ()                              { return m_maxTempLayer;              } 
+  Void      setMaxTempLayer                 ( Int maxTempLayer )            { m_maxTempLayer = maxTempLayer;      }
+  //======== 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; }
+
+  Int       getMaxCUChromaQpAdjustmentDepth ()         const { return m_maxCUChromaQpAdjustmentDepth;  }
+  Void      setMaxCUChromaQpAdjustmentDepth (Int value)      { m_maxCUChromaQpAdjustmentDepth = value; }
+
+  Void      setChromaCbQpOffset             ( Int   i )      { m_chromaCbQpOffset = i; }
+  Void      setChromaCrQpOffset             ( Int   i )      { m_chromaCrQpOffset = i; }
+
+  Void      setChromaFormatIdc              ( ChromaFormat cf ) { m_chromaFormatIDC = cf; }
+  ChromaFormat  getChromaFormatIdc          ( )              { return m_chromaFormatIDC; }
+
+#if ADAPTIVE_QP_SELECTION
+  Void      setUseAdaptQpSelect             ( Bool   i ) { m_bUseAdaptQpSelect    = i; }
+  Bool      getUseAdaptQpSelect             ()           { return   m_bUseAdaptQpSelect; }
+#endif
+
+  Bool      getUseExtendedPrecision         ()         const { return m_useExtendedPrecision;  }
+  Void      setUseExtendedPrecision         (Bool value)     { m_useExtendedPrecision = value; }
+
+  Bool      getUseHighPrecisionPredictionWeighting() const { return m_useHighPrecisionPredictionWeighting; }
+  Void      setUseHighPrecisionPredictionWeighting(Bool value) { m_useHighPrecisionPredictionWeighting = value; }
+
+  Void      setUseAdaptiveQP                ( Bool  b )      { m_bUseAdaptiveQP = b; }
+  Void      setQPAdaptationRange            ( Int   i )      { m_iQPAdaptationRange = i; }
+
+  //====== Sequence ========
+  Int       getFrameRate                    ()      { return  m_iFrameRate; }
+  UInt      getFrameSkip                    ()      { return  m_FrameSkip; }
+  Int       getSourceWidth                  ()      { return  m_iSourceWidth; }
+  Int       getSourceHeight                 ()      { return  m_iSourceHeight; }
+  Int       getFramesToBeEncoded            ()      { return  m_framesToBeEncoded; }
+  Void setLambdaModifier                    ( UInt uiIndex, Double dValue ) { m_adLambdaModifier[ uiIndex ] = dValue; }
+  Double getLambdaModifier                  ( UInt uiIndex ) const { return m_adLambdaModifier[ uiIndex ]; }
+
+  //==== Coding Structure ========
+  UInt      getIntraPeriod                  ()      { return  m_uiIntraPeriod; }
+  UInt      getDecodingRefreshType          ()      { return  m_uiDecodingRefreshType; }
+  Int       getGOPSize                      ()      { return  m_iGOPSize; }
+  Int       getMaxDecPicBuffering           (UInt tlayer) { return m_maxDecPicBuffering[tlayer]; }
+  Int       getNumReorderPics               (UInt tlayer) { return m_numReorderPics[tlayer]; }
+  Int       getQP                           ()      { return  m_iQP; }
+
+  Int       getPad                          ( Int i )      { assert (i < 2 );                      return  m_aiPad[i]; }
+
+  //======== Transform =============
+  UInt      getQuadtreeTULog2MaxSize        ()      const { return m_uiQuadtreeTULog2MaxSize; }
+  UInt      getQuadtreeTULog2MinSize        ()      const { return m_uiQuadtreeTULog2MinSize; }
+  UInt      getQuadtreeTUMaxDepthInter      ()      const { return m_uiQuadtreeTUMaxDepthInter; }
+  UInt      getQuadtreeTUMaxDepthIntra      ()      const { return m_uiQuadtreeTUMaxDepthIntra; }
+
+  //==== Loop/Deblock Filter ========
+  Bool      getLoopFilterDisable            ()      { return  m_bLoopFilterDisable;       }
+  Bool      getLoopFilterOffsetInPPS        ()      { return m_loopFilterOffsetInPPS; }
+  Int       getLoopFilterBetaOffset         ()      { return m_loopFilterBetaOffsetDiv2; }
+  Int       getLoopFilterTcOffset           ()      { return m_loopFilterTcOffsetDiv2; }
+  Bool      getDeblockingFilterControlPresent()  { return  m_DeblockingFilterControlPresent; }
+  Bool      getDeblockingFilterMetric       ()      { return m_DeblockingFilterMetric; }
+
+  //==== Motion search ========
+  Int       getFastSearch                   ()      { return  m_iFastSearch; }
+  Int       getSearchRange                  ()      { return  m_iSearchRange; }
+
+  //==== Quality control ========
+  Int       getMaxDeltaQP                   ()      { return  m_iMaxDeltaQP; }
+  Int       getMaxCuDQPDepth                ()      { return  m_iMaxCuDQPDepth; }
+  Bool      getUseAdaptiveQP                ()      { return  m_bUseAdaptiveQP; }
+  Int       getQPAdaptationRange            ()      { return  m_iQPAdaptationRange; }
+
+  //==== Tool list ========
+  Void      setUseASR                       ( Bool  b )     { m_bUseASR     = b; }
+  Void      setUseHADME                     ( Bool  b )     { m_bUseHADME   = b; }
+  Void      setUseRDOQ                      ( Bool  b )     { m_useRDOQ    = b; }
+  Void      setUseRDOQTS                    ( Bool  b )     { m_useRDOQTS  = b; }
+  Void      setRDpenalty                 ( UInt  b )     { m_rdPenalty  = b; }
+  Void      setUseFastEnc                   ( Bool  b )     { m_bUseFastEnc = b; }
+  Void      setUseEarlyCU                   ( Bool  b )     { m_bUseEarlyCU = b; }
+  Void      setUseFastDecisionForMerge      ( Bool  b )     { m_useFastDecisionForMerge = b; }
+  Void      setUseCbfFastMode            ( Bool  b )     { m_bUseCbfFastMode = b; }
+  Void      setUseEarlySkipDetection        ( Bool  b )     { m_useEarlySkipDetection = b; }
+  Void      setUseConstrainedIntraPred      ( Bool  b )     { m_bUseConstrainedIntraPred = b; }
+  Void      setPCMInputBitDepthFlag         ( Bool  b )     { m_bPCMInputBitDepthFlag = b; }
+  Void      setPCMFilterDisableFlag         ( Bool  b )     {  m_bPCMFilterDisableFlag = b; }
+  Void      setUsePCM                       ( Bool  b )     {  m_usePCM = b;               }
+  Void      setPCMLog2MaxSize               ( UInt u )      { m_pcmLog2MaxSize = u;      }
+  Void      setPCMLog2MinSize               ( UInt u )     { m_uiPCMLog2MinSize = u;      }
+  Void      setdQPs                         ( Int*  p )     { m_aidQP       = p; }
+  Void      setDeltaQpRD                    ( UInt  u )     {m_uiDeltaQpRD  = u; }
+  Bool      getUseASR                       ()      { return m_bUseASR;     }
+  Bool      getUseHADME                     ()      { return m_bUseHADME;   }
+  Bool      getUseRDOQ                      ()      { return m_useRDOQ;    }
+  Bool      getUseRDOQTS                    ()      { return m_useRDOQTS;  }
+  Int       getRDpenalty                    ()      { return m_rdPenalty;  }
+  Bool      getUseFastEnc                   ()      { return m_bUseFastEnc; }
+  Bool      getUseEarlyCU                   ()      { return m_bUseEarlyCU; }
+  Bool      getUseFastDecisionForMerge      ()      { return m_useFastDecisionForMerge; }
+  Bool      getUseCbfFastMode               ()      { return m_bUseCbfFastMode; }
+  Bool      getUseEarlySkipDetection        ()      { return m_useEarlySkipDetection; }
+  Bool      getUseConstrainedIntraPred      ()      { return m_bUseConstrainedIntraPred; }
+  Bool      getPCMInputBitDepthFlag         ()      { return m_bPCMInputBitDepthFlag;   }
+  Bool      getPCMFilterDisableFlag         ()      { return m_bPCMFilterDisableFlag;   }
+  Bool      getUsePCM                       ()      { return m_usePCM;                 }
+  UInt      getPCMLog2MaxSize               ()      { return m_pcmLog2MaxSize;  }
+  UInt      getPCMLog2MinSize               ()      { return  m_uiPCMLog2MinSize;  }
+
+  Bool      getUseCrossComponentPrediction        ()                const { return m_useCrossComponentPrediction;   }
+  Void      setUseCrossComponentPrediction        (const Bool value)      { m_useCrossComponentPrediction = value;  }
+  Bool      getUseReconBasedCrossCPredictionEstimate ()                const { return m_reconBasedCrossCPredictionEstimate;  }
+  Void      setUseReconBasedCrossCPredictionEstimate (const Bool value)      { m_reconBasedCrossCPredictionEstimate = value; }
+  Void      setSaoOffsetBitShift(ChannelType type, UInt uiBitShift)          { m_saoOffsetBitShift[type] = uiBitShift; }
+
+  Bool getUseTransformSkip                             ()      { return m_useTransformSkip;        }
+  Void setUseTransformSkip                             ( Bool b ) { m_useTransformSkip  = b;       }
+  Bool getUseResidualRotation                          ()            const { return m_useResidualRotation;  }
+  Void setUseResidualRotation                          (const Bool value)  { m_useResidualRotation = value; }
+  Bool getUseSingleSignificanceMapContext              ()            const { return m_useSingleSignificanceMapContext;  }
+  Void setUseSingleSignificanceMapContext              (const Bool value)  { m_useSingleSignificanceMapContext = value; }
+  Bool getUseGolombRiceParameterAdaptation             ()                 const { return m_useGolombRiceParameterAdaptation;  }
+  Void setUseGolombRiceParameterAdaptation             (const Bool value)       { m_useGolombRiceParameterAdaptation = value; }
+  Bool getAlignCABACBeforeBypass                       ()       const      { return m_alignCABACBeforeBypass;  }
+  Void setAlignCABACBeforeBypass                       (const Bool value)  { m_alignCABACBeforeBypass = value; }
+  Bool getUseResidualDPCM                              (const RDPCMSignallingMode signallingMode)        const      { return m_useResidualDPCM[signallingMode];  }
+  Void setUseResidualDPCM                              (const RDPCMSignallingMode signallingMode, const Bool value) { m_useResidualDPCM[signallingMode] = value; }
+  Bool getUseTransformSkipFast                         ()      { return m_useTransformSkipFast;    }
+  Void setUseTransformSkipFast                         ( Bool b ) { m_useTransformSkipFast  = b;   }
+  UInt getTransformSkipLog2MaxSize                     () const      { return m_transformSkipLog2MaxSize;     }
+  Void setTransformSkipLog2MaxSize                     ( UInt u )    { m_transformSkipLog2MaxSize  = u;       }
+  Void setDisableIntraReferenceSmoothing               (Bool bValue) { m_disableIntraReferenceSmoothing=bValue; }
+  Bool getDisableIntraReferenceSmoothing               ()      const { return m_disableIntraReferenceSmoothing; }
+
+  Int*      getdQPs                         ()      { return m_aidQP;       }
+  UInt      getDeltaQpRD                    ()      { return m_uiDeltaQpRD; }
+
+  //====== Slice ========
+  Void  setSliceMode                   ( SliceConstraint  i )        { m_sliceMode = i;              }
+  Void  setSliceArgument               ( Int  i )                    { m_sliceArgument = i;          }
+  SliceConstraint getSliceMode         () const                      { return m_sliceMode;           }
+  Int   getSliceArgument               ()                            { return m_sliceArgument;       }
+  //====== Dependent Slice ========
+  Void  setSliceSegmentMode            ( SliceConstraint  i )        { m_sliceSegmentMode = i;       }
+  Void  setSliceSegmentArgument        ( Int  i )                    { m_sliceSegmentArgument = i;   }
+  SliceConstraint getSliceSegmentMode  () const                      { 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  setSaoCtuBoundary              (Bool val)                    { m_saoCtuBoundary = val; }
+  Bool  getSaoCtuBoundary              ()                            { return m_saoCtuBoundary; }
+  Void  setLFCrossTileBoundaryFlag               ( Bool   val  )     { m_loopFilterAcrossTilesEnabledFlag = val; }
+  Bool  getLFCrossTileBoundaryFlag               ()                  { return m_loopFilterAcrossTilesEnabledFlag;   }
+  Void  setTileUniformSpacingFlag      ( Bool b )                    { m_tileUniformSpacingFlag = b; }
+  Bool  getTileUniformSpacingFlag      ()                            { return m_tileUniformSpacingFlag; }
+  Void  setNumColumnsMinus1            ( Int i )                     { m_iNumColumnsMinus1 = i; }
+  Int   getNumColumnsMinus1            ()                            { return m_iNumColumnsMinus1; }
+  Void  setColumnWidth ( const std::vector<Int>& columnWidth )       { m_tileColumnWidth = columnWidth; }
+  UInt  getColumnWidth                 ( UInt columnIdx )            { return m_tileColumnWidth[columnIdx]; }
+  Void  setNumRowsMinus1               ( Int i )                     { m_iNumRowsMinus1 = i; }
+  Int   getNumRowsMinus1               ()                            { return m_iNumRowsMinus1; }
+  Void  setRowHeight ( const std::vector<Int>& rowHeight)            { m_tileRowHeight = rowHeight; }
+  UInt  getRowHeight                   ( UInt rowIdx )               { return m_tileRowHeight[rowIdx]; }
+  Void  xCheckGSParameters();
+  Void  setWaveFrontSynchro(Int iWaveFrontSynchro)                   { m_iWaveFrontSynchro = iWaveFrontSynchro; }
+  Int   getWaveFrontsynchro()                                        { return m_iWaveFrontSynchro; }
+  Void  setWaveFrontSubstreams(Int iWaveFrontSubstreams)             { m_iWaveFrontSubstreams = iWaveFrontSubstreams; }
+  Int   getWaveFrontSubstreams()                                     { return m_iWaveFrontSubstreams; }
+  Void  setDecodedPictureHashSEIEnabled(Int b)                       { m_decodedPictureHashSEIEnabled = b; }
+  Int   getDecodedPictureHashSEIEnabled()                            { return m_decodedPictureHashSEIEnabled; }
+  Void  setBufferingPeriodSEIEnabled(Int b)                          { m_bufferingPeriodSEIEnabled = b; }
+  Int   getBufferingPeriodSEIEnabled()                               { return m_bufferingPeriodSEIEnabled; }
+  Void  setPictureTimingSEIEnabled(Int b)                            { m_pictureTimingSEIEnabled = b; }
+  Int   getPictureTimingSEIEnabled()                                 { return m_pictureTimingSEIEnabled; }
+  Void  setRecoveryPointSEIEnabled(Int b)                            { m_recoveryPointSEIEnabled = b; }
+  Int   getRecoveryPointSEIEnabled()                                 { return m_recoveryPointSEIEnabled; }
+  Void  setToneMappingInfoSEIEnabled(Bool b)                         { m_toneMappingInfoSEIEnabled = b;  }
+  Bool  getToneMappingInfoSEIEnabled()                               { return m_toneMappingInfoSEIEnabled;  }
+  Void  setTMISEIToneMapId(Int b)                                    { m_toneMapId = b;  }
+  Int   getTMISEIToneMapId()                                         { return m_toneMapId;  }
+  Void  setTMISEIToneMapCancelFlag(Bool b)                           { m_toneMapCancelFlag=b;  }
+  Bool  getTMISEIToneMapCancelFlag()                                 { return m_toneMapCancelFlag;  }
+  Void  setTMISEIToneMapPersistenceFlag(Bool b)                      { m_toneMapPersistenceFlag = b;  }
+  Bool   getTMISEIToneMapPersistenceFlag()                           { return m_toneMapPersistenceFlag;  }
+  Void  setTMISEICodedDataBitDepth(Int b)                            { m_codedDataBitDepth = b;  }
+  Int   getTMISEICodedDataBitDepth()                                 { return m_codedDataBitDepth;  }
+  Void  setTMISEITargetBitDepth(Int b)                               { m_targetBitDepth = b;  }
+  Int   getTMISEITargetBitDepth()                                    { return m_targetBitDepth;  }
+  Void  setTMISEIModelID(Int b)                                      { m_modelId = b;  }
+  Int   getTMISEIModelID()                                           { return m_modelId;  }
+  Void  setTMISEIMinValue(Int b)                                     { m_minValue = b;  }
+  Int   getTMISEIMinValue()                                          { return m_minValue;  }
+  Void  setTMISEIMaxValue(Int b)                                     { m_maxValue = b;  }
+  Int   getTMISEIMaxValue()                                          { return m_maxValue;  }
+  Void  setTMISEISigmoidMidpoint(Int b)                              { m_sigmoidMidpoint = b;  }
+  Int   getTMISEISigmoidMidpoint()                                   { return m_sigmoidMidpoint;  }
+  Void  setTMISEISigmoidWidth(Int b)                                 { m_sigmoidWidth = b;  }
+  Int   getTMISEISigmoidWidth()                                      { return m_sigmoidWidth;  }
+  Void  setTMISEIStartOfCodedInterva( Int*  p )                      { m_startOfCodedInterval = p;  }
+  Int*  getTMISEIStartOfCodedInterva()                               { return m_startOfCodedInterval;  }
+  Void  setTMISEINumPivots(Int b)                                    { m_numPivots = b;  }
+  Int   getTMISEINumPivots()                                         { return m_numPivots;  }
+  Void  setTMISEICodedPivotValue( Int*  p )                          { m_codedPivotValue = p;  }
+  Int*  getTMISEICodedPivotValue()                                   { return m_codedPivotValue;  }
+  Void  setTMISEITargetPivotValue( Int*  p )                         { m_targetPivotValue = p;  }
+  Int*  getTMISEITargetPivotValue()                                  { return m_targetPivotValue;  }
+  Void  setTMISEICameraIsoSpeedIdc(Int b)                            { m_cameraIsoSpeedIdc = b;  }
+  Int   getTMISEICameraIsoSpeedIdc()                                 { return m_cameraIsoSpeedIdc;  }
+  Void  setTMISEICameraIsoSpeedValue(Int b)                          { m_cameraIsoSpeedValue = b;  }
+  Int   getTMISEICameraIsoSpeedValue()                               { return m_cameraIsoSpeedValue;  }
+  Void  setTMISEIExposureIndexIdc(Int b)                             { m_exposureIndexIdc = b;  }
+  Int   getTMISEIExposurIndexIdc()                                   { return m_exposureIndexIdc;  }
+  Void  setTMISEIExposureIndexValue(Int b)                           { m_exposureIndexValue = b;  }
+  Int   getTMISEIExposurIndexValue()                                 { return m_exposureIndexValue;  }
+  Void  setTMISEIExposureCompensationValueSignFlag(Int b)            { m_exposureCompensationValueSignFlag = b;  }
+  Int   getTMISEIExposureCompensationValueSignFlag()                 { return m_exposureCompensationValueSignFlag;  }
+  Void  setTMISEIExposureCompensationValueNumerator(Int b)           { m_exposureCompensationValueNumerator = b;  }
+  Int   getTMISEIExposureCompensationValueNumerator()                { return m_exposureCompensationValueNumerator;  }
+  Void  setTMISEIExposureCompensationValueDenomIdc(Int b)            { m_exposureCompensationValueDenomIdc =b;  }
+  Int   getTMISEIExposureCompensationValueDenomIdc()                 { return m_exposureCompensationValueDenomIdc;  }
+  Void  setTMISEIRefScreenLuminanceWhite(Int b)                      { m_refScreenLuminanceWhite = b;  }
+  Int   getTMISEIRefScreenLuminanceWhite()                           { return m_refScreenLuminanceWhite;  }
+  Void  setTMISEIExtendedRangeWhiteLevel(Int b)                      { m_extendedRangeWhiteLevel = b;  }
+  Int   getTMISEIExtendedRangeWhiteLevel()                           { return m_extendedRangeWhiteLevel;  }
+  Void  setTMISEINominalBlackLevelLumaCodeValue(Int b)               { m_nominalBlackLevelLumaCodeValue = b;  }
+  Int   getTMISEINominalBlackLevelLumaCodeValue()                    { return m_nominalBlackLevelLumaCodeValue;  }
+  Void  setTMISEINominalWhiteLevelLumaCodeValue(Int b)               { m_nominalWhiteLevelLumaCodeValue = b;  }
+  Int   getTMISEINominalWhiteLevelLumaCodeValue()                    { return m_nominalWhiteLevelLumaCodeValue;  }
+  Void  setTMISEIExtendedWhiteLevelLumaCodeValue(Int b)              { m_extendedWhiteLevelLumaCodeValue =b;  }
+  Int   getTMISEIExtendedWhiteLevelLumaCodeValue()                   { return m_extendedWhiteLevelLumaCodeValue;  }
+  Void  setFramePackingArrangementSEIEnabled(Int b)                  { m_framePackingSEIEnabled = b; }
+  Int   getFramePackingArrangementSEIEnabled()                       { return m_framePackingSEIEnabled; }
+  Void  setFramePackingArrangementSEIType(Int b)                     { m_framePackingSEIType = b; }
+  Int   getFramePackingArrangementSEIType()                          { return m_framePackingSEIType; }
+  Void  setFramePackingArrangementSEIId(Int b)                       { m_framePackingSEIId = b; }
+  Int   getFramePackingArrangementSEIId()                            { return m_framePackingSEIId; }
+  Void  setFramePackingArrangementSEIQuincunx(Int b)                 { m_framePackingSEIQuincunx = b; }
+  Int   getFramePackingArrangementSEIQuincunx()                      { return m_framePackingSEIQuincunx; }
+  Void  setFramePackingArrangementSEIInterpretation(Int b)           { m_framePackingSEIInterpretation = b; }
+  Int   getFramePackingArrangementSEIInterpretation()                { return m_framePackingSEIInterpretation; }
+  Void  setSegmentedRectFramePackingArrangementSEIEnabled(Int b)     { m_segmentedRectFramePackingSEIEnabled = b; }
+  Int   getSegmentedRectFramePackingArrangementSEIEnabled()          { return m_segmentedRectFramePackingSEIEnabled; }
+  Void  setSegmentedRectFramePackingArrangementSEICancel(Int b)      { m_segmentedRectFramePackingSEICancel = b; }
+  Int   getSegmentedRectFramePackingArrangementSEICancel()           { return m_segmentedRectFramePackingSEICancel; }
+  Void  setSegmentedRectFramePackingArrangementSEIType(Int b)        { m_segmentedRectFramePackingSEIType = b; }
+  Int   getSegmentedRectFramePackingArrangementSEIType()             { return m_segmentedRectFramePackingSEIType; }
+  Void  setSegmentedRectFramePackingArrangementSEIPersistence(Int b) { m_segmentedRectFramePackingSEIPersistence = b; }
+  Int   getSegmentedRectFramePackingArrangementSEIPersistence()      { return m_segmentedRectFramePackingSEIPersistence; }
+  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  setNoDisplaySEITLayer(Int b)                                 { m_noDisplaySEITLayer = b;    }
+  Int   getNoDisplaySEITLayer()                                      { return m_noDisplaySEITLayer; }
+  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  setTMCTSSEIEnabled(Bool b)                                   { m_tmctsSEIEnabled = b; }
+  Bool  getTMCTSSEIEnabled()                                         { return m_tmctsSEIEnabled; }
+  Void  setTimeCodeSEIEnabled(Bool b)                                { m_timeCodeSEIEnabled = b; }
+  Bool  getTimeCodeSEIEnabled()                                      { return m_timeCodeSEIEnabled; }
+  Void  setNumberOfTimeSets(Int value)                               { m_timeCodeSEINumTs = value; }
+  Int   getNumberOfTimesets()                                        { return m_timeCodeSEINumTs; }
+  Void  setTimeSet(TComSEITimeSet element, Int index)                { m_timeSetArray[index] = element; }
+  TComSEITimeSet &getTimeSet(Int index)                              { return m_timeSetArray[index]; }
+  const TComSEITimeSet &getTimeSet(Int index) const                  { return m_timeSetArray[index]; }
+  Void  setKneeSEIEnabled(Int b)                                     { m_kneeSEIEnabled = b; }
+  Bool  getKneeSEIEnabled()                                          { return m_kneeSEIEnabled; }
+  Void  setKneeSEIId(Int b)                                          { m_kneeSEIId = b; }
+  Int   getKneeSEIId()                                               { return m_kneeSEIId; }
+  Void  setKneeSEICancelFlag(Bool b)                                 { m_kneeSEICancelFlag=b; }
+  Bool  getKneeSEICancelFlag()                                       { return m_kneeSEICancelFlag; }
+  Void  setKneeSEIPersistenceFlag(Bool b)                            { m_kneeSEIPersistenceFlag = b; }
+  Bool  getKneeSEIPersistenceFlag()                                  { return m_kneeSEIPersistenceFlag; }
+  Void  setKneeSEIInputDrange(Int b)                                 { m_kneeSEIInputDrange = b; }
+  Int   getKneeSEIInputDrange()                                      { return m_kneeSEIInputDrange; }
+  Void  setKneeSEIInputDispLuminance(Int b)                          { m_kneeSEIInputDispLuminance = b; }
+  Int   getKneeSEIInputDispLuminance()                               { return m_kneeSEIInputDispLuminance; }
+  Void  setKneeSEIOutputDrange(Int b)                                { m_kneeSEIOutputDrange = b; }
+  Int   getKneeSEIOutputDrange()                                     { return m_kneeSEIOutputDrange; }
+  Void  setKneeSEIOutputDispLuminance(Int b)                         { m_kneeSEIOutputDispLuminance = b; }
+  Int   getKneeSEIOutputDispLuminance()                              { return m_kneeSEIOutputDispLuminance; }
+  Void  setKneeSEINumKneePointsMinus1(Int b)                         { m_kneeSEINumKneePointsMinus1 = b; }
+  Int   getKneeSEINumKneePointsMinus1()                              { return m_kneeSEINumKneePointsMinus1; }
+  Void  setKneeSEIInputKneePoint(Int *p)                             { m_kneeSEIInputKneePoint = p; }
+  Int*  getKneeSEIInputKneePoint()                                   { return m_kneeSEIInputKneePoint; }
+  Void  setKneeSEIOutputKneePoint(Int *p)                            { m_kneeSEIOutputKneePoint = p; }
+  Int*  getKneeSEIOutputKneePoint()                                  { return m_kneeSEIOutputKneePoint; }
+  Void  setMasteringDisplaySEI(const TComSEIMasteringDisplay &src)   { m_masteringDisplay = src; }
+  const TComSEIMasteringDisplay &getMasteringDisplaySEI() const      { return m_masteringDisplay; }
+  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    ( ScalingListMode u )          { m_useScalingListId       = u;   }
+  ScalingListMode getUseScalingListId    ()                          { return m_useScalingListId;      }
+  Void         setScalingListFile     ( Char*  pch )                 { m_scalingListFile     = pch; }
+  Char*        getScalingListFile     ()                             { return m_scalingListFile;    }
+  Void         setTMVPModeId ( Int  u )                              { m_TMVPModeId = u;    }
+  Int          getTMVPModeId ()                                      { return m_TMVPModeId; }
+  Void         setSignHideFlag( Int signHideFlag )                   { m_signHideFlag = signHideFlag; }
+  Int          getSignHideFlag()                                     { return m_signHideFlag; }
+  Bool         getUseRateCtrl         ()                             { return m_RCEnableRateControl;   }
+  Void         setUseRateCtrl         ( Bool b )                     { m_RCEnableRateControl = b;      }
+  Int          getTargetBitrate       ()                             { return m_RCTargetBitrate;       }
+  Void         setTargetBitrate       ( Int bitrate )                { m_RCTargetBitrate  = bitrate;   }
+  Int          getKeepHierBit         ()                             { return m_RCKeepHierarchicalBit; }
+  Void         setKeepHierBit         ( Int i )                      { m_RCKeepHierarchicalBit = i;    }
+  Bool         getLCULevelRC          ()                             { return m_RCLCULevelRC; }
+  Void         setLCULevelRC          ( Bool b )                     { m_RCLCULevelRC = b; }
+  Bool         getUseLCUSeparateModel ()                             { return m_RCUseLCUSeparateModel; }
+  Void         setUseLCUSeparateModel ( Bool b )                     { m_RCUseLCUSeparateModel = b;    }
+  Int          getInitialQP           ()                             { return m_RCInitialQP;           }
+  Void         setInitialQP           ( Int QP )                     { m_RCInitialQP = QP;             }
+  Bool         getForceIntraQP        ()                             { return m_RCForceIntraQP;        }
+  Void         setForceIntraQP        ( Bool b )                     { m_RCForceIntraQP = b;           }
+  Bool         getTransquantBypassEnableFlag()                       { return m_TransquantBypassEnableFlag; }
+  Void         setTransquantBypassEnableFlag(Bool flag)              { m_TransquantBypassEnableFlag = flag; }
+  Bool         getCUTransquantBypassFlagForceValue()                 { return m_CUTransquantBypassFlagForce; }
+  Void         setCUTransquantBypassFlagForceValue(Bool flag)        { m_CUTransquantBypassFlagForce = flag; }
+  CostMode     getCostMode( )                                        { return m_costMode; }
+  Void         setCostMode(CostMode m )                              { m_costMode = m; }
+
+  Void         setVPS(TComVPS *p)                                    { m_cVPS = *p; }
+  TComVPS *    getVPS()                                              { return &m_cVPS; }
+  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; }
+
+  UInt         getBitDepthConstraintValue() const                    { return m_bitDepthConstraintValue; }
+  Void         setBitDepthConstraintValue(UInt v)                    { m_bitDepthConstraintValue=v; }
+
+  ChromaFormat getChromaFormatConstraintValue() const                { return m_chromaFormatConstraintValue; }
+  Void         setChromaFormatConstraintValue(ChromaFormat v)        { m_chromaFormatConstraintValue=v; }
+
+  Bool         getIntraConstraintFlag() const                        { return m_intraConstraintFlag; }
+  Void         setIntraConstraintFlag(Bool b)                        { m_intraConstraintFlag=b; }
+
+  Bool         getLowerBitRateConstraintFlag() const                 { return m_lowerBitRateConstraintFlag; }
+  Void         setLowerBitRateConstraintFlag(Bool b)                 { m_lowerBitRateConstraintFlag=b; }
+  Bool      getChromaSamplingFilterHintEnabled()                     { return m_chromaSamplingFilterHintEnabled;}
+  Void      setChromaSamplingFilterHintEnabled(Bool i)               { m_chromaSamplingFilterHintEnabled = i;}
+  Int       getChromaSamplingHorFilterIdc()                          { return m_chromaSamplingHorFilterIdc;}
+  Void      setChromaSamplingHorFilterIdc(Int i)                     { m_chromaSamplingHorFilterIdc = i;}
+  Int       getChromaSamplingVerFilterIdc()                          { return m_chromaSamplingVerFilterIdc;}
+  Void      setChromaSamplingVerFilterIdc(Int i)                     { m_chromaSamplingVerFilterIdc = i;}
+
+#if Q0189_TMVP_CONSTRAINTS
+  Void  setTMVPConstraintsSEIEnabled(Int b)                  { m_TMVPConstraintsSEIEnabled = b; }
+  Int   getTMVPConstraintsSEIEnabled()                       {  return m_TMVPConstraintsSEIEnabled; }
+
+#endif
+#if P0123_ALPHA_CHANNEL_SEI
+  Void  setAlphaSEIEnabled(Bool b)                           { m_alphaSEIEnabled       = b; }
+  Bool  getAlphaSEIEnabled()                                 { return m_alphaSEIEnabled; }
+  Void  setAlphaCancelFlag(Bool b)                           { m_alphaCancelFlag       = b; }
+  Bool  getAlphaCancelFlag()                                 { return m_alphaCancelFlag; }
+  Void  setAlphaUseIdc(Int idc)                              { m_alphaUseIdc           = idc; }
+  Int   getAlphaUseIdc()                                     { return m_alphaUseIdc; }
+  Void  setAlphaBitDepthMinus8(Int d)                        { m_alphaBitDepthMinus8   = d; }
+  Int   getAlphaBitDepthMinus8()                             { return m_alphaBitDepthMinus8; }
+  Void  setAlphaTransparentValue(Int v)                      { m_alphaTransparentValue = v; }
+  Int   getAlphaTransparentValue()                           { return m_alphaTransparentValue; }
+  Void  setAlphaOpaqueValue(Int v)                           { m_alphaOpaqueValue      = v; }
+  Int   getAlphaOpaqueValue()                                { return m_alphaOpaqueValue; }
+  Void  setAlphaIncrementFlag(Bool b)                        { m_alphaIncrementFlag    = b; }
+  Int   getAlphaIncrementFlag()                              { return m_alphaIncrementFlag; }
+  Void  setAlphaClipFlag(Bool b)                             { m_alphaClipFlag         = b; }
+  Bool  getAlphaClipFlag()                                   { return m_alphaClipFlag; }
+  Void  setAlphaClipTypeFlag(Bool b)                         { m_alphaClipTypeFlag     = b; }
+  Bool  getAlphaClipTypeFlag()                               { return m_alphaClipTypeFlag; }
+#endif
+#if Q0074_COLOUR_REMAPPING_SEI
+  Void  setCRISEIFile( Char* pch )                           { m_colourRemapSEIFile = pch; }
+  Char* getCRISEIFile()                                      { return m_colourRemapSEIFile; }
+  Void  setCRISEIId(Int i)                                   { m_colourRemapSEIId = i; }
+  Int   getCRISEIId()                                        { return m_colourRemapSEIId; }
+  Void  setCRISEICancelFlag(Bool b)                          { m_colourRemapSEICancelFlag = b; }
+  Bool  getCRISEICancelFlag()                                { return m_colourRemapSEICancelFlag; }
+  Void  setCRISEIPersistenceFlag(Bool b)                     { m_colourRemapSEIPersistenceFlag = b; }
+  Bool  getCRISEIPersistenceFlag()                           { return m_colourRemapSEIPersistenceFlag; }
+  Void  setCRISEIVideoSignalInfoPresentFlag(Bool b)          { m_colourRemapSEIVideoSignalInfoPresentFlag = b; }
+  Bool  getCRISEIVideoSignalInfoPresentFlag()                { return m_colourRemapSEIVideoSignalInfoPresentFlag; }
+  Void  setCRISEIFullRangeFlag(Bool b)                       { m_colourRemapSEIFullRangeFlag = b; }
+  Bool  getCRISEIFullRangeFlag()                             { return m_colourRemapSEIFullRangeFlag; }
+  Void  setCRISEIPrimaries(Int i)                            { m_colourRemapSEIPrimaries = i; }
+  Int   getCRISEIPrimaries()                                 { return m_colourRemapSEIPrimaries; }  
+  Void  setCRISEITransferFunction(Int i)                     { m_colourRemapSEITransferFunction = i; }
+  Int   getCRISEITransferFunction()                          { return m_colourRemapSEITransferFunction; }  
+  Void  setCRISEIMatrixCoefficients(Int i)                   { m_colourRemapSEIMatrixCoefficients = i; }
+  Int   getCRISEIMatrixCoefficients()                        { return m_colourRemapSEIMatrixCoefficients; }
+  Void  setCRISEIInputBitDepth(Int i)                        { m_colourRemapSEIInputBitDepth = i; }
+  Int   getCRISEIInputBitDepth()                             { return m_colourRemapSEIInputBitDepth; } 
+  Void  setCRISEIBitDepth(Int i)                             { m_colourRemapSEIBitDepth = i; }
+  Int   getCRISEIBitDepth()                                  { return m_colourRemapSEIBitDepth; } 
+  Void  setCRISEIPreLutNumValMinus1(Int *i)                  { for(Int c=0 ; c<3 ; c++) m_colourRemapSEIPreLutNumValMinus1[c] = i[c]; }
+  Int   getCRISEIPreLutNumValMinus1(Int i)                   { return m_colourRemapSEIPreLutNumValMinus1[i]; }
+  Void  setCRISEIPreLutCodedValue(Int **i)                   { for(Int c=0 ; c<3 ; c++) m_colourRemapSEIPreLutCodedValue[c] = i[c]; }
+  Int*  getCRISEIPreLutCodedValue(Int i)                     { return m_colourRemapSEIPreLutCodedValue[i]; }
+  Void  setCRISEIPreLutTargetValue(Int **i)                  { for(Int c=0 ; c<3 ; c++) m_colourRemapSEIPreLutTargetValue[c] = i[c]; }
+  Int*  getCRISEIPreLutTargetValue(Int i)                    { return m_colourRemapSEIPreLutTargetValue[i]; }
+  Void  setCRISEIMatrixPresentFlag(Bool b)                   { m_colourRemapSEIMatrixPresentFlag = b; }
+  Bool  getCRISEIMatrixPresentFlag()                         { return m_colourRemapSEIMatrixPresentFlag; }
+  Void  setCRISEILog2MatrixDenom(Int i)                      { m_colourRemapSEILog2MatrixDenom = i; }
+  Int   getCRISEILog2MatrixDenom()                           { return m_colourRemapSEILog2MatrixDenom; } 
+  Void  setCRISEICoeffs(Int i[3][3])                         { for(Int c=0 ; c<3 ; c++) for(Int j=0 ; j<3 ; j++) m_colourRemapSEICoeffs[c][j] = i[c][j]; }
+  Int*  getCRISEICoeffs(Int i)                               { return m_colourRemapSEICoeffs[i]; }
+  Void  setCRISEIPostLutNumValMinus1(Int *i)                 { for(Int c=0 ; c<3 ; c++) m_colourRemapSEIPostLutNumValMinus1[c] = i[c]; }
+  Int   getCRISEIPostLutNumValMinus1(Int i)                  { return m_colourRemapSEIPostLutNumValMinus1[i]; }
+  Void  setCRISEIPostLutCodedValue(Int **i)                  { for(Int c=0 ; c<3 ; c++) m_colourRemapSEIPostLutCodedValue[c] = i[c]; }
+  Int*  getCRISEIPostLutCodedValue(Int i)                    { return m_colourRemapSEIPostLutCodedValue[i]; }
+  Void  setCRISEIPostLutTargetValue(Int **i)                 { for(Int c=0 ; c<3 ; c++) m_colourRemapSEIPostLutTargetValue[c] = i[c]; }
+  Int*  getCRISEIPostLutTargetValue(Int i)                   { return m_colourRemapSEIPostLutTargetValue[i]; }
+#endif
+#if SVC_EXTENSION
+  UInt      getLayerId            () { return m_layerId;              }
+  Void      setLayerId            (UInt layer) { m_layerId = layer; }
+  UInt      getNumLayer           () { return m_numLayer;             }  
+  Void      setNumLayer           (UInt uiNum)   { m_numLayer = uiNum;  }
+  Void      setConformanceWindow(Window& conformanceWindow ) { m_conformanceWindow = conformanceWindow; }
+  Void      setElRapSliceTypeB(Int bEnabled) {m_elRapSliceBEnabled = bEnabled;}
+  Int       getElRapSliceTypeB()              {return m_elRapSliceBEnabled;}
+#if M0040_ADAPTIVE_RESOLUTION_CHANGE
+  Void      setAdaptiveResolutionChange(Int x) { m_adaptiveResolutionChange = x;    }
+  Int       getAdaptiveResolutionChange()      { return m_adaptiveResolutionChange; }
+#endif
+#if R0071_IRAP_EOS_CROSS_LAYER_IMPACTS
+  Void      setLayerSwitchOffBegin(Int x)    { m_layerSwitchOffBegin = x;    }
+  Int       getLayerSwitchOffBegin()         { return m_layerSwitchOffBegin; }
+  Void      setLayerSwitchOffEnd(Int x)      { m_layerSwitchOffEnd = x;      }
+  Int       getLayerSwitchOffEnd()           { return m_layerSwitchOffEnd;   }
+#endif
+#if HIGHER_LAYER_IRAP_SKIP_FLAG
+  Void      setSkipPictureAtArcSwitch(Int x) { m_skipPictureAtArcSwitch = x;    }
+  Int       getSkipPictureAtArcSwitch()      { return m_skipPictureAtArcSwitch; }
+#endif
+#if AUXILIARY_PICTURES
+  Void         setChromaFormatIDC(ChromaFormat x) { m_chromaFormatIDC = x;    }
+  ChromaFormat getChromaFormatIDC()               { return m_chromaFormatIDC; }
+#endif
+#if O0153_ALT_OUTPUT_LAYER_FLAG
+  Bool      getAltOuputLayerFlag() const { return m_altOutputLayerFlag; }
+  Void      setAltOuputLayerFlag(Bool b) { m_altOutputLayerFlag = b;    }
+#endif
+#if O0149_CROSS_LAYER_BLA_FLAG
+  Bool      getCrossLayerBLAFlag() const { return m_crossLayerBLAFlag; }
+  Void      setCrossLayerBLAFlag(Bool b) { m_crossLayerBLAFlag = b;    }
+#endif
+#if FAST_INTRA_SHVC
+  Bool      getUseFastIntraScalable         ()      { return m_useFastIntraScalable; }
+  Void      setUseFastIntraScalable         ( Bool  b )     { m_useFastIntraScalable = b; }
+#endif
+#if VPS_EXTN_DIRECT_REF_LAYERS
+  Int       getNumDirectRefLayers           ()                              { return m_numDirectRefLayers;      }
+  Void      setNumDirectRefLayers           (Int num)                       { m_numDirectRefLayers = num;       }
+
+  Int       getRefLayerId                   (Int i)                         { return m_refLayerId[i];           }
+  Void      setRefLayerId                   (Int i, Int refLayerId)         { m_refLayerId[i] = refLayerId;     }
+
+  Int       getNumActiveRefLayers           ()                              { return m_numActiveRefLayers;      }
+  Void      setNumActiveRefLayers           (Int num)                       { m_numActiveRefLayers = num;       }
+
+  Int       getPredLayerIdx                 (Int lyaerIdc)                  { return m_predLayerIdx[lyaerIdc];          }
+  Void      setPredLayerIdx                 (Int lyaerIdc, Int refLayerIdx) { m_predLayerIdx[lyaerIdc] = refLayerIdx;   }
+
+  Int       getNumSamplePredRefLayers       ()                              { return m_numSamplePredRefLayers;  }
+  Void      setNumSamplePredRefLayers       (Int num)                       { m_numSamplePredRefLayers = num;   }
+
+  Int       getSamplePredRefLayerId         (Int layerIdc)                  { return m_samplePredRefLayerId[layerIdc];       }
+  Void      setSamplePredRefLayerId         (Int layerIdc, Int refLayerId)  { m_samplePredRefLayerId[layerIdc] = refLayerId; }
+
+  Int       getNumMotionPredRefLayers       ()                              { return m_numMotionPredRefLayers;  }
+  Void      setNumMotionPredRefLayers       (Int num)                       { m_numMotionPredRefLayers = num;   }
+
+  Int       getMotionPredRefLayerId         (Int layerIdc)                  { return m_motionPredRefLayerId[layerIdc];       }
+  Void      setMotionPredRefLayerId         (Int layerIdc, Int refLayerId)  { m_motionPredRefLayerId[layerIdc] = refLayerId; }
+
+  Bool      getSamplePredEnabledFlag        (Int layerIdx)                  { return m_samplePredEnabledFlag[layerIdx];  }
+  Void      setSamplePredEnabledFlag        (Int layerIdx, Bool flag)       { m_samplePredEnabledFlag[layerIdx] = flag;  }
+
+  Bool      getMotionPredEnabledFlag        (Int layerIdx)                  { return m_motionPredEnabledFlag[layerIdx];  }
+  Void      setMotionPredEnabledFlag        (Int layerIdx,Bool flag)        { m_motionPredEnabledFlag[layerIdx] = flag;  }
+#endif
+  Int       getMaxTidIlRefPicsPlus1         ()                              { return m_maxTidIlRefPicsPlus1; }
+  Void      setMaxTidIlRefPicsPlus1         (Int num)                       { m_maxTidIlRefPicsPlus1 = num;  }
+#if LAYERS_NOT_PRESENT_SEI
+  Void  setLayersNotPresentSEIEnabled(Int b)             { m_layersNotPresentSEIEnabled = b; }
+  Int   getLayersNotPresentSEIEnabled()                  { return m_layersNotPresentSEIEnabled; }
+#endif
+#if N0383_IL_CONSTRAINED_TILE_SETS_SEI
+  Void  setInterLayerConstrainedTileSetsSEIEnabled(Bool b) { m_interLayerConstrainedTileSetsSEIEnabled = b; }
+  Bool  getInterLayerConstrainedTileSetsSEIEnabled()       { return m_interLayerConstrainedTileSetsSEIEnabled; }
+  Void  setIlNumSetsInMessage(UInt b)                      { m_ilNumSetsInMessage = b; }
+  Int   getIlNumSetsInMessage()                            { return m_ilNumSetsInMessage; }
+  Void  setSkippedTileSetPresentFlag(Bool b)               { m_skippedTileSetPresentFlag = b; }
+  Bool  getSkippedTileSetPresentFlag()                     { return m_skippedTileSetPresentFlag; }
+  Void  setTopLeftTileIndex(UInt *b)
+  {
+    for (UInt i = 0; i < m_ilNumSetsInMessage; i++)
+    {
+      m_topLeftTileIndex[i] = b[i];
+    }
+  }
+  UInt  getTopLeftTileIndex(UInt b)                        { return m_topLeftTileIndex[b]; }
+  Void  setBottomRightTileIndex(UInt *b)
+  {
+    for (UInt i = 0; i < m_ilNumSetsInMessage; i++)
+    {
+      m_bottomRightTileIndex[i] = b[i];
+    }
+  }
+  UInt  getBottomRightTileIndex(UInt b)                    { return m_bottomRightTileIndex[b]; }
+  Void  setIlcIdc(UInt *b)
+  {
+    for (UInt i = 0; i < m_ilNumSetsInMessage; i++)
+    {
+      m_ilcIdc[i] = b[i];
+    }
+  }
+  UInt  getIlcIdc(UInt b)                                  { return m_ilcIdc[b]; }
+#endif
+#if Q0096_OVERLAY_SEI  
+  Void                                setOverlaySEIEnabled(Int b)                                              { m_overlaySEIEnabled = b; }
+  Bool                                getOverlaySEIEnabled()                                                   { return m_overlaySEIEnabled; }
+  Void                                setOverlaySEICancelFlag(Int b)                                           { m_overlayInfoCancelFlag = b; } 
+  Bool                                getOverlaySEICancelFlag()                                                { return m_overlayInfoCancelFlag; } 
+  Void                                setOverlaySEIContentAuxIdMinus128(UInt b)                                { m_overlayContentAuxIdMinus128 = b; }     
+  UInt                                getOverlaySEIContentAuxIdMinus128()                                      { return m_overlayContentAuxIdMinus128; }     
+  Void                                setOverlaySEILabelAuxIdMinus128(UInt b)                                  { m_overlayLabelAuxIdMinus128 = b; }     
+  UInt                                getOverlaySEILabelAuxIdMinus128()                                        { return m_overlayLabelAuxIdMinus128; }  
+  Void                                setOverlaySEIAlphaAuxIdMinus128(UInt b)                                  { m_overlayAlphaAuxIdMinus128 = b; }     
+  UInt                                getOverlaySEIAlphaAuxIdMinus128()                                        { return m_overlayAlphaAuxIdMinus128; }  
+  Void                                setOverlaySEIElementLabelValueLengthMinus8(UInt b)                       { m_overlayElementLabelValueLengthMinus8 = b; }     
+  UInt                                getOverlaySEIElementLabelValueLengthMinus8()                             { return m_overlayElementLabelValueLengthMinus8; }  
+  Void                                setOverlaySEINumOverlaysMinus1(UInt b)                                   { m_numOverlaysMinus1 = b; }     
+  UInt                                getOverlaySEINumOverlaysMinus1()                                         { return m_numOverlaysMinus1; }     
+  Void                                setOverlaySEIIdx(const std::vector<UInt>& b)                             { m_overlayIdx = b; }      
+  std::vector<UInt>                   getOverlaySEIIdx()                                                       { return m_overlayIdx; }      
+  Void                                setOverlaySEILanguagePresentFlag(const std::vector<Bool>& b)             { m_overlayLanguagePresentFlag = b; }      
+  std::vector<Bool>                   getOverlaySEILanguagePresentFlag()                                       { return m_overlayLanguagePresentFlag; }   
+  Void                                setOverlaySEIContentLayerId(const std::vector<UInt>& b)                  { m_overlayContentLayerId = b; }      
+  std::vector<UInt>                   getOverlaySEIContentLayerId()                                            { return m_overlayContentLayerId; }      
+  Void                                setOverlaySEILabelPresentFlag(const std::vector<Bool>& b)                { m_overlayLabelPresentFlag = b; }      
+  std::vector<Bool>                   getOverlaySEILabelPresentFlag()                                          { return m_overlayLabelPresentFlag; } 
+  Void                                setOverlaySEILabelLayerId(const std::vector<UInt>& b)                    { m_overlayLabelLayerId = b; }      
+  std::vector<UInt>                   getOverlaySEILabelLayerId()                                              { return m_overlayLabelLayerId; }   
+  Void                                setOverlaySEIAlphaPresentFlag(const std::vector<Bool>& b)                { m_overlayAlphaPresentFlag = b; }      
+  std::vector<Bool>                   getOverlaySEIAlphaPresentFlag()                                          { return m_overlayAlphaPresentFlag; }     
+  Void                                setOverlaySEIAlphaLayerId(const std::vector<UInt>& b)                    { m_overlayAlphaLayerId = b; }      
+  std::vector<UInt>                   getOverlaySEIAlphaLayerId()                                              { return m_overlayAlphaLayerId; }   
+  Void                                setOverlaySEINumElementsMinus1(const std::vector<UInt>& b)               { m_numOverlayElementsMinus1 = b; }      
+  std::vector<UInt>                   getOverlaySEINumElementsMinus1()                                         { return m_numOverlayElementsMinus1; }     
+  Void                                setOverlaySEIElementLabelMin(const std::vector< std::vector<UInt> >& b)  { m_overlayElementLabelMin = b; }      
+  std::vector< std::vector<UInt> >    getOverlaySEIElementLabelMin()                                           { return m_overlayElementLabelMin; }   
+  Void                                setOverlaySEIElementLabelMax(const std::vector< std::vector<UInt> >& b)  { m_overlayElementLabelMax = b; }      
+  std::vector< std::vector<UInt> >    getOverlaySEIElementLabelMax()                                           { return m_overlayElementLabelMax; }              
+  Void                                setOverlaySEILanguage(const std::vector<string>& b)                      { m_overlayLanguage = b; }      
+  std::vector<string>                 getOverlaySEILanguage()                                                  { return m_overlayLanguage; }   
+  Void                                setOverlaySEIName(const std::vector<string>& b)                          { m_overlayName = b; }      
+  std::vector<string>                 getOverlaySEIName()                                                      { return m_overlayName; }   
+  Void                                setOverlaySEIElementName(const std::vector< std::vector<string> >& b)    { m_overlayElementName = b; }      
+  std::vector< std::vector<string> >  getOverlaySEIElementName()                                               { return m_overlayElementName; }   
+  Void                                setOverlaySEIPersistenceFlag(Int b)                                      { m_overlayInfoPersistenceFlag = b; } 
+  Bool                                getOverlaySEIPersistenceFlag()                                           { return m_overlayInfoPersistenceFlag; } 
+#endif
+#if Q0048_CGS_3D_ASYMLUT
+  Void      setCGSFlag(Int n)             { m_nCGSFlag = n;    }
+  Int       getCGSFlag()                  { return m_nCGSFlag; }
+  Void      setCGSMaxOctantDepth(Int n)   { m_nCGSMaxOctantDepth = n;    }
+  Int       getCGSMaxOctantDepth()        { return m_nCGSMaxOctantDepth; }
+  Void      setCGSMaxYPartNumLog2(Int n)  { m_nCGSMaxYPartNumLog2 = n;    }
+  Int       getCGSMaxYPartNumLog2()       { return m_nCGSMaxYPartNumLog2; }
+  Void      setCGSLUTBit(Int n)           { m_nCGSLUTBit = n;    }
+  Int       getCGSLUTBit()                { return m_nCGSLUTBit; }
+#if R0151_CGS_3D_ASYMLUT_IMPROVE
+  Void      setCGSAdaptChroma(Int n)      { m_nCGSAdaptiveChroma = n;  }
+  Int       getCGSAdaptChroma()           { return m_nCGSAdaptiveChroma; }
+#endif
+#if R0179_ENC_OPT_3DLUT_SIZE
+  Void      setCGSLutSizeRDO(Int n)      { m_nCGSLutSizeRDO = n;  }
+  Int       getCGSLutSizeRDO()           { return m_nCGSLutSizeRDO; }
+#endif
+#endif
+#endif
+};
+
+#if SVC_EXTENSION
+#if REPN_FORMAT_IN_VPS
+struct RepFormatCfg
+{
+  Int   m_chromaFormatIdc;
+  Bool  m_separateColourPlaneFlag;
+  Int   m_picWidthInLumaSamples;
+  Int   m_picHeightInLumaSamples;
+  Int   m_bitDepthLuma;
+  Int   m_bitDepthChroma;
+  RepFormatCfg()
+    : m_chromaFormatIdc         (CHROMA_420)
+    , m_separateColourPlaneFlag (0)
+    , m_picWidthInLumaSamples   (352)
+    , m_picHeightInLumaSamples  (288)
+    , m_bitDepthLuma            (8)
+    , m_bitDepthChroma          (8)
+  {}
+};
+std::istringstream &operator>>(std::istringstream &in, RepFormatCfg &repFormatCfg);
+#endif
+#endif //SVC_EXTENSION
+
+//! \}
+
+#endif // !defined(AFX_TENCCFG_H__6B99B797_F4DA_4E46_8E78_7656339A6C41__INCLUDED_)
Index: /tags/SHM-9.0/source/Lib/TLibEncoder/TEncCu.cpp
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibEncoder/TEncCu.cpp	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibEncoder/TEncCu.cpp	(revision 1088)
@@ -0,0 +1,1901 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TEncCu.cpp
+    \brief    Coding Unit (CU) encoder class
+*/
+
+#include <stdio.h>
+#include "TEncTop.h"
+#include "TEncCu.h"
+#include "TEncAnalyze.h"
+#include "TLibCommon/Debug.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, ChromaFormat chromaFormat)
+{
+  Int i;
+
+  m_uhTotalDepth   = uhTotalDepth + 1;
+  m_ppcBestCU      = new TComDataCU*[m_uhTotalDepth-1];
+  m_ppcTempCU      = new TComDataCU*[m_uhTotalDepth-1];
+
+  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( chromaFormat, uiNumPartitions, uiWidth, uiHeight, false, uiMaxWidth >> (m_uhTotalDepth - 1) );
+    m_ppcTempCU[i] = new TComDataCU; m_ppcTempCU[i]->create( chromaFormat, uiNumPartitions, uiWidth, uiHeight, false, uiMaxWidth >> (m_uhTotalDepth - 1) );
+
+    m_ppcPredYuvBest[i] = new TComYuv; m_ppcPredYuvBest[i]->create(uiWidth, uiHeight, chromaFormat);
+    m_ppcResiYuvBest[i] = new TComYuv; m_ppcResiYuvBest[i]->create(uiWidth, uiHeight, chromaFormat);
+    m_ppcRecoYuvBest[i] = new TComYuv; m_ppcRecoYuvBest[i]->create(uiWidth, uiHeight, chromaFormat);
+
+    m_ppcPredYuvTemp[i] = new TComYuv; m_ppcPredYuvTemp[i]->create(uiWidth, uiHeight, chromaFormat);
+    m_ppcResiYuvTemp[i] = new TComYuv; m_ppcResiYuvTemp[i]->create(uiWidth, uiHeight, chromaFormat);
+    m_ppcRecoYuvTemp[i] = new TComYuv; m_ppcRecoYuvTemp[i]->create(uiWidth, uiHeight, chromaFormat);
+
+    m_ppcOrigYuv    [i] = new TComYuv; m_ppcOrigYuv    [i]->create(uiWidth, uiHeight, chromaFormat);
+  }
+
+  m_bEncodeDQP          = false;
+  m_CodeChromaQpAdjFlag = false;
+  m_ChromaQpAdjIdc      = 0;
+
+  // 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(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(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_pcRdCost           = pcEncTop->getRdCost();
+  
+#if SVC_EXTENSION
+  m_ppcTEncTop         = pcEncTop->getLayerEnc();
+  for(UInt i=0 ; i< m_uhTotalDepth-1 ; i++)
+  {    
+    m_ppcBestCU[i]->setLayerId(pcEncTop->getLayerId());
+    m_ppcTempCU[i]->setLayerId(pcEncTop->getLayerId());
+  }
+#endif
+  
+  m_pcEntropyCoder     = pcEncTop->getEntropyCoder();
+  m_pcBinCABAC         = pcEncTop->getBinCABAC();
+
+  m_pppcRDSbacCoder    = pcEncTop->getRDSbacCoder();
+  m_pcRDGoOnSbacCoder  = pcEncTop->getRDGoOnSbacCoder();
+
+  m_pcRateCtrl         = pcEncTop->getRateCtrl();
+}
+
+// ====================================================================================================================
+// Public member functions
+// ====================================================================================================================
+
+/** \param  rpcCU pointer of CU data class
+ */
+Void TEncCu::compressCtu( TComDataCU* pCtu )
+{
+  // initialize CU data
+  m_ppcBestCU[0]->initCtu( pCtu->getPic(), pCtu->getCtuRsAddr() );
+  m_ppcTempCU[0]->initCtu( pCtu->getPic(), pCtu->getCtuRsAddr() );
+
+#if N0383_IL_CONSTRAINED_TILE_SETS_SEI
+  m_disableILP = xCheckTileSetConstraint(pCtu);
+  m_pcPredSearch->setDisableILP(m_disableILP);
+#endif
+
+  // analysis of CU
+  DEBUG_STRING_NEW(sDebug)
+
+  xCompressCU( m_ppcBestCU[0], m_ppcTempCU[0], 0 DEBUG_STRING_PASS_INTO(sDebug) );
+  DEBUG_STRING_OUTPUT(std::cout, sDebug)
+
+#if ADAPTIVE_QP_SELECTION
+  if( m_pcEncCfg->getUseAdaptQpSelect() )
+  {
+    if(pCtu->getSlice()->getSliceType()!=I_SLICE) //IIII
+    {
+      xCtuCollectARLStats( pCtu );
+    }
+  }
+#endif
+
+#if N0383_IL_CONSTRAINED_TILE_SETS_SEI
+  xVerifyTileSetConstraint(pCtu);
+#endif
+}
+/** \param  pcCU  pointer of CU data class
+ */
+Void TEncCu::encodeCtu ( TComDataCU* pCtu )
+{
+  if ( pCtu->getSlice()->getPPS()->getUseDQP() )
+  {
+    setdQPFlag(true);
+  }
+
+  if ( pCtu->getSlice()->getUseChromaQpAdj() )
+  {
+    setCodeChromaQpAdjFlag(true);
+  }
+
+  // Encode CU data
+  xEncodeCU( pCtu, 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 *pcBestCU, PartSize eParentPartSize, Bool &bTestAMP_Hor, Bool &bTestAMP_Ver, Bool &bTestMergeAMP_Hor, Bool &bTestMergeAMP_Ver)
+#else
+Void TEncCu::deriveTestModeAMP (TComDataCU *pcBestCU, PartSize eParentPartSize, Bool &bTestAMP_Hor, Bool &bTestAMP_Ver)
+#endif
+{
+  if ( pcBestCU->getPartitionSize(0) == SIZE_2NxN )
+  {
+    bTestAMP_Hor = true;
+  }
+  else if ( pcBestCU->getPartitionSize(0) == SIZE_Nx2N )
+  {
+    bTestAMP_Ver = true;
+  }
+  else if ( pcBestCU->getPartitionSize(0) == SIZE_2Nx2N && pcBestCU->getMergeFlag(0) == false && pcBestCU->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 == NUMBER_OF_PART_SIZES ) //! if parent is intra
+  {
+    if ( pcBestCU->getPartitionSize(0) == SIZE_2NxN )
+    {
+      bTestMergeAMP_Hor = true;
+    }
+    else if ( pcBestCU->getPartitionSize(0) == SIZE_Nx2N )
+    {
+      bTestMergeAMP_Ver = true;
+    }
+  }
+
+  if ( pcBestCU->getPartitionSize(0) == SIZE_2Nx2N && pcBestCU->isSkipped(0) == false )
+  {
+    bTestMergeAMP_Hor = true;
+    bTestMergeAMP_Ver = true;
+  }
+
+  if ( pcBestCU->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-CTU-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 DEBUG_STRING_FN_DECLARE(sDebug_), PartSize eParentPartSize )
+#else
+Void TEncCu::xCompressCU( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, UInt uiDepth )
+#endif
+{
+  TComPic* pcPic = rpcBestCU->getPic();
+  DEBUG_STRING_NEW(sDebug)
+
+  // get Original YUV data from picture
+  m_ppcOrigYuv[uiDepth]->copyFromPicYuv( pcPic->getPicYuvOrg(), rpcBestCU->getCtuRsAddr(), rpcBestCU->getZorderIdxInCtu() );
+
+    // variable for Early CU determination
+  Bool    bSubBranch = true;
+
+  // variable for Cbf fast mode PU decision
+  Bool    doNotBlockPu = true;
+  Bool    earlyDetectionSkipMode = false;
+
+  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;
+
+  const UInt numberValidComponents = rpcBestCU->getPic()->getNumberValidComponents();
+
+  if( (g_uiMaxCUWidth>>uiDepth) >= rpcTempCU->getSlice()->getPPS()->getMinCuDQPSize() )
+  {
+    Int idQP = m_pcEncCfg->getMaxDeltaQP();
+#if REPN_FORMAT_IN_VPS
+    iMinQP = Clip3( -rpcTempCU->getSlice()->getQpBDOffsetY(), MAX_QP, iBaseQP-idQP );
+    iMaxQP = Clip3( -rpcTempCU->getSlice()->getQpBDOffsetY(), MAX_QP, iBaseQP+idQP );
+#else
+    iMinQP = Clip3( -rpcTempCU->getSlice()->getSPS()->getQpBDOffset(CHANNEL_TYPE_LUMA), MAX_QP, iBaseQP-idQP );
+    iMaxQP = Clip3( -rpcTempCU->getSlice()->getSPS()->getQpBDOffset(CHANNEL_TYPE_LUMA), MAX_QP, iBaseQP+idQP );
+#endif
+  }
+  else
+  {
+    iMinQP = rpcTempCU->getQP(0);
+    iMaxQP = rpcTempCU->getQP(0);
+  }
+
+  if ( m_pcEncCfg->getUseRateCtrl() )
+  {
+    iMinQP = m_pcRateCtrl->getRCQP();
+    iMaxQP = m_pcRateCtrl->getRCQP();
+  }
+
+  // transquant-bypass (TQB) processing loop variable initialisation ---
+
+  const Int lowestQP = iMinQP; // For TQB, use this QP which is the lowest non TQB QP tested (rather than QP'=0) - that way delta QPs are smaller, and TQB can be tested at all CU levels.
+
+  if ( (rpcTempCU->getSlice()->getPPS()->getTransquantBypassEnableFlag()) )
+  {
+    isAddLowestQP = true; // mark that the first iteration is to cost TQB mode.
+    iMinQP = iMinQP - 1;  // increase loop variable range by 1, to allow testing of TQB mode along with other QPs
+    if ( m_pcEncCfg->getCUTransquantBypassFlagForceValue() )
+    {
+      iMaxQP = iMinQP;
+    }
+  }
+
+  TComSlice * pcSlice = rpcTempCU->getPic()->getSlice(rpcTempCU->getPic()->getCurrSliceIdx());
+  // We need to split, so don't try these modes.
+#if REPN_FORMAT_IN_VPS
+  if ( ( uiRPelX < rpcBestCU->getSlice()->getPicWidthInLumaSamples() ) &&
+       ( uiBPelY < rpcBestCU->getSlice()->getPicHeightInLumaSamples() ) )
+#else
+  if ( ( uiRPelX < rpcBestCU->getSlice()->getSPS()->getPicWidthInLumaSamples() ) &&
+       ( uiBPelY < rpcBestCU->getSlice()->getSPS()->getPicHeightInLumaSamples() ) )
+#endif
+  {
+#if HIGHER_LAYER_IRAP_SKIP_FLAG
+    if (m_pcEncCfg->getSkipPictureAtArcSwitch() && m_pcEncCfg->getAdaptiveResolutionChange() > 0 && pcSlice->getLayerId() == 1 && pcSlice->getPOC() == m_pcEncCfg->getAdaptiveResolutionChange())
+    {
+      Int iQP = iBaseQP;
+      const Bool bIsLosslessMode = isAddLowestQP && (iQP == iMinQP);
+
+      if( bIsLosslessMode )
+      {
+        iQP = lowestQP;
+      }
+
+      rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
+      
+      xCheckRDCostMerge2Nx2N( rpcBestCU, rpcTempCU, &earlyDetectionSkipMode, true );
+    }
+    else
+    {
+#endif
+#if ENCODER_FAST_MODE
+    Bool testInter = true;
+    if( rpcBestCU->getLayerId() > 0 )
+    {
+      if(pcSlice->getSliceType() == P_SLICE && pcSlice->getNumRefIdx(REF_PIC_LIST_0) == pcSlice->getActiveNumILRRefIdx())
+      {
+        testInter = false;
+      }
+      if(pcSlice->getSliceType() == B_SLICE && pcSlice->getNumRefIdx(REF_PIC_LIST_0) == pcSlice->getActiveNumILRRefIdx() && pcSlice->getNumRefIdx(REF_PIC_LIST_1) == pcSlice->getActiveNumILRRefIdx()) 
+      {
+        testInter = false;
+      }
+    }
+#endif
+    for (Int iQP=iMinQP; iQP<=iMaxQP; iQP++)
+    {
+      const Bool bIsLosslessMode = isAddLowestQP && (iQP == iMinQP);
+
+      if (bIsLosslessMode)
+      {
+        iQP = lowestQP;
+      }
+
+      m_ChromaQpAdjIdc = 0;
+      if (pcSlice->getUseChromaQpAdj())
+      {
+        /* Pre-estimation of chroma QP based on input block activity may be performed
+         * here, using for example m_ppcOrigYuv[uiDepth] */
+        /* To exercise the current code, the index used for adjustment is based on
+         * block position
+         */
+        Int lgMinCuSize = pcSlice->getSPS()->getLog2MinCodingBlockSize();
+        m_ChromaQpAdjIdc = ((uiLPelX >> lgMinCuSize) + (uiTPelY >> lgMinCuSize)) % (pcSlice->getPPS()->getChromaQpAdjTableSize() + 1);
+      }
+
+      rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
+
+      // do inter modes, SKIP and 2Nx2N
+#if ENCODER_FAST_MODE == 1
+      if( rpcBestCU->getSlice()->getSliceType() != I_SLICE && testInter )
+#else
+      if( rpcBestCU->getSlice()->getSliceType() != I_SLICE )
+#endif
+      {
+        // 2Nx2N
+        if(m_pcEncCfg->getUseEarlySkipDetection())
+        {
+          xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2Nx2N DEBUG_STRING_PASS_INTO(sDebug) );
+          rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );//by Competition for inter_2Nx2N
+        }
+        // SKIP
+        xCheckRDCostMerge2Nx2N( rpcBestCU, rpcTempCU DEBUG_STRING_PASS_INTO(sDebug), &earlyDetectionSkipMode );//by Merge for inter_2Nx2N
+        rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
+        
+#if ENCODER_FAST_MODE == 2
+        if (testInter)
+        {
+#endif
+        if(!m_pcEncCfg->getUseEarlySkipDetection())
+        {
+          // 2Nx2N, NxN
+          xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2Nx2N DEBUG_STRING_PASS_INTO(sDebug) );
+          rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
+          if(m_pcEncCfg->getUseCbfFastMode())
+          {
+            doNotBlockPu = rpcBestCU->getQtRootCbf( 0 ) != 0;
+          }
+        }
+#if ENCODER_FAST_MODE == 2
+        }
+#endif
+      }
+
+      if (bIsLosslessMode) // Restore loop variable if lossless mode was searched.
+      {
+        iQP = iMinQP;
+      }
+    }
+
+    if(!earlyDetectionSkipMode)
+    {
+      for (Int iQP=iMinQP; iQP<=iMaxQP; iQP++)
+      {
+        const Bool bIsLosslessMode = isAddLowestQP && (iQP == iMinQP); // If lossless, then iQP is irrelevant for subsequent modules.
+
+        if (bIsLosslessMode)
+        {
+          iQP = lowestQP;
+        }
+
+        rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
+
+        // do inter modes, NxN, 2NxN, and Nx2N
+#if ENCODER_FAST_MODE
+        if( rpcBestCU->getSlice()->getSliceType() != I_SLICE && testInter )
+#else
+        if( rpcBestCU->getSlice()->getSliceType() != I_SLICE )
+#endif
+        {
+          // 2Nx2N, NxN
+          if(!( (rpcBestCU->getWidth(0)==8) && (rpcBestCU->getHeight(0)==8) ))
+          {
+            if( uiDepth == g_uiMaxCUDepth - g_uiAddCUDepth && doNotBlockPu)
+            {
+              xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_NxN DEBUG_STRING_PASS_INTO(sDebug)   );
+              rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
+            }
+          }
+
+          if(doNotBlockPu)
+          {
+            xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_Nx2N DEBUG_STRING_PASS_INTO(sDebug)  );
+            rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
+            if(m_pcEncCfg->getUseCbfFastMode() && rpcBestCU->getPartitionSize(0) == SIZE_Nx2N )
+            {
+              doNotBlockPu = rpcBestCU->getQtRootCbf( 0 ) != 0;
+            }
+          }
+          if(doNotBlockPu)
+          {
+            xCheckRDCostInter      ( rpcBestCU, rpcTempCU, SIZE_2NxN DEBUG_STRING_PASS_INTO(sDebug)  );
+            rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
+            if(m_pcEncCfg->getUseCbfFastMode() && rpcBestCU->getPartitionSize(0) == SIZE_2NxN)
+            {
+              doNotBlockPu = rpcBestCU->getQtRootCbf( 0 ) != 0;
+            }
+          }
+
+          //! 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)
+              {
+                xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2NxnU DEBUG_STRING_PASS_INTO(sDebug) );
+                rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
+                if(m_pcEncCfg->getUseCbfFastMode() && rpcBestCU->getPartitionSize(0) == SIZE_2NxnU )
+                {
+                  doNotBlockPu = rpcBestCU->getQtRootCbf( 0 ) != 0;
+                }
+              }
+              if(doNotBlockPu)
+              {
+                xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2NxnD DEBUG_STRING_PASS_INTO(sDebug) );
+                rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
+                if(m_pcEncCfg->getUseCbfFastMode() && rpcBestCU->getPartitionSize(0) == SIZE_2NxnD )
+                {
+                  doNotBlockPu = rpcBestCU->getQtRootCbf( 0 ) != 0;
+                }
+              }
+            }
+#if AMP_MRG
+            else if ( bTestMergeAMP_Hor )
+            {
+              if(doNotBlockPu)
+              {
+                xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2NxnU DEBUG_STRING_PASS_INTO(sDebug), true );
+                rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
+                if(m_pcEncCfg->getUseCbfFastMode() && rpcBestCU->getPartitionSize(0) == SIZE_2NxnU )
+                {
+                  doNotBlockPu = rpcBestCU->getQtRootCbf( 0 ) != 0;
+                }
+              }
+              if(doNotBlockPu)
+              {
+                xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2NxnD DEBUG_STRING_PASS_INTO(sDebug), true );
+                rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
+                if(m_pcEncCfg->getUseCbfFastMode() && rpcBestCU->getPartitionSize(0) == SIZE_2NxnD )
+                {
+                  doNotBlockPu = rpcBestCU->getQtRootCbf( 0 ) != 0;
+                }
+              }
+            }
+#endif
+
+            //! Do horizontal AMP
+            if ( bTestAMP_Ver )
+            {
+              if(doNotBlockPu)
+              {
+                xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_nLx2N DEBUG_STRING_PASS_INTO(sDebug) );
+                rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
+                if(m_pcEncCfg->getUseCbfFastMode() && rpcBestCU->getPartitionSize(0) == SIZE_nLx2N )
+                {
+                  doNotBlockPu = rpcBestCU->getQtRootCbf( 0 ) != 0;
+                }
+              }
+              if(doNotBlockPu)
+              {
+                xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_nRx2N DEBUG_STRING_PASS_INTO(sDebug) );
+                rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
+              }
+            }
+#if AMP_MRG
+            else if ( bTestMergeAMP_Ver )
+            {
+              if(doNotBlockPu)
+              {
+                xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_nLx2N DEBUG_STRING_PASS_INTO(sDebug), true );
+                rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
+                if(m_pcEncCfg->getUseCbfFastMode() && rpcBestCU->getPartitionSize(0) == SIZE_nLx2N )
+                {
+                  doNotBlockPu = rpcBestCU->getQtRootCbf( 0 ) != 0;
+                }
+              }
+              if(doNotBlockPu)
+              {
+                xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_nRx2N DEBUG_STRING_PASS_INTO(sDebug), true );
+                rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
+              }
+            }
+#endif
+
+#else
+            xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2NxnU );
+            rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
+            xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2NxnD );
+            rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
+            xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_nLx2N );
+            rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
+
+            xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_nRx2N );
+            rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
+
+#endif
+          }
+        }
+
+        // do normal intra modes
+        // speedup for inter frames
+        Double intraCost = 0.0;
+
+        if((rpcBestCU->getSlice()->getSliceType() == I_SLICE)                                     ||
+#if ENCODER_FAST_MODE
+          rpcBestCU->getPredictionMode(0) == NUMBER_OF_PREDICTION_MODES                           ||  // if there is no valid inter prediction
+          !testInter                                                                              ||
+#endif
+           (rpcBestCU->getCbf( 0, COMPONENT_Y  ) != 0)                                            ||
+          ((rpcBestCU->getCbf( 0, COMPONENT_Cb ) != 0) && (numberValidComponents > COMPONENT_Cb)) ||
+          ((rpcBestCU->getCbf( 0, COMPONENT_Cr ) != 0) && (numberValidComponents > COMPONENT_Cr))  ) // avoid very complex intra if it is unlikely
+        {
+          xCheckRDCostIntra( rpcBestCU, rpcTempCU, intraCost, SIZE_2Nx2N DEBUG_STRING_PASS_INTO(sDebug) );
+          rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
+          if( uiDepth == g_uiMaxCUDepth - g_uiAddCUDepth )
+          {
+            if( rpcTempCU->getWidth(0) > ( 1 << rpcTempCU->getSlice()->getSPS()->getQuadtreeTULog2MinSize() ) )
+            {
+              Double tmpIntraCost;
+              xCheckRDCostIntra( rpcBestCU, rpcTempCU, tmpIntraCost, SIZE_NxN DEBUG_STRING_PASS_INTO(sDebug)   );
+              intraCost = std::min(intraCost, tmpIntraCost);
+              rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
+            }
+          }
+        }
+
+        // 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 = getTotalBits(rpcBestCU->getWidth(0), rpcBestCU->getHeight(0), rpcBestCU->getPic()->getChromaFormat(), g_bitDepth);
+          UInt uiBestBits = rpcBestCU->getTotalBits();
+          if((uiBestBits > uiRawBits) || (rpcBestCU->getTotalCost() > m_pcRdCost->calcRdCost(uiRawBits, 0)))
+          {
+            xCheckIntraPCM (rpcBestCU, rpcTempCU);
+            rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
+          }
+        }
+#if ENCODER_FAST_MODE
+#if N0383_IL_CONSTRAINED_TILE_SETS_SEI
+        if(pcPic->getLayerId() > 0 && !m_disableILP)
+#else
+        if(pcPic->getLayerId() > 0)
+#endif
+        {
+          for(Int refLayer = 0; refLayer < pcSlice->getActiveNumILRRefIdx(); refLayer++)
+          {  
+            xCheckRDCostILRUni( rpcBestCU, rpcTempCU, pcSlice->getVPS()->getRefLayerId( pcSlice->getLayerId(), pcSlice->getInterLayerPredLayerIdc(refLayer) ) );
+            rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
+          }
+        }
+#endif
+
+        if (bIsLosslessMode) // Restore loop variable if lossless mode was searched.
+        {
+          iQP = iMinQP;
+        }
+      }
+    }
+
+    m_pcEntropyCoder->resetBits();
+    m_pcEntropyCoder->encodeSplitFlag( rpcBestCU, 0, uiDepth, true );
+    rpcBestCU->getTotalBits() += m_pcEntropyCoder->getNumberOfWrittenBits(); // split bits
+    rpcBestCU->getTotalBins() += ((TEncBinCABAC *)((TEncSbac*)m_pcEntropyCoder->m_pcEntropyCoderIf)->getEncBinIf())->getBinsCoded();
+    rpcBestCU->getTotalCost()  = m_pcRdCost->calcRdCost( rpcBestCU->getTotalBits(), rpcBestCU->getTotalDistortion() );
+
+    // Early CU determination
+    if( m_pcEncCfg->getUseEarlyCU() && rpcBestCU->isSkipped(0) )
+    {
+      bSubBranch = false;
+    }
+    else
+    {
+      bSubBranch = true;
+    }
+#if HIGHER_LAYER_IRAP_SKIP_FLAG
+    }
+#endif
+  }
+  else
+  {
+    bBoundary = true;
+  }
+
+  // copy orginal YUV samples to PCM buffer
+  if( rpcBestCU->isLosslessCoded(0) && (rpcBestCU->getIPCMFlag(0) == false))
+  {
+    xFillPCMBuffer(rpcBestCU, m_ppcOrigYuv[uiDepth]);
+  }
+
+  if( (g_uiMaxCUWidth>>uiDepth) == rpcTempCU->getSlice()->getPPS()->getMinCuDQPSize() )
+  {
+    Int idQP = m_pcEncCfg->getMaxDeltaQP();
+#if REPN_FORMAT_IN_VPS
+    iMinQP = Clip3( -rpcTempCU->getSlice()->getQpBDOffsetY(), MAX_QP, iBaseQP-idQP );
+    iMaxQP = Clip3( -rpcTempCU->getSlice()->getQpBDOffsetY(), MAX_QP, iBaseQP+idQP );
+#else
+    iMinQP = Clip3( -rpcTempCU->getSlice()->getSPS()->getQpBDOffset(CHANNEL_TYPE_LUMA), MAX_QP, iBaseQP-idQP );
+    iMaxQP = Clip3( -rpcTempCU->getSlice()->getSPS()->getQpBDOffset(CHANNEL_TYPE_LUMA), MAX_QP, iBaseQP+idQP );
+#endif    
+  }
+  else if( (g_uiMaxCUWidth>>uiDepth) > rpcTempCU->getSlice()->getPPS()->getMinCuDQPSize() )
+  {
+    iMinQP = iBaseQP;
+    iMaxQP = iBaseQP;
+  }
+  else
+  {
+    const Int iStartQP = rpcTempCU->getQP(0);
+    iMinQP = iStartQP;
+    iMaxQP = iStartQP;
+  }
+
+  if ( m_pcEncCfg->getUseRateCtrl() )
+  {
+    iMinQP = m_pcRateCtrl->getRCQP();
+    iMaxQP = m_pcRateCtrl->getRCQP();
+  }
+
+  if ( m_pcEncCfg->getCUTransquantBypassFlagForceValue() )
+  {
+    iMaxQP = iMinQP; // If all TUs are forced into using transquant bypass, do not loop here.
+  }
+
+  for (Int iQP=iMinQP; iQP<=iMaxQP; iQP++)
+  {
+    const Bool bIsLosslessMode = false; // False at this level. Next level down may set it to true.
+
+    rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
+
+    // further split
+    if( bSubBranch && uiDepth < g_uiMaxCUDepth - g_uiAddCUDepth )
+    {
+      UChar       uhNextDepth         = uiDepth+1;
+      TComDataCU* pcSubBestPartCU     = m_ppcBestCU[uhNextDepth];
+      TComDataCU* pcSubTempPartCU     = m_ppcTempCU[uhNextDepth];
+      DEBUG_STRING_NEW(sTempDebug)
+
+      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.
+
+#if REPN_FORMAT_IN_VPS
+        if( ( pcSubBestPartCU->getCUPelX() < pcSlice->getPicWidthInLumaSamples() ) && ( pcSubBestPartCU->getCUPelY() < pcSlice->getPicHeightInLumaSamples() ) )
+#else
+        if( ( pcSubBestPartCU->getCUPelX() < pcSlice->getSPS()->getPicWidthInLumaSamples() ) && ( pcSubBestPartCU->getCUPelY() < pcSlice->getSPS()->getPicHeightInLumaSamples() ) )
+#endif
+        {
+          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
+          DEBUG_STRING_NEW(sChild)
+          if ( !rpcBestCU->isInter(0) )
+          {
+            xCompressCU( pcSubBestPartCU, pcSubTempPartCU, uhNextDepth DEBUG_STRING_PASS_INTO(sChild), NUMBER_OF_PART_SIZES );
+          }
+          else
+          {
+
+            xCompressCU( pcSubBestPartCU, pcSubTempPartCU, uhNextDepth DEBUG_STRING_PASS_INTO(sChild), rpcBestCU->getPartitionSize(0) );
+          }
+          DEBUG_STRING_APPEND(sTempDebug, sChild)
+#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
+        {
+          pcSubBestPartCU->copyToPic( uhNextDepth );
+          rpcTempCU->copyPartFrom( pcSubBestPartCU, uiPartUnitIdx, uhNextDepth );
+        }
+      }
+
+      if( !bBoundary )
+      {
+        m_pcEntropyCoder->resetBits();
+        m_pcEntropyCoder->encodeSplitFlag( rpcTempCU, 0, uiDepth, true );
+
+        rpcTempCU->getTotalBits() += m_pcEntropyCoder->getNumberOfWrittenBits(); // split bits
+        rpcTempCU->getTotalBins() += ((TEncBinCABAC *)((TEncSbac*)m_pcEntropyCoder->m_pcEntropyCoderIf)->getEncBinIf())->getBinsCoded();
+      }
+      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( (     rpcTempCU->getCbf(uiBlkIdx, COMPONENT_Y)
+                || (rpcTempCU->getCbf(uiBlkIdx, COMPONENT_Cb) && (numberValidComponents > COMPONENT_Cb))
+                || (rpcTempCU->getCbf(uiBlkIdx, COMPONENT_Cr) && (numberValidComponents > COMPONENT_Cr)) ) )
+          {
+            hasResidual = true;
+            break;
+          }
+        }
+
+        UInt uiTargetPartIdx = 0;
+        if ( hasResidual )
+        {
+#if !RDO_WITHOUT_DQP_BITS
+          m_pcEntropyCoder->resetBits();
+          m_pcEntropyCoder->encodeQP( rpcTempCU, uiTargetPartIdx, false );
+          rpcTempCU->getTotalBits() += m_pcEntropyCoder->getNumberOfWrittenBits(); // dQP bits
+          rpcTempCU->getTotalBins() += ((TEncBinCABAC *)((TEncSbac*)m_pcEntropyCoder->m_pcEntropyCoderIf)->getEncBinIf())->getBinsCoded();
+          rpcTempCU->getTotalCost()  = m_pcRdCost->calcRdCost( rpcTempCU->getTotalBits(), rpcTempCU->getTotalDistortion() );
+#endif
+
+          Bool foundNonZeroCbf = false;
+          rpcTempCU->setQPSubCUs( rpcTempCU->getRefQP( uiTargetPartIdx ), 0, uiDepth, foundNonZeroCbf );
+          assert( foundNonZeroCbf );
+        }
+        else
+        {
+          rpcTempCU->setQPSubParts( rpcTempCU->getRefQP( uiTargetPartIdx ), 0, uiDepth ); // set QP to default QP
+        }
+      }
+
+      m_pppcRDSbacCoder[uhNextDepth][CI_NEXT_BEST]->store(m_pppcRDSbacCoder[uiDepth][CI_TEMP_BEST]);
+
+      // TODO: this does not account for the slice bytes already written. See other instances of FIXED_NUMBER_OF_BYTES
+      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)
+      {
+        if (m_pcEncCfg->getCostMode()==COST_MIXED_LOSSLESS_LOSSY_CODING)
+          rpcBestCU->getTotalCost()=rpcTempCU->getTotalCost() + (1.0 / m_pcRdCost->getLambda());
+        else
+          rpcBestCU->getTotalCost()=rpcTempCU->getTotalCost()+1;
+      }
+
+      xCheckBestMode( rpcBestCU, rpcTempCU, uiDepth DEBUG_STRING_PASS_INTO(sDebug) DEBUG_STRING_PASS_INTO(sTempDebug) DEBUG_STRING_PASS_INTO(false) ); // RD compare current larger prediction
+                                                                                       // with sub partitioned prediction.
+    }
+  }
+
+  DEBUG_STRING_APPEND(sDebug_, sDebug);
+
+  rpcBestCU->copyToPic(uiDepth);                                                     // Copy Best data to Picture for next partition prediction.
+
+  xCopyYuv2Pic( rpcBestCU->getPic(), rpcBestCU->getCtuRsAddr(), rpcBestCU->getZorderIdxInCtu(), uiDepth, uiDepth, rpcBestCU, uiLPelX, uiTPelY );   // Copy Yuv data to picture Yuv
+  if (bBoundary)
+  {
+    return;
+  }
+
+  // Assert if Best prediction mode is NONE
+  // Selected mode's RD-cost must be not MAX_DOUBLE.
+  assert( rpcBestCU->getPartitionSize ( 0 ) != NUMBER_OF_PART_SIZES       );
+  assert( rpcBestCU->getPredictionMode( 0 ) != NUMBER_OF_PREDICTION_MODES );
+  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
+  const Int  currentCTUTsAddr = pcPic->getPicSym()->getCtuRsToTsAddrMap(pcCU->getCtuRsAddr());
+  const Bool isLastSubCUOfCtu = pcCU->isLastSubCUOfCtu(uiAbsPartIdx);
+  if ( isLastSubCUOfCtu )
+  {
+    // The 1-terminating bit is added to all streams, so don't add it here when it's 1.
+    // i.e. when the slice segment CurEnd CTU address is the current CTU address+1.
+    if (pcSlice->getSliceSegmentCurEndCtuTsAddr() != currentCTUTsAddr+1)
+    {
+      m_pcEntropyCoder->encodeTerminatingBit( 0 );
+    }
+  }
+}
+
+/** 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 ));
+  }
+#if REPN_FORMAT_IN_VPS
+  return Clip3(-pcCU->getSlice()->getQpBDOffsetY(), MAX_QP, iBaseQp+iQpOffset );
+#else
+  return Clip3(-pcCU->getSlice()->getSPS()->getQpBDOffset(CHANNEL_TYPE_LUMA), MAX_QP, iBaseQp+iQpOffset );
+#endif
+}
+
+/** 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;
+
+  TComSlice * pcSlice = pcCU->getPic()->getSlice(pcCU->getPic()->getCurrSliceIdx());
+#if HIGHER_LAYER_IRAP_SKIP_FLAG
+  if (m_pcEncCfg->getSkipPictureAtArcSwitch() && m_pcEncCfg->getAdaptiveResolutionChange() > 0 && pcSlice->getLayerId() == 1 && pcSlice->getPOC() == m_pcEncCfg->getAdaptiveResolutionChange())
+  {
+    pcCU->setSkipFlagSubParts(true, uiAbsPartIdx, uiDepth);
+  }
+#endif
+
+#if REPN_FORMAT_IN_VPS
+  if( ( uiRPelX < pcSlice->getPicWidthInLumaSamples() ) && ( uiBPelY < pcSlice->getPicHeightInLumaSamples() ) )
+#else
+  if( ( uiRPelX < pcSlice->getSPS()->getPicWidthInLumaSamples() ) && ( uiBPelY < pcSlice->getSPS()->getPicHeightInLumaSamples() ) )
+#endif
+  {
+    m_pcEntropyCoder->encodeSplitFlag( pcCU, uiAbsPartIdx, uiDepth );
+  }
+  else
+  {
+    bBoundary = true;
+  }
+
+  if( ( ( uiDepth < pcCU->getDepth( uiAbsPartIdx ) ) && ( uiDepth < (g_uiMaxCUDepth-g_uiAddCUDepth) ) ) || bBoundary )
+  {
+    UInt uiQNumParts = ( pcPic->getNumPartitionsInCtu() >> (uiDepth<<1) )>>2;
+    if( (g_uiMaxCUWidth>>uiDepth) == pcCU->getSlice()->getPPS()->getMinCuDQPSize() && pcCU->getSlice()->getPPS()->getUseDQP())
+    {
+      setdQPFlag(true);
+    }
+
+    if( (g_uiMaxCUWidth>>uiDepth) == pcCU->getSlice()->getPPS()->getMinCuChromaQpAdjSize() && pcCU->getSlice()->getUseChromaQpAdj())
+    {
+      setCodeChromaQpAdjFlag(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] ];
+#if REPN_FORMAT_IN_VPS
+      if( ( uiLPelX < pcSlice->getPicWidthInLumaSamples() ) && ( uiTPelY < pcSlice->getPicHeightInLumaSamples() ) )
+#else
+      if( ( uiLPelX < pcSlice->getSPS()->getPicWidthInLumaSamples() ) && ( uiTPelY < pcSlice->getSPS()->getPicHeightInLumaSamples() ) )
+#endif
+      {
+        xEncodeCU( pcCU, uiAbsPartIdx, uiDepth+1 );
+      }
+    }
+    return;
+  }
+
+  if( (g_uiMaxCUWidth>>uiDepth) >= pcCU->getSlice()->getPPS()->getMinCuDQPSize() && pcCU->getSlice()->getPPS()->getUseDQP())
+  {
+    setdQPFlag(true);
+  }
+
+  if( (g_uiMaxCUWidth>>uiDepth) >= pcCU->getSlice()->getPPS()->getMinCuChromaQpAdjSize() && pcCU->getSlice()->getUseChromaQpAdj())
+  {
+    setCodeChromaQpAdjFlag(true);
+  }
+
+  if (pcCU->getSlice()->getPPS()->getTransquantBypassEnableFlag())
+  {
+    m_pcEntropyCoder->encodeCUTransquantBypassFlag( pcCU, uiAbsPartIdx );
+  }
+
+  if( !pcCU->getSlice()->isIntra() )
+  {
+    m_pcEntropyCoder->encodeSkipFlag( pcCU, uiAbsPartIdx );
+  }
+
+  if( pcCU->isSkipped( uiAbsPartIdx ) )
+  {
+    m_pcEntropyCoder->encodeMergeIndex( pcCU, uiAbsPartIdx );
+    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 );
+
+  // Encode Coefficients
+  Bool bCodeDQP = getdQPFlag();
+  Bool codeChromaQpAdj = getCodeChromaQpAdjFlag();
+  m_pcEntropyCoder->encodeCoeff( pcCU, uiAbsPartIdx, uiDepth, bCodeDQP, codeChromaQpAdj );
+  setCodeChromaQpAdjFlag( codeChromaQpAdj );
+  setdQPFlag( bCodeDQP );
+
+  // --- write terminating bit ---
+  finishCU(pcCU,uiAbsPartIdx,uiDepth);
+}
+
+Int xCalcHADs8x8_ISlice(Pel *piOrg, Int iStrideOrg)
+{
+  Int k, i, j, jj;
+  Int diff[64], m1[8][8], m2[8][8], m3[8][8], iSumHad = 0;
+
+  for( k = 0; k < 64; k += 8 )
+  {
+    diff[k+0] = piOrg[0] ;
+    diff[k+1] = piOrg[1] ;
+    diff[k+2] = piOrg[2] ;
+    diff[k+3] = piOrg[3] ;
+    diff[k+4] = piOrg[4] ;
+    diff[k+5] = piOrg[5] ;
+    diff[k+6] = piOrg[6] ;
+    diff[k+7] = piOrg[7] ;
+
+    piOrg += iStrideOrg;
+  }
+
+  //horizontal
+  for (j=0; j < 8; j++)
+  {
+    jj = j << 3;
+    m2[j][0] = diff[jj  ] + diff[jj+4];
+    m2[j][1] = diff[jj+1] + diff[jj+5];
+    m2[j][2] = diff[jj+2] + diff[jj+6];
+    m2[j][3] = diff[jj+3] + diff[jj+7];
+    m2[j][4] = diff[jj  ] - diff[jj+4];
+    m2[j][5] = diff[jj+1] - diff[jj+5];
+    m2[j][6] = diff[jj+2] - diff[jj+6];
+    m2[j][7] = diff[jj+3] - diff[jj+7];
+
+    m1[j][0] = m2[j][0] + m2[j][2];
+    m1[j][1] = m2[j][1] + m2[j][3];
+    m1[j][2] = m2[j][0] - m2[j][2];
+    m1[j][3] = m2[j][1] - m2[j][3];
+    m1[j][4] = m2[j][4] + m2[j][6];
+    m1[j][5] = m2[j][5] + m2[j][7];
+    m1[j][6] = m2[j][4] - m2[j][6];
+    m1[j][7] = m2[j][5] - m2[j][7];
+
+    m2[j][0] = m1[j][0] + m1[j][1];
+    m2[j][1] = m1[j][0] - m1[j][1];
+    m2[j][2] = m1[j][2] + m1[j][3];
+    m2[j][3] = m1[j][2] - m1[j][3];
+    m2[j][4] = m1[j][4] + m1[j][5];
+    m2[j][5] = m1[j][4] - m1[j][5];
+    m2[j][6] = m1[j][6] + m1[j][7];
+    m2[j][7] = m1[j][6] - m1[j][7];
+  }
+
+  //vertical
+  for (i=0; i < 8; i++)
+  {
+    m3[0][i] = m2[0][i] + m2[4][i];
+    m3[1][i] = m2[1][i] + m2[5][i];
+    m3[2][i] = m2[2][i] + m2[6][i];
+    m3[3][i] = m2[3][i] + m2[7][i];
+    m3[4][i] = m2[0][i] - m2[4][i];
+    m3[5][i] = m2[1][i] - m2[5][i];
+    m3[6][i] = m2[2][i] - m2[6][i];
+    m3[7][i] = m2[3][i] - m2[7][i];
+
+    m1[0][i] = m3[0][i] + m3[2][i];
+    m1[1][i] = m3[1][i] + m3[3][i];
+    m1[2][i] = m3[0][i] - m3[2][i];
+    m1[3][i] = m3[1][i] - m3[3][i];
+    m1[4][i] = m3[4][i] + m3[6][i];
+    m1[5][i] = m3[5][i] + m3[7][i];
+    m1[6][i] = m3[4][i] - m3[6][i];
+    m1[7][i] = m3[5][i] - m3[7][i];
+
+    m2[0][i] = m1[0][i] + m1[1][i];
+    m2[1][i] = m1[0][i] - m1[1][i];
+    m2[2][i] = m1[2][i] + m1[3][i];
+    m2[3][i] = m1[2][i] - m1[3][i];
+    m2[4][i] = m1[4][i] + m1[5][i];
+    m2[5][i] = m1[4][i] - m1[5][i];
+    m2[6][i] = m1[6][i] + m1[7][i];
+    m2[7][i] = m1[6][i] - m1[7][i];
+  }
+
+  for (i = 0; i < 8; i++)
+  {
+    for (j = 0; j < 8; j++)
+    {
+      iSumHad += abs(m2[i][j]);
+    }
+  }
+  iSumHad -= abs(m2[0][0]);
+  iSumHad =(iSumHad+2)>>2;
+  return(iSumHad);
+}
+
+Int  TEncCu::updateCtuDataISlice(TComDataCU* pCtu, Int width, Int height)
+{
+  Int  xBl, yBl;
+  const Int iBlkSize = 8;
+
+  Pel* pOrgInit   = pCtu->getPic()->getPicYuvOrg()->getAddr(COMPONENT_Y, pCtu->getCtuRsAddr(), 0);
+  Int  iStrideOrig = pCtu->getPic()->getPicYuvOrg()->getStride(COMPONENT_Y);
+  Pel  *pOrg;
+
+  Int iSumHad = 0;
+  for ( yBl=0; (yBl+iBlkSize)<=height; yBl+= iBlkSize)
+  {
+    for ( xBl=0; (xBl+iBlkSize)<=width; xBl+= iBlkSize)
+    {
+      pOrg = pOrgInit + iStrideOrig*yBl + xBl;
+      iSumHad += xCalcHADs8x8_ISlice(pOrg, iStrideOrig);
+    }
+  }
+  return(iSumHad);
+}
+
+/** check RD costs for a CU block encoded with merge
+ * \param rpcBestCU
+ * \param rpcTempCU
+ * \returns Void
+ */
+#if HIGHER_LAYER_IRAP_SKIP_FLAG
+Void TEncCu::xCheckRDCostMerge2Nx2N( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU DEBUG_STRING_FN_DECLARE(sDebug), Bool *earlyDetectionSkipMode, Bool bUseSkip )
+#else
+Void TEncCu::xCheckRDCostMerge2Nx2N( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU DEBUG_STRING_FN_DECLARE(sDebug), Bool *earlyDetectionSkipMode )
+#endif
+{
+  assert( rpcTempCU->getSlice()->getSliceType() != I_SLICE );
+  TComMvField  cMvFieldNeighbours[2 * MRG_MAX_NUM_CANDS]; // double length for mv of both lists
+  UChar uhInterDirNeighbours[MRG_MAX_NUM_CANDS];
+  Int numValidMergeCand = 0;
+  const Bool bTransquantBypassFlag = rpcTempCU->getCUTransquantBypass(0);
+
+  for( UInt ui = 0; ui < rpcTempCU->getSlice()->getMaxNumMergeCand(); ++ui )
+  {
+    uhInterDirNeighbours[ui] = 0;
+  }
+  UChar uhDepth = rpcTempCU->getDepth( 0 );
+  rpcTempCU->setPartSizeSubParts( SIZE_2Nx2N, 0, uhDepth ); // interprets depth relative to CTU level
+  rpcTempCU->getInterMergeCandidates( 0, 0, cMvFieldNeighbours,uhInterDirNeighbours, numValidMergeCand );
+
+  Int mergeCandBuffer[MRG_MAX_NUM_CANDS];
+  for( UInt ui = 0; ui < numValidMergeCand; ++ui )
+  {
+    mergeCandBuffer[ui] = 0;
+  }
+
+  Bool bestIsSkip = false;
+
+  UInt iteration;
+  if ( rpcTempCU->isLosslessCoded(0))
+  {
+    iteration = 1;
+  }
+  else
+  {
+    iteration = 2;
+  }
+  DEBUG_STRING_NEW(bestStr)
+
+#if HIGHER_LAYER_IRAP_SKIP_FLAG
+  for( UInt uiNoResidual = bUseSkip?1:0; uiNoResidual < iteration; ++uiNoResidual )
+#else
+  for( UInt uiNoResidual = 0; uiNoResidual < iteration; ++uiNoResidual )
+#endif
+  {
+    for( UInt uiMergeCand = 0; uiMergeCand < numValidMergeCand; ++uiMergeCand )
+    {
+#if REF_IDX_ME_ZEROMV
+      Bool bZeroMVILR = rpcTempCU->xCheckZeroMVILRMerge(uhInterDirNeighbours[uiMergeCand], cMvFieldNeighbours[0 + 2*uiMergeCand], cMvFieldNeighbours[1 + 2*uiMergeCand]);
+      if(bZeroMVILR)
+      {
+#endif
+#if N0383_IL_CONSTRAINED_TILE_SETS_SEI
+      if (!(rpcTempCU->isInterLayerReference(uhInterDirNeighbours[uiMergeCand], cMvFieldNeighbours[0 + 2*uiMergeCand], cMvFieldNeighbours[1 + 2*uiMergeCand]) && m_disableILP))
+      {
+#endif
+      if(!(uiNoResidual==1 && mergeCandBuffer[uiMergeCand]==1))
+      {
+        if( !(bestIsSkip && uiNoResidual == 0) )
+        {
+          DEBUG_STRING_NEW(tmpStr)
+          // set MC parameters
+          rpcTempCU->setPredModeSubParts( MODE_INTER, 0, uhDepth ); // interprets depth relative to CTU level
+          rpcTempCU->setCUTransquantBypassSubParts( bTransquantBypassFlag, 0, uhDepth );
+          rpcTempCU->setChromaQpAdjSubParts( bTransquantBypassFlag ? 0 : m_ChromaQpAdjIdc, 0, uhDepth );
+          rpcTempCU->setPartSizeSubParts( SIZE_2Nx2N, 0, uhDepth ); // interprets depth relative to CTU level
+          rpcTempCU->setMergeFlagSubParts( true, 0, 0, uhDepth ); // interprets depth relative to CTU level
+          rpcTempCU->setMergeIndexSubParts( uiMergeCand, 0, 0, uhDepth ); // interprets depth relative to CTU level
+          rpcTempCU->setInterDirSubParts( uhInterDirNeighbours[uiMergeCand], 0, 0, uhDepth ); // interprets depth relative to CTU level
+          rpcTempCU->getCUMvField( REF_PIC_LIST_0 )->setAllMvField( cMvFieldNeighbours[0 + 2*uiMergeCand], SIZE_2Nx2N, 0, 0 ); // interprets depth relative to rpcTempCU level
+          rpcTempCU->getCUMvField( REF_PIC_LIST_1 )->setAllMvField( cMvFieldNeighbours[1 + 2*uiMergeCand], SIZE_2Nx2N, 0, 0 ); // interprets depth relative to rpcTempCU level
+
+          // do MC
+          m_pcPredSearch->motionCompensation ( rpcTempCU, m_ppcPredYuvTemp[uhDepth] );
+          // estimate residual and encode everything
+          m_pcPredSearch->encodeResAndCalcRdInterCU( rpcTempCU,
+                                                     m_ppcOrigYuv    [uhDepth],
+                                                     m_ppcPredYuvTemp[uhDepth],
+                                                     m_ppcResiYuvTemp[uhDepth],
+                                                     m_ppcResiYuvBest[uhDepth],
+                                                     m_ppcRecoYuvTemp[uhDepth],
+                                                     (uiNoResidual != 0) DEBUG_STRING_PASS_INTO(tmpStr) );
+
+#ifdef DEBUG_STRING
+          DebugInterPredResiReco(tmpStr, *(m_ppcPredYuvTemp[uhDepth]), *(m_ppcResiYuvBest[uhDepth]), *(m_ppcRecoYuvTemp[uhDepth]), DebugStringGetPredModeMask(rpcTempCU->getPredictionMode(0)));
+#endif
+
+          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 DEBUG_STRING_PASS_INTO(bestStr) DEBUG_STRING_PASS_INTO(tmpStr));
+
+          rpcTempCU->initEstData( uhDepth, orgQP, bTransquantBypassFlag );
+
+          if( m_pcEncCfg->getUseFastDecisionForMerge() && !bestIsSkip )
+          {
+            bestIsSkip = rpcBestCU->getQtRootCbf(0) == 0;
+          }
+        }
+      }
+#if N0383_IL_CONSTRAINED_TILE_SETS_SEI
+      }
+#endif
+#if REF_IDX_ME_ZEROMV 
+      }
+#endif
+    }
+
+    if(uiNoResidual == 0 && m_pcEncCfg->getUseEarlySkipDetection())
+    {
+      if(rpcBestCU->getQtRootCbf( 0 ) == 0)
+      {
+        if( rpcBestCU->getMergeFlag( 0 ))
+        {
+          *earlyDetectionSkipMode = true;
+        }
+        else if(m_pcEncCfg->getFastSearch() != SELECTIVE)
+        {
+          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;
+          }
+        }
+      }
+    }
+  }
+  DEBUG_STRING_APPEND(sDebug, bestStr)
+}
+
+
+#if AMP_MRG
+Void TEncCu::xCheckRDCostInter( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, PartSize ePartSize DEBUG_STRING_FN_DECLARE(sDebug), Bool bUseMRG)
+#else
+Void TEncCu::xCheckRDCostInter( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, PartSize ePartSize )
+#endif
+{
+  DEBUG_STRING_NEW(sTest)
+
+  UChar uhDepth = rpcTempCU->getDepth( 0 );
+
+  rpcTempCU->setDepthSubParts( uhDepth, 0 );
+
+  rpcTempCU->setSkipFlagSubParts( false, 0, uhDepth );
+
+  rpcTempCU->setPartSizeSubParts  ( ePartSize,  0, uhDepth );
+  rpcTempCU->setPredModeSubParts  ( MODE_INTER, 0, uhDepth );
+  rpcTempCU->setChromaQpAdjSubParts( rpcTempCU->getCUTransquantBypass(0) ? 0 : m_ChromaQpAdjIdc, 0, uhDepth );
+  
+#if SVC_EXTENSION
+#if AMP_MRG
+  rpcTempCU->setMergeAMP (true);
+  Bool ret = m_pcPredSearch->predInterSearch ( rpcTempCU, m_ppcOrigYuv[uhDepth], m_ppcPredYuvTemp[uhDepth], m_ppcResiYuvTemp[uhDepth], m_ppcRecoYuvTemp[uhDepth] DEBUG_STRING_PASS_INTO(sTest), false, bUseMRG );
+#else  
+  Bool ret = m_pcPredSearch->predInterSearch ( rpcTempCU, m_ppcOrigYuv[uhDepth], m_ppcPredYuvTemp[uhDepth], m_ppcResiYuvTemp[uhDepth], m_ppcRecoYuvTemp[uhDepth] );
+#endif
+
+  if( !ret )
+  {
+    return;
+  }
+#else
+#if AMP_MRG
+  rpcTempCU->setMergeAMP (true);
+  m_pcPredSearch->predInterSearch ( rpcTempCU, m_ppcOrigYuv[uhDepth], m_ppcPredYuvTemp[uhDepth], m_ppcResiYuvTemp[uhDepth], m_ppcRecoYuvTemp[uhDepth] DEBUG_STRING_PASS_INTO(sTest), false, bUseMRG );
+#else
+  m_pcPredSearch->predInterSearch ( rpcTempCU, m_ppcOrigYuv[uhDepth], m_ppcPredYuvTemp[uhDepth], m_ppcResiYuvTemp[uhDepth], m_ppcRecoYuvTemp[uhDepth] );
+#endif
+#endif
+
+#if AMP_MRG
+  if ( !rpcTempCU->getMergeAMP() )
+  {
+    return;
+  }
+#endif
+
+  m_pcPredSearch->encodeResAndCalcRdInterCU( rpcTempCU, m_ppcOrigYuv[uhDepth], m_ppcPredYuvTemp[uhDepth], m_ppcResiYuvTemp[uhDepth], m_ppcResiYuvBest[uhDepth], m_ppcRecoYuvTemp[uhDepth], false DEBUG_STRING_PASS_INTO(sTest) );
+  rpcTempCU->getTotalCost()  = m_pcRdCost->calcRdCost( rpcTempCU->getTotalBits(), rpcTempCU->getTotalDistortion() );
+
+#ifdef DEBUG_STRING
+  DebugInterPredResiReco(sTest, *(m_ppcPredYuvTemp[uhDepth]), *(m_ppcResiYuvBest[uhDepth]), *(m_ppcRecoYuvTemp[uhDepth]), DebugStringGetPredModeMask(rpcTempCU->getPredictionMode(0)));
+#endif
+
+  xCheckDQP( rpcTempCU );
+  xCheckBestMode(rpcBestCU, rpcTempCU, uhDepth DEBUG_STRING_PASS_INTO(sDebug) DEBUG_STRING_PASS_INTO(sTest));
+}
+
+Void TEncCu::xCheckRDCostIntra( TComDataCU *&rpcBestCU,
+                                TComDataCU *&rpcTempCU,
+                                Double      &cost,
+                                PartSize     eSize
+                                DEBUG_STRING_FN_DECLARE(sDebug) )
+{
+  DEBUG_STRING_NEW(sTest)
+
+  UInt uiDepth = rpcTempCU->getDepth( 0 );
+
+  rpcTempCU->setSkipFlagSubParts( false, 0, uiDepth );
+
+  rpcTempCU->setPartSizeSubParts( eSize, 0, uiDepth );
+  rpcTempCU->setPredModeSubParts( MODE_INTRA, 0, uiDepth );
+  rpcTempCU->setChromaQpAdjSubParts( rpcTempCU->getCUTransquantBypass(0) ? 0 : m_ChromaQpAdjIdc, 0, uiDepth );
+
+  Bool bSeparateLumaChroma = true; // choose estimation mode
+
+  Distortion uiPreCalcDistC = 0;
+  if (rpcBestCU->getPic()->getChromaFormat()==CHROMA_400)
+  {
+    bSeparateLumaChroma=true;
+  }
+
+  Pel resiLuma[NUMBER_OF_STORED_RESIDUAL_TYPES][MAX_CU_SIZE * MAX_CU_SIZE];
+
+  if( !bSeparateLumaChroma )
+  {
+    // after this function, the direction will be PLANAR, DC, HOR or VER
+    // however, if Luma ends up being one of those, the chroma dir must be later changed to DM_CHROMA.
+    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], resiLuma, uiPreCalcDistC, bSeparateLumaChroma DEBUG_STRING_PASS_INTO(sTest) );
+
+  m_ppcRecoYuvTemp[uiDepth]->copyToPicComponent(COMPONENT_Y, rpcTempCU->getPic()->getPicYuvRec(), rpcTempCU->getCtuRsAddr(), rpcTempCU->getZorderIdxInCtu() );
+
+  if (rpcBestCU->getPic()->getChromaFormat()!=CHROMA_400)
+  {
+    m_pcPredSearch->estIntraPredChromaQT( rpcTempCU, m_ppcOrigYuv[uiDepth], m_ppcPredYuvTemp[uiDepth], m_ppcResiYuvTemp[uiDepth], m_ppcRecoYuvTemp[uiDepth], resiLuma, uiPreCalcDistC DEBUG_STRING_PASS_INTO(sTest) );
+  }
+
+  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 );
+  m_pcEntropyCoder->encodeIPCMInfo(rpcTempCU, 0, true );
+
+  // Encode Coefficients
+  Bool bCodeDQP = getdQPFlag();
+  Bool codeChromaQpAdjFlag = getCodeChromaQpAdjFlag();
+  m_pcEntropyCoder->encodeCoeff( rpcTempCU, 0, uiDepth, bCodeDQP, codeChromaQpAdjFlag );
+  setCodeChromaQpAdjFlag( codeChromaQpAdjFlag );
+  setdQPFlag( bCodeDQP );
+
+  m_pcRDGoOnSbacCoder->store(m_pppcRDSbacCoder[uiDepth][CI_TEMP_BEST]);
+
+  rpcTempCU->getTotalBits() = m_pcEntropyCoder->getNumberOfWrittenBits();
+  rpcTempCU->getTotalBins() = ((TEncBinCABAC *)((TEncSbac*)m_pcEntropyCoder->m_pcEntropyCoderIf)->getEncBinIf())->getBinsCoded();
+  rpcTempCU->getTotalCost() = m_pcRdCost->calcRdCost( rpcTempCU->getTotalBits(), rpcTempCU->getTotalDistortion() );
+
+  xCheckDQP( rpcTempCU );
+
+  cost = rpcTempCU->getTotalCost();
+
+  xCheckBestMode(rpcBestCU, rpcTempCU, uiDepth DEBUG_STRING_PASS_INTO(sDebug) DEBUG_STRING_PASS_INTO(sTest));
+}
+
+
+/** 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->setChromaQpAdjSubParts( rpcTempCU->getCUTransquantBypass(0) ? 0 : m_ChromaQpAdjIdc, 0, uiDepth );
+
+  m_pcPredSearch->IPCMSearch( rpcTempCU, m_ppcOrigYuv[uiDepth], m_ppcPredYuvTemp[uiDepth], m_ppcResiYuvTemp[uiDepth], m_ppcRecoYuvTemp[uiDepth]);
+
+  m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[uiDepth][CI_CURR_BEST]);
+
+  m_pcEntropyCoder->resetBits();
+
+  if ( rpcTempCU->getSlice()->getPPS()->getTransquantBypassEnableFlag())
+  {
+    m_pcEntropyCoder->encodeCUTransquantBypassFlag( rpcTempCU, 0,          true );
+  }
+
+  m_pcEntropyCoder->encodeSkipFlag ( rpcTempCU, 0,          true );
+  m_pcEntropyCoder->encodePredMode ( rpcTempCU, 0,          true );
+  m_pcEntropyCoder->encodePartSize ( rpcTempCU, 0, uiDepth, true );
+  m_pcEntropyCoder->encodeIPCMInfo ( rpcTempCU, 0, true );
+
+  m_pcRDGoOnSbacCoder->store(m_pppcRDSbacCoder[uiDepth][CI_TEMP_BEST]);
+
+  rpcTempCU->getTotalBits() = m_pcEntropyCoder->getNumberOfWrittenBits();
+  rpcTempCU->getTotalBins() = ((TEncBinCABAC *)((TEncSbac*)m_pcEntropyCoder->m_pcEntropyCoderIf)->getEncBinIf())->getBinsCoded();
+  rpcTempCU->getTotalCost() = m_pcRdCost->calcRdCost( rpcTempCU->getTotalBits(), rpcTempCU->getTotalDistortion() );
+
+  xCheckDQP( rpcTempCU );
+  DEBUG_STRING_NEW(a)
+  DEBUG_STRING_NEW(b)
+  xCheckBestMode(rpcBestCU, rpcTempCU, uiDepth DEBUG_STRING_PASS_INTO(a) DEBUG_STRING_PASS_INTO(b));
+}
+
+/** 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 DEBUG_STRING_FN_DECLARE(sParent) DEBUG_STRING_FN_DECLARE(sTest) DEBUG_STRING_PASS_INTO(Bool bAddSizeInfo) )
+{
+  if( rpcTempCU->getTotalCost() < rpcBestCU->getTotalCost() )
+  {
+    TComYuv* pcYuv;
+    // Change Information data
+    TComDataCU* pcCU = rpcBestCU;
+    rpcBestCU = rpcTempCU;
+    rpcTempCU = pcCU;
+
+    // Change Prediction data
+    pcYuv = m_ppcPredYuvBest[uiDepth];
+    m_ppcPredYuvBest[uiDepth] = m_ppcPredYuvTemp[uiDepth];
+    m_ppcPredYuvTemp[uiDepth] = pcYuv;
+
+    // Change Reconstruction data
+    pcYuv = m_ppcRecoYuvBest[uiDepth];
+    m_ppcRecoYuvBest[uiDepth] = m_ppcRecoYuvTemp[uiDepth];
+    m_ppcRecoYuvTemp[uiDepth] = pcYuv;
+
+    pcYuv = NULL;
+    pcCU  = NULL;
+
+    // store temp best CI for next CU coding
+    m_pppcRDSbacCoder[uiDepth][CI_TEMP_BEST]->store(m_pppcRDSbacCoder[uiDepth][CI_NEXT_BEST]);
+
+
+#ifdef DEBUG_STRING
+    DEBUG_STRING_SWAP(sParent, sTest)
+    const PredMode predMode=rpcBestCU->getPredictionMode(0);
+    if ((DebugOptionList::DebugString_Structure.getInt()&DebugStringGetPredModeMask(predMode)) && bAddSizeInfo)
+    {
+      std::stringstream ss(stringstream::out);
+      ss <<"###: " << (predMode==MODE_INTRA?"Intra   ":"Inter   ") << partSizeToString[rpcBestCU->getPartitionSize(0)] << " CU at " << rpcBestCU->getCUPelX() << ", " << rpcBestCU->getCUPelY() << " width=" << UInt(rpcBestCU->getWidth(0)) << std::endl;
+      sParent+=ss.str();
+    }
+#endif
+  }
+}
+
+Void TEncCu::xCheckDQP( TComDataCU* pcCU )
+{
+  UInt uiDepth = pcCU->getDepth( 0 );
+
+  if( pcCU->getSlice()->getPPS()->getUseDQP() && (g_uiMaxCUWidth>>uiDepth) >= pcCU->getSlice()->getPPS()->getMinCuDQPSize() )
+  {
+    if ( pcCU->getQtRootCbf( 0) )
+    {
+#if !RDO_WITHOUT_DQP_BITS
+      m_pcEntropyCoder->resetBits();
+      m_pcEntropyCoder->encodeQP( pcCU, 0, false );
+      pcCU->getTotalBits() += m_pcEntropyCoder->getNumberOfWrittenBits(); // dQP bits
+      pcCU->getTotalBins() += ((TEncBinCABAC *)((TEncSbac*)m_pcEntropyCoder->m_pcEntropyCoderIf)->getEncBinIf())->getBinsCoded();
+      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 uiAbsPartIdxInRaster = g_auiZscanToRaster[uiAbsPartIdx];
+  UInt uiSrcBlkWidth = rpcPic->getNumPartInCtuWidth() >> (uiSrcDepth);
+  UInt uiBlkWidth    = rpcPic->getNumPartInCtuWidth() >> (uiDepth);
+  UInt uiPartIdxX = ( ( uiAbsPartIdxInRaster % rpcPic->getNumPartInCtuWidth() ) % uiSrcBlkWidth) / uiBlkWidth;
+  UInt uiPartIdxY = ( ( uiAbsPartIdxInRaster / rpcPic->getNumPartInCtuWidth() ) % uiSrcBlkWidth) / uiBlkWidth;
+  UInt uiPartIdx = uiPartIdxY * ( uiSrcBlkWidth / uiBlkWidth ) + uiPartIdxX;
+  m_ppcRecoYuvBest[uiSrcDepth]->copyToPicYuv( rpcPic->getPicYuvRec (), uiCUAddr, uiAbsPartIdx, uiDepth - uiSrcDepth, uiPartIdx);
+
+  m_ppcPredYuvBest[uiSrcDepth]->copyToPicYuv( rpcPic->getPicYuvPred (), uiCUAddr, uiAbsPartIdx, uiDepth - uiSrcDepth, uiPartIdx);
+}
+
+Void TEncCu::xCopyYuv2Tmp( UInt uiPartUnitIdx, UInt uiNextDepth )
+{
+  UInt uiCurrDepth = uiNextDepth - 1;
+  m_ppcRecoYuvBest[uiNextDepth]->copyToPartYuv( m_ppcRecoYuvTemp[uiCurrDepth], uiPartUnitIdx );
+  m_ppcPredYuvBest[uiNextDepth]->copyToPartYuv( m_ppcPredYuvBest[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 )
+{
+  const ChromaFormat format = pCU->getPic()->getChromaFormat();
+  const UInt numberValidComponents = getNumberValidComponents(format);
+  for (UInt componentIndex = 0; componentIndex < numberValidComponents; componentIndex++)
+  {
+    const ComponentID component = ComponentID(componentIndex);
+
+    const UInt width  = pCU->getWidth(0)  >> getComponentScaleX(component, format);
+    const UInt height = pCU->getHeight(0) >> getComponentScaleY(component, format);
+
+    Pel *source      = pOrgYuv->getAddr(component, 0, width);
+    Pel *destination = pCU->getPCMSample(component);
+
+    const UInt sourceStride = pOrgYuv->getStride(component);
+
+    for (Int line = 0; line < height; line++)
+    {
+      for (Int column = 0; column < width; column++)
+      {
+        destination[column] = source[column];
+      }
+
+      source      += sourceStride;
+      destination += width;
+    }
+  }
+}
+
+#if ADAPTIVE_QP_SELECTION
+/** Collect ARL statistics from one block
+  */
+Int TEncCu::xTuCollectARLStats(TCoeff* rpcCoeff, TCoeff* rpcArlCoeff, Int NumCoeffInCU, Double* cSum, UInt* numSamples )
+{
+  for( Int n = 0; n < NumCoeffInCU; n++ )
+  {
+    TCoeff u = abs( rpcCoeff[ n ] );
+    TCoeff 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 CTU
+ * \param pcCU
+ */
+Void TEncCu::xCtuCollectARLStats(TComDataCU* pCtu )
+{
+  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 = pCtu->getCoeff(COMPONENT_Y);
+  TCoeff* pArlCoeffY = pCtu->getArlCoeff(COMPONENT_Y);
+
+  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 < pCtu->getTotalNumPart(); i ++ )
+  {
+    UInt uiTrIdx = pCtu->getTransformIdx(i);
+
+    if(pCtu->isInter(i) && pCtu->getCbf( i, COMPONENT_Y, uiTrIdx ) )
+    {
+      xTuCollectARLStats(pCoeffY, pArlCoeffY, uiMinNumCoeffInCU, cSum, numSamples);
+    }//Note that only InterY is processed. QP rounding is based on InterY data only.
+
+    pCoeffY  += uiMinNumCoeffInCU;
+    pArlCoeffY  += uiMinNumCoeffInCU;
+  }
+
+  for(Int u=1; u<LEVEL_RANGE;u++)
+  {
+    m_pcTrQuant->getSliceSumC()[u] += cSum[ u ] ;
+    m_pcTrQuant->getSliceNSamples()[u] += numSamples[ u ] ;
+  }
+  m_pcTrQuant->getSliceSumC()[LEVEL_RANGE] += cSum[ LEVEL_RANGE ] ;
+  m_pcTrQuant->getSliceNSamples()[LEVEL_RANGE] += numSamples[ LEVEL_RANGE ] ;
+}
+#endif
+
+#if SVC_EXTENSION
+#if N0383_IL_CONSTRAINED_TILE_SETS_SEI
+Bool TEncCu::xCheckTileSetConstraint( TComDataCU*& rpcCU )
+{
+  Bool disableILP = false;
+
+  if (rpcCU->getLayerId() == (m_pcEncCfg->getNumLayer() - 1)  && m_pcEncCfg->getInterLayerConstrainedTileSetsSEIEnabled() && rpcCU->getPic()->getPicSym()->getTileSetIdxMap(rpcCU->getCtuRsAddr()) >= 0)
+  {
+    if (rpcCU->getPic()->getPicSym()->getTileSetType(rpcCU->getCtuRsAddr()) == 2)
+    {
+      disableILP = true;
+    }
+    if (rpcCU->getPic()->getPicSym()->getTileSetType(rpcCU->getCtuRsAddr()) == 1)
+    {
+      Int currCUaddr = rpcCU->getCtuRsAddr();
+      Int frameWitdhInCU  = rpcCU->getPic()->getPicSym()->getFrameWidthInCtus();
+      Int frameHeightInCU = rpcCU->getPic()->getPicSym()->getFrameHeightInCtus();
+      Bool leftCUExists   = (currCUaddr % frameWitdhInCU) > 0;
+      Bool aboveCUExists  = (currCUaddr / frameWitdhInCU) > 0;
+      Bool rightCUExists  = (currCUaddr % frameWitdhInCU) < (frameWitdhInCU - 1);
+      Bool belowCUExists  = (currCUaddr / frameWitdhInCU) < (frameHeightInCU - 1);
+      Int currTileSetIdx  = rpcCU->getPic()->getPicSym()->getTileSetIdxMap(currCUaddr);
+      // Check if CU is at tile set boundary
+      if ( (leftCUExists && rpcCU->getPic()->getPicSym()->getTileSetIdxMap(currCUaddr-1) != currTileSetIdx) ||
+           (leftCUExists && aboveCUExists && rpcCU->getPic()->getPicSym()->getTileSetIdxMap(currCUaddr-frameWitdhInCU-1) != currTileSetIdx) ||
+           (aboveCUExists && rpcCU->getPic()->getPicSym()->getTileSetIdxMap(currCUaddr-frameWitdhInCU) != currTileSetIdx) ||
+           (aboveCUExists && rightCUExists && rpcCU->getPic()->getPicSym()->getTileSetIdxMap(currCUaddr-frameWitdhInCU+1) != currTileSetIdx) ||
+           (rightCUExists && rpcCU->getPic()->getPicSym()->getTileSetIdxMap(currCUaddr+1) != currTileSetIdx) ||
+           (rightCUExists && belowCUExists && rpcCU->getPic()->getPicSym()->getTileSetIdxMap(currCUaddr+frameWitdhInCU+1) != currTileSetIdx) ||
+           (belowCUExists && rpcCU->getPic()->getPicSym()->getTileSetIdxMap(currCUaddr+frameWitdhInCU) != currTileSetIdx) ||
+           (belowCUExists && leftCUExists && rpcCU->getPic()->getPicSym()->getTileSetIdxMap(currCUaddr+frameWitdhInCU-1) != currTileSetIdx) )
+      {
+        disableILP = true;  // Disable ILP in tile set boundary CU
+      }
+    }
+  }
+
+  return disableILP;
+}
+
+Void TEncCu::xVerifyTileSetConstraint( TComDataCU*& rpcCU )
+{
+  if (rpcCU->getLayerId() == (m_pcEncCfg->getNumLayer() - 1)  && m_pcEncCfg->getInterLayerConstrainedTileSetsSEIEnabled() && rpcCU->getPic()->getPicSym()->getTileSetIdxMap(rpcCU->getCtuRsAddr()) >= 0 &&
+      m_disableILP)
+  {
+    UInt numPartitions = rpcCU->getPic()->getNumPartitionsInCtu();
+    for (UInt i = 0; i < numPartitions; i++)
+    {
+      if (!rpcCU->isIntra(i))
+      {
+        for (UInt refList = 0; refList < 2; refList++)
+        {
+          if (rpcCU->getInterDir(i) & (1<<refList))
+          {
+            TComCUMvField *mvField = rpcCU->getCUMvField(RefPicList(refList));
+            if (mvField->getRefIdx(i) >= 0)
+            {
+              assert(!(rpcCU->getSlice()->getRefPic(RefPicList(refList), mvField->getRefIdx(i))->isILR(rpcCU->getLayerId())));
+            }
+          }
+        }
+      }
+    }
+  }
+}
+#endif
+
+#if ENCODER_FAST_MODE
+Void TEncCu::xCheckRDCostILRUni(TComDataCU *&rpcBestCU, TComDataCU *&rpcTempCU, UInt refLayerId)
+{
+  UChar uhDepth = rpcTempCU->getDepth( 0 );
+  rpcTempCU->setDepthSubParts( uhDepth, 0 );
+#if SKIP_FLAG
+  rpcTempCU->setSkipFlagSubParts( false, 0, uhDepth );
+#endif
+  rpcTempCU->setPartSizeSubParts  ( SIZE_2Nx2N,  0, uhDepth );  //2Nx2N
+  rpcTempCU->setPredModeSubParts  ( MODE_INTER, 0, uhDepth );
+  rpcTempCU->setCUTransquantBypassSubParts  ( m_pcEncCfg->getCUTransquantBypassFlagForceValue(), 0, uhDepth );
+  Bool exitILR = m_pcPredSearch->predInterSearchILRUni( rpcTempCU, m_ppcOrigYuv[uhDepth], m_ppcPredYuvTemp[uhDepth], m_ppcResiYuvTemp[uhDepth], m_ppcRecoYuvTemp[uhDepth], refLayerId );
+  if(!exitILR)
+  {
+     return;
+  }
+  m_pcPredSearch->encodeResAndCalcRdInterCU( rpcTempCU, m_ppcOrigYuv[uhDepth], m_ppcPredYuvTemp[uhDepth], m_ppcResiYuvTemp[uhDepth], m_ppcResiYuvBest[uhDepth], m_ppcRecoYuvTemp[uhDepth], false );
+  rpcTempCU->getTotalCost()  = m_pcRdCost->calcRdCost( rpcTempCU->getTotalBits(), rpcTempCU->getTotalDistortion() );
+  xCheckDQP( rpcTempCU );
+  xCheckBestMode(rpcBestCU, rpcTempCU, uhDepth);
+  return;
+}
+#endif
+#endif //SVC_EXTENSION
+//! \}
Index: /tags/SHM-9.0/source/Lib/TLibEncoder/TEncCu.h
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibEncoder/TEncCu.h	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibEncoder/TEncCu.h	(revision 1088)
@@ -0,0 +1,197 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TEncCu.h
+    \brief    Coding Unit (CU) encoder class (header)
+*/
+
+#ifndef __TENCCU__
+#define __TENCCU__
+
+// Include files
+#include "TLibCommon/CommonDef.h"
+#include "TLibCommon/TComYuv.h"
+#include "TLibCommon/TComPrediction.h"
+#include "TLibCommon/TComTrQuant.h"
+#include "TLibCommon/TComBitCounter.h"
+#include "TLibCommon/TComDataCU.h"
+
+#include "TEncEntropy.h"
+#include "TEncSearch.h"
+#include "TEncRateCtrl.h"
+//! \ingroup TLibEncoder
+//! \{
+
+class TEncTop;
+class TEncSbac;
+class TEncCavlc;
+class TEncSlice;
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// CU encoder class
+class TEncCu
+{
+private:
+
+  TComDataCU**            m_ppcBestCU;      ///< Best CUs in each depth
+  TComDataCU**            m_ppcTempCU;      ///< Temporary CUs in each depth
+  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;
+  Bool                    m_CodeChromaQpAdjFlag;
+  Int                     m_ChromaQpAdjIdc;
+
+  //  Access channel
+  TEncCfg*                m_pcEncCfg;
+  TEncSearch*             m_pcPredSearch;
+  TComTrQuant*            m_pcTrQuant;
+  TComRdCost*             m_pcRdCost;
+
+  TEncEntropy*            m_pcEntropyCoder;
+  TEncBinCABAC*           m_pcBinCABAC;
+
+  // SBAC RD
+  TEncSbac***             m_pppcRDSbacCoder;
+  TEncSbac*               m_pcRDGoOnSbacCoder;
+  TEncRateCtrl*           m_pcRateCtrl;
+
+#if SVC_EXTENSION
+  TEncTop**               m_ppcTEncTop;
+#if N0383_IL_CONSTRAINED_TILE_SETS_SEI
+  Bool                    m_disableILP;
+#endif
+#endif //SVC_EXTENSION
+public:
+  /// copy parameters from encoder class
+  Void  init                ( TEncTop* pcEncTop );
+
+  /// create internal buffers
+  Void  create              ( UChar uhTotalDepth, UInt iMaxWidth, UInt iMaxHeight, ChromaFormat chromaFormat );
+
+  /// destroy internal buffers
+  Void  destroy             ();
+
+  /// CTU analysis function
+  Void  compressCtu         ( TComDataCU*  pCtu );
+
+  /// CTU encoding function
+  Void  encodeCtu           ( TComDataCU*  pCtu );
+
+  Int   updateCtuDataISlice ( TComDataCU* pCtu, Int width, Int height );
+
+protected:
+  Void  finishCU            ( TComDataCU*  pcCU, UInt uiAbsPartIdx,           UInt uiDepth        );
+#if AMP_ENC_SPEEDUP
+  Void  xCompressCU         ( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, UInt uiDepth DEBUG_STRING_FN_DECLARE(sDebug), PartSize eParentPartSize = NUMBER_OF_PART_SIZES );
+#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 DEBUG_STRING_FN_DECLARE(sParent) DEBUG_STRING_FN_DECLARE(sTest) DEBUG_STRING_PASS_INTO(Bool bAddSizeInfo=true));
+#if HIGHER_LAYER_IRAP_SKIP_FLAG
+  Void  xCheckRDCostMerge2Nx2N( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU DEBUG_STRING_FN_DECLARE(sDebug), Bool *earlyDetectionSkipMode, Bool bUseSkip=false);
+#else  
+  Void  xCheckRDCostMerge2Nx2N( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU DEBUG_STRING_FN_DECLARE(sDebug), Bool *earlyDetectionSkipMode );
+#endif
+
+#if AMP_MRG
+  Void  xCheckRDCostInter   ( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, PartSize ePartSize DEBUG_STRING_FN_DECLARE(sDebug), Bool bUseMRG = false  );
+#else
+  Void  xCheckRDCostInter   ( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, PartSize ePartSize  );
+#endif
+
+  Void  xCheckRDCostIntra   ( TComDataCU *&rpcBestCU,
+                              TComDataCU *&rpcTempCU,
+                              Double      &cost,
+                              PartSize     ePartSize
+                              DEBUG_STRING_FN_DECLARE(sDebug)
+                            );
+
+  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;           }
+
+  Bool getCodeChromaQpAdjFlag() { return m_CodeChromaQpAdjFlag; }
+  Void setCodeChromaQpAdjFlag( Bool b ) { m_CodeChromaQpAdjFlag = b; }
+
+#if ADAPTIVE_QP_SELECTION
+  // Adaptive reconstruction level (ARL) statistics collection functions
+  Void xCtuCollectARLStats(TComDataCU* pCtu);
+  Int  xTuCollectARLStats(TCoeff* rpcCoeff, TCoeff* rpcArlCoeff, Int NumCoeffInCU, Double* cSum, UInt* numSamples );
+#endif
+
+#if AMP_ENC_SPEEDUP
+#if AMP_MRG
+  Void deriveTestModeAMP (TComDataCU *pcBestCU, PartSize eParentPartSize, Bool &bTestAMP_Hor, Bool &bTestAMP_Ver, Bool &bTestMergeAMP_Hor, Bool &bTestMergeAMP_Ver);
+#else
+  Void deriveTestModeAMP (TComDataCU *pcBestCU, PartSize eParentPartSize, Bool &bTestAMP_Hor, Bool &bTestAMP_Ver);
+#endif
+#endif
+
+  Void  xFillPCMBuffer     ( TComDataCU* pCU, TComYuv* pOrgYuv );
+
+#if SVC_EXTENSION
+  TEncTop*   getLayerEnc(UInt layerIdx)  {return m_ppcTEncTop[layerIdx]; }
+#if ENCODER_FAST_MODE
+  Void  xCheckRDCostILRUni  ( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, UInt refLayerId);
+#endif
+#if N0383_IL_CONSTRAINED_TILE_SETS_SEI
+  Bool xCheckTileSetConstraint( TComDataCU*& rpcCU );
+  Void xVerifyTileSetConstraint( TComDataCU*& rpcCU );
+#endif
+#endif //SVC_EXTENSION
+};
+
+//! \}
+
+#endif // __TENCMB__
Index: /tags/SHM-9.0/source/Lib/TLibEncoder/TEncEntropy.cpp
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibEncoder/TEncEntropy.cpp	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibEncoder/TEncEntropy.cpp	(revision 1088)
@@ -0,0 +1,756 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TEncEntropy.cpp
+    \brief    entropy encoder class
+*/
+
+#include "TEncEntropy.h"
+#include "TLibCommon/TypeDef.h"
+#include "TLibCommon/TComSampleAdaptiveOffset.h"
+#include "TLibCommon/TComTU.h"
+
+#if ENVIRONMENT_VARIABLE_DEBUG_AND_TEST
+#include "../TLibCommon/Debug.h"
+static const Bool bDebugPredEnabled = DebugOptionList::DebugPred.getInt()!=0;
+#endif
+
+//! \ingroup TLibEncoder
+//! \{
+
+Void TEncEntropy::setEntropyCoder ( TEncEntropyIf* e, TComSlice* pcSlice )
+{
+  m_pcEntropyCoderIf = e;
+  m_pcEntropyCoderIf->setSlice ( pcSlice );
+}
+
+Void TEncEntropy::encodeSliceHeader ( TComSlice* pcSlice )
+{
+  m_pcEntropyCoderIf->codeSliceHeader( pcSlice );
+  return;
+}
+
+Void  TEncEntropy::encodeTilesWPPEntryPoint( TComSlice* pSlice )
+{
+  m_pcEntropyCoderIf->codeTilesWPPEntryPoint( pSlice );
+}
+
+Void TEncEntropy::encodeTerminatingBit      ( UInt uiIsLast )
+{
+  m_pcEntropyCoderIf->codeTerminatingBit( uiIsLast );
+
+  return;
+}
+
+Void TEncEntropy::encodeSliceFinish()
+{
+  m_pcEntropyCoderIf->codeSliceFinish();
+}
+
+#if Q0048_CGS_3D_ASYMLUT
+Void TEncEntropy::encodePPS( TComPPS* pcPPS, TEnc3DAsymLUT * pc3DAsymLUT  )
+{
+  m_pcEntropyCoderIf->codePPS( pcPPS, pc3DAsymLUT );
+  return;
+}
+#else
+Void TEncEntropy::encodePPS( TComPPS* pcPPS )
+{
+  m_pcEntropyCoderIf->codePPS( pcPPS );
+  return;
+}
+#endif
+
+Void TEncEntropy::encodeSPS( TComSPS* pcSPS )
+{
+  m_pcEntropyCoderIf->codeSPS( pcSPS );
+  return;
+}
+
+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 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 );
+}
+
+
+/** 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( bRD )
+  {
+    uiAbsPartIdx = 0;
+  }
+
+  m_pcEntropyCoderIf->codeIPCMInfo ( pcCU, uiAbsPartIdx );
+
+}
+
+Void TEncEntropy::xEncodeTransform( Bool& bCodeDQP, Bool& codeChromaQpAdj, TComTU &rTu )
+{
+//pcCU, absPartIdxCU, uiAbsPartIdx, uiDepth+1, uiTrIdx+1, quadrant,
+  TComDataCU *pcCU=rTu.getCU();
+  const UInt uiAbsPartIdx=rTu.GetAbsPartIdxTU();
+  const UInt numValidComponent = pcCU->getPic()->getNumberValidComponents();
+  const Bool bChroma = isChromaEnabled(pcCU->getPic()->getChromaFormat());
+  const UInt uiTrIdx = rTu.GetTransformDepthRel();
+  const UInt uiDepth = rTu.GetTransformDepthTotal();
+#if ENVIRONMENT_VARIABLE_DEBUG_AND_TEST
+  const Bool bDebugRQT=g_bFinalEncode && DebugOptionList::DebugRQT.getInt()!=0;
+  if (bDebugRQT)
+    printf("x..codeTransform: offsetLuma=%d offsetChroma=%d absPartIdx=%d, uiDepth=%d\n width=%d, height=%d, uiTrIdx=%d, uiInnerQuadIdx=%d\n",
+           rTu.getCoefficientOffset(COMPONENT_Y), rTu.getCoefficientOffset(COMPONENT_Cb), uiAbsPartIdx, uiDepth, rTu.getRect(COMPONENT_Y).width, rTu.getRect(COMPONENT_Y).height, rTu.GetTransformDepthRel(), rTu.GetSectionNumber());
+#endif
+  const UInt uiSubdiv = pcCU->getTransformIdx( uiAbsPartIdx ) > uiTrIdx;// + pcCU->getDepth( uiAbsPartIdx ) > uiDepth;
+  const UInt uiLog2TrafoSize = rTu.GetLog2LumaTrSize();
+
+
+  UInt cbf[MAX_NUM_COMPONENT] = {0,0,0};
+  Bool bHaveACodedBlock       = false;
+  Bool bHaveACodedChromaBlock = false;
+
+  for(UInt ch=0; ch<numValidComponent; ch++)
+  {
+    const ComponentID compID = ComponentID(ch);
+
+    cbf[compID] = pcCU->getCbf( uiAbsPartIdx, compID , uiTrIdx );
+    
+    if (cbf[ch] != 0)
+    {
+      bHaveACodedBlock = true;
+      if (isChroma(compID)) bHaveACodedChromaBlock = true;
+    }
+  }
+
+  if( pcCU->isIntra(uiAbsPartIdx) && pcCU->getPartitionSize(uiAbsPartIdx) == SIZE_NxN && uiDepth == pcCU->getDepth(uiAbsPartIdx) )
+  {
+    assert( uiSubdiv );
+  }
+  else if( pcCU->isInter(uiAbsPartIdx) && (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;
+
+  for(UInt ch=COMPONENT_Cb; ch<numValidComponent; ch++)
+  {
+    const ComponentID compID=ComponentID(ch);
+    if( bFirstCbfOfCU || rTu.ProcessingAllQuadrants(compID) )
+    {
+      if( bFirstCbfOfCU || pcCU->getCbf( uiAbsPartIdx, compID, uiTrDepthCurr - 1 ) )
+      {
+        m_pcEntropyCoderIf->codeQtCbf( rTu, compID, (uiSubdiv == 0) );
+      }
+    }
+    else
+    {
+      assert( pcCU->getCbf( uiAbsPartIdx, compID, uiTrDepthCurr ) == pcCU->getCbf( uiAbsPartIdx, compID, uiTrDepthCurr - 1 ) );
+    }
+  }
+
+  if( uiSubdiv )
+  {
+    TComTURecurse tuRecurseChild(rTu, true);
+    do
+    {
+      xEncodeTransform( bCodeDQP, codeChromaQpAdj, tuRecurseChild );
+    }
+    while (tuRecurseChild.nextSection(rTu));
+  }
+  else
+  {
+    {
+      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" );
+    }
+
+    if( !pcCU->isIntra(uiAbsPartIdx) && uiDepth == pcCU->getDepth( uiAbsPartIdx ) && (!bChroma || (!pcCU->getCbf( uiAbsPartIdx, COMPONENT_Cb, 0 ) && !pcCU->getCbf( uiAbsPartIdx, COMPONENT_Cr, 0 ) ) ) )
+    {
+      assert( pcCU->getCbf( uiAbsPartIdx, COMPONENT_Y, 0 ) );
+      //      printf( "saved one bin! " );
+    }
+    else
+    {
+      m_pcEntropyCoderIf->codeQtCbf( rTu, COMPONENT_Y, true ); //luma CBF is always at the lowest level
+    }
+
+    if ( bHaveACodedBlock )
+    {
+      // dQP: only for CTU once
+      if ( pcCU->getSlice()->getPPS()->getUseDQP() )
+      {
+        if ( bCodeDQP )
+        {
+          encodeQP( pcCU, rTu.GetAbsPartIdxCU() );
+          bCodeDQP = false;
+        }
+      }
+
+      if ( pcCU->getSlice()->getUseChromaQpAdj() )
+      {
+        if ( bHaveACodedChromaBlock && codeChromaQpAdj && !pcCU->getCUTransquantBypass(rTu.GetAbsPartIdxCU()) )
+        {
+          encodeChromaQpAdjustment( pcCU, rTu.GetAbsPartIdxCU() );
+          codeChromaQpAdj = false;
+        }
+      }
+
+      const UInt numValidComp=pcCU->getPic()->getNumberValidComponents();
+
+      for(UInt ch=COMPONENT_Y; ch<numValidComp; ch++)
+      {
+        const ComponentID compID=ComponentID(ch);
+
+        if (rTu.ProcessComponentSection(compID))
+        {
+#if ENVIRONMENT_VARIABLE_DEBUG_AND_TEST
+          if (bDebugRQT) printf("Call NxN for chan %d width=%d height=%d cbf=%d\n", compID, rTu.getRect(compID).width, rTu.getRect(compID).height, 1);
+#endif
+
+          if (rTu.getRect(compID).width != rTu.getRect(compID).height)
+          {
+            //code two sub-TUs
+            TComTURecurse subTUIterator(rTu, false, TComTU::VERTICAL_SPLIT, true, compID);
+
+            do
+            {
+              const UChar subTUCBF = pcCU->getCbf(subTUIterator.GetAbsPartIdxTU(compID), compID, (uiTrIdx + 1));
+
+              if (subTUCBF != 0)
+              {
+#if ENVIRONMENT_VARIABLE_DEBUG_AND_TEST
+                if (bDebugRQT) printf("Call NxN for chan %d width=%d height=%d cbf=%d\n", compID, subTUIterator.getRect(compID).width, subTUIterator.getRect(compID).height, 1);
+#endif
+                m_pcEntropyCoderIf->codeCoeffNxN( subTUIterator, (pcCU->getCoeff(compID) + subTUIterator.getCoefficientOffset(compID)), compID );
+              }
+            }
+            while (subTUIterator.nextSection(rTu));
+          }
+          else
+          {
+            if (isChroma(compID) && (cbf[COMPONENT_Y] != 0))
+            {
+              m_pcEntropyCoderIf->codeCrossComponentPrediction( rTu, compID );
+            }
+
+            if (cbf[compID] != 0)
+            {
+              m_pcEntropyCoderIf->codeCoeffNxN( rTu, (pcCU->getCoeff(compID) + rTu.getCoefficientOffset(compID)), compID );
+            }
+          }
+        }
+      }
+    }
+  }
+}
+
+
+// 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 )
+{
+  m_pcEntropyCoderIf->codeIntraDirChroma( pcCU, uiAbsPartIdx );
+
+#if ENVIRONMENT_VARIABLE_DEBUG_AND_TEST
+  if (bDebugPredEnabled && g_bFinalEncode)
+  {
+    UInt cdir=pcCU->getIntraDir(CHANNEL_TYPE_CHROMA, uiAbsPartIdx);
+    if (cdir==36) cdir=pcCU->getIntraDir(CHANNEL_TYPE_LUMA, uiAbsPartIdx);
+    printf("coding chroma Intra dir: %d, uiAbsPartIdx: %d, luma dir: %d\n", cdir, uiAbsPartIdx, pcCU->getIntraDir(CHANNEL_TYPE_LUMA, uiAbsPartIdx));
+  }
+#endif
+}
+
+
+Void TEncEntropy::encodePredInfo( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  if( pcCU->isIntra( uiAbsPartIdx ) )                                 // If it is Intra mode, encode intra prediction mode.
+  {
+    encodeIntraDirModeLuma  ( pcCU, uiAbsPartIdx,true );
+    if (pcCU->getPic()->getChromaFormat()!=CHROMA_400)
+    {
+      encodeIntraDirModeChroma( pcCU, uiAbsPartIdx );
+
+      if (enable4ChromaPUsInIntraNxNCU(pcCU->getPic()->getChromaFormat()) && pcCU->getPartitionSize( uiAbsPartIdx )==SIZE_NxN)
+      {
+        UInt uiPartOffset = ( pcCU->getPic()->getNumPartitionsInCtu() >> ( pcCU->getDepth(uiAbsPartIdx) << 1 ) ) >> 2;
+        encodeIntraDirModeChroma( pcCU, uiAbsPartIdx + uiPartOffset   );
+        encodeIntraDirModeChroma( pcCU, uiAbsPartIdx + uiPartOffset*2 );
+        encodeIntraDirModeChroma( pcCU, uiAbsPartIdx + uiPartOffset*3 );
+      }
+    }
+  }
+  else                                                                // if it is Inter mode, encode motion vector and reference index
+  {
+    encodePUWise( pcCU, uiAbsPartIdx );
+  }
+}
+
+Void TEncEntropy::encodeCrossComponentPrediction( TComTU &rTu, ComponentID compID )
+{
+  m_pcEntropyCoderIf->codeCrossComponentPrediction( rTu, compID );
+}
+
+/** encode motion information for every PU block
+ * \param pcCU
+ * \param uiAbsPartIdx
+ * \param bRD
+ * \returns Void
+ */
+Void TEncEntropy::encodePUWise( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+#if ENVIRONMENT_VARIABLE_DEBUG_AND_TEST
+  const Bool bDebugPred = bDebugPredEnabled && g_bFinalEncode;
+#endif
+
+  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 )
+  {
+    encodeMergeFlag( pcCU, uiSubPartIdx );
+    if ( pcCU->getMergeFlag( uiSubPartIdx ) )
+    {
+      encodeMergeIndex( pcCU, uiSubPartIdx );
+#if ENVIRONMENT_VARIABLE_DEBUG_AND_TEST
+      if (bDebugPred)
+      {
+        std::cout << "Coded merge flag, CU absPartIdx: " << uiAbsPartIdx << " PU(" << uiPartIdx << ") absPartIdx: " << uiSubPartIdx;
+        std::cout << " merge index: " << (UInt)pcCU->getMergeIndex(uiSubPartIdx) << std::endl;
+      }
+#endif
+    }
+    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 ) );
+#if ENVIRONMENT_VARIABLE_DEBUG_AND_TEST
+          if (bDebugPred)
+          {
+            std::cout << "refListIdx: " << uiRefListIdx << std::endl;
+            std::cout << "MVD horizontal: " << pcCU->getCUMvField(RefPicList(uiRefListIdx))->getMvd( uiAbsPartIdx ).getHor() << std::endl;
+            std::cout << "MVD vertical:   " << pcCU->getCUMvField(RefPicList(uiRefListIdx))->getMvd( uiAbsPartIdx ).getVer() << std::endl;
+            std::cout << "MVPIdxPU: " << pcCU->getMVPIdx(RefPicList( uiRefListIdx ), uiSubPartIdx) << std::endl;
+            std::cout << "InterDir: " << (UInt)pcCU->getInterDir(uiSubPartIdx) << std::endl;
+          }
+#endif
+        }
+      }
+    }
+  }
+
+  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->isInter( 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->isInter( 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( TComTU &rTu, const ComponentID compID, const Bool lowestLevel )
+{
+  m_pcEntropyCoderIf->codeQtCbf( rTu, compID, lowestLevel );
+}
+
+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( TComTU &rTu, const ChannelType chType )
+{
+  m_pcEntropyCoderIf->codeQtCbfZero( rTu, chType );
+}
+
+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 );
+  }
+}
+
+/** encode chroma qp adjustment
+ * \returns Void
+ */
+Void TEncEntropy::encodeChromaQpAdjustment( TComDataCU* cu, UInt absPartIdx, Bool inRd )
+{
+  if( inRd )
+  {
+    absPartIdx = 0;
+  }
+
+  m_pcEntropyCoderIf->codeChromaQpAdjustment( cu, absPartIdx );
+}
+
+// texture
+
+/** encode coefficients
+ * \param pcCU
+ * \param uiAbsPartIdx
+ * \param uiDepth
+ * \param uiWidth
+ * \param uiHeight
+ */
+Void TEncEntropy::encodeCoeff( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, Bool& bCodeDQP, Bool& codeChromaQpAdj )
+{
+#if ENVIRONMENT_VARIABLE_DEBUG_AND_TEST
+  const Bool bDebugRQT=g_bFinalEncode && DebugOptionList::DebugRQT.getInt()!=0;
+#endif
+
+  if( pcCU->isIntra(uiAbsPartIdx) )
+  {
+    if (false)
+    {
+      DTRACE_CABAC_VL( g_nSymbolCounter++ )
+      DTRACE_CABAC_T( "\tdecodeTransformIdx()\tCUDepth=" )
+      DTRACE_CABAC_V( uiDepth )
+      DTRACE_CABAC_T( "\n" )
+    }
+  }
+  else
+  {
+    if( !(pcCU->getMergeFlag( uiAbsPartIdx ) && pcCU->getPartitionSize(uiAbsPartIdx) == SIZE_2Nx2N ) )
+    {
+      m_pcEntropyCoderIf->codeQtRootCbf( pcCU, uiAbsPartIdx );
+    }
+    if ( !pcCU->getQtRootCbf( uiAbsPartIdx ) )
+    {
+      return;
+    }
+  }
+
+  TComTURecurse tuRecurse(pcCU, uiAbsPartIdx, uiDepth);
+#if ENVIRONMENT_VARIABLE_DEBUG_AND_TEST
+  if (bDebugRQT) printf("..codeCoeff: uiAbsPartIdx=%d, PU format=%d, 2Nx2N=%d, NxN=%d\n", uiAbsPartIdx, pcCU->getPartitionSize(uiAbsPartIdx), SIZE_2Nx2N, SIZE_NxN);
+#endif
+
+  xEncodeTransform( bCodeDQP, codeChromaQpAdj, tuRecurse );
+}
+
+Void TEncEntropy::encodeCoeffNxN( TComTU &rTu, TCoeff* pcCoef, const ComponentID compID)
+{
+  TComDataCU *pcCU = rTu.getCU();
+
+  if (pcCU->getCbf(rTu.GetAbsPartIdxTU(), compID, rTu.GetTransformDepthRel()) != 0)
+  {
+    if (rTu.getRect(compID).width != rTu.getRect(compID).height)
+    {
+      //code two sub-TUs
+      TComTURecurse subTUIterator(rTu, false, TComTU::VERTICAL_SPLIT, true, compID);
+
+      const UInt subTUSize = subTUIterator.getRect(compID).width * subTUIterator.getRect(compID).height;
+
+      do
+      {
+        const UChar subTUCBF = pcCU->getCbf(subTUIterator.GetAbsPartIdxTU(compID), compID, (subTUIterator.GetTransformDepthRel() + 1));
+
+        if (subTUCBF != 0)
+        {
+          m_pcEntropyCoderIf->codeCoeffNxN( subTUIterator, (pcCoef + (subTUIterator.GetSectionNumber() * subTUSize)), compID);
+        }
+      }
+      while (subTUIterator.nextSection(rTu));
+    }
+    else
+    {
+      m_pcEntropyCoderIf->codeCoeffNxN(rTu, pcCoef, compID);
+    }
+  }
+}
+
+Void TEncEntropy::estimateBit (estBitsSbacStruct* pcEstBitsSbac, Int width, Int height, const ChannelType chType)
+{
+  const UInt heightAtEntropyCoding = (width != height) ? (height >> 1) : height;
+
+  m_pcEntropyCoderIf->estBit ( pcEstBitsSbac, width, heightAtEntropyCoding, chType );
+}
+
+Int TEncEntropy::countNonZeroCoeffs( TCoeff* pcCoef, UInt uiSize )
+{
+  Int count = 0;
+
+  for ( Int i = 0; i < uiSize; i++ )
+  {
+    count += pcCoef[i] != 0;
+  }
+
+  return count;
+}
+
+/** encode quantization matrix
+ * \param scalingList quantization matrix information
+ */
+Void TEncEntropy::encodeScalingList( TComScalingList* scalingList )
+{
+  m_pcEntropyCoderIf->codeScalingList( scalingList );
+}
+
+#if POC_RESET_IDC_SIGNALLING
+Void  TEncEntropy::encodeSliceHeaderExtn( TComSlice* pSlice, Int shBitsWrittenTillNow )
+{
+  m_pcEntropyCoderIf->codeSliceHeaderExtn( pSlice, shBitsWrittenTillNow );
+}
+#endif
+
+//! \}
Index: /tags/SHM-9.0/source/Lib/TLibEncoder/TEncEntropy.h
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibEncoder/TEncEntropy.h	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibEncoder/TEncEntropy.h	(revision 1088)
@@ -0,0 +1,217 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TEncEntropy.h
+    \brief    entropy encoder class (header)
+*/
+
+#ifndef __TENCENTROPY__
+#define __TENCENTROPY__
+
+#include "TLibCommon/TComSlice.h"
+#include "TLibCommon/TComDataCU.h"
+#include "TLibCommon/TComBitStream.h"
+#include "TLibCommon/ContextModel.h"
+#include "TLibCommon/TComPic.h"
+#include "TLibCommon/TComTrQuant.h"
+#include "TLibCommon/TComSampleAdaptiveOffset.h"
+#include "TLibCommon/TComChromaFormat.h"
+
+class TEncSbac;
+class TEncCavlc;
+class SEI;
+#if Q0048_CGS_3D_ASYMLUT
+class TEnc3DAsymLUT;
+#endif
+
+// ====================================================================================================================
+// 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 UInt  getNumberOfWrittenBits()                = 0;
+
+  virtual Void  codeVPS                 ( TComVPS* pcVPS )                                      = 0;
+  virtual Void  codeSPS                 ( TComSPS* pcSPS )                                      = 0;
+  virtual Void  codePPS                 ( TComPPS* pcPPS 
+#if Q0048_CGS_3D_ASYMLUT
+    , TEnc3DAsymLUT * pc3DAsymLUT
+#endif
+    )                                      = 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;
+
+#if POC_RESET_IDC_SIGNALLING
+  virtual Void codeSliceHeaderExtn     ( TComSlice* pSlice, Int shBitsWrittenTillNow )     = 0;
+#endif
+
+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;
+  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         ( TComTU &rTu, const ComponentID compID, const Bool lowestLevel ) = 0;
+  virtual Void codeQtRootCbf     ( TComDataCU* pcCU, UInt uiAbsPartIdx ) = 0;
+  virtual Void codeQtCbfZero     ( TComTU &rTu, const ChannelType chType ) = 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 codeCrossComponentPrediction( TComTU &rTu, ComponentID compID ) = 0;
+
+  virtual Void codeDeltaQP       ( TComDataCU* pcCU, UInt uiAbsPartIdx ) = 0;
+  virtual Void codeChromaQpAdjustment( TComDataCU* pcCU, UInt uiAbsPartIdx ) = 0;
+  virtual Void codeCoeffNxN      ( TComTU &rTu, TCoeff* pcCoef, const ComponentID compID ) = 0;
+  virtual Void codeTransformSkipFlags ( TComTU &rTu, ComponentID component ) = 0;
+#if SVC_EXTENSION
+  virtual Void codeSAOBlkParam   (SAOBlkParam& saoBlkParam, UInt* saoMaxOffsetQVal, Bool* sliceEnabled, Bool leftMergeAvail, Bool aboveMergeAvail, Bool onlyEstMergeInfo = false)    =0;
+#else
+  virtual Void codeSAOBlkParam   (SAOBlkParam& saoBlkParam, Bool* sliceEnabled, Bool leftMergeAvail, Bool aboveMergeAvail, Bool onlyEstMergeInfo = false)    =0;
+#endif
+  virtual Void estBit               (estBitsSbacStruct* pcEstBitsSbac, Int width, Int height, ChannelType chType) = 0;
+
+  virtual Void codeDFFlag (UInt uiCode, const Char *pSymbolName) = 0;
+  virtual Void codeDFSvlc (Int iCode, const Char *pSymbolName)   = 0;
+
+  virtual Void codeExplicitRdpcmMode ( TComTU &rTu, const ComponentID compID ) = 0;
+
+  virtual ~TEncEntropyIf() {}
+};
+
+/// entropy encoder class
+class TEncEntropy
+{
+public:
+  Void    setEntropyCoder           ( TEncEntropyIf* e, TComSlice* pcSlice );
+  Void    setBitstream              ( TComBitIf* p )          { m_pcEntropyCoderIf->setBitstream(p);  }
+  Void    resetBits                 ()                        { m_pcEntropyCoderIf->resetBits();      }
+  UInt    getNumberOfWrittenBits    ()                        { return m_pcEntropyCoderIf->getNumberOfWrittenBits(); }
+  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;
+
+#if POC_RESET_IDC_SIGNALLING
+  Void    encodeSliceHeaderExtn( TComSlice* pSlice, Int shBitsWrittenTillNow );
+#endif
+public:
+  Void encodeVPS               ( TComVPS* pcVPS);
+  // SPS
+  Void encodeSPS               ( TComSPS* pcSPS );
+  Void encodePPS               ( TComPPS* pcPPS 
+#if Q0048_CGS_3D_ASYMLUT
+    , TEnc3DAsymLUT * pc3DAsymLUT
+#endif
+    );
+  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 );
+  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 );
+  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 );
+  Void encodeIntraDirModeLuma  ( TComDataCU* pcCU, UInt absPartIdx, Bool isMultiplePU = false );
+
+  Void encodeIntraDirModeChroma( TComDataCU* pcCU, UInt uiAbsPartIdx );
+
+  Void encodeTransformSubdivFlag( UInt uiSymbol, UInt uiCtx );
+  Void encodeQtCbf             ( TComTU &rTu, const ComponentID compID, const Bool lowestLevel );
+
+  Void encodeQtCbfZero         ( TComTU &rTu, const ChannelType chType );
+  Void encodeQtRootCbfZero     ( TComDataCU* pcCU );
+  Void encodeQtRootCbf         ( TComDataCU* pcCU, UInt uiAbsPartIdx );
+  Void encodeQP                ( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool bRD = false );
+  Void encodeChromaQpAdjustment ( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool bRD = false );
+
+  Void encodeScalingList       ( TComScalingList* scalingList );
+
+  Void encodeCrossComponentPrediction( TComTU &rTu, ComponentID compID );
+
+private:
+  Void xEncodeTransform        ( Bool& bCodeDQP, Bool& codeChromaQpAdj, TComTU &rTu );
+
+public:
+  Void encodeCoeff             ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, Bool& bCodeDQP, Bool& codeChromaQpAdj );
+
+  Void encodeCoeffNxN         ( TComTU &rTu, TCoeff* pcCoef, const ComponentID compID );
+
+  Void estimateBit             ( estBitsSbacStruct* pcEstBitsSbac, Int width, Int height, ChannelType chType );
+#if SVC_EXTENSION
+  Void encodeSAOBlkParam(SAOBlkParam& saoBlkParam, UInt* saoMaxOffsetQVal, Bool* sliceEnabled, Bool leftMergeAvail, Bool aboveMergeAvail){m_pcEntropyCoderIf->codeSAOBlkParam(saoBlkParam, saoMaxOffsetQVal, sliceEnabled, leftMergeAvail, aboveMergeAvail, false);}
+#else
+  Void encodeSAOBlkParam(SAOBlkParam& saoBlkParam, Bool* sliceEnabled, Bool leftMergeAvail, Bool aboveMergeAvail){m_pcEntropyCoderIf->codeSAOBlkParam(saoBlkParam, sliceEnabled, leftMergeAvail, aboveMergeAvail, false);}
+#endif
+  static Int countNonZeroCoeffs( TCoeff* pcCoef, UInt uiSize );
+
+};// END CLASS DEFINITION TEncEntropy
+
+//! \}
+
+#endif // __TENCENTROPY__
+
Index: /tags/SHM-9.0/source/Lib/TLibEncoder/TEncGOP.cpp
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibEncoder/TEncGOP.cpp	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibEncoder/TEncGOP.cpp	(revision 1088)
@@ -0,0 +1,5435 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TEncGOP.cpp
+    \brief    GOP encoder class
+*/
+
+#include <list>
+#include <algorithm>
+#include <functional>
+
+#include "TEncTop.h"
+#include "TEncGOP.h"
+#include "TEncAnalyze.h"
+#include "libmd5/MD5.h"
+#include "TLibCommon/SEI.h"
+#include "TLibCommon/NAL.h"
+#include "NALwrite.h"
+#include <time.h>
+#include <math.h>
+#if P0297_VPS_POC_LSB_ALIGNED_FLAG
+#include <limits.h>
+#endif
+
+using namespace std;
+
+#if ENVIRONMENT_VARIABLE_DEBUG_AND_TEST
+Bool g_bFinalEncode = false;
+#endif
+
+//! \ingroup TLibEncoder
+//! \{
+
+// ====================================================================================================================
+// Constructor / destructor / initialization / destroy
+// ====================================================================================================================
+Int getLSB(Int poc, Int maxLSB)
+{
+  if (poc >= 0)
+  {
+    return poc % maxLSB;
+  }
+  else
+  {
+    return (maxLSB - ((-poc) % maxLSB)) % maxLSB;
+  }
+}
+
+TEncGOP::TEncGOP()
+{
+  m_iLastIDR            = 0;
+  m_iGopSize            = 0;
+  m_iNumPicCoded        = 0; //Niko
+  m_bFirst              = true;
+#if ALLOW_RECOVERY_POINT_AS_RAP
+  m_iLastRecoveryPicPOC = 0;
+#endif
+
+  m_pcCfg               = NULL;
+  m_pcSliceEncoder      = NULL;
+  m_pcListPic           = NULL;
+
+  m_pcEntropyCoder      = NULL;
+  m_pcCavlcCoder        = NULL;
+  m_pcSbacCoder         = NULL;
+  m_pcBinCABAC          = NULL;
+
+  m_bSeqFirst           = true;
+
+  m_bRefreshPending     = 0;
+  m_pocCRA            = 0;
+  m_numLongTermRefPicSPS = 0;
+  ::memset(m_ltRefPicPocLsbSps, 0, sizeof(m_ltRefPicPocLsbSps));
+  ::memset(m_ltRefPicUsedByCurrPicFlag, 0, sizeof(m_ltRefPicUsedByCurrPicFlag));
+  m_cpbRemovalDelay   = 0;
+  m_lastBPSEI         = 0;
+  xResetNonNestedSEIPresentFlags();
+  xResetNestedSEIPresentFlags();
+  m_associatedIRAPType = NAL_UNIT_CODED_SLICE_IDR_N_LP;
+  m_associatedIRAPPOC  = 0;
+#if POC_RESET_IDC_ENCODER
+  m_pocCraWithoutReset = 0;
+  m_associatedIrapPocBeforeReset = 0;
+#endif
+#if SVC_EXTENSION
+  m_pcPredSearch        = NULL;
+#if Q0048_CGS_3D_ASYMLUT
+  m_temp = NULL;
+  m_pColorMappedPic = NULL;
+#endif
+#if POC_RESET_IDC_ENCODER
+  m_lastPocPeriodId = -1;
+#endif
+#if R0071_IRAP_EOS_CROSS_LAYER_IMPACTS
+  m_noRaslOutputFlag = false;
+  m_prevPicHasEos    = false;
+#endif
+#endif //SVC_EXTENSION
+  return;
+}
+
+TEncGOP::~TEncGOP()
+{
+#if Q0048_CGS_3D_ASYMLUT
+  if(m_pColorMappedPic)
+  {
+    m_pColorMappedPic->destroy();
+    delete m_pColorMappedPic;
+    m_pColorMappedPic = NULL;                
+  }
+  if(m_temp)
+  {
+    free_mem2DintWithPad(m_temp, m_iTap>>1, 0);
+    m_temp = NULL;
+  }
+#endif
+}
+
+/** Create list to contain pointers to CTU start addresses of slice.
+ */
+#if SVC_EXTENSION
+Void  TEncGOP::create( UInt layerId )
+{
+  m_bLongtermTestPictureHasBeenCoded = 0;
+  m_bLongtermTestPictureHasBeenCoded2 = 0;
+  m_layerId = layerId;
+}
+#else
+Void  TEncGOP::create()
+{
+  m_bLongtermTestPictureHasBeenCoded = 0;
+  m_bLongtermTestPictureHasBeenCoded2 = 0;
+}
+#endif
+
+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_pcSAO                = pcTEncTop->getSAO();
+  m_pcRateCtrl           = pcTEncTop->getRateCtrl();
+  m_lastBPSEI          = 0;
+  m_totalCoded         = 0;
+
+#if SVC_EXTENSION
+  m_ppcTEncTop           = pcTEncTop->getLayerEnc();
+  m_pcPredSearch         = pcTEncTop->getPredSearch();                       ///< encoder search class
+#if Q0048_CGS_3D_ASYMLUT
+  if( pcTEncTop->getLayerId() )
+  {
+    UInt prevLayerIdx = 0;
+    UInt prevLayerId  = 0;
+
+    if (pcTEncTop->getNumActiveRefLayers() > 0)
+    {
+      prevLayerIdx = pcTEncTop->getPredLayerIdx( pcTEncTop->getNumActiveRefLayers() - 1);
+      prevLayerId  = pcTEncTop->getRefLayerId(prevLayerIdx);
+    }
+    m_Enc3DAsymLUTPicUpdate.create( m_pcCfg->getCGSMaxOctantDepth() , g_bitDepthLayer[CHANNEL_TYPE_LUMA][prevLayerId] , g_bitDepthLayer[CHANNEL_TYPE_CHROMA][prevLayerId] , g_bitDepthLayer[CHANNEL_TYPE_LUMA][pcTEncTop->getLayerId()] , g_bitDepthLayer[CHANNEL_TYPE_CHROMA][pcTEncTop->getLayerId()] , m_pcCfg->getCGSMaxYPartNumLog2() /*, m_pcCfg->getCGSPhaseAlignment()*/ );
+    m_Enc3DAsymLUTPPS.create(   m_pcCfg->getCGSMaxOctantDepth() , g_bitDepthLayer[CHANNEL_TYPE_LUMA][prevLayerId] , g_bitDepthLayer[CHANNEL_TYPE_CHROMA][prevLayerId] , g_bitDepthLayer[CHANNEL_TYPE_LUMA][pcTEncTop->getLayerId()] , g_bitDepthLayer[CHANNEL_TYPE_CHROMA][pcTEncTop->getLayerId()] , m_pcCfg->getCGSMaxYPartNumLog2() /*, m_pcCfg->getCGSPhaseAlignment()*/ );
+    if(!m_pColorMappedPic)
+    {
+      m_pColorMappedPic = new TComPicYuv;
+      m_pColorMappedPic->create( m_ppcTEncTop[0]->getSourceWidth(), m_ppcTEncTop[0]->getSourceHeight(), m_ppcTEncTop[0]->getChromaFormatIDC(), g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth, NULL );
+    }
+  }
+#endif
+#endif //SVC_EXTENSION
+}
+
+SEIActiveParameterSets* TEncGOP::xCreateSEIActiveParameterSets (TComSPS *sps)
+{
+  SEIActiveParameterSets *seiActiveParameterSets = new SEIActiveParameterSets();
+  seiActiveParameterSets->activeVPSId = m_pcCfg->getVPS()->getVPSId();
+  seiActiveParameterSets->m_selfContainedCvsFlag = false;
+  seiActiveParameterSets->m_noParameterSetUpdateFlag = false;
+#if !R0247_SEI_ACTIVE
+  seiActiveParameterSets->numSpsIdsMinus1 = 0;
+  seiActiveParameterSets->activeSeqParameterSetId.resize(seiActiveParameterSets->numSpsIdsMinus1 + 1);
+  seiActiveParameterSets->activeSeqParameterSetId[0] = sps->getSPSId();
+#else
+  seiActiveParameterSets->numSpsIdsMinus1 = m_pcCfg->getNumLayer()-1;
+  seiActiveParameterSets->activeSeqParameterSetId.resize(seiActiveParameterSets->numSpsIdsMinus1 + 1);
+  seiActiveParameterSets->layerSpsIdx.resize(seiActiveParameterSets->numSpsIdsMinus1+ 1);  
+  for (Int c=0; c <= seiActiveParameterSets->numSpsIdsMinus1; c++)
+  {
+     seiActiveParameterSets->activeSeqParameterSetId[c] = c;
+  }
+  for (Int c=1; c <= seiActiveParameterSets->numSpsIdsMinus1; c++)
+  {
+     seiActiveParameterSets->layerSpsIdx[c] = c;
+  }
+#endif
+  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;
+}
+
+SEISegmentedRectFramePacking* TEncGOP::xCreateSEISegmentedRectFramePacking()
+{
+  SEISegmentedRectFramePacking *seiSegmentedRectFramePacking = new SEISegmentedRectFramePacking();
+  seiSegmentedRectFramePacking->m_arrangementCancelFlag = m_pcCfg->getSegmentedRectFramePackingArrangementSEICancel();
+  seiSegmentedRectFramePacking->m_contentInterpretationType = m_pcCfg->getSegmentedRectFramePackingArrangementSEIType();
+  seiSegmentedRectFramePacking->m_arrangementPersistenceFlag = m_pcCfg->getSegmentedRectFramePackingArrangementSEIPersistence();
+  return seiSegmentedRectFramePacking;
+}
+
+SEIDisplayOrientation* TEncGOP::xCreateSEIDisplayOrientation()
+{
+  SEIDisplayOrientation *seiDisplayOrientation = new SEIDisplayOrientation();
+  seiDisplayOrientation->cancelFlag = false;
+  seiDisplayOrientation->horFlip = false;
+  seiDisplayOrientation->verFlip = false;
+  seiDisplayOrientation->anticlockwiseRotation = m_pcCfg->getDisplayOrientationSEIAngle();
+  return seiDisplayOrientation;
+}
+SEIToneMappingInfo*  TEncGOP::xCreateSEIToneMappingInfo()
+{
+  SEIToneMappingInfo *seiToneMappingInfo = new SEIToneMappingInfo();
+  seiToneMappingInfo->m_toneMapId = m_pcCfg->getTMISEIToneMapId();
+  seiToneMappingInfo->m_toneMapCancelFlag = m_pcCfg->getTMISEIToneMapCancelFlag();
+  seiToneMappingInfo->m_toneMapPersistenceFlag = m_pcCfg->getTMISEIToneMapPersistenceFlag();
+
+  seiToneMappingInfo->m_codedDataBitDepth = m_pcCfg->getTMISEICodedDataBitDepth();
+  assert(seiToneMappingInfo->m_codedDataBitDepth >= 8 && seiToneMappingInfo->m_codedDataBitDepth <= 14);
+  seiToneMappingInfo->m_targetBitDepth = m_pcCfg->getTMISEITargetBitDepth();
+  assert(seiToneMappingInfo->m_targetBitDepth >= 1 && seiToneMappingInfo->m_targetBitDepth <= 17);
+  seiToneMappingInfo->m_modelId = m_pcCfg->getTMISEIModelID();
+  assert(seiToneMappingInfo->m_modelId >=0 &&seiToneMappingInfo->m_modelId<=4);
+
+  switch( seiToneMappingInfo->m_modelId)
+  {
+  case 0:
+    {
+      seiToneMappingInfo->m_minValue = m_pcCfg->getTMISEIMinValue();
+      seiToneMappingInfo->m_maxValue = m_pcCfg->getTMISEIMaxValue();
+      break;
+    }
+  case 1:
+    {
+      seiToneMappingInfo->m_sigmoidMidpoint = m_pcCfg->getTMISEISigmoidMidpoint();
+      seiToneMappingInfo->m_sigmoidWidth = m_pcCfg->getTMISEISigmoidWidth();
+      break;
+    }
+  case 2:
+    {
+      UInt num = 1u<<(seiToneMappingInfo->m_targetBitDepth);
+      seiToneMappingInfo->m_startOfCodedInterval.resize(num);
+      Int* ptmp = m_pcCfg->getTMISEIStartOfCodedInterva();
+      if(ptmp)
+      {
+        for(Int i=0; i<num;i++)
+        {
+          seiToneMappingInfo->m_startOfCodedInterval[i] = ptmp[i];
+        }
+      }
+      break;
+    }
+  case 3:
+    {
+      seiToneMappingInfo->m_numPivots = m_pcCfg->getTMISEINumPivots();
+      seiToneMappingInfo->m_codedPivotValue.resize(seiToneMappingInfo->m_numPivots);
+      seiToneMappingInfo->m_targetPivotValue.resize(seiToneMappingInfo->m_numPivots);
+      Int* ptmpcoded = m_pcCfg->getTMISEICodedPivotValue();
+      Int* ptmptarget = m_pcCfg->getTMISEITargetPivotValue();
+      if(ptmpcoded&&ptmptarget)
+      {
+        for(Int i=0; i<(seiToneMappingInfo->m_numPivots);i++)
+        {
+          seiToneMappingInfo->m_codedPivotValue[i]=ptmpcoded[i];
+          seiToneMappingInfo->m_targetPivotValue[i]=ptmptarget[i];
+         }
+       }
+       break;
+     }
+  case 4:
+     {
+       seiToneMappingInfo->m_cameraIsoSpeedIdc = m_pcCfg->getTMISEICameraIsoSpeedIdc();
+       seiToneMappingInfo->m_cameraIsoSpeedValue = m_pcCfg->getTMISEICameraIsoSpeedValue();
+       assert( seiToneMappingInfo->m_cameraIsoSpeedValue !=0 );
+       seiToneMappingInfo->m_exposureIndexIdc = m_pcCfg->getTMISEIExposurIndexIdc();
+       seiToneMappingInfo->m_exposureIndexValue = m_pcCfg->getTMISEIExposurIndexValue();
+       assert( seiToneMappingInfo->m_exposureIndexValue !=0 );
+       seiToneMappingInfo->m_exposureCompensationValueSignFlag = m_pcCfg->getTMISEIExposureCompensationValueSignFlag();
+       seiToneMappingInfo->m_exposureCompensationValueNumerator = m_pcCfg->getTMISEIExposureCompensationValueNumerator();
+       seiToneMappingInfo->m_exposureCompensationValueDenomIdc = m_pcCfg->getTMISEIExposureCompensationValueDenomIdc();
+       seiToneMappingInfo->m_refScreenLuminanceWhite = m_pcCfg->getTMISEIRefScreenLuminanceWhite();
+       seiToneMappingInfo->m_extendedRangeWhiteLevel = m_pcCfg->getTMISEIExtendedRangeWhiteLevel();
+       assert( seiToneMappingInfo->m_extendedRangeWhiteLevel >= 100 );
+       seiToneMappingInfo->m_nominalBlackLevelLumaCodeValue = m_pcCfg->getTMISEINominalBlackLevelLumaCodeValue();
+       seiToneMappingInfo->m_nominalWhiteLevelLumaCodeValue = m_pcCfg->getTMISEINominalWhiteLevelLumaCodeValue();
+       assert( seiToneMappingInfo->m_nominalWhiteLevelLumaCodeValue > seiToneMappingInfo->m_nominalBlackLevelLumaCodeValue );
+       seiToneMappingInfo->m_extendedWhiteLevelLumaCodeValue = m_pcCfg->getTMISEIExtendedWhiteLevelLumaCodeValue();
+       assert( seiToneMappingInfo->m_extendedWhiteLevelLumaCodeValue >= seiToneMappingInfo->m_nominalWhiteLevelLumaCodeValue );
+       break;
+    }
+  default:
+    {
+      assert(!"Undefined SEIToneMapModelId");
+      break;
+    }
+  }
+  return seiToneMappingInfo;
+}
+
+SEITempMotionConstrainedTileSets* TEncGOP::xCreateSEITempMotionConstrainedTileSets ()
+{
+  TComPPS *pps = m_pcEncTop->getPPS();
+  SEITempMotionConstrainedTileSets *sei = new SEITempMotionConstrainedTileSets();
+  if(pps->getTilesEnabledFlag())
+  {
+    sei->m_mc_all_tiles_exact_sample_value_match_flag = false;
+    sei->m_each_tile_one_tile_set_flag                = false;
+    sei->m_limited_tile_set_display_flag              = false;
+    sei->setNumberOfTileSets((pps->getNumTileColumnsMinus1() + 1) * (pps->getNumTileRowsMinus1() + 1));
+
+    for(Int i=0; i < sei->getNumberOfTileSets(); i++)
+    {
+      sei->tileSetData(i).m_mcts_id = i;  //depends the application;
+      sei->tileSetData(i).setNumberOfTileRects(1);
+
+      for(Int j=0; j<sei->tileSetData(i).getNumberOfTileRects(); j++)
+      {
+        sei->tileSetData(i).topLeftTileIndex(j)     = i+j;
+        sei->tileSetData(i).bottomRightTileIndex(j) = i+j;
+      }
+
+      sei->tileSetData(i).m_exact_sample_value_match_flag    = false;
+      sei->tileSetData(i).m_mcts_tier_level_idc_present_flag = false;
+    }
+  }
+  else
+  {
+    assert(!"Tile is not enabled");
+  }
+  return sei;
+}
+
+SEIKneeFunctionInfo* TEncGOP::xCreateSEIKneeFunctionInfo()
+{
+  SEIKneeFunctionInfo *seiKneeFunctionInfo = new SEIKneeFunctionInfo();
+  seiKneeFunctionInfo->m_kneeId = m_pcCfg->getKneeSEIId();
+  seiKneeFunctionInfo->m_kneeCancelFlag = m_pcCfg->getKneeSEICancelFlag();
+  if ( !seiKneeFunctionInfo->m_kneeCancelFlag )
+  {
+    seiKneeFunctionInfo->m_kneePersistenceFlag = m_pcCfg->getKneeSEIPersistenceFlag();
+    seiKneeFunctionInfo->m_kneeInputDrange = m_pcCfg->getKneeSEIInputDrange();
+    seiKneeFunctionInfo->m_kneeInputDispLuminance = m_pcCfg->getKneeSEIInputDispLuminance();
+    seiKneeFunctionInfo->m_kneeOutputDrange = m_pcCfg->getKneeSEIOutputDrange();
+    seiKneeFunctionInfo->m_kneeOutputDispLuminance = m_pcCfg->getKneeSEIOutputDispLuminance();
+
+    seiKneeFunctionInfo->m_kneeNumKneePointsMinus1 = m_pcCfg->getKneeSEINumKneePointsMinus1();
+    Int* piInputKneePoint  = m_pcCfg->getKneeSEIInputKneePoint();
+    Int* piOutputKneePoint = m_pcCfg->getKneeSEIOutputKneePoint();
+    if(piInputKneePoint&&piOutputKneePoint)
+    {
+      seiKneeFunctionInfo->m_kneeInputKneePoint.resize(seiKneeFunctionInfo->m_kneeNumKneePointsMinus1+1);
+      seiKneeFunctionInfo->m_kneeOutputKneePoint.resize(seiKneeFunctionInfo->m_kneeNumKneePointsMinus1+1);
+      for(Int i=0; i<=seiKneeFunctionInfo->m_kneeNumKneePointsMinus1; i++)
+      {
+        seiKneeFunctionInfo->m_kneeInputKneePoint[i] = piInputKneePoint[i];
+        seiKneeFunctionInfo->m_kneeOutputKneePoint[i] = piOutputKneePoint[i];
+       }
+    }
+  }
+  return seiKneeFunctionInfo;
+}
+
+SEIChromaSamplingFilterHint* TEncGOP::xCreateSEIChromaSamplingFilterHint(Bool bChromaLocInfoPresent, Int iHorFilterIndex, Int iVerFilterIndex)
+{
+  SEIChromaSamplingFilterHint *seiChromaSamplingFilterHint = new SEIChromaSamplingFilterHint();
+  seiChromaSamplingFilterHint->m_verChromaFilterIdc = iVerFilterIndex;
+  seiChromaSamplingFilterHint->m_horChromaFilterIdc = iHorFilterIndex;
+  seiChromaSamplingFilterHint->m_verFilteringProcessFlag = 1;
+  seiChromaSamplingFilterHint->m_targetFormatIdc = 3;
+  seiChromaSamplingFilterHint->m_perfectReconstructionFlag = false;
+  if(seiChromaSamplingFilterHint->m_verChromaFilterIdc == 1)
+  {
+    seiChromaSamplingFilterHint->m_numVerticalFilters = 1;
+    seiChromaSamplingFilterHint->m_verTapLengthMinus1 = (Int*)malloc(seiChromaSamplingFilterHint->m_numVerticalFilters * sizeof(Int));
+    seiChromaSamplingFilterHint->m_verFilterCoeff =    (Int**)malloc(seiChromaSamplingFilterHint->m_numVerticalFilters * sizeof(Int*));
+    for(Int i = 0; i < seiChromaSamplingFilterHint->m_numVerticalFilters; i ++)
+    {
+      seiChromaSamplingFilterHint->m_verTapLengthMinus1[i] = 0;
+      seiChromaSamplingFilterHint->m_verFilterCoeff[i] = (Int*)malloc(seiChromaSamplingFilterHint->m_verTapLengthMinus1[i] * sizeof(Int));
+      for(Int j = 0; j < seiChromaSamplingFilterHint->m_verTapLengthMinus1[i]; j ++)
+      {
+        seiChromaSamplingFilterHint->m_verFilterCoeff[i][j] = 0;
+      }
+    }
+  }
+  else
+  {
+    seiChromaSamplingFilterHint->m_numVerticalFilters = 0;
+    seiChromaSamplingFilterHint->m_verTapLengthMinus1 = NULL;
+    seiChromaSamplingFilterHint->m_verFilterCoeff = NULL;
+  }
+  if(seiChromaSamplingFilterHint->m_horChromaFilterIdc == 1)
+  {
+    seiChromaSamplingFilterHint->m_numHorizontalFilters = 1;
+    seiChromaSamplingFilterHint->m_horTapLengthMinus1 = (Int*)malloc(seiChromaSamplingFilterHint->m_numHorizontalFilters * sizeof(Int));
+    seiChromaSamplingFilterHint->m_horFilterCoeff = (Int**)malloc(seiChromaSamplingFilterHint->m_numHorizontalFilters * sizeof(Int*));
+    for(Int i = 0; i < seiChromaSamplingFilterHint->m_numHorizontalFilters; i ++)
+    {
+      seiChromaSamplingFilterHint->m_horTapLengthMinus1[i] = 0;
+      seiChromaSamplingFilterHint->m_horFilterCoeff[i] = (Int*)malloc(seiChromaSamplingFilterHint->m_horTapLengthMinus1[i] * sizeof(Int));
+      for(Int j = 0; j < seiChromaSamplingFilterHint->m_horTapLengthMinus1[i]; j ++)
+      {
+        seiChromaSamplingFilterHint->m_horFilterCoeff[i][j] = 0;
+      }
+    }
+  }
+  else
+  {
+    seiChromaSamplingFilterHint->m_numHorizontalFilters = 0;
+    seiChromaSamplingFilterHint->m_horTapLengthMinus1 = NULL;
+    seiChromaSamplingFilterHint->m_horFilterCoeff = NULL;
+  }
+  return seiChromaSamplingFilterHint;
+}
+
+Void TEncGOP::xCreateLeadingSEIMessages (/*SEIMessages seiMessages,*/ AccessUnit &accessUnit, TComSPS *sps)
+{
+  OutputNALUnit nalu(NAL_UNIT_PREFIX_SEI);
+
+  if(m_pcCfg->getActiveParameterSetsSEIEnabled()
+#if R0247_SEI_ACTIVE
+    && m_layerId == 0
+#endif
+    )
+  {
+    SEIActiveParameterSets *sei = xCreateSEIActiveParameterSets (sps);
+
+    //nalu = NALUnit(NAL_UNIT_PREFIX_SEI);
+    m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
+#if O0164_MULTI_LAYER_HRD
+    m_seiWriter.writeSEImessage(nalu.m_Bitstream, *sei, m_pcEncTop->getVPS(), sps); 
+#else
+    m_seiWriter.writeSEImessage(nalu.m_Bitstream, *sei, sps); 
+#endif
+    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);
+#if O0164_MULTI_LAYER_HRD
+    m_seiWriter.writeSEImessage(nalu.m_Bitstream, *sei, m_pcEncTop->getVPS(), sps);
+#else
+    m_seiWriter.writeSEImessage(nalu.m_Bitstream, *sei, sps);
+#endif
+    writeRBSPTrailingBits(nalu.m_Bitstream);
+    accessUnit.push_back(new NALUnitEBSP(nalu));
+    delete sei;
+  }
+  if(m_pcCfg->getSegmentedRectFramePackingArrangementSEIEnabled())
+  {
+    SEISegmentedRectFramePacking *sei = xCreateSEISegmentedRectFramePacking ();
+
+    nalu = NALUnit(NAL_UNIT_PREFIX_SEI);
+    m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
+#if O0164_MULTI_LAYER_HRD
+    m_seiWriter.writeSEImessage(nalu.m_Bitstream, *sei, m_pcEncTop->getVPS(), sps); 
+#else
+    m_seiWriter.writeSEImessage(nalu.m_Bitstream, *sei, sps); 
+#endif
+    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);
+#if O0164_MULTI_LAYER_HRD
+    m_seiWriter.writeSEImessage(nalu.m_Bitstream, *sei, m_pcEncTop->getVPS(), sps); 
+#else
+    m_seiWriter.writeSEImessage(nalu.m_Bitstream, *sei, sps);
+#endif
+    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);
+#if O0164_MULTI_LAYER_HRD
+    m_seiWriter.writeSEImessage(nalu.m_Bitstream, *sei, m_pcEncTop->getVPS(), sps);
+#else
+    m_seiWriter.writeSEImessage(nalu.m_Bitstream, *sei, sps);
+#endif
+    writeRBSPTrailingBits(nalu.m_Bitstream);
+    accessUnit.push_back(new NALUnitEBSP(nalu));
+    delete sei;
+  }
+
+  if(m_pcCfg->getTMCTSSEIEnabled())
+  {
+    SEITempMotionConstrainedTileSets *sei_tmcts = xCreateSEITempMotionConstrainedTileSets ();
+
+    nalu = NALUnit(NAL_UNIT_PREFIX_SEI);
+    m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
+#if O0164_MULTI_LAYER_HRD
+    m_seiWriter.writeSEImessage(nalu.m_Bitstream, *sei_tmcts, m_pcEncTop->getVPS(), sps);
+#else
+    m_seiWriter.writeSEImessage(nalu.m_Bitstream, *sei_tmcts, sps);
+#endif
+    writeRBSPTrailingBits(nalu.m_Bitstream);
+    accessUnit.push_back(new NALUnitEBSP(nalu));
+    delete sei_tmcts;
+  }
+
+  if(m_pcCfg->getTimeCodeSEIEnabled())
+  {
+    SEITimeCode sei_time_code;
+    //  Set data as per command line options
+    sei_time_code.numClockTs = m_pcCfg->getNumberOfTimesets();
+    for(Int i = 0; i < sei_time_code.numClockTs; i++)
+      sei_time_code.timeSetArray[i] = m_pcCfg->getTimeSet(i);
+
+    nalu = NALUnit(NAL_UNIT_PREFIX_SEI);
+    m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
+#if O0164_MULTI_LAYER_HRD
+    m_seiWriter.writeSEImessage(nalu.m_Bitstream, sei_time_code, m_pcEncTop->getVPS(), sps);
+#else
+    m_seiWriter.writeSEImessage(nalu.m_Bitstream, sei_time_code, sps);
+#endif
+    writeRBSPTrailingBits(nalu.m_Bitstream);
+    accessUnit.push_back(new NALUnitEBSP(nalu));
+  }
+
+  if(m_pcCfg->getKneeSEIEnabled())
+  {
+    SEIKneeFunctionInfo *sei = xCreateSEIKneeFunctionInfo();
+
+    nalu = NALUnit(NAL_UNIT_PREFIX_SEI);
+    m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
+#if O0164_MULTI_LAYER_HRD
+    m_seiWriter.writeSEImessage(nalu.m_Bitstream, *sei, m_pcEncTop->getVPS(), sps);
+#else
+    m_seiWriter.writeSEImessage(nalu.m_Bitstream, *sei, sps);
+#endif
+    writeRBSPTrailingBits(nalu.m_Bitstream);
+    accessUnit.push_back(new NALUnitEBSP(nalu));
+    delete sei;
+  }
+    
+  if(m_pcCfg->getMasteringDisplaySEI().colourVolumeSEIEnabled)
+  {
+    const TComSEIMasteringDisplay &seiCfg=m_pcCfg->getMasteringDisplaySEI();
+    SEIMasteringDisplayColourVolume mdcv;
+    mdcv.values = seiCfg;
+
+    nalu = NALUnit(NAL_UNIT_PREFIX_SEI);
+    m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
+#if O0164_MULTI_LAYER_HRD
+    m_seiWriter.writeSEImessage(nalu.m_Bitstream, mdcv, m_pcEncTop->getVPS(), sps);
+#else
+    m_seiWriter.writeSEImessage(nalu.m_Bitstream, mdcv, sps);
+#endif
+    writeRBSPTrailingBits(nalu.m_Bitstream);
+    accessUnit.push_back(new NALUnitEBSP(nalu));
+      
+  }
+
+#if Q0074_COLOUR_REMAPPING_SEI
+  if(m_pcCfg->getCRISEIFile() && strlen(m_pcCfg->getCRISEIFile()))
+  {
+    SEIColourRemappingInfo *sei = xCreateSEIColourRemappingInfo ();
+      
+#if SVC_EXTENSION
+    nalu = NALUnit(NAL_UNIT_PREFIX_SEI, 0, sps->getLayerId());  // SEI-CRI is applied per layer
+#else
+    nalu = NALUnit(NAL_UNIT_PREFIX_SEI);
+#endif
+    m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
+#if O0164_MULTI_LAYER_HRD
+    m_seiWriter.writeSEImessage(nalu.m_Bitstream, *sei, m_pcEncTop->getVPS(), sps);
+#else
+    m_seiWriter.writeSEImessage(nalu.m_Bitstream, *sei, sps);
+#endif
+    writeRBSPTrailingBits(nalu.m_Bitstream);
+    accessUnit.push_back(new NALUnitEBSP(nalu));
+    delete sei;
+  }
+#endif
+
+#if SVC_EXTENSION
+#if LAYERS_NOT_PRESENT_SEI
+  if(m_pcCfg->getLayersNotPresentSEIEnabled())
+  {
+    SEILayersNotPresent *sei = xCreateSEILayersNotPresent ();
+    m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
+#if O0164_MULTI_LAYER_HRD
+    m_seiWriter.writeSEImessage(nalu.m_Bitstream, *sei, m_pcEncTop->getVPS(), sps); 
+#else
+    m_seiWriter.writeSEImessage(nalu.m_Bitstream, *sei, sps); 
+#endif
+    writeRBSPTrailingBits(nalu.m_Bitstream);
+    accessUnit.push_back(new NALUnitEBSP(nalu));
+    delete sei;
+  }
+#endif
+
+#if N0383_IL_CONSTRAINED_TILE_SETS_SEI
+  if(m_pcCfg->getInterLayerConstrainedTileSetsSEIEnabled())
+  {
+    SEIInterLayerConstrainedTileSets *sei = xCreateSEIInterLayerConstrainedTileSets ();
+
+    nalu = NALUnit(NAL_UNIT_PREFIX_SEI, 0, m_pcCfg->getNumLayer()-1); // For highest layer
+    m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
+#if O0164_MULTI_LAYER_HRD
+    m_seiWriter.writeSEImessage(nalu.m_Bitstream, *sei, m_pcEncTop->getVPS(), sps); 
+#else
+    m_seiWriter.writeSEImessage(nalu.m_Bitstream, *sei, sps); 
+#endif
+    writeRBSPTrailingBits(nalu.m_Bitstream);
+    accessUnit.push_back(new NALUnitEBSP(nalu));
+    delete sei;
+  }
+#endif
+
+#if P0123_ALPHA_CHANNEL_SEI
+  if( m_pcCfg->getAlphaSEIEnabled() && m_pcEncTop->getVPS()->getScalabilityId(m_layerId, AUX_ID) && m_pcEncTop->getVPS()->getDimensionId(m_pcEncTop->getVPS()->getLayerIdxInVps(m_layerId), m_pcEncTop->getVPS()->getNumScalabilityTypes() - 1) == AUX_ALPHA )
+  {
+    SEIAlphaChannelInfo *sei = xCreateSEIAlphaChannelInfo();
+    m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
+#if O0164_MULTI_LAYER_HRD
+    m_seiWriter.writeSEImessage(nalu.m_Bitstream, *sei, m_pcEncTop->getVPS(), sps);
+#else
+    m_seiWriter.writeSEImessage(nalu.m_Bitstream, *sei, sps);
+#endif
+    writeRBSPTrailingBits(nalu.m_Bitstream);
+    accessUnit.push_back(new NALUnitEBSP(nalu));
+    delete sei;
+  }
+#endif
+
+#if Q0096_OVERLAY_SEI
+  if(m_pcCfg->getOverlaySEIEnabled())
+  {    
+    SEIOverlayInfo *sei = xCreateSEIOverlayInfo();       
+    m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
+#if O0164_MULTI_LAYER_HRD
+    m_seiWriter.writeSEImessage(nalu.m_Bitstream, *sei, m_pcEncTop->getVPS(), sps); 
+#else
+    m_seiWriter.writeSEImessage(nalu.m_Bitstream, *sei, sps); 
+#endif
+    writeRBSPTrailingBits(nalu.m_Bitstream);
+    accessUnit.push_back(new NALUnitEBSP(nalu));
+    delete sei;
+  }
+#endif
+#endif //SVC_EXTENSION
+}
+
+// ====================================================================================================================
+// Public member functions
+// ====================================================================================================================
+#if SVC_EXTENSION
+Void TEncGOP::compressGOP( Int iPicIdInGOP, Int iPOCLast, Int iNumPicRcvd, TComList<TComPic*>& rcListPic,
+                           TComList<TComPicYuv*>& rcListPicYuvRecOut, std::list<AccessUnit>& accessUnitsInGOP,
+                           Bool isField, Bool isTff, const InputColourSpaceConversion snr_conversion, const Bool printFrameMSE )
+#else
+Void TEncGOP::compressGOP( Int iPOCLast, Int iNumPicRcvd, TComList<TComPic*>& rcListPic,
+                           TComList<TComPicYuv*>& rcListPicYuvRecOut, std::list<AccessUnit>& accessUnitsInGOP,
+                           Bool isField, Bool isTff, const InputColourSpaceConversion snr_conversion, const Bool printFrameMSE )
+#endif
+{
+  // TODO: Split this function up.
+
+  TComPic*        pcPic = NULL;
+  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
+
+  xInitGOP( iPOCLast, iNumPicRcvd, rcListPic, rcListPicYuvRecOut, isField );
+
+  m_iNumPicCoded = 0;
+  SEIPictureTiming pictureTimingSEI;
+  Bool writeSOP = m_pcCfg->getSOPDescriptionSEIEnabled();
+
+  // Initialize Scalable Nesting SEI with single layer values
+  SEIScalableNesting scalableNestingSEI;
+  scalableNestingSEI.m_bitStreamSubsetFlag           = 1;      // If the nested SEI messages are picture buffereing SEI mesages, picure timing SEI messages or sub-picture timing SEI messages, bitstream_subset_flag shall be equal to 1
+  scalableNestingSEI.m_nestingOpFlag                 = 0;
+  scalableNestingSEI.m_nestingNumOpsMinus1           = 0;      //nesting_num_ops_minus1
+  scalableNestingSEI.m_allLayersFlag                 = 0;
+  scalableNestingSEI.m_nestingNoOpMaxTemporalIdPlus1 = 6 + 1;  //nesting_no_op_max_temporal_id_plus1
+  scalableNestingSEI.m_nestingNumLayersMinus1        = 1 - 1;  //nesting_num_layers_minus1
+  scalableNestingSEI.m_nestingLayerId[0]             = 0;
+  scalableNestingSEI.m_callerOwnsSEIs                = true;
+
+  Int picSptDpbOutputDuDelay = 0;
+  UInt *accumBitsDU = NULL;
+  UInt *accumNalsDU = NULL;
+  SEIDecodingUnitInfo decodingUnitInfoSEI;
+
+#if EFFICIENT_FIELD_IRAP
+  Int IRAPGOPid = -1;
+  Bool IRAPtoReorder = false;
+  Bool swapIRAPForward = false;
+  if(isField)
+  {
+    Int pocCurr;
+#if SVC_EXTENSION
+    for ( Int iGOPid=iPicIdInGOP; iGOPid < iPicIdInGOP+1; iGOPid++ )
+#else
+    for ( Int iGOPid=0; iGOPid < m_iGopSize; iGOPid++ )
+#endif    
+    {
+      // determine actual POC
+      if(iPOCLast == 0) //case first frame or first top field
+      {
+        pocCurr=0;
+      }
+      else if(iPOCLast == 1 && isField) //case first bottom field, just like the first frame, the poc computation is not right anymore, we set the right value
+      {
+        pocCurr = 1;
+      }
+      else
+      {
+        pocCurr = iPOCLast - iNumPicRcvd + m_pcCfg->getGOPEntry(iGOPid).m_POC - isField;
+      }
+
+      // check if POC corresponds to IRAP
+      NalUnitType tmpUnitType = getNalUnitType(pocCurr, m_iLastIDR, isField);
+      if(tmpUnitType >= NAL_UNIT_CODED_SLICE_BLA_W_LP && tmpUnitType <= NAL_UNIT_CODED_SLICE_CRA) // if picture is an IRAP
+      {
+        if(pocCurr%2 == 0 && iGOPid < m_iGopSize-1 && m_pcCfg->getGOPEntry(iGOPid).m_POC == m_pcCfg->getGOPEntry(iGOPid+1).m_POC-1)
+        { // if top field and following picture in enc order is associated bottom field
+          IRAPGOPid = iGOPid;
+          IRAPtoReorder = true;
+          swapIRAPForward = true; 
+          break;
+        }
+        if(pocCurr%2 != 0 && iGOPid > 0 && m_pcCfg->getGOPEntry(iGOPid).m_POC == m_pcCfg->getGOPEntry(iGOPid-1).m_POC+1)
+        {
+          // if picture is an IRAP remember to process it first
+          IRAPGOPid = iGOPid;
+          IRAPtoReorder = true;
+          swapIRAPForward = false; 
+          break;
+        }
+      }
+    }
+  }
+#endif
+  // reset flag indicating whether pictures have been encoded
+  for ( Int iGOPid=0; iGOPid < m_iGopSize; iGOPid++ )
+  {
+    m_pcCfg->setEncodedFlag(iGOPid, false);
+  }
+#if SVC_EXTENSION
+  for ( Int iGOPid=iPicIdInGOP; iGOPid < iPicIdInGOP+1; iGOPid++ )
+#else
+  for ( Int iGOPid=0; iGOPid < m_iGopSize; iGOPid++ )
+#endif
+  {
+#if EFFICIENT_FIELD_IRAP
+    if(IRAPtoReorder)
+    {
+      if(swapIRAPForward)
+      {
+        if(iGOPid == IRAPGOPid)
+        {
+          iGOPid = IRAPGOPid +1;
+        }
+        else if(iGOPid == IRAPGOPid +1)
+        {
+          iGOPid = IRAPGOPid;
+        }
+      }
+      else
+      {
+        if(iGOPid == IRAPGOPid -1)
+        {
+          iGOPid = IRAPGOPid;
+        }
+        else if(iGOPid == IRAPGOPid)
+        {
+          iGOPid = IRAPGOPid -1;
+        }
+      }
+    }
+#endif
+
+    UInt uiColDir = 1;
+    //-- For time output for each slice
+    clock_t iBeforeTime = clock();
+
+    //select uiColDir
+    Int iCloseLeft=1, iCloseRight=-1;
+    for(Int i = 0; i<m_pcCfg->getGOPEntry(iGOPid).m_numRefPics; i++)
+    {
+      Int iRef = m_pcCfg->getGOPEntry(iGOPid).m_referencePics[i];
+      if(iRef>0&&(iRef<iCloseRight||iCloseRight==-1))
+      {
+        iCloseRight=iRef;
+      }
+      else if(iRef<0&&(iRef>iCloseLeft||iCloseLeft==1))
+      {
+        iCloseLeft=iRef;
+      }
+    }
+    if(iCloseRight>-1)
+    {
+      iCloseRight=iCloseRight+m_pcCfg->getGOPEntry(iGOPid).m_POC-1;
+    }
+    if(iCloseLeft<1)
+    {
+      iCloseLeft=iCloseLeft+m_pcCfg->getGOPEntry(iGOPid).m_POC-1;
+      while(iCloseLeft<0)
+      {
+        iCloseLeft+=m_iGopSize;
+      }
+    }
+    Int iLeftQP=0, iRightQP=0;
+    for(Int i=0; i<m_iGopSize; i++)
+    {
+      if(m_pcCfg->getGOPEntry(i).m_POC==(iCloseLeft%m_iGopSize)+1)
+      {
+        iLeftQP= m_pcCfg->getGOPEntry(i).m_QPOffset;
+      }
+      if (m_pcCfg->getGOPEntry(i).m_POC==(iCloseRight%m_iGopSize)+1)
+      {
+        iRightQP=m_pcCfg->getGOPEntry(i).m_QPOffset;
+      }
+    }
+    if(iCloseRight>-1&&iRightQP<iLeftQP)
+    {
+      uiColDir=0;
+    }
+
+    /////////////////////////////////////////////////////////////////////////////////////////////////// Initial to start encoding
+    Int iTimeOffset;
+    Int pocCurr;
+
+    if(iPOCLast == 0) //case first frame or first top field
+    {
+      pocCurr=0;
+      iTimeOffset = 1;
+    }
+    else if(iPOCLast == 1 && isField) //case first bottom field, just like the first frame, the poc computation is not right anymore, we set the right value
+    {
+      pocCurr = 1;
+      iTimeOffset = 1;
+    }
+    else
+    {
+      pocCurr = iPOCLast - iNumPicRcvd + m_pcCfg->getGOPEntry(iGOPid).m_POC - ((isField && m_iGopSize>1) ? 1:0);
+      iTimeOffset = m_pcCfg->getGOPEntry(iGOPid).m_POC;
+    }
+
+    if(pocCurr>=m_pcCfg->getFramesToBeEncoded())
+    {
+#if EFFICIENT_FIELD_IRAP
+      if(IRAPtoReorder)
+      {
+        if(swapIRAPForward)
+        {
+          if(iGOPid == IRAPGOPid)
+          {
+            iGOPid = IRAPGOPid +1;
+            IRAPtoReorder = false;
+          }
+          else if(iGOPid == IRAPGOPid +1)
+          {
+            iGOPid --;
+          }
+        }
+        else
+        {
+          if(iGOPid == IRAPGOPid)
+          {
+            iGOPid = IRAPGOPid -1;
+          }
+          else if(iGOPid == IRAPGOPid -1)
+          {
+            iGOPid = IRAPGOPid;
+            IRAPtoReorder = false;
+          }
+        }
+      }
+#endif
+      continue;
+    }
+
+#if M0040_ADAPTIVE_RESOLUTION_CHANGE
+    if (m_pcEncTop->getAdaptiveResolutionChange() > 0 && ((m_layerId > 0 && pocCurr < m_pcEncTop->getAdaptiveResolutionChange()) ||
+                                                          (m_layerId == 0 && pocCurr > m_pcEncTop->getAdaptiveResolutionChange())) )
+    {
+      continue;
+    }
+#endif
+#if R0071_IRAP_EOS_CROSS_LAYER_IMPACTS
+    if (pocCurr > m_pcEncTop->getLayerSwitchOffBegin() && pocCurr < m_pcEncTop->getLayerSwitchOffEnd())
+    {
+      continue;
+    }
+#endif
+
+    if( getNalUnitType(pocCurr, m_iLastIDR, isField) == NAL_UNIT_CODED_SLICE_IDR_W_RADL || getNalUnitType(pocCurr, m_iLastIDR, isField) == NAL_UNIT_CODED_SLICE_IDR_N_LP )
+    {
+      m_iLastIDR = pocCurr;
+    }
+    // start a new access unit: create an entry in the list of output access units
+    accessUnitsInGOP.push_back(AccessUnit());
+    AccessUnit& accessUnit = accessUnitsInGOP.back();
+    xGetBuffer( rcListPic, rcListPicYuvRecOut, iNumPicRcvd, iTimeOffset, pcPic, pcPicYuvRecOut, pocCurr, isField );
+
+    //  Slice data initialization
+    pcPic->clearSliceBuffer();
+    assert(pcPic->getNumAllocatedSlice() == 1);
+    m_pcSliceEncoder->setSliceIdx(0);
+    pcPic->setCurrSliceIdx(0);
+#if SVC_EXTENSION
+    pcPic->setLayerId( m_layerId );
+    m_pcSliceEncoder->initEncSlice ( pcPic, iPOCLast, pocCurr, iNumPicRcvd, iGOPid, pcSlice, m_pcEncTop->getSPS(), m_pcEncTop->getPPS(), m_pcEncTop->getVPS(), isField );
+#else
+    m_pcSliceEncoder->initEncSlice ( pcPic, iPOCLast, pocCurr, iNumPicRcvd, iGOPid, pcSlice, m_pcEncTop->getSPS(), m_pcEncTop->getPPS(), isField );
+#endif
+
+    //Set Frame/Field coding
+    pcSlice->getPic()->setField(isField);
+
+#if SVC_EXTENSION
+#if POC_RESET_FLAG
+    if( !pcSlice->getPocResetFlag() ) // For picture that are not reset, we should adjust the value of POC calculated from the configuration files.
+    {
+      // Subtract POC adjustment value until now.
+      pcSlice->setPOC( pcSlice->getPOC() - m_pcEncTop->getPocAdjustmentValue() );
+    }
+    else
+    {
+      // Check if this is the first slice in the picture
+      // In the encoder, the POC values are copied along with copySliceInfo, so we only need
+      // to do this for the first slice.
+      Int pocAdjustValue = pcSlice->getPOC() - m_pcEncTop->getPocAdjustmentValue();
+      if( pcSlice->getSliceIdx() == 0 )
+      {
+        TComList<TComPic*>::iterator  iterPic = rcListPic.begin();  
+
+        // Iterate through all picture in DPB
+        while( iterPic != rcListPic.end() )
+        {              
+          TComPic *dpbPic = *iterPic;
+          if( dpbPic->getPOC() == pocCurr )
+          {
+            if( dpbPic->getReconMark() )
+            {
+              assert( !( dpbPic->getSlice(0)->isReferenced() ) && !( dpbPic->getOutputMark() ) );
+            }
+          }
+          // Check if the picture pointed to by iterPic is either used for reference or
+          // needed for output, are in the same layer, and not the current picture.
+          if( /* ( ( dpbPic->getSlice(0)->isReferenced() ) || ( dpbPic->getOutputMark() ) )
+              && */ ( dpbPic->getLayerId() == pcSlice->getLayerId() )
+              && ( dpbPic->getReconMark() ) 
+            )
+          {
+            for(Int i = dpbPic->getNumAllocatedSlice()-1; i >= 0; i--)
+            {
+              TComSlice *slice = dpbPic->getSlice(i);
+              TComReferencePictureSet *rps = slice->getRPS();
+              slice->setPOC( dpbPic->getSlice(i)->getPOC() - pocAdjustValue );
+
+              // Also adjust the POC value stored in the RPS of each such slice
+              for(Int j = rps->getNumberOfPictures(); j >= 0; j--)
+              {
+                rps->setPOC( j, rps->getPOC(j) - pocAdjustValue );
+              }
+              // Also adjust the value of refPOC
+              for(Int k = 0; k < 2; k++)  // For List 0 and List 1
+              {
+                RefPicList list = (k == 1) ? REF_PIC_LIST_1 : REF_PIC_LIST_0;
+                for(Int j = 0; j < slice->getNumRefIdx(list); j++)
+                {
+                  slice->setRefPOC( slice->getRefPOC(list, j) - pocAdjustValue, list, j);
+                }
+              }
+            }
+          }
+          iterPic++;
+        }
+        m_pcEncTop->setPocAdjustmentValue( m_pcEncTop->getPocAdjustmentValue() + pocAdjustValue );
+      }
+      pcSlice->setPocValueBeforeReset( pcSlice->getPOC() - m_pcEncTop->getPocAdjustmentValue() + pocAdjustValue );
+      pcSlice->setPOC( 0 );
+    }
+#endif
+#if POC_RESET_IDC_ENCODER
+    pcSlice->setPocValueBeforeReset( pocCurr );
+    // Check if the current picture is to be assigned as a reset picture
+    determinePocResetIdc(pocCurr, pcSlice);
+
+#if P0297_VPS_POC_LSB_ALIGNED_FLAG
+    Bool pocResettingFlag = false;
+
+    if (pcSlice->getPocResetIdc() != 0)
+    {
+      if (pcSlice->getVPS()->getVpsPocLsbAlignedFlag())
+      {
+        pocResettingFlag = true;
+      }
+      else if (m_pcEncTop->getPocDecrementedInDPBFlag())
+      {
+        pocResettingFlag = false;
+      }
+      else
+      {
+        pocResettingFlag = true;
+      }
+    }
+#endif
+
+    // If reset, do the following steps:
+#if P0297_VPS_POC_LSB_ALIGNED_FLAG
+    if( pocResettingFlag )
+#else
+    if( pcSlice->getPocResetIdc() )
+#endif
+    {
+      updatePocValuesOfPics(pocCurr, pcSlice);
+    }
+    else
+    {
+      // Check the base layer picture is IDR. If so, just set current POC equal to 0 (alignment of POC)
+      if( ( m_ppcTEncTop[0]->getGOPEncoder()->getIntraRefreshType() == 2) && ( pocCurr % m_ppcTEncTop[0]->getGOPEncoder()->getIntraRefreshInterval() == 0 ) )        
+      {
+        m_pcEncTop->setPocAdjustmentValue( pocCurr );
+      }
+      // else
+      {
+        // Just subtract POC by the current cumulative POC delta
+        pcSlice->setPOC( pocCurr - m_pcEncTop->getPocAdjustmentValue() );
+      }
+
+      Int maxPocLsb = 1 << pcSlice->getSPS()->getBitsForPOC();
+      pcSlice->setPocMsbVal( pcSlice->getPOC() - ( pcSlice->getPOC() & (maxPocLsb-1) ) );
+    }
+    // Update the POC of current picture, pictures in the DPB, including references inside the reference pictures
+
+#endif
+
+#if O0149_CROSS_LAYER_BLA_FLAG
+    if( m_layerId == 0 && (getNalUnitType(pocCurr, m_iLastIDR, isField) == NAL_UNIT_CODED_SLICE_IDR_W_RADL || getNalUnitType(pocCurr, m_iLastIDR, isField) == NAL_UNIT_CODED_SLICE_IDR_N_LP) )
+    {
+      pcSlice->setCrossLayerBLAFlag(m_pcEncTop->getCrossLayerBLAFlag());
+    }
+    else
+    {
+      pcSlice->setCrossLayerBLAFlag(false);
+    }
+#endif
+#if R0071_IRAP_EOS_CROSS_LAYER_IMPACTS
+    // Set the nal unit type
+    pcSlice->setNalUnitType(getNalUnitType(pocCurr, m_iLastIDR, isField));
+#endif
+#if NO_CLRAS_OUTPUT_FLAG
+    if (m_layerId == 0 &&
+        (pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_LP
+      || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_RADL
+      || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_N_LP
+      || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_W_RADL
+      || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_N_LP
+      || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_CRA))
+    {
+      if (m_bFirst)
+      {
+        m_pcEncTop->setNoClrasOutputFlag(true);
+      }
+#if R0071_IRAP_EOS_CROSS_LAYER_IMPACTS
+      else if (m_prevPicHasEos)
+      {
+        m_pcEncTop->setNoClrasOutputFlag(true);
+      }
+#endif
+      else if (pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_LP
+            || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_RADL
+            || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_N_LP)
+      {
+        m_pcEncTop->setNoClrasOutputFlag(true);
+      }
+#if O0149_CROSS_LAYER_BLA_FLAG
+      else if ((pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_W_RADL || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_N_LP) &&
+               pcSlice->getCrossLayerBLAFlag())
+      {
+        m_pcEncTop->setNoClrasOutputFlag(true);
+      }
+#endif
+      else
+      {
+        m_pcEncTop->setNoClrasOutputFlag(false);
+      }
+      if (m_pcEncTop->getNoClrasOutputFlag())
+      {
+        for (UInt i = 0; i < m_pcCfg->getNumLayer(); i++)
+        {
+          m_ppcTEncTop[i]->setLayerInitializedFlag(false);
+          m_ppcTEncTop[i]->setFirstPicInLayerDecodedFlag(false);
+        }
+      }
+    }
+#endif
+#if R0071_IRAP_EOS_CROSS_LAYER_IMPACTS
+    xCheckLayerReset(pcSlice);
+    xSetNoRaslOutputFlag(pcSlice);
+    xSetLayerInitializedFlag(pcSlice);
+#endif
+#if M0040_ADAPTIVE_RESOLUTION_CHANGE
+    if (m_pcEncTop->getAdaptiveResolutionChange() > 0 && m_layerId > 0 && pocCurr > m_pcEncTop->getAdaptiveResolutionChange())
+    {
+      pcSlice->setActiveNumILRRefIdx(0);
+      pcSlice->setInterLayerPredEnabledFlag(false);
+      pcSlice->setMFMEnabledFlag(false);
+    }
+#endif
+#endif //SVC_EXTENSION
+
+    pcSlice->setLastIDR(m_iLastIDR);
+    pcSlice->setSliceIdx(0);
+    //set default slice level flag to the same as SPS level flag
+    pcSlice->setLFCrossSliceBoundaryFlag(  pcSlice->getPPS()->getLoopFilterAcrossSlicesEnabledFlag()  );
+    pcSlice->setScalingList ( m_pcEncTop->getScalingList()  );
+    if(m_pcEncTop->getUseScalingListId() == SCALING_LIST_OFF)
+    {
+      m_pcEncTop->getTrQuant()->setFlatScalingList(pcSlice->getSPS()->getChromaFormatIdc());
+      m_pcEncTop->getTrQuant()->setUseScalingList(false);
+      m_pcEncTop->getSPS()->setScalingListPresentFlag(false);
+      m_pcEncTop->getPPS()->setScalingListPresentFlag(false);
+    }
+    else if(m_pcEncTop->getUseScalingListId() == SCALING_LIST_DEFAULT)
+    {
+#if SCALINGLIST_INFERRING
+      // inferring of the scaling list can be moved to the config file
+      UInt refLayerId = 0;
+#if VPS_AVC_BL_FLAG_REMOVAL
+      if( m_layerId > 0 && !m_pcEncTop->getVPS()->getNonHEVCBaseLayerFlag() && m_pcEncTop->getVPS()->getRecursiveRefLayerFlag( m_layerId, refLayerId ) )
+#else
+      if( m_layerId > 0 && !m_pcEncTop->getVPS()->getAvcBaseLayerFlag() && m_pcEncTop->getVPS()->getRecursiveRefLayerFlag( m_layerId, refLayerId ) )
+#endif
+      {
+        m_pcEncTop->getSPS()->setInferScalingListFlag( true );
+        m_pcEncTop->getSPS()->setScalingListRefLayerId( refLayerId );
+        m_pcEncTop->getSPS()->setScalingListPresentFlag( false );
+        m_pcEncTop->getPPS()->setInferScalingListFlag( false );
+        m_pcEncTop->getPPS()->setScalingListPresentFlag( false );
+
+        // infer the scaling list from the reference layer
+        pcSlice->setScalingList ( m_ppcTEncTop[pcSlice->getVPS()->getLayerIdxInVps(refLayerId)]->getScalingList() );
+      }
+      else
+      {
+#endif
+      pcSlice->setDefaultScalingList ();
+      m_pcEncTop->getSPS()->setScalingListPresentFlag(false);
+      m_pcEncTop->getPPS()->setScalingListPresentFlag(false);
+
+#if SCALINGLIST_INFERRING
+      }
+#endif
+
+      m_pcEncTop->getTrQuant()->setScalingList(pcSlice->getScalingList(), pcSlice->getSPS()->getChromaFormatIdc());
+      m_pcEncTop->getTrQuant()->setUseScalingList(true);
+    }
+    else if(m_pcEncTop->getUseScalingListId() == SCALING_LIST_FILE_READ)
+    {
+#if SCALINGLIST_INFERRING
+      // inferring of the scaling list can be moved to the config file
+      UInt refLayerId = 0;
+#if VPS_AVC_BL_FLAG_REMOVAL
+      if( m_layerId > 0 && !m_pcEncTop->getVPS()->getNonHEVCBaseLayerFlag() && m_pcEncTop->getVPS()->getRecursiveRefLayerFlag( m_layerId, refLayerId ) )
+#else
+      if( m_layerId > 0 && !m_pcEncTop->getVPS()->getAvcBaseLayerFlag() && m_pcEncTop->getVPS()->getRecursiveRefLayerFlag( m_layerId, refLayerId ) )
+#endif
+      {
+        m_pcEncTop->getSPS()->setInferScalingListFlag( true );
+        m_pcEncTop->getSPS()->setScalingListRefLayerId( refLayerId );
+        m_pcEncTop->getSPS()->setScalingListPresentFlag( false );
+        m_pcEncTop->getPPS()->setInferScalingListFlag( false );
+        m_pcEncTop->getPPS()->setScalingListPresentFlag( false );
+
+        // infer the scaling list from the reference layer
+        pcSlice->setScalingList ( m_ppcTEncTop[pcSlice->getVPS()->getLayerIdxInVps(refLayerId)]->getScalingList() );
+      }
+      else
+      {
+#endif
+      pcSlice->setDefaultScalingList ();
+      if(pcSlice->getScalingList()->xParseScalingList(m_pcCfg->getScalingListFile()))
+      {
+        Bool bParsedScalingList=false; // Use of boolean so that assertion outputs useful string
+        assert(bParsedScalingList);
+        exit(1);
+      }
+      pcSlice->getScalingList()->checkDcOfMatrix();
+      m_pcEncTop->getSPS()->setScalingListPresentFlag(pcSlice->checkDefaultScalingList());
+      m_pcEncTop->getPPS()->setScalingListPresentFlag(false);
+
+#if SCALINGLIST_INFERRING
+    }
+#endif
+
+      m_pcEncTop->getTrQuant()->setScalingList(pcSlice->getScalingList(), pcSlice->getSPS()->getChromaFormatIdc());
+      m_pcEncTop->getTrQuant()->setUseScalingList(true);
+    }
+    else
+    {
+      printf("error : ScalingList == %d no support\n",m_pcEncTop->getUseScalingListId());
+      assert(0);
+    }
+
+    if(pcSlice->getSliceType()==B_SLICE&&m_pcCfg->getGOPEntry(iGOPid).m_sliceType=='P')
+    {
+      pcSlice->setSliceType(P_SLICE);
+    }
+    if(pcSlice->getSliceType()==B_SLICE&&m_pcCfg->getGOPEntry(iGOPid).m_sliceType=='I')
+    {
+      pcSlice->setSliceType(I_SLICE);
+    }
+    
+#if !R0071_IRAP_EOS_CROSS_LAYER_IMPACTS
+    // Set the nal unit type
+    pcSlice->setNalUnitType(getNalUnitType(pocCurr, m_iLastIDR, isField));
+#endif
+#if SVC_EXTENSION
+    if (m_layerId > 0)
+    {
+      Int interLayerPredLayerIdcTmp[MAX_VPS_LAYER_IDX_PLUS1];
+      Int activeNumILRRefIdxTmp = 0;
+
+      for( Int i = 0; i < pcSlice->getActiveNumILRRefIdx(); i++ )
+      {
+        UInt refLayerIdc = pcSlice->getInterLayerPredLayerIdc(i);
+        UInt refLayerId = pcSlice->getVPS()->getRefLayerId(m_layerId, refLayerIdc);
+#if VPS_EXTN_DIRECT_REF_LAYERS
+        TComList<TComPic*> *cListPic = m_ppcTEncTop[pcSlice->getVPS()->getLayerIdxInVps(m_layerId)]->getRefLayerEnc(refLayerIdc)->getListPic();
+#else
+        TComList<TComPic*> *cListPic = m_ppcTEncTop[pcSlice->getVPS()->getLayerIdxInVps(m_layerId)-1]->getListPic();
+#endif
+        pcSlice->setBaseColPic( *cListPic, refLayerIdc );
+
+        // Apply temporal layer restriction to inter-layer prediction
+        Int maxTidIlRefPicsPlus1 = m_pcEncTop->getVPS()->getMaxTidIlRefPicsPlus1(pcSlice->getBaseColPic(refLayerIdc)->getSlice(0)->getLayerIdx(), pcSlice->getLayerIdx());
+        if( ((Int)(pcSlice->getBaseColPic(refLayerIdc)->getSlice(0)->getTLayer())<=maxTidIlRefPicsPlus1-1) || (maxTidIlRefPicsPlus1==0 && pcSlice->getBaseColPic(refLayerIdc)->getSlice(0)->getRapPicFlag()) )
+        {
+          interLayerPredLayerIdcTmp[activeNumILRRefIdxTmp++] = refLayerIdc; // add picture to the list of valid inter-layer pictures
+        }
+        else
+        {
+          continue; // ILP is not valid due to temporal layer restriction
+        }
+
+#if O0098_SCALED_REF_LAYER_ID
+        const Window &scalEL = m_pcEncTop->getScaledRefLayerWindowForLayer(refLayerId);
+#else
+        const Window &scalEL = m_pcEncTop->getScaledRefLayerWindow(refLayerIdc);
+#endif
+
+#if REF_REGION_OFFSET
+        const Window &windowRL  = m_pcEncTop->getRefLayerWindowForLayer(pcSlice->getVPS()->getRefLayerId(m_layerId, refLayerIdc));
+        Int widthBL   = pcSlice->getBaseColPic(refLayerIdc)->getPicYuvRec()->getWidth(COMPONENT_Y) - windowRL.getWindowLeftOffset() - windowRL.getWindowRightOffset();
+        Int heightBL  = pcSlice->getBaseColPic(refLayerIdc)->getPicYuvRec()->getHeight(COMPONENT_Y) - windowRL.getWindowTopOffset() - windowRL.getWindowBottomOffset();
+#else
+        Int widthBL   = pcSlice->getBaseColPic(refLayerIdc)->getPicYuvRec()->getWidth(COMPONENT_Y);
+        Int heightBL  = pcSlice->getBaseColPic(refLayerIdc)->getPicYuvRec()->getHeight(COMPONENT_Y);
+#if Q0200_CONFORMANCE_BL_SIZE
+        Int chromaFormatIdc = pcSlice->getBaseColPic(refLayerIdc)->getSlice(0)->getChromaFormatIdc();
+        const Window &confBL = pcSlice->getBaseColPic(refLayerIdc)->getConformanceWindow();
+        widthBL  -= ( confBL.getWindowLeftOffset() + confBL.getWindowRightOffset() ) * TComSPS::getWinUnitX( chromaFormatIdc );
+        heightBL -= ( confBL.getWindowTopOffset() + confBL.getWindowBottomOffset() ) * TComSPS::getWinUnitY( chromaFormatIdc );
+#endif
+#endif
+        Int widthEL   = pcPic->getPicYuvRec()->getWidth(COMPONENT_Y)  - scalEL.getWindowLeftOffset() - scalEL.getWindowRightOffset();
+        Int heightEL  = pcPic->getPicYuvRec()->getHeight(COMPONENT_Y) - scalEL.getWindowTopOffset()  - scalEL.getWindowBottomOffset();
+
+#if RESAMPLING_FIX
+#if REF_REGION_OFFSET
+        // conformance check: the values of RefLayerRegionWidthInSamplesY, RefLayerRegionHeightInSamplesY, ScaledRefRegionWidthInSamplesY and ScaledRefRegionHeightInSamplesY shall be greater than 0
+        assert(widthEL > 0 && heightEL > 0 && widthBL > 0 && widthEL > 0);
+
+        // conformance check: ScaledRefRegionWidthInSamplesY shall be greater or equal to RefLayerRegionWidthInSamplesY and ScaledRefRegionHeightInSamplesY shall be greater or equal to RefLayerRegionHeightInSamplesY
+        assert(widthEL >= widthBL && heightEL >= heightBL);
+
+#if R0209_GENERIC_PHASE
+        // conformance check: when ScaledRefRegionWidthInSamplesY is equal to RefLayerRegionWidthInSamplesY, PhaseHorY shall be equal to 0, when ScaledRefRegionWidthInSamplesC is equal to RefLayerRegionWidthInSamplesC, PhaseHorC shall be equal to 0, when ScaledRefRegionHeightInSamplesY is equal to RefLayerRegionHeightInSamplesY, PhaseVerY shall be equal to 0, and when ScaledRefRegionHeightInSamplesC is equal to RefLayerRegionHeightInSamplesC, PhaseVerC shall be equal to 0.
+        Bool phaseSetPresentFlag;
+        Int phaseHorLuma, phaseVerLuma, phaseHorChroma, phaseVerChroma;
+        pcSlice->getPPS()->getResamplingPhase( refLayerId, phaseSetPresentFlag, phaseHorLuma, phaseVerLuma, phaseHorChroma, phaseVerChroma );
+
+        assert( ( (widthEL  != widthBL)  || (phaseHorLuma == 0 && phaseHorChroma == 0) )
+             && ( (heightEL != heightBL) || (phaseVerLuma == 0 && phaseVerChroma == 0) ) );
+#endif
+#endif
+#endif
+
+        g_mvScalingFactor[refLayerIdc][0] = widthEL  == widthBL  ? 4096 : Clip3(-4096, 4095, ((widthEL  << 8) + (widthBL  >> 1)) / widthBL);
+        g_mvScalingFactor[refLayerIdc][1] = heightEL == heightBL ? 4096 : Clip3(-4096, 4095, ((heightEL << 8) + (heightBL >> 1)) / heightBL);
+
+        g_posScalingFactor[refLayerIdc][0] = ((widthBL  << 16) + (widthEL  >> 1)) / widthEL;
+        g_posScalingFactor[refLayerIdc][1] = ((heightBL << 16) + (heightEL >> 1)) / heightEL;
+
+#if Q0048_CGS_3D_ASYMLUT 
+        TComPicYuv* pBaseColRec = pcSlice->getBaseColPic(refLayerIdc)->getPicYuvRec();
+        if( pcSlice->getPPS()->getCGSFlag() )
+        {
+#if R0150_CGS_SIGNAL_CONSTRAINTS
+          // all reference layers are currently taken as CGS reference layers
+          m_Enc3DAsymLUTPPS.addRefLayerId( pcSlice->getVPS()->getRefLayerId(m_layerId, refLayerIdc) );
+          m_Enc3DAsymLUTPicUpdate.addRefLayerId( pcSlice->getVPS()->getRefLayerId(m_layerId, refLayerIdc) );
+#endif
+          if(g_posScalingFactor[refLayerIdc][0] < (1<<16) || g_posScalingFactor[refLayerIdc][1] < (1<<16)) //if(pcPic->isSpatialEnhLayer(refLayerIdc))
+          {
+            //downsampling;
+            downScalePic(pcPic->getPicYuvOrg(), pcSlice->getBaseColPic(refLayerIdc)->getPicYuvOrg());
+            //pcSlice->getBaseColPic(refLayerIdc)->getPicYuvOrg()->dump("ds.yuv", true, true);
+            m_Enc3DAsymLUTPPS.setDsOrigPic(pcSlice->getBaseColPic(refLayerIdc)->getPicYuvOrg());
+            m_Enc3DAsymLUTPicUpdate.setDsOrigPic(pcSlice->getBaseColPic(refLayerIdc)->getPicYuvOrg());
+          }
+          else
+          {
+            m_Enc3DAsymLUTPPS.setDsOrigPic(pcPic->getPicYuvOrg());
+            m_Enc3DAsymLUTPicUpdate.setDsOrigPic(pcPic->getPicYuvOrg());
+          }
+
+          Bool bSignalPPS = m_bSeqFirst;
+          bSignalPPS |= m_pcCfg->getGOPSize() > 1 ? pocCurr % m_pcCfg->getIntraPeriod() == 0 : pocCurr % m_pcCfg->getFrameRate() == 0;
+          xDetermin3DAsymLUT( pcSlice , pcPic , refLayerIdc , m_pcCfg , bSignalPPS );
+          m_Enc3DAsymLUTPPS.colorMapping( pcSlice->getBaseColPic(refLayerIdc)->getPicYuvRec(),  m_pColorMappedPic );
+          pBaseColRec = m_pColorMappedPic;
+        }
+#endif
+#if SVC_EXTENSION
+        if( pcPic->isSpatialEnhLayer(refLayerIdc) )
+        {
+          // check for the sample prediction picture type
+          if( pcSlice->getVPS()->isSamplePredictionType( pcSlice->getVPS()->getLayerIdxInVps(m_layerId), pcSlice->getVPS()->getLayerIdxInVps(refLayerId) ) )
+          {
+#if P0312_VERT_PHASE_ADJ
+            //when PhasePositionEnableFlag is equal to 1, set vertPhasePositionFlag to 0 if BL is top field and 1 if bottom
+            if( scalEL.getVertPhasePositionEnableFlag() )
+            {
+              pcSlice->setVertPhasePositionFlag( pcSlice->getPOC()%2, refLayerIdc );
+            }
+#endif
+#if O0215_PHASE_ALIGNMENT_REMOVAL
+            m_pcPredSearch->upsampleBasePic( pcSlice, refLayerIdc, pcPic->getFullPelBaseRec(refLayerIdc), pBaseColRec, pcPic->getPicYuvRec() );
+#else
+#if O0215_PHASE_ALIGNMENT
+#if O0194_JOINT_US_BITSHIFT
+#if Q0048_CGS_3D_ASYMLUT 
+            m_pcPredSearch->upsampleBasePic( pcSlice, refLayerIdc, pcPic->getFullPelBaseRec(refLayerIdc), pBaseColRec, pcPic->getPicYuvRec(), pcSlice->getVPS()->getPhaseAlignFlag() );
+#else
+            m_pcPredSearch->upsampleBasePic( pcSlice, refLayerIdc, pcPic->getFullPelBaseRec(refLayerIdc), pcSlice->getBaseColPic(refLayerIdc)->getPicYuvRec(), pcPic->getPicYuvRec(), pcSlice->getVPS()->getPhaseAlignFlag() );
+#endif
+#else
+#if Q0048_CGS_3D_ASYMLUT
+            m_pcPredSearch->upsampleBasePic( refLayerIdc, pcPic->getFullPelBaseRec(refLayerIdc), pBaseColRec, pcPic->getPicYuvRec(), scalEL, pcSlice->getVPS()->getPhaseAlignFlag() );
+#else
+            m_pcPredSearch->upsampleBasePic( refLayerIdc, pcPic->getFullPelBaseRec(refLayerIdc), pcSlice->getBaseColPic(refLayerIdc)->getPicYuvRec(), pcPic->getPicYuvRec(), scalEL, pcSlice->getVPS()->getPhaseAlignFlag() );
+#endif
+#endif
+#else
+#if O0194_JOINT_US_BITSHIFT
+#if Q0048_CGS_3D_ASYMLUT 
+#if REF_REGION_OFFSET
+          m_pcPredSearch->upsampleBasePic( pcSlice, refLayerIdc, pcPic->getFullPelBaseRec(refLayerIdc), pBaseColRec, pcPic->getPicYuvRec(), scalEL, altRL );
+#else
+          m_pcPredSearch->upsampleBasePic( pcSlice, refLayerIdc, pcPic->getFullPelBaseRec(refLayerIdc), pBaseColRec, pcPic->getPicYuvRec(), scalEL );
+#endif
+#else
+          m_pcPredSearch->upsampleBasePic( pcSlice, refLayerIdc, pcPic->getFullPelBaseRec(refLayerIdc), pcSlice->getBaseColPic(refLayerIdc)->getPicYuvRec(), pcPic->getPicYuvRec(), scalEL );
+#endif
+#else
+#if Q0048_CGS_3D_ASYMLUT 
+            m_pcPredSearch->upsampleBasePic( refLayerIdc, pcPic->getFullPelBaseRec(refLayerIdc), pBaseColRec, pcPic->getPicYuvRec(), scalEL );
+#else
+            m_pcPredSearch->upsampleBasePic( refLayerIdc, pcPic->getFullPelBaseRec(refLayerIdc), pcSlice->getBaseColPic(refLayerIdc)->getPicYuvRec(), pcPic->getPicYuvRec(), scalEL );
+#endif
+#endif
+#endif
+#endif
+          }
+        }
+        else
+        {
+#if Q0048_CGS_3D_ASYMLUT 
+          pcPic->setFullPelBaseRec( refLayerIdc, pBaseColRec );
+#else
+          pcPic->setFullPelBaseRec( refLayerIdc, pcSlice->getBaseColPic(refLayerIdc)->getPicYuvRec() );
+#endif
+        }
+        pcSlice->setFullPelBaseRec ( refLayerIdc, pcPic->getFullPelBaseRec(refLayerIdc) );
+#endif //SVC_EXTENSION
+      }
+
+      // Update the list of active inter-layer pictures
+      for ( Int i = 0; i < activeNumILRRefIdxTmp; i++)
+      {
+        pcSlice->setInterLayerPredLayerIdc( interLayerPredLayerIdcTmp[i], i );
+      }
+
+#if !O0225_TID_BASED_IL_RPS_DERIV || Q0060_MAX_TID_REF_EQUAL_TO_ZERO
+      pcSlice->setActiveNumILRRefIdx( activeNumILRRefIdxTmp );
+#endif 
+      if ( pcSlice->getActiveNumILRRefIdx() == 0 )
+      {
+        // No valid inter-layer pictures -> disable inter-layer prediction
+        pcSlice->setInterLayerPredEnabledFlag(false);
+      }
+
+      if( pocCurr % m_pcCfg->getIntraPeriod() == 0 )
+      {
+        if(pcSlice->getVPS()->getCrossLayerIrapAlignFlag())
+        {
+          TComList<TComPic*> *cListPic = m_ppcTEncTop[pcSlice->getVPS()->getLayerIdxInVps(m_layerId)]->getRefLayerEnc(0)->getListPic();
+          TComPic* picLayer0 = pcSlice->getRefPic(*cListPic, pcSlice->getPOC() );
+          if(picLayer0)
+          {
+            pcSlice->setNalUnitType(picLayer0->getSlice(0)->getNalUnitType());
+          }
+          else
+          {
+            pcSlice->setNalUnitType(NAL_UNIT_CODED_SLICE_CRA);
+          }
+        }
+        else
+        {
+#if !ALIGN_IRAP_BUGFIX
+          pcSlice->setNalUnitType(NAL_UNIT_CODED_SLICE_CRA);
+#endif
+        }
+      }
+#if ISLICE_TYPE_NUMDIR
+      if( pcSlice->getActiveNumILRRefIdx() == 0 && pcSlice->getNalUnitType() >= NAL_UNIT_CODED_SLICE_BLA_W_LP && pcSlice->getNalUnitType() <= NAL_UNIT_CODED_SLICE_CRA && (m_pcEncTop->getNumDirectRefLayers() == 0) )
+#else
+      if( pcSlice->getActiveNumILRRefIdx() == 0 && pcSlice->getNalUnitType() >= NAL_UNIT_CODED_SLICE_BLA_W_LP && pcSlice->getNalUnitType() <= NAL_UNIT_CODED_SLICE_CRA )
+#endif
+      {
+        pcSlice->setSliceType(I_SLICE);
+      }
+      else if( !m_pcEncTop->getElRapSliceTypeB() )
+      {
+        if( (pcSlice->getNalUnitType() >= NAL_UNIT_CODED_SLICE_BLA_W_LP) &&
+          (pcSlice->getNalUnitType() <= NAL_UNIT_CODED_SLICE_CRA) &&
+          pcSlice->getSliceType() == B_SLICE )
+        {
+          pcSlice->setSliceType(P_SLICE);
+        }
+      }      
+    }
+#endif //#if SVC_EXTENSION
+
+    if(pcSlice->getTemporalLayerNonReferenceFlag())
+    {
+      if (pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_TRAIL_R &&
+#if SVC_EXTENSION
+        ( m_iGopSize != 1 || m_ppcTEncTop[pcSlice->getVPS()->getLayerIdxInVps(m_layerId)]->getIntraPeriod() > 1 ) )
+#else
+          !(m_iGopSize == 1 && pcSlice->getSliceType() == I_SLICE))
+#endif
+        // Add this condition to avoid POC issues with encoder_intra_main.cfg configuration (see #1127 in bug tracker)
+      {
+        pcSlice->setNalUnitType(NAL_UNIT_CODED_SLICE_TRAIL_N);
+      }
+      if(pcSlice->getNalUnitType()==NAL_UNIT_CODED_SLICE_RADL_R)
+      {
+        pcSlice->setNalUnitType(NAL_UNIT_CODED_SLICE_RADL_N);
+      }
+      if(pcSlice->getNalUnitType()==NAL_UNIT_CODED_SLICE_RASL_R)
+      {
+        pcSlice->setNalUnitType(NAL_UNIT_CODED_SLICE_RASL_N);
+      }
+    }
+
+#if EFFICIENT_FIELD_IRAP
+    if ( pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_LP
+      || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_RADL
+      || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_N_LP
+      || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_W_RADL
+      || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_N_LP
+      || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_CRA )  // IRAP picture
+    {
+      m_associatedIRAPType = pcSlice->getNalUnitType();
+#if POC_RESET_IDC_ENCODER
+      m_associatedIRAPPOC = pcSlice->getPOC();
+      m_associatedIrapPocBeforeReset = pocCurr;
+#else
+      m_associatedIRAPPOC = pocCurr;
+#endif
+    }
+    pcSlice->setAssociatedIRAPType(m_associatedIRAPType);
+    pcSlice->setAssociatedIRAPPOC(m_associatedIRAPPOC);
+#if POC_RESET_IDC_ENCODER
+    pcSlice->setAssociatedIrapPocBeforeReset(m_associatedIrapPocBeforeReset);
+#endif
+#endif
+    // Do decoding refresh marking if any
+#if NO_CLRAS_OUTPUT_FLAG
+    pcSlice->decodingRefreshMarking(m_pocCRA, m_bRefreshPending, rcListPic, m_pcEncTop->getNoClrasOutputFlag());
+#else
+    pcSlice->decodingRefreshMarking(m_pocCRA, m_bRefreshPending, rcListPic);
+#endif
+#if POC_RESET_IDC_ENCODER
+    // m_pocCRA may have been update here; update m_pocCraWithoutReset
+    m_pocCraWithoutReset = m_pocCRA + m_pcEncTop->getPocAdjustmentValue();
+#endif
+    m_pcEncTop->selectReferencePictureSet(pcSlice, pocCurr, iGOPid);
+    pcSlice->getRPS()->setNumberOfLongtermPictures(0);
+#if !EFFICIENT_FIELD_IRAP
+    if ( pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_LP
+      || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_RADL
+      || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_N_LP
+      || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_W_RADL
+      || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_N_LP
+      || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_CRA )  // IRAP picture
+    {
+      m_associatedIRAPType = pcSlice->getNalUnitType();
+      m_associatedIRAPPOC = pocCurr;
+    }
+    pcSlice->setAssociatedIRAPType(m_associatedIRAPType);
+    pcSlice->setAssociatedIRAPPOC(m_associatedIRAPPOC);
+#endif
+
+#if ALLOW_RECOVERY_POINT_AS_RAP
+    if ((pcSlice->checkThatAllRefPicsAreAvailable(rcListPic, pcSlice->getRPS(), false, m_iLastRecoveryPicPOC, m_pcCfg->getDecodingRefreshType() == 3) != 0) || (pcSlice->isIRAP()) 
+#if EFFICIENT_FIELD_IRAP
+      || (isField && pcSlice->getAssociatedIRAPType() >= NAL_UNIT_CODED_SLICE_BLA_W_LP && pcSlice->getAssociatedIRAPType() <= NAL_UNIT_CODED_SLICE_CRA && pcSlice->getAssociatedIRAPPOC() == pcSlice->getPOC()+1)
+#endif
+      )
+    {
+      pcSlice->createExplicitReferencePictureSetFromReference(rcListPic, pcSlice->getRPS(), pcSlice->isIRAP(), m_iLastRecoveryPicPOC, m_pcCfg->getDecodingRefreshType() == 3);
+    }
+#else
+    if ((pcSlice->checkThatAllRefPicsAreAvailable(rcListPic, pcSlice->getRPS(), false) != 0) || (pcSlice->isIRAP()))
+    {
+      pcSlice->createExplicitReferencePictureSetFromReference(rcListPic, pcSlice->getRPS(), pcSlice->isIRAP());
+    }
+#endif
+#if ALIGNED_BUMPING
+#if POC_RESET_IDC_ENCODER
+    pcSlice->checkLeadingPictureRestrictions(rcListPic, true);
+#else
+    pcSlice->checkLeadingPictureRestrictions(rcListPic);
+#endif
+#endif
+    pcSlice->applyReferencePictureSet(rcListPic, pcSlice->getRPS());
+
+    if(pcSlice->getTLayer() > 0 
+      &&  !( pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_RADL_N     // Check if not a leading picture
+          || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_RADL_R
+          || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_RASL_N
+          || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_RASL_R )
+        )
+    {
+      if(pcSlice->isTemporalLayerSwitchingPoint(rcListPic) || pcSlice->getSPS()->getTemporalIdNestingFlag())
+      {
+#if SVC_EXTENSION && !Q0108_TSA_STSA
+        if( pcSlice->getLayerId() > 0 )
+        {
+          Bool oneRefLayerTSA = false, oneRefLayerNotTSA = false;
+          for( Int i = 0; i < pcSlice->getLayerId(); i++)
+          {
+            TComList<TComPic *> *cListPic = m_ppcTEncTop[i]->getListPic();
+            TComPic *lowerLayerPic = pcSlice->getRefPic(*cListPic, pcSlice->getPOC());
+            if( lowerLayerPic && pcSlice->getVPS()->getDirectDependencyFlag(pcSlice->getLayerId(), i) )
+            {
+              if( ( lowerLayerPic->getSlice(0)->getNalUnitType() == NAL_UNIT_CODED_SLICE_TSA_N ) ||
+                  ( lowerLayerPic->getSlice(0)->getNalUnitType() == NAL_UNIT_CODED_SLICE_TSA_R ) 
+                )
+              {
+                if(pcSlice->getTemporalLayerNonReferenceFlag() )
+                {
+                  pcSlice->setNalUnitType(NAL_UNIT_CODED_SLICE_TSA_N);
+                }
+                else
+                {
+                  pcSlice->setNalUnitType(NAL_UNIT_CODED_SLICE_TSA_R );
+                }
+                oneRefLayerTSA = true;
+              }
+              else
+              {
+                oneRefLayerNotTSA = true;
+              }
+            }
+          }
+          assert( !( oneRefLayerNotTSA && oneRefLayerTSA ) ); // Only one variable should be true - failure of this assert means
+                                                                // that two independent reference layers that are not dependent on
+                                                                // each other, but are reference for current layer have inconsistency
+          if( oneRefLayerNotTSA /*&& !oneRefLayerTSA*/ )          // No reference layer is TSA - set current as TRAIL
+          {
+            if(pcSlice->getTemporalLayerNonReferenceFlag() )
+            {
+              pcSlice->setNalUnitType( NAL_UNIT_CODED_SLICE_TRAIL_N );
+            }
+            else
+            {
+              pcSlice->setNalUnitType( NAL_UNIT_CODED_SLICE_TRAIL_R );
+            }
+          }
+          else  // This means there is no reference layer picture for current picture in this AU
+          {
+            if(pcSlice->getTemporalLayerNonReferenceFlag() )
+            {
+              pcSlice->setNalUnitType(NAL_UNIT_CODED_SLICE_TSA_N);
+            }
+            else
+            {
+              pcSlice->setNalUnitType(NAL_UNIT_CODED_SLICE_TSA_R );
+            }
+          }
+        }
+#else
+        if(pcSlice->getTemporalLayerNonReferenceFlag())
+        {
+          pcSlice->setNalUnitType(NAL_UNIT_CODED_SLICE_TSA_N);
+        }
+        else
+        {
+          pcSlice->setNalUnitType(NAL_UNIT_CODED_SLICE_TSA_R);
+        }
+#endif
+      }
+      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 SVC_EXTENSION && !Q0108_TSA_STSA
+          if( pcSlice->getLayerId() > 0 )
+          {
+            Bool oneRefLayerSTSA = false, oneRefLayerNotSTSA = false;
+            for( Int i = 0; i < pcSlice->getLayerId(); i++)
+            {
+              TComList<TComPic *> *cListPic = m_ppcTEncTop[i]->getListPic();
+              TComPic *lowerLayerPic = pcSlice->getRefPic(*cListPic, pcSlice->getPOC());
+              if( lowerLayerPic && pcSlice->getVPS()->getDirectDependencyFlag(pcSlice->getLayerId(), i) )
+              {
+                if( ( lowerLayerPic->getSlice(0)->getNalUnitType() == NAL_UNIT_CODED_SLICE_STSA_N ) ||
+                    ( lowerLayerPic->getSlice(0)->getNalUnitType() == NAL_UNIT_CODED_SLICE_STSA_R ) 
+                  )
+                {
+                  if(pcSlice->getTemporalLayerNonReferenceFlag() )
+                  {
+                    pcSlice->setNalUnitType(NAL_UNIT_CODED_SLICE_STSA_N);
+                  }
+                  else
+                  {
+                    pcSlice->setNalUnitType(NAL_UNIT_CODED_SLICE_STSA_R );
+                  }
+                  oneRefLayerSTSA = true;
+                }
+                else
+                {
+                  oneRefLayerNotSTSA = true;
+                }
+              }
+            }
+            assert( !( oneRefLayerNotSTSA && oneRefLayerSTSA ) ); // Only one variable should be true - failure of this assert means
+                                                                  // that two independent reference layers that are not dependent on
+                                                                  // each other, but are reference for current layer have inconsistency
+            if( oneRefLayerNotSTSA /*&& !oneRefLayerSTSA*/ )          // No reference layer is STSA - set current as TRAIL
+            {
+              if(pcSlice->getTemporalLayerNonReferenceFlag() )
+              {
+                pcSlice->setNalUnitType( NAL_UNIT_CODED_SLICE_TRAIL_N );
+              }
+              else
+              {
+                pcSlice->setNalUnitType( NAL_UNIT_CODED_SLICE_TRAIL_R );
+              }
+            }
+            else  // This means there is no reference layer picture for current picture in this AU
+            {
+              if(pcSlice->getTemporalLayerNonReferenceFlag() )
+              {
+                pcSlice->setNalUnitType(NAL_UNIT_CODED_SLICE_STSA_N);
+              }
+              else
+              {
+                pcSlice->setNalUnitType(NAL_UNIT_CODED_SLICE_STSA_R );
+              }
+            }
+          }
+#else
+          if(pcSlice->getTemporalLayerNonReferenceFlag())
+          {
+            pcSlice->setNalUnitType(NAL_UNIT_CODED_SLICE_STSA_N);
+          }
+          else
+          {
+            pcSlice->setNalUnitType(NAL_UNIT_CODED_SLICE_STSA_R);
+          }
+#endif
+        }
+      }
+    }
+    arrangeLongtermPicturesInRPS(pcSlice, rcListPic);
+    TComRefPicListModification* refPicListModification = pcSlice->getRefPicListModification();
+    refPicListModification->setRefPicListModificationFlagL0(0);
+    refPicListModification->setRefPicListModificationFlagL1(0);
+    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()));
+
+#if SVC_EXTENSION
+    if( m_layerId > 0 && pcSlice->getActiveNumILRRefIdx() )
+    {
+#if POC_RESET_FLAG || POC_RESET_IDC_ENCODER
+      if ( pocCurr > 0 && pcSlice->isRADL() && pcPic->getSlice(0)->getBaseColPic(pcPic->getSlice(0)->getInterLayerPredLayerIdc(0))->getSlice(0)->isRASL())
+#else
+      if (pcSlice->getPOC()>0  && pcSlice->isRADL() && pcPic->getSlice(0)->getBaseColPic(pcPic->getSlice(0)->getInterLayerPredLayerIdc(0))->getSlice(0)->isRASL())
+#endif
+      {
+        pcSlice->setActiveNumILRRefIdx(0);
+        pcSlice->setInterLayerPredEnabledFlag(0);
+      }
+      if( pcSlice->getNalUnitType() >= NAL_UNIT_CODED_SLICE_BLA_W_LP && pcSlice->getNalUnitType() <= NAL_UNIT_CODED_SLICE_CRA )
+      {
+        pcSlice->setNumRefIdx(REF_PIC_LIST_0, pcSlice->getActiveNumILRRefIdx());
+        pcSlice->setNumRefIdx(REF_PIC_LIST_1, pcSlice->getActiveNumILRRefIdx());
+      }
+      else
+      {
+        pcSlice->setNumRefIdx(REF_PIC_LIST_0, pcSlice->getNumRefIdx(REF_PIC_LIST_0)+pcSlice->getActiveNumILRRefIdx());
+        pcSlice->setNumRefIdx(REF_PIC_LIST_1, pcSlice->getNumRefIdx(REF_PIC_LIST_1)+pcSlice->getActiveNumILRRefIdx());
+      }
+
+      // check for the reference pictures whether there is at least one either temporal picture or ILRP with sample prediction type
+      if( pcSlice->getNumRefIdx( REF_PIC_LIST_0 ) - pcSlice->getActiveNumILRRefIdx() == 0 && pcSlice->getNumRefIdx( REF_PIC_LIST_1 ) - pcSlice->getActiveNumILRRefIdx() == 0 )
+      {
+        Bool foundSamplePredPicture = false;                
+
+        for( Int i = 0; i < pcSlice->getActiveNumILRRefIdx(); i++ )
+        {
+          if( pcSlice->getVPS()->isSamplePredictionType( pcSlice->getVPS()->getLayerIdxInVps(m_layerId), pcSlice->getInterLayerPredLayerIdc(i) ) )
+          {
+            foundSamplePredPicture = true;
+            break;
+          }
+        }
+
+        if( !foundSamplePredPicture )
+        {
+          pcSlice->setSliceType(I_SLICE);
+          pcSlice->setInterLayerPredEnabledFlag(0);
+          pcSlice->setActiveNumILRRefIdx(0);
+        }
+      }
+    }
+#endif //SVC_EXTENSION
+
+#if Q0108_TSA_STSA
+   if( ( pcSlice->getTLayer() == 0 && pcSlice->getLayerId() > 0  )    // only for enhancement layer and with temporal layer 0
+     && !( pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_RADL_N     
+          || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_RADL_R
+          || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_RASL_N
+          || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_RASL_R 
+          || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_W_RADL
+          || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_N_LP
+          || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_CRA
+          )
+        )
+    {
+        Bool isSTSA=true;
+        Bool isIntra=false;
+
+        for( Int i = 0; i < pcSlice->getLayerId(); i++)
+        {
+          TComList<TComPic *> *cListPic = m_ppcTEncTop[pcSlice->getVPS()->getLayerIdxInVps(i)]->getListPic();
+          TComPic *lowerLayerPic = pcSlice->getRefPic(*cListPic, pcSlice->getPOC());
+          if( lowerLayerPic && pcSlice->getVPS()->getDirectDependencyFlag(pcSlice->getLayerIdx(), i) )
+          {
+            if( lowerLayerPic->getSlice(0)->getSliceType() == I_SLICE)
+            { 
+              isIntra = true;
+            }
+          }
+        }
+
+        for(Int ii=iGOPid+1; ii < m_pcCfg->getGOPSize() && isSTSA; 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 && isIntra == false)
+        {    
+          if(pcSlice->getTemporalLayerNonReferenceFlag())
+          {
+            pcSlice->setNalUnitType(NAL_UNIT_CODED_SLICE_STSA_N);
+          }
+          else
+          {
+            pcSlice->setNalUnitType(NAL_UNIT_CODED_SLICE_STSA_R);
+          }
+        }
+    }
+#endif
+
+#if ADAPTIVE_QP_SELECTION
+    pcSlice->setTrQuant( m_pcEncTop->getTrQuant() );
+#endif      
+
+#if SVC_EXTENSION
+    if( pcSlice->getSliceType() == B_SLICE )
+    {
+      pcSlice->setColFromL0Flag(1-uiColDir);
+    }
+
+    //  Set reference list
+    if(m_layerId ==  0 || ( m_layerId > 0 && pcSlice->getActiveNumILRRefIdx() == 0 ) )
+    {
+      pcSlice->setRefPicList( rcListPic );
+    }
+
+    if( m_layerId > 0 && pcSlice->getActiveNumILRRefIdx() )
+    {
+      pcSlice->setILRPic( m_pcEncTop->getIlpList() );
+#if !REF_IDX_MFM
+      //  Set reference list
+      pcSlice->setRefPicList ( rcListPic );
+#endif
+      pcSlice->setRefPicListModificationSvc();
+      pcSlice->setRefPicList( rcListPic, false, m_pcEncTop->getIlpList());
+
+#if REF_IDX_MFM
+      if( pcSlice->getMFMEnabledFlag() )
+      {
+        Bool found         = false;
+        UInt ColFromL0Flag = pcSlice->getColFromL0Flag();
+        UInt ColRefIdx     = pcSlice->getColRefIdx();
+
+        for(Int colIdx = 0; colIdx < pcSlice->getNumRefIdx( RefPicList(1 - ColFromL0Flag) ); colIdx++) 
+        {
+          RefPicList refList = RefPicList(1 - ColFromL0Flag);
+          TComPic* refPic = pcSlice->getRefPic(refList, colIdx);
+
+          // It is a requirement of bitstream conformance when the collocated picture, used for temporal motion vector prediction, is an inter-layer reference picture, 
+          // VpsInterLayerMotionPredictionEnabled[ LayerIdxInVps[ currLayerId ] ][ LayerIdxInVps[ rLId ] ] shall be equal to 1, where rLId is set equal to nuh_layer_id of the inter-layer picture.
+          if( refPic->isILR(m_layerId) && pcSlice->getVPS()->isMotionPredictionType( pcSlice->getVPS()->getLayerIdxInVps(m_layerId), refPic->getLayerIdx() )
+#if MFM_ENCCONSTRAINT
+            && pcSlice->getBaseColPic( *m_ppcTEncTop[refPic->getLayerIdx()]->getListPic() )->checkSameRefInfo() == true 
+#endif
+            ) 
+          { 
+            ColRefIdx = colIdx; 
+            found = true;
+            break; 
+          }
+        }
+
+        if( found == false )
+        {
+          ColFromL0Flag = 1 - ColFromL0Flag;
+          for(Int colIdx = 0; colIdx < pcSlice->getNumRefIdx( RefPicList(1 - ColFromL0Flag) ); colIdx++) 
+          {
+            RefPicList refList = RefPicList(1 - ColFromL0Flag);
+            TComPic* refPic = pcSlice->getRefPic(refList, colIdx);
+
+            // It is a requirement of bitstream conformance when the collocated picture, used for temporal motion vector prediction, is an inter-layer reference picture, 
+            // VpsInterLayerMotionPredictionEnabled[ LayerIdxInVps[ currLayerId ] ][ LayerIdxInVps[ rLId ] ] shall be equal to 1, where rLId is set equal to nuh_layer_id of the inter-layer picture.
+            if( refPic->isILR(m_layerId) && pcSlice->getVPS()->isMotionPredictionType( pcSlice->getVPS()->getLayerIdxInVps(m_layerId), refPic->getLayerIdx() )
+#if MFM_ENCCONSTRAINT
+              && pcSlice->getBaseColPic( *m_ppcTEncTop[refPic->getLayerIdx()]->getListPic() )->checkSameRefInfo() == true 
+#endif
+              ) 
+            { 
+              ColRefIdx = colIdx; 
+              found = true; 
+              break; 
+            } 
+          }
+        }
+
+        if(found == true)
+        {
+          pcSlice->setColFromL0Flag(ColFromL0Flag);
+          pcSlice->setColRefIdx(ColRefIdx);
+        }
+      }
+#endif
+    }
+#else //SVC_EXTENSION
+    //  Set reference list
+    pcSlice->setRefPicList ( rcListPic );
+#endif //#if SVC_EXTENSION
+
+    //  Slice info. refinement
+    if ( (pcSlice->getSliceType() == B_SLICE) && (pcSlice->getNumRefIdx(REF_PIC_LIST_1) == 0) )
+    {
+      pcSlice->setSliceType ( P_SLICE );
+    }
+
+    if (pcSlice->getSliceType() == B_SLICE)
+    {
+#if !SVC_EXTENSION
+      pcSlice->setColFromL0Flag(1-uiColDir);
+#endif
+      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 (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);
+#if SVC_EXTENSION
+      if( pcSlice->getIdrPicFlag() )
+      {
+        pcSlice->setEnableTMVPFlag(0);
+      }
+      else
+#endif
+      pcSlice->setEnableTMVPFlag(1);
+    }
+    else
+    {
+      pcSlice->getSPS()->setTMVPFlagsPresent(0);
+      pcSlice->setEnableTMVPFlag(0);
+    }
+
+#if SVC_EXTENSION
+    if( m_layerId > 0 && !pcSlice->isIntra() )
+    {
+      Int colFromL0Flag = 1;
+      Int colRefIdx = 0;
+
+      // check whether collocated picture is valid
+      if( pcSlice->getEnableTMVPFlag() )
+      {
+        colFromL0Flag = pcSlice->getColFromL0Flag();
+        colRefIdx = pcSlice->getColRefIdx();
+
+        TComPic* refPic = pcSlice->getRefPic(RefPicList(1-colFromL0Flag), colRefIdx);
+
+        assert( refPic );
+
+        // It is a requirement of bitstream conformance when the collocated picture, used for temporal motion vector prediction, is an inter-layer reference picture, 
+        // VpsInterLayerMotionPredictionEnabled[ LayerIdxInVps[ currLayerId ] ][ LayerIdxInVps[ rLId ] ] shall be equal to 1, where rLId is set equal to nuh_layer_id of the inter-layer picture.
+        if( refPic->isILR(m_layerId) && !pcSlice->getVPS()->isMotionPredictionType( pcSlice->getVPS()->getLayerIdxInVps(m_layerId), refPic->getLayerIdx() ) )
+        {
+          pcSlice->setEnableTMVPFlag(false);
+          pcSlice->setMFMEnabledFlag(false);
+          colRefIdx = 0;
+        }
+      }
+
+      // remove motion only ILRP from the end of the colFromL0Flag reference picture list
+      RefPicList refList = RefPicList(colFromL0Flag);
+      Int numRefIdx = pcSlice->getNumRefIdx(refList);
+
+      if( numRefIdx > 0 )
+      {
+        for( Int refIdx = pcSlice->getNumRefIdx(refList) - 1; refIdx > 0; refIdx-- )
+        {
+          TComPic* refPic = pcSlice->getRefPic(refList, refIdx);
+
+          if( !refPic->isILR(m_layerId) || ( refPic->isILR(m_layerId) && pcSlice->getVPS()->isSamplePredictionType( pcSlice->getVPS()->getLayerIdxInVps(m_layerId), refPic->getLayerIdx() ) ) )
+          {
+            break;
+          }
+          else
+          {
+            assert( numRefIdx > 1 );
+            numRefIdx--;              
+          }
+        }
+
+        pcSlice->setNumRefIdx( refList, numRefIdx );
+      }
+
+      // remove motion only ILRP from the end of the (1-colFromL0Flag) reference picture list up to colRefIdx
+      refList = RefPicList(1 - colFromL0Flag);
+      numRefIdx = pcSlice->getNumRefIdx(refList);
+
+      if( numRefIdx > 0 )
+      {
+        for( Int refIdx = pcSlice->getNumRefIdx(refList) - 1; refIdx > colRefIdx; refIdx-- )
+        {
+          TComPic* refPic = pcSlice->getRefPic(refList, refIdx);
+
+          if( !refPic->isILR(m_layerId) || ( refPic->isILR(m_layerId) && pcSlice->getVPS()->isSamplePredictionType( pcSlice->getVPS()->getLayerIdxInVps(m_layerId), refPic->getLayerIdx() ) ) )
+          {
+            break;
+          }
+          else
+          {
+            assert( numRefIdx > 1 );
+            numRefIdx--;              
+          }
+        }
+
+        pcSlice->setNumRefIdx( refList, numRefIdx );
+      }
+
+      assert( pcSlice->getNumRefIdx(REF_PIC_LIST_0) > 0 && ( pcSlice->isInterP() || (pcSlice->isInterB() && pcSlice->getNumRefIdx(REF_PIC_LIST_1) > 0) ) );
+    }
+#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());
+
+    pcPic->getPicSym()->initTiles(pcSlice->getPPS());
+    pcPic->getPicSym()->initCtuTsRsAddrMaps();
+
+    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 POC_RESET_FLAG || POC_RESET_IDC_ENCODER
+      if ( ( pocCurr == 0 && m_pcCfg->getInitialQP() > 0 ) || ( frameLevel == 0 && m_pcCfg->getForceIntraQP() ) ) // QP is specified
+#else
+      if ( ( pcSlice->getPOC() == 0 && m_pcCfg->getInitialQP() > 0 ) || ( frameLevel == 0 && m_pcCfg->getForceIntraQP() ) ) // QP is specified
+#endif
+      {
+        Int    NumberBFrames = ( m_pcCfg->getGOPSize() - 1 );
+        Double dLambda_scale = 1.0 - Clip3( 0.0, 0.5, 0.05*(Double)NumberBFrames );
+        Double dQPFactor     = 0.57*dLambda_scale;
+        Int    SHIFT_QP      = 12;
+        Int    bitdepth_luma_qp_scale = 0;
+        Double qp_temp = (Double) sliceQP + bitdepth_luma_qp_scale - SHIFT_QP;
+        lambda = dQPFactor*pow( 2.0, qp_temp/3.0 );
+      }
+      else if ( frameLevel == 0 )   // intra case, but use the model
+      {
+        m_pcSliceEncoder->calCostSliceI(pcPic);
+
+        if ( m_pcCfg->getIntraPeriod() != 1 )   // do not refine allocated bits for all intra case
+        {
+          Int bits = m_pcRateCtrl->getRCSeq()->getLeftAverageBits();
+          bits = m_pcRateCtrl->getRCPic()->getRefineBitsForIntra( bits );
+          if ( bits < 200 )
+          {
+            bits = 200;
+          }
+          m_pcRateCtrl->getRCPic()->setTargetBits( bits );
+        }
+
+        list<TEncRCPic*> listPreviousPicture = m_pcRateCtrl->getPicList();
+        m_pcRateCtrl->getRCPic()->getLCUInitTargetBits();
+        lambda  = m_pcRateCtrl->getRCPic()->estimatePicLambda( listPreviousPicture, pcSlice->getSliceType());
+        sliceQP = m_pcRateCtrl->getRCPic()->estimatePicQP( lambda, listPreviousPicture );
+      }
+      else    // normal case
+      {
+        list<TEncRCPic*> listPreviousPicture = m_pcRateCtrl->getPicList();
+        lambda  = m_pcRateCtrl->getRCPic()->estimatePicLambda( listPreviousPicture, pcSlice->getSliceType());
+        sliceQP = m_pcRateCtrl->getRCPic()->estimatePicQP( lambda, listPreviousPicture );
+      }
+
+#if REPN_FORMAT_IN_VPS
+      sliceQP = Clip3( -pcSlice->getQpBDOffsetY(), MAX_QP, sliceQP );
+#else
+      sliceQP = Clip3( -pcSlice->getSPS()->getQpBDOffset(CHANNEL_TYPE_LUMA), MAX_QP, sliceQP );
+#endif
+      m_pcRateCtrl->getRCPic()->setPicEstQP( sliceQP );
+
+      m_pcSliceEncoder->resetQP( pcPic, sliceQP, lambda );
+    }
+
+    UInt uiNumSliceSegments = 1;
+
+#if AVC_BASE
+#if VPS_AVC_BL_FLAG_REMOVAL
+    if( m_layerId == 0 && m_pcEncTop->getVPS()->getNonHEVCBaseLayerFlag() )
+#else
+    if( m_layerId == 0 && m_pcEncTop->getVPS()->getAvcBaseLayerFlag() )
+#endif
+    {
+      pcPic->getPicYuvOrg()->copyToPic( pcPic->getPicYuvRec() );
+#if O0194_WEIGHTED_PREDICTION_CGS
+      // Calculate for the base layer to be used in EL as Inter layer reference
+      if( m_pcEncTop->getInterLayerWeightedPredFlag() )
+      {
+        m_pcSliceEncoder->estimateILWpParam( pcSlice );
+      }
+#endif
+      return;
+    }
+#endif
+
+    // Allocate some coders, now the number of tiles are known.
+    const Int numSubstreams = pcSlice->getPPS()->getNumSubstreams();
+    std::vector<TComOutputBitstream> substreamsOut(numSubstreams);
+
+    // now compress (trial encode) the various slice segments (slices, and dependent slices)
+    {
+      const UInt numberOfCtusInFrame=pcPic->getPicSym()->getNumberOfCtusInFrame();
+      pcSlice->setSliceCurStartCtuTsAddr( 0 );
+      pcSlice->setSliceSegmentCurStartCtuTsAddr( 0 );
+
+      for(UInt nextCtuTsAddr = 0; nextCtuTsAddr < numberOfCtusInFrame; )
+      {
+        m_pcSliceEncoder->precompressSlice( pcPic );
+        m_pcSliceEncoder->compressSlice   ( pcPic );
+
+        const UInt curSliceSegmentEnd = pcSlice->getSliceSegmentCurEndCtuTsAddr();
+        if (curSliceSegmentEnd < numberOfCtusInFrame)
+        {
+          const Bool bNextSegmentIsDependentSlice=curSliceSegmentEnd<pcSlice->getSliceCurEndCtuTsAddr();
+          const UInt sliceBits=pcSlice->getSliceBits();
+          pcPic->allocateNewSlice();
+          // prepare for next slice
+          pcPic->setCurrSliceIdx                    ( uiNumSliceSegments );
+          m_pcSliceEncoder->setSliceIdx             ( uiNumSliceSegments   );
+          pcSlice = pcPic->getSlice                 ( uiNumSliceSegments   );
+          pcSlice->copySliceInfo                    ( pcPic->getSlice(uiNumSliceSegments-1)  );
+          pcSlice->setSliceIdx                      ( uiNumSliceSegments   );
+          if (bNextSegmentIsDependentSlice)
+          {
+            pcSlice->setSliceBits(sliceBits);
+          }
+          else
+          {
+            pcSlice->setSliceCurStartCtuTsAddr      ( curSliceSegmentEnd );
+            pcSlice->setSliceBits(0);
+          }
+          pcSlice->setDependentSliceSegmentFlag(bNextSegmentIsDependentSlice);
+          pcSlice->setSliceSegmentCurStartCtuTsAddr ( curSliceSegmentEnd );
+          uiNumSliceSegments ++;
+        }
+        nextCtuTsAddr = curSliceSegmentEnd;
+      }
+    }
+
+#if N0383_IL_CONSTRAINED_TILE_SETS_SEI
+    if (m_pcCfg->getInterLayerConstrainedTileSetsSEIEnabled())
+    {
+      xBuildTileSetsMap(pcPic->getPicSym());
+    }
+#endif
+
+    pcSlice = pcPic->getSlice(0);
+
+    // SAO parameter estimation using non-deblocked pixels for CTU bottom and right boundary areas
+    if( pcSlice->getSPS()->getUseSAO() && m_pcCfg->getSaoCtuBoundary() )
+    {
+      m_pcSAO->getPreDBFStatistics(pcPic);
+    }
+
+    //-- Loop filter
+    Bool bLFCrossTileBoundary = pcSlice->getPPS()->getLoopFilterAcrossTilesEnabledFlag();
+    m_pcLoopFilter->setCfg(bLFCrossTileBoundary);
+    if ( m_pcCfg->getDeblockingFilterMetric() )
+    {
+      dblMetric(pcPic, uiNumSliceSegments);
+    }
+    m_pcLoopFilter->loopFilterPic( pcPic );
+
+    /////////////////////////////////////////////////////////////////////////////////////////////////// File writing
+    // Set entropy coder
+    m_pcEntropyCoder->setEntropyCoder   ( m_pcCavlcCoder, pcSlice );
+
+    /* write various header sets. */
+    if ( m_bSeqFirst )
+    {
+#if SVC_EXTENSION
+      OutputNALUnit nalu( NAL_UNIT_VPS, 0, 0 ); // The value of nuh_layer_id of VPS NAL unit shall be equal to 0.
+#if AVC_BASE
+#if VPS_AVC_BL_FLAG_REMOVAL
+      if( ( m_layerId > 0 && m_pcEncTop->getVPS()->getNonHEVCBaseLayerFlag() ) || ( m_layerId == 0 && !m_pcEncTop->getVPS()->getNonHEVCBaseLayerFlag() ) )
+#else
+      if( ( m_layerId > 0 && m_pcEncTop->getVPS()->getAvcBaseLayerFlag() ) || ( m_layerId == 0 && !m_pcEncTop->getVPS()->getAvcBaseLayerFlag() ) )
+#endif
+#else
+      if( m_layerId == 0 )
+#endif
+      {
+#else
+      OutputNALUnit nalu(NAL_UNIT_VPS);
+#endif
+#if VPS_VUI_OFFSET
+      // The following code also calculates the VPS VUI offset
+#endif
+#if !P0125_REVERT_VPS_EXTN_OFFSET_TO_RESERVED
+#if VPS_EXTN_OFFSET_CALC
+      OutputNALUnit tempNalu(NAL_UNIT_VPS, 0, 0        ); // The value of nuh_layer_id of VPS NAL unit shall be equal to 0.
+      m_pcEntropyCoder->setBitstream(&tempNalu.m_Bitstream);
+      m_pcEntropyCoder->encodeVPS(m_pcEncTop->getVPS());  // Use to calculate the VPS extension offset
+#endif
+#endif
+      m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
+      m_pcEntropyCoder->encodeVPS(m_pcEncTop->getVPS());
+      writeRBSPTrailingBits(nalu.m_Bitstream);
+      accessUnit.push_back(new NALUnitEBSP(nalu));
+      actualTotalBits += UInt(accessUnit.back()->m_nalUnitData.str().size()) * 8;
+#if SVC_EXTENSION
+      }
+#endif
+
+#if SVC_EXTENSION
+      nalu = NALUnit(NAL_UNIT_SPS, 0, m_layerId);
+#else
+      nalu = NALUnit(NAL_UNIT_SPS);
+#endif
+#if Q0078_ADD_LAYER_SETS
+      if (m_pcEncTop->getVPS()->getNumDirectRefLayers(m_layerId) == 0 && m_pcEncTop->getVPS()->getNumAddLayerSets() > 0)
+      {
+        nalu.m_layerId = 0; // For independent base layer rewriting
+      }
+#endif
+      m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
+      if (m_bSeqFirst)
+      {
+        pcSlice->getSPS()->setNumLongTermRefPicSPS(m_numLongTermRefPicSPS);
+        assert (m_numLongTermRefPicSPS <= MAX_NUM_LONG_TERM_REF_PICS);
+        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() == FIXED_NUMBER_OF_CTU ) ? ( pcPic->getNumberOfCtusInFrame() / maxCU ) : ( 0 );
+        if( pcPic->getNumberOfCtusInFrame() % 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 O0092_0094_DEPENDENCY_CONSTRAINT
+      assert( pcSlice->getSPS()->getLayerId() == 0 || pcSlice->getSPS()->getLayerId() == m_layerId || m_pcEncTop->getVPS()->getRecursiveRefLayerFlag(m_layerId, pcSlice->getSPS()->getLayerId()) );
+#endif
+      m_pcEntropyCoder->encodeSPS(pcSlice->getSPS());
+      writeRBSPTrailingBits(nalu.m_Bitstream);
+      accessUnit.push_back(new NALUnitEBSP(nalu));
+      actualTotalBits += UInt(accessUnit.back()->m_nalUnitData.str().size()) * 8;
+
+#if SVC_EXTENSION
+      nalu = NALUnit(NAL_UNIT_PPS, 0, m_layerId);
+#else
+      nalu = NALUnit(NAL_UNIT_PPS);
+#endif
+#if Q0078_ADD_LAYER_SETS
+      if (m_pcEncTop->getVPS()->getNumDirectRefLayers(m_layerId) == 0 && m_pcEncTop->getVPS()->getNumAddLayerSets() > 0)
+      {
+        nalu.m_layerId = 0; // For independent base layer rewriting
+      }
+#endif
+      m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
+#if O0092_0094_DEPENDENCY_CONSTRAINT
+      assert( pcSlice->getPPS()->getLayerId() == 0 || pcSlice->getPPS()->getLayerId() == m_layerId || m_pcEncTop->getVPS()->getRecursiveRefLayerFlag(m_layerId, pcSlice->getPPS()->getLayerId()) );
+#endif
+#if Q0048_CGS_3D_ASYMLUT
+      m_pcEntropyCoder->encodePPS(pcSlice->getPPS(), &m_Enc3DAsymLUTPPS);
+#else
+      m_pcEntropyCoder->encodePPS(pcSlice->getPPS());
+#endif
+      writeRBSPTrailingBits(nalu.m_Bitstream);
+      accessUnit.push_back(new NALUnitEBSP(nalu));
+      actualTotalBits += UInt(accessUnit.back()->m_nalUnitData.str().size()) * 8;
+
+      xCreateLeadingSEIMessages(accessUnit, pcSlice->getSPS());
+
+#if O0164_MULTI_LAYER_HRD
+      if (pcSlice->getLayerId() == 0 && m_pcEncTop->getVPS()->getVpsVuiBspHrdPresentFlag())
+      {
+        Int j;
+#if VPS_VUI_BSP_HRD_PARAMS
+        TComVPS *vps = m_pcEncTop->getVPS();
+        for(Int i = 0; i < vps->getNumOutputLayerSets(); i++)
+        {
+          for(Int k = 0; k < vps->getNumSignalledPartitioningSchemes(i); k++)
+          {
+            for(Int l = 0; l < vps->getNumPartitionsInSchemeMinus1(i, k)+1; l++)
+            {
+#endif
+              nalu = NALUnit(NAL_UNIT_PREFIX_SEI, 0, 1);
+              m_pcEntropyCoder->setEntropyCoder(m_pcCavlcCoder, pcSlice);
+              m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
+#if VPS_VUI_BSP_HRD_PARAMS
+              SEIScalableNesting *scalableBspNestingSei = xCreateBspNestingSEI(pcSlice, i, k, l);
+#else
+              SEIScalableNesting *scalableBspNestingSei = xCreateBspNestingSEI(pcSlice);
+#endif
+              m_seiWriter.writeSEImessage(nalu.m_Bitstream, *scalableBspNestingSei, m_pcEncTop->getVPS(), pcSlice->getSPS());
+              writeRBSPTrailingBits(nalu.m_Bitstream);
+
+              UInt seiPositionInAu = xGetFirstSeiLocation(accessUnit);
+              UInt offsetPosition = m_activeParameterSetSEIPresentInAU 
+                + m_bufferingPeriodSEIPresentInAU 
+                + m_pictureTimingSEIPresentInAU
+                + m_nestedPictureTimingSEIPresentInAU;  // Insert SEI after APS, BP and PT SEI
+              AccessUnit::iterator it;
+              for(j = 0, it = accessUnit.begin(); j < seiPositionInAu + offsetPosition; j++)
+              {
+                it++;
+              }
+              accessUnit.insert(it, new NALUnitEBSP(nalu));
+#if VPS_VUI_BSP_HRD_PARAMS
+            }
+          }
+        }
+#endif
+      }
+#endif
+
+      m_bSeqFirst = false;
+    }
+#if Q0048_CGS_3D_ASYMLUT
+    else if( m_pcCfg->getCGSFlag() && pcSlice->getLayerId() && pcSlice->getCGSOverWritePPS() )
+    {
+      OutputNALUnit nalu(NAL_UNIT_PPS, 0, m_layerId);
+      m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
+      m_pcEntropyCoder->encodePPS(pcSlice->getPPS() , &m_Enc3DAsymLUTPPS );
+      writeRBSPTrailingBits(nalu.m_Bitstream);
+      accessUnit.push_back(new NALUnitEBSP(nalu));
+    }
+#endif
+
+    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 (Int j = iGOPid; j < m_iGopSize; j++)
+      {
+        Int deltaPOC = m_pcCfg->getGOPEntry(j).m_POC - m_pcCfg->getGOPEntry(prevEntryId).m_POC;
+        if ((SOPcurrPOC + deltaPOC) < m_pcCfg->getFramesToBeEncoded())
+        {
+          SOPcurrPOC += deltaPOC;
+          SOPDescriptionSEI.m_sopDescVclNaluType[i] = getNalUnitType(SOPcurrPOC, m_iLastIDR, isField);
+          SOPDescriptionSEI.m_sopDescTemporalId[i] = m_pcCfg->getGOPEntry(j).m_temporalId;
+          SOPDescriptionSEI.m_sopDescStRpsIdx[i] = m_pcEncTop->getReferencePictureSetIdxForSOP(pcSlice, SOPcurrPOC, j);
+          SOPDescriptionSEI.m_sopDescPocDelta[i] = deltaPOC;
+
+          prevEntryId = j;
+          i++;
+        }
+      }
+
+      SOPDescriptionSEI.m_numPicsInSopMinus1 = i - 1;
+
+#if O0164_MULTI_LAYER_HRD
+      m_seiWriter.writeSEImessage( nalu.m_Bitstream, SOPDescriptionSEI, m_pcEncTop->getVPS(), pcSlice->getSPS());
+#else
+      m_seiWriter.writeSEImessage( nalu.m_Bitstream, SOPDescriptionSEI, pcSlice->getSPS());
+#endif
+      writeRBSPTrailingBits(nalu.m_Bitstream);
+      accessUnit.push_back(new NALUnitEBSP(nalu));
+
+      writeSOP = false;
+    }
+#if Q0189_TMVP_CONSTRAINTS
+   if( m_pcEncTop->getTMVPConstraintsSEIEnabled() == 1 &&
+      (m_pcEncTop->getTMVPModeId() == 1 || m_pcEncTop->getTMVPModeId() == 2) &&
+      pcSlice->getLayerId() >0 && 
+      (pcSlice->getNalUnitType() ==  NAL_UNIT_CODED_SLICE_IDR_W_RADL || pcSlice->getNalUnitType() ==  NAL_UNIT_CODED_SLICE_IDR_N_LP))
+   {
+      OutputNALUnit nalu(NAL_UNIT_PREFIX_SEI);
+      SEITMVPConstrains seiTMVPConstrains;
+      m_pcEntropyCoder->setEntropyCoder(m_pcCavlcCoder, pcSlice);
+      m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
+      seiTMVPConstrains.no_intra_layer_col_pic_flag = 1;
+      seiTMVPConstrains.prev_pics_not_used_flag = 1;
+#if O0164_MULTI_LAYER_HRD
+      m_seiWriter.writeSEImessage( nalu.m_Bitstream, seiTMVPConstrains, m_pcEncTop->getVPS(), pcSlice->getSPS() );
+#else
+      m_seiWriter.writeSEImessage( nalu.m_Bitstream, seiTMVPConstrains, pcSlice->getSPS() );
+#endif
+      writeRBSPTrailingBits(nalu.m_Bitstream);
+      accessUnit.push_back(new NALUnitEBSP(nalu));
+   }
+#endif
+#if Q0247_FRAME_FIELD_INFO
+    if(  pcSlice->getLayerId()> 0 &&
+     ( (m_pcCfg->getProgressiveSourceFlag() && m_pcCfg->getInterlacedSourceFlag()) || m_pcCfg->getFrameFieldInfoPresentFlag()))
+    {
+      OutputNALUnit nalu(NAL_UNIT_PREFIX_SEI);
+      SEIFrameFieldInfo seiFFInfo;
+      m_pcEntropyCoder->setEntropyCoder(m_pcCavlcCoder, pcSlice);
+      m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
+      seiFFInfo.m_ffinfo_picStruct = (isField && pcSlice->getPic()->isTopField())? 1 : isField? 2 : 0;
+#if O0164_MULTI_LAYER_HRD
+      m_seiWriter.writeSEImessage( nalu.m_Bitstream, seiFFInfo, m_pcEncTop->getVPS(), pcSlice->getSPS() );
+#else
+      m_seiWriter.writeSEImessage( nalu.m_Bitstream, seiFFInfo, pcSlice->getSPS() );
+#endif
+      writeRBSPTrailingBits(nalu.m_Bitstream);
+      accessUnit.push_back(new NALUnitEBSP(nalu));
+    }
+#endif
+
+    if( ( m_pcCfg->getPictureTimingSEIEnabled() || m_pcCfg->getDecodingUnitInfoSEIEnabled() ) &&
+        ( pcSlice->getSPS()->getVuiParametersPresentFlag() ) &&
+        ( ( pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getNalHrdParametersPresentFlag() )
+       || ( pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getVclHrdParametersPresentFlag() ) ) )
+    {
+      if( pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getSubPicCpbParamsPresentFlag() )
+      {
+        UInt numDU = pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getNumDU();
+        pictureTimingSEI.m_numDecodingUnitsMinus1     = ( numDU - 1 );
+        pictureTimingSEI.m_duCommonCpbRemovalDelayFlag = false;
+
+        if( pictureTimingSEI.m_numNalusInDuMinus1 == NULL )
+        {
+          pictureTimingSEI.m_numNalusInDuMinus1       = new UInt[ numDU ];
+        }
+        if( pictureTimingSEI.m_duCpbRemovalDelayMinus1  == NULL )
+        {
+          pictureTimingSEI.m_duCpbRemovalDelayMinus1  = new UInt[ numDU ];
+        }
+        if( accumBitsDU == NULL )
+        {
+          accumBitsDU                                  = new UInt[ numDU ];
+        }
+        if( accumNalsDU == NULL )
+        {
+          accumNalsDU                                  = new UInt[ numDU ];
+        }
+      }
+      pictureTimingSEI.m_auCpbRemovalDelay = std::min<Int>(std::max<Int>(1, m_totalCoded - m_lastBPSEI), static_cast<Int>(pow(2, static_cast<Double>(pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getCpbRemovalDelayLengthMinus1()+1)))); // Syntax element signalled as minus, hence the .
+#if POC_RESET_FLAG || POC_RESET_IDC_ENCODER
+      pictureTimingSEI.m_picDpbOutputDelay = pcSlice->getSPS()->getNumReorderPics(pcSlice->getSPS()->getMaxTLayers()-1) + pocCurr - m_totalCoded;
+#else
+      pictureTimingSEI.m_picDpbOutputDelay = pcSlice->getSPS()->getNumReorderPics(pcSlice->getSPS()->getMaxTLayers()-1) + pcSlice->getPOC() - m_totalCoded;
+#endif
+#if EFFICIENT_FIELD_IRAP
+      if(IRAPGOPid > 0 && IRAPGOPid < m_iGopSize)
+      {
+        // if pictures have been swapped there is likely one more picture delay on their tid. Very rough approximation
+        pictureTimingSEI.m_picDpbOutputDelay ++;
+      }
+#endif
+      Int factor = pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getTickDivisorMinus2() + 2;
+      pictureTimingSEI.m_picDpbOutputDuDelay = factor * pictureTimingSEI.m_picDpbOutputDelay;
+      if( m_pcCfg->getDecodingUnitInfoSEIEnabled() )
+      {
+        picSptDpbOutputDuDelay = factor * pictureTimingSEI.m_picDpbOutputDelay;
+      }
+    }
+
+    if( ( m_pcCfg->getBufferingPeriodSEIEnabled() ) && ( pcSlice->getSliceType() == I_SLICE ) &&
+        ( pcSlice->getSPS()->getVuiParametersPresentFlag() ) &&
+        ( ( pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getNalHrdParametersPresentFlag() )
+       || ( pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getVclHrdParametersPresentFlag() ) ) )
+    {
+      OutputNALUnit nalu(NAL_UNIT_PREFIX_SEI);
+      m_pcEntropyCoder->setEntropyCoder(m_pcCavlcCoder, pcSlice);
+      m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
+
+      SEIBufferingPeriod sei_buffering_period;
+
+      UInt uiInitialCpbRemovalDelay = (90000/2);                      // 0.5 sec
+      sei_buffering_period.m_initialCpbRemovalDelay      [0][0]     = uiInitialCpbRemovalDelay;
+      sei_buffering_period.m_initialCpbRemovalDelayOffset[0][0]     = uiInitialCpbRemovalDelay;
+      sei_buffering_period.m_initialCpbRemovalDelay      [0][1]     = uiInitialCpbRemovalDelay;
+      sei_buffering_period.m_initialCpbRemovalDelayOffset[0][1]     = uiInitialCpbRemovalDelay;
+
+      Double dTmp = (Double)pcSlice->getSPS()->getVuiParameters()->getTimingInfo()->getNumUnitsInTick() / (Double)pcSlice->getSPS()->getVuiParameters()->getTimingInfo()->getTimeScale();
+
+      UInt uiTmp = (UInt)( dTmp * 90000.0 );
+      uiInitialCpbRemovalDelay -= uiTmp;
+      uiInitialCpbRemovalDelay -= uiTmp / ( pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getTickDivisorMinus2() + 2 );
+      sei_buffering_period.m_initialAltCpbRemovalDelay      [0][0]  = uiInitialCpbRemovalDelay;
+      sei_buffering_period.m_initialAltCpbRemovalDelayOffset[0][0]  = uiInitialCpbRemovalDelay;
+      sei_buffering_period.m_initialAltCpbRemovalDelay      [0][1]  = uiInitialCpbRemovalDelay;
+      sei_buffering_period.m_initialAltCpbRemovalDelayOffset[0][1]  = uiInitialCpbRemovalDelay;
+
+      sei_buffering_period.m_rapCpbParamsPresentFlag              = 0;
+      //for the concatenation, it can be set to one during splicing.
+      sei_buffering_period.m_concatenationFlag = 0;
+      //since the temporal layer HRD is not ready, we assumed it is fixed
+      sei_buffering_period.m_auCpbRemovalDelayDelta = 1;
+
+      sei_buffering_period.m_cpbDelayOffset = 0;
+      sei_buffering_period.m_dpbDelayOffset = 0;
+
+#if O0164_MULTI_LAYER_HRD
+      m_seiWriter.writeSEImessage( nalu.m_Bitstream, sei_buffering_period, m_pcEncTop->getVPS(), pcSlice->getSPS());
+#else
+      m_seiWriter.writeSEImessage( nalu.m_Bitstream, sei_buffering_period, pcSlice->getSPS());
+#endif
+      writeRBSPTrailingBits(nalu.m_Bitstream);
+
+      {
+        UInt seiPositionInAu = xGetFirstSeiLocation(accessUnit);
+        UInt offsetPosition = m_activeParameterSetSEIPresentInAU;   // Insert BP SEI after APS SEI
+        AccessUnit::iterator it = accessUnit.begin();
+        for(Int j = 0; 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);
+#if O0164_MULTI_LAYER_HRD
+        m_seiWriter.writeSEImessage( naluTmp.m_Bitstream, scalableNestingSEI, m_pcEncTop->getVPS(), pcSlice->getSPS());
+#else
+        m_seiWriter.writeSEImessage( naluTmp.m_Bitstream, scalableNestingSEI, pcSlice->getSPS());
+#endif
+        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 = accessUnit.begin();
+        for(Int j = 0; j < seiPositionInAu + offsetPosition; j++)
+        {
+          it++;
+        }
+        accessUnit.insert(it, new NALUnitEBSP(naluTmp));
+        m_nestedBufferingPeriodSEIPresentInAU = true;
+      }
+
+      m_lastBPSEI = m_totalCoded;
+      m_cpbRemovalDelay = 0;
+    }
+    m_cpbRemovalDelay ++;
+
+    if(pcSlice->getSPS()->getVuiParametersPresentFlag() && m_pcCfg->getChromaSamplingFilterHintEnabled() && ( pcSlice->getSliceType() == I_SLICE ))
+    {
+      SEIChromaSamplingFilterHint *seiChromaSamplingFilterHint = xCreateSEIChromaSamplingFilterHint(m_pcCfg->getChromaLocInfoPresentFlag(), m_pcCfg->getChromaSamplingHorFilterIdc(), m_pcCfg->getChromaSamplingVerFilterIdc());
+
+      OutputNALUnit naluTmp(NAL_UNIT_PREFIX_SEI); 
+      m_pcEntropyCoder->setEntropyCoder(m_pcCavlcCoder, pcSlice);
+      m_pcEntropyCoder->setBitstream(&naluTmp.m_Bitstream);
+#if O0164_MULTI_LAYER_HRD
+      m_seiWriter.writeSEImessage(naluTmp.m_Bitstream, *seiChromaSamplingFilterHint, m_pcEncTop->getVPS(), pcSlice->getSPS());
+#else
+      m_seiWriter.writeSEImessage(naluTmp.m_Bitstream, *seiChromaSamplingFilterHint, pcSlice->getSPS()); 
+#endif
+      writeRBSPTrailingBits(naluTmp.m_Bitstream);
+      accessUnit.push_back(new NALUnitEBSP(naluTmp));
+      delete seiChromaSamplingFilterHint;
+    }
+
+    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"
+
+#if O0164_MULTI_LAYER_HRD
+        m_seiWriter.writeSEImessage( nalu.m_Bitstream, seiGradualDecodingRefreshInfo, m_pcEncTop->getVPS(), pcSlice->getSPS() );
+#else
+        m_seiWriter.writeSEImessage( nalu.m_Bitstream, seiGradualDecodingRefreshInfo, pcSlice->getSPS() );
+#endif
+        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;
+#if POC_RESET_FLAG || POC_RESET_IDC_ENCODER
+      sei_recovery_point.m_exactMatchingFlag = ( pocCurr == 0 ) ? (true) : (false);
+#else
+      sei_recovery_point.m_exactMatchingFlag = ( pcSlice->getPOC() == 0 ) ? (true) : (false);
+#endif
+      sei_recovery_point.m_brokenLinkFlag    = false;
+#if ALLOW_RECOVERY_POINT_AS_RAP
+      if(m_pcCfg->getDecodingRefreshType() == 3)
+      {
+        m_iLastRecoveryPicPOC = pocCurr;
+      }
+#endif
+
+#if O0164_MULTI_LAYER_HRD
+      m_seiWriter.writeSEImessage( nalu.m_Bitstream, sei_recovery_point, m_pcEncTop->getVPS(), pcSlice->getSPS() );
+#else
+      m_seiWriter.writeSEImessage( nalu.m_Bitstream, sei_recovery_point, pcSlice->getSPS() );
+#endif
+      writeRBSPTrailingBits(nalu.m_Bitstream);
+      accessUnit.push_back(new NALUnitEBSP(nalu));
+    }
+
+    if( m_pcEncTop->getNoDisplaySEITLayer() )
+    {
+      if( pcSlice->getTLayer() >= m_pcEncTop->getNoDisplaySEITLayer() )
+      {
+        // No display SEI
+        OutputNALUnit nalu(NAL_UNIT_PREFIX_SEI);
+        m_pcEntropyCoder->setEntropyCoder(m_pcCavlcCoder, pcSlice);
+        m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
+
+        SEINoDisplay seiNoDisplay;
+        seiNoDisplay.m_noDisplay = true;
+
+#if O0164_MULTI_LAYER_HRD
+        m_seiWriter.writeSEImessage( nalu.m_Bitstream, seiNoDisplay, m_pcEncTop->getVPS(), pcSlice->getSPS() );
+#else
+        m_seiWriter.writeSEImessage( nalu.m_Bitstream, seiNoDisplay, pcSlice->getSPS() );
+#endif
+        writeRBSPTrailingBits(nalu.m_Bitstream);
+        accessUnit.push_back(new NALUnitEBSP(nalu));
+      }
+    }
+
+    /* use the main bitstream buffer for storing the marshalled picture */
+    m_pcEntropyCoder->setBitstream(NULL);
+
+    pcSlice = pcPic->getSlice(0);
+
+
+#if HIGHER_LAYER_IRAP_SKIP_FLAG
+    if ( pcSlice->getSPS()->getUseSAO() && !( m_pcEncTop->getSkipPictureAtArcSwitch() && m_pcEncTop->getAdaptiveResolutionChange() > 0 && pcSlice->getLayerId() == 1 && pcSlice->getPOC() == m_pcEncTop->getAdaptiveResolutionChange()) )
+#else
+    if (pcSlice->getSPS()->getUseSAO())
+#endif
+    {
+      Bool sliceEnabled[MAX_NUM_COMPONENT];
+      TComBitCounter tempBitCounter;
+      tempBitCounter.resetBits();
+      m_pcEncTop->getRDGoOnSbacCoder()->setBitstream(&tempBitCounter);
+      m_pcSAO->initRDOCabacCoder(m_pcEncTop->getRDGoOnSbacCoder(), pcSlice);
+      m_pcSAO->SAOProcess(pcPic, sliceEnabled, pcPic->getSlice(0)->getLambdas()
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+                          , m_pcCfg->getSaoCtuBoundary()
+#endif
+                         );
+      m_pcSAO->PCMLFDisableProcess(pcPic);
+      m_pcEncTop->getRDGoOnSbacCoder()->setBitstream(NULL);
+
+      //assign SAO slice header
+      for(Int s=0; s< uiNumSliceSegments; s++)
+      {
+        pcPic->getSlice(s)->setSaoEnabledFlag(CHANNEL_TYPE_LUMA, sliceEnabled[COMPONENT_Y]);
+        assert(sliceEnabled[COMPONENT_Cb] == sliceEnabled[COMPONENT_Cr]);
+        pcPic->getSlice(s)->setSaoEnabledFlag(CHANNEL_TYPE_CHROMA, sliceEnabled[COMPONENT_Cb]);
+      }
+    }
+
+    // pcSlice is currently slice 0.
+    Int64 binCountsInNalUnits   = 0; // For implementation of cabac_zero_word stuffing (section 7.4.3.10)
+    Int64 numBytesInVclNalUnits = 0; // For implementation of cabac_zero_word stuffing (section 7.4.3.10)
+
+    for( UInt sliceSegmentStartCtuTsAddr = 0, sliceIdxCount=0; sliceSegmentStartCtuTsAddr < pcPic->getPicSym()->getNumberOfCtusInFrame(); sliceIdxCount++, sliceSegmentStartCtuTsAddr=pcSlice->getSliceSegmentCurEndCtuTsAddr() )
+    {
+      pcSlice = pcPic->getSlice(sliceIdxCount);
+      if(sliceIdxCount > 0 && pcSlice->getSliceType()!= I_SLICE)
+      {
+        pcSlice->checkColRefIdx(sliceIdxCount, pcPic);
+      }
+      pcPic->setCurrSliceIdx(sliceIdxCount);
+      m_pcSliceEncoder->setSliceIdx(sliceIdxCount);
+
+      pcSlice->setRPS(pcPic->getSlice(0)->getRPS());
+      pcSlice->setRPSidx(pcPic->getSlice(0)->getRPSidx());
+
+      for ( UInt ui = 0 ; ui < numSubstreams; ui++ )
+      {
+        substreamsOut[ui].clear();
+      }
+
+      m_pcEntropyCoder->setEntropyCoder   ( m_pcCavlcCoder, pcSlice );
+      m_pcEntropyCoder->resetEntropy      ();
+      /* start slice NALunit */
+#if SVC_EXTENSION
+      OutputNALUnit nalu( pcSlice->getNalUnitType(), pcSlice->getTLayer(), m_layerId );
+#else
+      OutputNALUnit nalu( pcSlice->getNalUnitType(), pcSlice->getTLayer() );
+#endif
+      m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
+
+#if R0071_IRAP_EOS_CROSS_LAYER_IMPACTS
+      if (pcSlice->isIRAP())
+      {
+        //the inference for NoOutputPriorPicsFlag
+        // KJS: This cannot happen at the encoder
+        if (!m_bFirst && pcSlice->isIRAP() && m_noRaslOutputFlag)
+        {
+          if (pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_CRA)
+          {
+            pcSlice->setNoOutputPriorPicsFlag(true);
+          }
+        }
+      }
+#else
+      pcSlice->setNoRaslOutputFlag(false);
+      if (pcSlice->isIRAP())
+      {
+        if (pcSlice->getNalUnitType() >= NAL_UNIT_CODED_SLICE_BLA_W_LP && pcSlice->getNalUnitType() <= NAL_UNIT_CODED_SLICE_IDR_N_LP)
+        {
+          pcSlice->setNoRaslOutputFlag(true);
+        }
+        //the inference for NoOutputPriorPicsFlag
+        // KJS: This cannot happen at the encoder
+        if (!m_bFirst && pcSlice->isIRAP() && pcSlice->getNoRaslOutputFlag())
+        {
+          if (pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_CRA)
+          {
+            pcSlice->setNoOutputPriorPicsFlag(true);
+          }
+        }
+      }
+#endif
+
+      tmpBitsBeforeWriting = m_pcEntropyCoder->getNumberOfWrittenBits();
+      m_pcEntropyCoder->encodeSliceHeader(pcSlice);
+      actualHeadBits += ( m_pcEntropyCoder->getNumberOfWrittenBits() - tmpBitsBeforeWriting );
+
+      pcSlice->setFinalized(true);
+
+#if ENVIRONMENT_VARIABLE_DEBUG_AND_TEST
+      g_bFinalEncode = true;
+#endif
+
+      pcSlice->clearSubstreamSizes(  );
+      {
+        UInt numBinsCoded = 0;
+        m_pcSliceEncoder->encodeSlice(pcPic, &(substreamsOut[0]), numBinsCoded);
+        binCountsInNalUnits+=numBinsCoded;
+      }
+
+#if ENVIRONMENT_VARIABLE_DEBUG_AND_TEST
+      g_bFinalEncode = false;
+#endif
+
+      {
+        // Construct the final bitstream by concatenating substreams.
+        // The final bitstream is either nalu.m_Bitstream or pcBitstreamRedirect;
+        // Complete the slice header info.
+        m_pcEntropyCoder->setEntropyCoder   ( m_pcCavlcCoder, pcSlice );
+        m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
+#if POC_RESET_IDC_SIGNALLING
+        tmpBitsBeforeWriting = m_pcEntropyCoder->getNumberOfWrittenBits();
+        m_pcEntropyCoder->encodeTilesWPPEntryPoint( pcSlice );
+        actualHeadBits += ( m_pcEntropyCoder->getNumberOfWrittenBits() - tmpBitsBeforeWriting );
+        m_pcEntropyCoder->encodeSliceHeaderExtn( pcSlice, actualHeadBits );
+#else
+        m_pcEntropyCoder->encodeTilesWPPEntryPoint( pcSlice );
+#endif
+
+        // Append substreams...
+        TComOutputBitstream *pcOut = pcBitstreamRedirect;
+        const Int numZeroSubstreamsAtStartOfSlice  = pcPic->getSubstreamForCtuAddr(pcSlice->getSliceSegmentCurStartCtuTsAddr(), false, pcSlice);
+        const Int numSubstreamsToCode  = pcSlice->getNumberOfSubstreamSizes()+1;
+        for ( UInt ui = 0 ; ui < numSubstreamsToCode; ui++ )
+        {
+          pcOut->addSubstream(&(substreamsOut[ui+numZeroSubstreamsAtStartOfSlice]));
+        }
+      }
+
+      // If current NALU is the first NALU of slice (containing slice header) and more NALUs exist (due to multiple dependent slices) then buffer it.
+      // If current NALU is the last NALU of slice and a NALU was buffered, then (a) Write current NALU (b) Update an write buffered NALU at approproate location in NALU list.
+      Bool bNALUAlignedWrittenToList    = false; // used to ensure current NALU is not written more than once to the NALU list.
+      xAttachSliceDataToNalUnit(nalu, pcBitstreamRedirect);
+      accessUnit.push_back(new NALUnitEBSP(nalu));
+      actualTotalBits += UInt(accessUnit.back()->m_nalUnitData.str().size()) * 8;
+      numBytesInVclNalUnits += Int64(accessUnit.back()->m_nalUnitData.str().size());
+      bNALUAlignedWrittenToList = true;
+
+      if (!bNALUAlignedWrittenToList)
+      {
+        nalu.m_Bitstream.writeAlignZero();
+        accessUnit.push_back(new NALUnitEBSP(nalu));
+      }
+
+      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
+      }
+    } // end iteration over slices
+
+    // cabac_zero_words processing
+    {
+      const Int log2subWidthCxsubHeightC = (pcPic->getComponentScaleX(COMPONENT_Cb)+pcPic->getComponentScaleY(COMPONENT_Cb));
+      const Int minCuWidth  = pcPic->getMinCUWidth();
+      const Int minCuHeight = pcPic->getMinCUHeight();
+#if REPN_FORMAT_IN_VPS
+      const Int paddedWidth = ((pcSlice->getPicWidthInLumaSamples()  + minCuWidth  - 1) / minCuWidth) * minCuWidth;
+      const Int paddedHeight= ((pcSlice->getPicHeightInLumaSamples() + minCuHeight - 1) / minCuHeight) * minCuHeight;
+#else
+      const Int paddedWidth = ((pcSlice->getSPS()->getPicWidthInLumaSamples()  + minCuWidth  - 1) / minCuWidth) * minCuWidth;
+      const Int paddedHeight= ((pcSlice->getSPS()->getPicHeightInLumaSamples() + minCuHeight - 1) / minCuHeight) * minCuHeight;
+#endif
+      const Int rawBits = paddedWidth * paddedHeight *
+                             (g_bitDepth[CHANNEL_TYPE_LUMA] + 2*(g_bitDepth[CHANNEL_TYPE_CHROMA]>>log2subWidthCxsubHeightC));
+      const Int64 threshold = (32LL/3)*numBytesInVclNalUnits + (rawBits/32);
+      if (binCountsInNalUnits >= threshold)
+      {
+        // need to add additional cabac zero words (each one accounts for 3 bytes (=00 00 03)) to increase numBytesInVclNalUnits
+        const Int64 targetNumBytesInVclNalUnits = ((binCountsInNalUnits - (rawBits/32))*3+31)/32;
+        const Int64 numberOfAdditionalBytesNeeded=targetNumBytesInVclNalUnits - numBytesInVclNalUnits;
+
+        if (numberOfAdditionalBytesNeeded>0) // It should be!
+        {
+          const Int64 numberOfAdditionalCabacZeroWords=(numberOfAdditionalBytesNeeded+2)/3;
+          const Int64 numberOfAdditionalCabacZeroBytes=numberOfAdditionalCabacZeroWords*3;
+          if (m_pcCfg->getCabacZeroWordPaddingEnabled())
+          {
+            std::vector<Char> zeroBytesPadding((size_t)numberOfAdditionalCabacZeroBytes, Char(0));
+            for(size_t i=0; i<numberOfAdditionalCabacZeroWords; i++)
+            {
+              zeroBytesPadding[i*3+2]=3;  // 00 00 03
+            }
+            accessUnit.back()->m_nalUnitData.write(&(zeroBytesPadding[0]), (size_t)numberOfAdditionalCabacZeroBytes);
+            printf("Adding %lld bytes of padding\n", numberOfAdditionalCabacZeroWords*3);
+          }
+          else
+          {
+            printf("Standard would normally require adding %lld bytes of padding\n", numberOfAdditionalCabacZeroWords*3);
+          }
+        }
+      }
+    }
+
+    pcPic->compressMotion();
+
+    //-- For time output for each slice
+    Double dEncTime = (Double)(clock()-iBeforeTime) / CLOCKS_PER_SEC;
+
+    std::string digestStr;
+    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;
+        UInt numChar=calcMD5(*pcPic->getPicYuvRec(), sei_recon_picture_digest.m_digest);
+        digestStr = digestToString(sei_recon_picture_digest.m_digest, numChar);
+      }
+      else if(m_pcCfg->getDecodedPictureHashSEIEnabled() == 2)
+      {
+        sei_recon_picture_digest.method = SEIDecodedPictureHash::CRC;
+        UInt numChar=calcCRC(*pcPic->getPicYuvRec(), sei_recon_picture_digest.m_digest);
+        digestStr = digestToString(sei_recon_picture_digest.m_digest, numChar);
+      }
+      else if(m_pcCfg->getDecodedPictureHashSEIEnabled() == 3)
+      {
+        sei_recon_picture_digest.method = SEIDecodedPictureHash::CHECKSUM;
+        UInt numChar=calcChecksum(*pcPic->getPicYuvRec(), sei_recon_picture_digest.m_digest);
+        digestStr = digestToString(sei_recon_picture_digest.m_digest, numChar);
+      }
+
+#if SVC_EXTENSION
+      OutputNALUnit nalu(NAL_UNIT_SUFFIX_SEI, pcSlice->getTLayer(), m_layerId);
+#else
+      OutputNALUnit nalu(NAL_UNIT_SUFFIX_SEI, pcSlice->getTLayer());
+#endif
+
+      /* write the SEI messages */
+      m_pcEntropyCoder->setEntropyCoder(m_pcCavlcCoder, pcSlice);
+#if O0164_MULTI_LAYER_HRD
+      m_seiWriter.writeSEImessage(nalu.m_Bitstream, sei_recon_picture_digest, m_pcEncTop->getVPS(), pcSlice->getSPS());
+#else
+      m_seiWriter.writeSEImessage(nalu.m_Bitstream, sei_recon_picture_digest, pcSlice->getSPS());
+#endif
+      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);
+#if O0164_MULTI_LAYER_HRD
+      m_seiWriter.writeSEImessage(nalu.m_Bitstream, sei_temporal_level0_index, m_pcEncTop->getVPS(), pcSlice->getSPS());
+#else
+      m_seiWriter.writeSEImessage(nalu.m_Bitstream, sei_temporal_level0_index, pcSlice->getSPS());      
+#endif
+      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));
+    }
+
+    m_pcCfg->setEncodedFlag(iGOPid, true);
+    xCalculateAddPSNR( pcPic, pcPic->getPicYuvRec(), accessUnit, dEncTime, snr_conversion, printFrameMSE );
+
+    //In case of field coding, compute the interlaced PSNR for both fields
+    if(isField)
+    {
+      Bool bothFieldsAreEncoded = false;
+      Int correspondingFieldPOC = pcPic->getPOC();
+      Int currentPicGOPPoc = m_pcCfg->getGOPEntry(iGOPid).m_POC;
+      if(pcPic->getPOC() == 0)
+      {
+        // particular case for POC 0 and 1. 
+        // If they are not encoded first and separately from other pictures, we need to change this 
+        // POC 0 is always encoded first then POC 1 is encoded
+        bothFieldsAreEncoded = false;
+      }
+      else if(pcPic->getPOC() == 1)
+      {
+        // if we are at POC 1, POC 0 has been encoded for sure
+        correspondingFieldPOC = 0;
+        bothFieldsAreEncoded = true;
+      }
+      else 
+      {
+        if(pcPic->getPOC()%2 == 1)
+        {
+          correspondingFieldPOC -= 1; // all odd POC are associated with the preceding even POC (e.g poc 1 is associated to poc 0)
+          currentPicGOPPoc      -= 1;
+        }
+        else
+        {
+          correspondingFieldPOC += 1; // all even POC are associated with the following odd POC (e.g poc 0 is associated to poc 1)
+          currentPicGOPPoc      += 1;
+        }
+        for(Int i = 0; i < m_iGopSize; i ++)
+        {
+          if(m_pcCfg->getGOPEntry(i).m_POC == currentPicGOPPoc)
+          {
+            bothFieldsAreEncoded = m_pcCfg->getGOPEntry(i).m_isEncoded;
+            break;
+          }
+        }
+      }
+
+      if(bothFieldsAreEncoded)
+      {        
+        //get complementary top field
+        TComList<TComPic*>::iterator   iterPic = rcListPic.begin();
+        while ((*iterPic)->getPOC() != correspondingFieldPOC)
+        {
+          iterPic ++;
+        }
+        TComPic* correspondingFieldPic = *(iterPic);
+
+        if( (pcPic->isTopField() && isTff) || (!pcPic->isTopField() && !isTff))
+        {
+          xCalculateInterlacedAddPSNR(pcPic, correspondingFieldPic, pcPic->getPicYuvRec(), correspondingFieldPic->getPicYuvRec(), accessUnit, dEncTime, snr_conversion, printFrameMSE );
+        }
+        else
+        {
+          xCalculateInterlacedAddPSNR(correspondingFieldPic, pcPic, correspondingFieldPic->getPicYuvRec(), pcPic->getPicYuvRec(), accessUnit, dEncTime, snr_conversion, printFrameMSE );
+        }
+      }
+    }
+
+    if (!digestStr.empty())
+    {
+      if(m_pcCfg->getDecodedPictureHashSEIEnabled() == 1)
+      {
+        printf(" [MD5:%s]", digestStr.c_str());
+      }
+      else if(m_pcCfg->getDecodedPictureHashSEIEnabled() == 2)
+      {
+        printf(" [CRC:%s]", digestStr.c_str());
+      }
+      else if(m_pcCfg->getDecodedPictureHashSEIEnabled() == 3)
+      {
+        printf(" [Checksum:%s]", digestStr.c_str());
+      }
+    }
+
+    if ( m_pcCfg->getUseRateCtrl() )
+    {
+      Double avgQP     = m_pcRateCtrl->getRCPic()->calAverageQP();
+      Double avgLambda = m_pcRateCtrl->getRCPic()->calAverageLambda();
+      if ( avgLambda < 0.0 )
+      {
+        avgLambda = lambda;
+      }
+
+      m_pcRateCtrl->getRCPic()->updateAfterPicture( actualHeadBits, actualTotalBits, avgQP, avgLambda, pcSlice->getSliceType());
+      m_pcRateCtrl->getRCPic()->addToPictureLsit( m_pcRateCtrl->getPicList() );
+
+      m_pcRateCtrl->getRCSeq()->updateAfterPic( actualTotalBits );
+      if ( pcSlice->getSliceType() != I_SLICE )
+      {
+        m_pcRateCtrl->getRCGOP()->updateAfterPicture( actualTotalBits );
+      }
+      else    // for intra picture, the estimated bits are used to update the current status in the GOP
+      {
+        m_pcRateCtrl->getRCGOP()->updateAfterPicture( estimatedBits );
+      }
+    }
+
+    if( ( m_pcCfg->getPictureTimingSEIEnabled() || m_pcCfg->getDecodingUnitInfoSEIEnabled() ) &&
+        ( pcSlice->getSPS()->getVuiParametersPresentFlag() ) &&
+        ( ( pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getNalHrdParametersPresentFlag() )
+        || ( pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getVclHrdParametersPresentFlag() ) ) )
+    {
+      TComVUI *vui = pcSlice->getSPS()->getVuiParameters();
+      TComHRD *hrd = vui->getHrdParameters();
+
+      if( hrd->getSubPicCpbParamsPresentFlag() )
+      {
+        Int i;
+        UInt64 ui64Tmp;
+        UInt uiPrev = 0;
+        UInt numDU = ( pictureTimingSEI.m_numDecodingUnitsMinus1 + 1 );
+        UInt *pCRD = &pictureTimingSEI.m_duCpbRemovalDelayMinus1[0];
+        UInt maxDiff = ( hrd->getTickDivisorMinus2() + 2 ) - 1;
+
+        for( i = 0; i < numDU; i ++ )
+        {
+          pictureTimingSEI.m_numNalusInDuMinus1[ i ]       = ( i == 0 ) ? ( accumNalsDU[ i ] - 1 ) : ( accumNalsDU[ i ] - accumNalsDU[ i - 1] - 1 );
+        }
+
+        if( numDU == 1 )
+        {
+          pCRD[ 0 ] = 0; /* don't care */
+        }
+        else
+        {
+          pCRD[ numDU - 1 ] = 0;/* by definition */
+          UInt tmp = 0;
+          UInt accum = 0;
+
+          for( i = ( numDU - 2 ); i >= 0; i -- )
+          {
+            ui64Tmp = ( ( ( accumBitsDU[ numDU - 1 ]  - accumBitsDU[ i ] ) * ( vui->getTimingInfo()->getTimeScale() / vui->getTimingInfo()->getNumUnitsInTick() ) * ( hrd->getTickDivisorMinus2() + 2 ) ) / ( m_pcCfg->getTargetBitrate() ) );
+            if( (UInt)ui64Tmp > maxDiff )
+            {
+              tmp ++;
+            }
+          }
+          uiPrev = 0;
+
+          UInt flag = 0;
+          for( i = ( numDU - 2 ); i >= 0; i -- )
+          {
+            flag = 0;
+            ui64Tmp = ( ( ( accumBitsDU[ numDU - 1 ]  - accumBitsDU[ i ] ) * ( vui->getTimingInfo()->getTimeScale() / vui->getTimingInfo()->getNumUnitsInTick() ) * ( hrd->getTickDivisorMinus2() + 2 ) ) / ( m_pcCfg->getTargetBitrate() ) );
+
+            if( (UInt)ui64Tmp > maxDiff )
+            {
+              if(uiPrev >= maxDiff - tmp)
+              {
+                ui64Tmp = uiPrev + 1;
+                flag = 1;
+              }
+              else                            ui64Tmp = maxDiff - tmp + 1;
+            }
+            pCRD[ i ] = (UInt)ui64Tmp - uiPrev - 1;
+            if( (Int)pCRD[ i ] < 0 )
+            {
+              pCRD[ i ] = 0;
+            }
+            else if (tmp > 0 && flag == 1)
+            {
+              tmp --;
+            }
+            accum += pCRD[ i ] + 1;
+            uiPrev = accum;
+          }
+        }
+      }
+
+      if( m_pcCfg->getPictureTimingSEIEnabled() )
+      {
+        {
+          OutputNALUnit nalu(NAL_UNIT_PREFIX_SEI, pcSlice->getTLayer());
+          m_pcEntropyCoder->setEntropyCoder(m_pcCavlcCoder, pcSlice);
+          pictureTimingSEI.m_picStruct = (isField && pcSlice->getPic()->isTopField())? 1 : isField? 2 : 0;
+#if O0164_MULTI_LAYER_HRD
+          m_seiWriter.writeSEImessage(nalu.m_Bitstream, pictureTimingSEI, m_pcEncTop->getVPS(), pcSlice->getSPS());
+#else
+          m_seiWriter.writeSEImessage(nalu.m_Bitstream, pictureTimingSEI, pcSlice->getSPS());
+#endif
+          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 = accessUnit.begin();
+          for(Int j = 0; 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);
+#if O0164_MULTI_LAYER_HRD
+          m_seiWriter.writeSEImessage(nalu.m_Bitstream, scalableNestingSEI, m_pcEncTop->getVPS(), pcSlice->getSPS());
+#else
+          m_seiWriter.writeSEImessage(nalu.m_Bitstream, scalableNestingSEI, pcSlice->getSPS());
+#endif
+          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 = accessUnit.begin();
+          for(Int j = 0; 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;
+
+          // Insert the first one in the right location, before the first slice
+          if(i == 0)
+          {
+            // Insert before the first slice.
+#if O0164_MULTI_LAYER_HRD
+            m_seiWriter.writeSEImessage(nalu.m_Bitstream, tempSEI, m_pcEncTop->getVPS(), pcSlice->getSPS());
+#else
+            m_seiWriter.writeSEImessage(nalu.m_Bitstream, tempSEI, pcSlice->getSPS());
+#endif
+            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
+            AccessUnit::iterator it = accessUnit.begin();
+            for(Int j = 0; j < seiPositionInAu + offsetPosition; j++)
+            {
+              it++;
+            }
+            accessUnit.insert(it, new NALUnitEBSP(nalu));
+          }
+          else
+          {
+            // For the second decoding unit onwards we know how many NALUs are present
+            AccessUnit::iterator it = accessUnit.begin();
+            for (Int ctr = 0; it != accessUnit.end(); it++)
+            {
+              if(ctr == accumNalsDU[ i - 1 ])
+              {
+                // Insert before the first slice.
+#if O0164_MULTI_LAYER_HRD
+                m_seiWriter.writeSEImessage(nalu.m_Bitstream, tempSEI, m_pcEncTop->getVPS(), pcSlice->getSPS());
+#else
+                m_seiWriter.writeSEImessage(nalu.m_Bitstream, tempSEI, pcSlice->getSPS());
+#endif
+                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++;
+              }
+            }
+          }
+        }
+      }
+    }
+
+#if R0071_IRAP_EOS_CROSS_LAYER_IMPACTS
+    m_prevPicHasEos = false;
+    if (m_pcCfg->getLayerSwitchOffBegin() < m_pcCfg->getLayerSwitchOffEnd())
+    {
+      Int pocNext;
+      if (iGOPid == m_iGopSize - 1)
+      {
+        pocNext = iPOCLast - iNumPicRcvd + m_iGopSize + m_pcCfg->getGOPEntry(0).m_POC;
+      }
+      else
+      {
+        pocNext = iPOCLast - iNumPicRcvd + m_pcCfg->getGOPEntry(iGOPid + 1).m_POC;
+      }
+
+      if (pocNext > m_pcCfg->getLayerSwitchOffBegin() && pocCurr < m_pcCfg->getLayerSwitchOffEnd())
+      {
+        OutputNALUnit nalu(NAL_UNIT_EOS, 0, pcSlice->getLayerId());
+        m_pcEntropyCoder->setEntropyCoder(m_pcCavlcCoder, pcSlice);
+        accessUnit.push_back(new NALUnitEBSP(nalu));
+        m_prevPicHasEos = true;
+      }
+    }
+#endif
+
+    xResetNonNestedSEIPresentFlags();
+    xResetNestedSEIPresentFlags();
+
+    pcPic->getPicYuvRec()->copyToPic(pcPicYuvRecOut);
+
+#if M0040_ADAPTIVE_RESOLUTION_CHANGE
+    pcPicYuvRecOut->setReconstructed(true);
+#endif
+#if P0297_VPS_POC_LSB_ALIGNED_FLAG
+    m_pcEncTop->setFirstPicInLayerDecodedFlag(true);
+#endif
+    pcPic->setReconMark   ( true );
+    m_bFirst = false;
+    m_iNumPicCoded++;
+    m_totalCoded ++;
+    /* logging: insert a newline at end of picture period */
+    printf("\n");
+    fflush(stdout);
+
+#if EFFICIENT_FIELD_IRAP
+    if(IRAPtoReorder)
+    {
+      if(swapIRAPForward)
+      {
+        if(iGOPid == IRAPGOPid)
+        {
+          iGOPid = IRAPGOPid +1;
+          IRAPtoReorder = false;
+        }
+        else if(iGOPid == IRAPGOPid +1)
+        {
+          iGOPid --;
+        }
+      }
+      else
+      {
+        if(iGOPid == IRAPGOPid)
+        {
+          iGOPid = IRAPGOPid -1;
+        }
+        else if(iGOPid == IRAPGOPid -1)
+        {
+          iGOPid = IRAPGOPid;
+          IRAPtoReorder = false;
+        }
+      }
+    }
+#endif
+  } // iGOPid-loop
+
+  delete pcBitstreamRedirect;
+
+  if( accumBitsDU != NULL) delete accumBitsDU;
+  if( accumNalsDU != NULL) delete accumNalsDU;
+
+#if SVC_EXTENSION
+  assert ( m_iNumPicCoded <= 1 );
+#else
+  assert ( (m_iNumPicCoded == iNumPicRcvd) );
+#endif
+}
+
+#if !SVC_EXTENSION
+Void TEncGOP::printOutSummary(UInt uiNumAllPicCoded, Bool isField, const Bool printMSEBasedSNR, const Bool printSequenceMSE)
+{
+  assert (uiNumAllPicCoded == m_gcAnalyzeAll.getNumPic());
+
+
+  //--CFG_KDY
+  const Int rateMultiplier=(isField?2:1);
+  m_gcAnalyzeAll.setFrmRate( m_pcCfg->getFrameRate()*rateMultiplier );
+  m_gcAnalyzeI.setFrmRate( m_pcCfg->getFrameRate()*rateMultiplier );
+  m_gcAnalyzeP.setFrmRate( m_pcCfg->getFrameRate()*rateMultiplier );
+  m_gcAnalyzeB.setFrmRate( m_pcCfg->getFrameRate()*rateMultiplier );
+  const ChromaFormat chFmt = m_pcCfg->getChromaFormatIdc();
+
+  //-- all
+  printf( "\n\nSUMMARY --------------------------------------------------------\n" );
+  m_gcAnalyzeAll.printOut('a', chFmt, printMSEBasedSNR, printSequenceMSE);
+
+  printf( "\n\nI Slices--------------------------------------------------------\n" );
+  m_gcAnalyzeI.printOut('i', chFmt, printMSEBasedSNR, printSequenceMSE);
+
+  printf( "\n\nP Slices--------------------------------------------------------\n" );
+  m_gcAnalyzeP.printOut('p', chFmt, printMSEBasedSNR, printSequenceMSE);
+
+  printf( "\n\nB Slices--------------------------------------------------------\n" );
+  m_gcAnalyzeB.printOut('b', chFmt, printMSEBasedSNR, printSequenceMSE);
+
+#if _SUMMARY_OUT_
+  m_gcAnalyzeAll.printSummary(chFmt, printSequenceMSE);
+#endif
+#if _SUMMARY_PIC_
+  m_gcAnalyzeI.printSummary(chFmt, printSequenceMSE,'I');
+  m_gcAnalyzeP.printSummary(chFmt, printSequenceMSE,'P');
+  m_gcAnalyzeB.printSummary(chFmt, printSequenceMSE,'B');
+#endif
+
+  if(isField)
+  {
+    //-- interlaced summary
+    m_gcAnalyzeAll_in.setFrmRate( m_pcCfg->getFrameRate());
+    m_gcAnalyzeAll_in.setBits(m_gcAnalyzeAll.getBits());
+    // prior to the above statement, the interlace analyser does not contain the correct total number of bits.
+
+    printf( "\n\nSUMMARY INTERLACED ---------------------------------------------\n" );
+    m_gcAnalyzeAll_in.printOut('a', chFmt, printMSEBasedSNR, printSequenceMSE);
+
+#if _SUMMARY_OUT_
+    m_gcAnalyzeAll_in.printSummary(chFmt, printSequenceMSE);
+#endif
+  }
+
+  printf("\nRVM: %.3lf\n" , xCalculateRVM());
+}
+#endif
+
+Void TEncGOP::preLoopFilterPicAll( TComPic* pcPic, UInt64& ruiDist )
+{
+  Bool bCalcDist = false;
+  m_pcLoopFilter->setCfg(m_pcCfg->getLFCrossTileBoundaryFlag());
+  m_pcLoopFilter->loopFilterPic( pcPic );
+
+  if (!bCalcDist)
+    ruiDist = xFindDistortionFrame(pcPic->getPicYuvOrg(), pcPic->getPicYuvRec());
+}
+
+// ====================================================================================================================
+// Protected member functions
+// ====================================================================================================================
+
+
+Void TEncGOP::xInitGOP( Int iPOCLast, Int iNumPicRcvd, TComList<TComPic*>& rcListPic, TComList<TComPicYuv*>& rcListPicYuvRecOut, Bool isField )
+{
+  assert( iNumPicRcvd > 0 );
+  //  Exception for the first frames
+  if ( ( isField && (iPOCLast == 0 || iPOCLast == 1) ) || (!isField  && (iPOCLast == 0))  )
+  {
+    m_iGopSize    = 1;
+  }
+  else
+  {
+    m_iGopSize    = m_pcCfg->getGOPSize();
+  }
+  assert (m_iGopSize > 0);
+
+  return;
+}
+
+
+Void TEncGOP::xGetBuffer( TComList<TComPic*>&      rcListPic,
+                         TComList<TComPicYuv*>&    rcListPicYuvRecOut,
+                         Int                       iNumPicRcvd,
+                         Int                       iTimeOffset,
+                         TComPic*&                 rpcPic,
+                         TComPicYuv*&              rpcPicYuvRecOut,
+                         Int                       pocCurr,
+                         Bool                      isField)
+{
+  Int i;
+  //  Rec. output
+  TComList<TComPicYuv*>::iterator     iterPicYuvRec = rcListPicYuvRecOut.end();
+
+  if (isField && pocCurr > 1 && m_iGopSize!=1)
+  {
+    iTimeOffset--;
+  }
+
+  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 != NULL);
+  assert (rpcPic->getPOC() == pocCurr);
+
+  return;
+}
+
+UInt64 TEncGOP::xFindDistortionFrame (TComPicYuv* pcPic0, TComPicYuv* pcPic1)
+{
+  UInt64  uiTotalDiff = 0;
+
+  for(Int chan=0; chan<pcPic0 ->getNumberValidComponents(); chan++)
+  {
+    const ComponentID ch=ComponentID(chan);
+    Pel*  pSrc0   = pcPic0 ->getAddr(ch);
+    Pel*  pSrc1   = pcPic1 ->getAddr(ch);
+    UInt  uiShift     = 2 * DISTORTION_PRECISION_ADJUSTMENT(g_bitDepth[toChannelType(ch)]-8);
+
+    const Int   iStride = pcPic0->getStride(ch);
+    const Int   iWidth  = pcPic0->getWidth(ch);
+    const Int   iHeight = pcPic0->getHeight(ch);
+
+    for(Int y = 0; y < iHeight; y++ )
+    {
+      for(Int x = 0; x < iWidth; x++ )
+      {
+        Intermediate_Int iTemp = pSrc0[x] - pSrc1[x];
+        uiTotalDiff += UInt64((iTemp*iTemp) >> uiShift);
+      }
+      pSrc0 += iStride;
+      pSrc1 += iStride;
+    }
+  }
+
+  return uiTotalDiff;
+}
+
+#if VERBOSE_RATE
+static const Char* nalUnitTypeToString(NalUnitType type)
+{
+  switch (type)
+  {
+    case NAL_UNIT_CODED_SLICE_TRAIL_R:    return "TRAIL_R";
+    case NAL_UNIT_CODED_SLICE_TRAIL_N:    return "TRAIL_N";
+    case NAL_UNIT_CODED_SLICE_TSA_R:      return "TSA_R";
+    case NAL_UNIT_CODED_SLICE_TSA_N:      return "TSA_N";
+    case NAL_UNIT_CODED_SLICE_STSA_R:     return "STSA_R";
+    case NAL_UNIT_CODED_SLICE_STSA_N:     return "STSA_N";
+    case NAL_UNIT_CODED_SLICE_BLA_W_LP:   return "BLA_W_LP";
+    case NAL_UNIT_CODED_SLICE_BLA_W_RADL: return "BLA_W_RADL";
+    case NAL_UNIT_CODED_SLICE_BLA_N_LP:   return "BLA_N_LP";
+    case NAL_UNIT_CODED_SLICE_IDR_W_RADL: return "IDR_W_RADL";
+    case NAL_UNIT_CODED_SLICE_IDR_N_LP:   return "IDR_N_LP";
+    case NAL_UNIT_CODED_SLICE_CRA:        return "CRA";
+    case NAL_UNIT_CODED_SLICE_RADL_R:     return "RADL_R";
+    case NAL_UNIT_CODED_SLICE_RADL_N:     return "RADL_N";
+    case NAL_UNIT_CODED_SLICE_RASL_R:     return "RASL_R";
+    case NAL_UNIT_CODED_SLICE_RASL_N:     return "RASL_N";
+    case NAL_UNIT_VPS:                    return "VPS";
+    case NAL_UNIT_SPS:                    return "SPS";
+    case NAL_UNIT_PPS:                    return "PPS";
+    case NAL_UNIT_ACCESS_UNIT_DELIMITER:  return "AUD";
+    case NAL_UNIT_EOS:                    return "EOS";
+    case NAL_UNIT_EOB:                    return "EOB";
+    case NAL_UNIT_FILLER_DATA:            return "FILLER";
+    case NAL_UNIT_PREFIX_SEI:             return "SEI";
+    case NAL_UNIT_SUFFIX_SEI:             return "SEI";
+    default:                              return "UNK";
+  }
+}
+#endif
+
+Void TEncGOP::xCalculateAddPSNR( TComPic* pcPic, TComPicYuv* pcPicD, const AccessUnit& accessUnit, Double dEncTime, const InputColourSpaceConversion conversion, const Bool printFrameMSE )
+{
+  Double  dPSNR[MAX_NUM_COMPONENT];
+
+  for(Int i=0; i<MAX_NUM_COMPONENT; i++)
+  {
+    dPSNR[i]=0.0;
+  }
+
+  TComPicYuv cscd;
+  if (conversion!=IPCOLOURSPACE_UNCHANGED)
+  {
+    cscd.create(pcPicD->getWidth(COMPONENT_Y), pcPicD->getHeight(COMPONENT_Y), pcPicD->getChromaFormat(), g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth);
+    TVideoIOYuv::ColourSpaceConvert(*pcPicD, cscd, conversion, g_bitDepth, false);
+  }
+  TComPicYuv &picd=(conversion==IPCOLOURSPACE_UNCHANGED)?*pcPicD : cscd;
+
+  //===== calculate PSNR =====
+  Double MSEyuvframe[MAX_NUM_COMPONENT] = {0, 0, 0};
+
+  for(Int chan=0; chan<pcPicD->getNumberValidComponents(); chan++)
+  {
+    const ComponentID ch=ComponentID(chan);
+    const Pel*  pOrg    = (conversion!=IPCOLOURSPACE_UNCHANGED) ? pcPic ->getPicYuvTrueOrg()->getAddr(ch) : pcPic ->getPicYuvOrg()->getAddr(ch);
+    Pel*  pRec    = picd.getAddr(ch);
+    const Int   iStride = pcPicD->getStride(ch);
+
+    const Int   iWidth  = pcPicD->getWidth (ch) - (m_pcEncTop->getPad(0) >> pcPic->getComponentScaleX(ch));
+    const Int   iHeight = pcPicD->getHeight(ch) - ((m_pcEncTop->getPad(1) >> (pcPic->isField()?1:0)) >> pcPic->getComponentScaleY(ch));
+
+    Int   iSize   = iWidth*iHeight;
+
+    UInt64 uiSSDtemp=0;
+    for(Int y = 0; y < iHeight; y++ )
+    {
+      for(Int x = 0; x < iWidth; x++ )
+      {
+        Intermediate_Int iDiff = (Intermediate_Int)( pOrg[x] - pRec[x] );
+        uiSSDtemp   += iDiff * iDiff;
+      }
+      pOrg += iStride;
+      pRec += iStride;
+    }
+    const Int maxval = 255 << (g_bitDepth[toChannelType(ch)] - 8);
+    const Double fRefValue = (Double) maxval * maxval * iSize;
+    dPSNR[ch]         = ( uiSSDtemp ? 10.0 * log10( fRefValue / (Double)uiSSDtemp ) : 999.99 );
+    MSEyuvframe[ch]   = (Double)uiSSDtemp/(iSize);
+  }
+
+
+  /* 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 SVC_EXTENSION
+  m_gcAnalyzeAll[pcPic->getSlice(0)->getVPS()->getLayerIdxInVps(m_layerId)].addResult (dPSNR, (Double)uibits, MSEyuvframe);
+  TComSlice*  pcSlice = pcPic->getSlice(0);
+  if (pcSlice->isIntra())
+  {
+    m_gcAnalyzeI[pcPic->getSlice(0)->getVPS()->getLayerIdxInVps(m_layerId)].addResult (dPSNR, (Double)uibits, MSEyuvframe);
+  }
+  if (pcSlice->isInterP())
+  {
+    m_gcAnalyzeP[pcPic->getSlice(0)->getVPS()->getLayerIdxInVps(m_layerId)].addResult (dPSNR, (Double)uibits, MSEyuvframe);
+  }
+  if (pcSlice->isInterB())
+  {
+    m_gcAnalyzeB[pcPic->getSlice(0)->getVPS()->getLayerIdxInVps(m_layerId)].addResult (dPSNR, (Double)uibits, MSEyuvframe);
+  }
+#else
+  m_gcAnalyzeAll.addResult (dPSNR, (Double)uibits, MSEyuvframe);
+  TComSlice*  pcSlice = pcPic->getSlice(0);
+  if (pcSlice->isIntra())
+  {
+    m_gcAnalyzeI.addResult (dPSNR, (Double)uibits, MSEyuvframe);
+  }
+  if (pcSlice->isInterP())
+  {
+    m_gcAnalyzeP.addResult (dPSNR, (Double)uibits, MSEyuvframe);
+  }
+  if (pcSlice->isInterB())
+  {
+    m_gcAnalyzeB.addResult (dPSNR, (Double)uibits, MSEyuvframe);
+  }
+#endif
+
+  Char c = (pcSlice->isIntra() ? 'I' : pcSlice->isInterP() ? 'P' : 'B');
+  if (!pcSlice->isReferenced()) c += 32;
+
+#if SVC_EXTENSION
+#if ADAPTIVE_QP_SELECTION  
+  printf("POC %4d LId: %1d TId: %1d ( %c-SLICE %s, nQP %d QP %d ) %10d bits",
+         pcSlice->getPOC(),
+         pcSlice->getLayerId(),
+         pcSlice->getTLayer(),
+         c,
+         NaluToStr( pcSlice->getNalUnitType() ).data(),
+         pcSlice->getSliceQpBase(),
+         pcSlice->getSliceQp(),
+         uibits );
+#else
+  printf("POC %4d LId: %1d TId: %1d ( %c-SLICE %s, QP %d ) %10d bits",
+         pcSlice->getPOC()-pcSlice->getLastIDR(),
+         pcSlice->getLayerId(),
+         pcSlice->getTLayer(),
+         c,
+         NaluToStr( pcSlice->getNalUnitType() ).data(),
+         pcSlice->getSliceQp(),
+         uibits );
+#endif
+#else
+#if ADAPTIVE_QP_SELECTION
+  printf("POC %4d TId: %1d ( %c-SLICE, nQP %d QP %d ) %10d bits",
+         pcSlice->getPOC(),
+         pcSlice->getTLayer(),
+         c,
+         pcSlice->getSliceQpBase(),
+         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]", dPSNR[COMPONENT_Y], dPSNR[COMPONENT_Cb], dPSNR[COMPONENT_Cr] );
+  if (printFrameMSE)
+  {
+    printf(" [Y MSE %6.4lf  U MSE %6.4lf  V MSE %6.4lf]", MSEyuvframe[COMPONENT_Y], MSEyuvframe[COMPONENT_Cb], MSEyuvframe[COMPONENT_Cr] );
+  }
+  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 SVC_EXTENSION
+#if VPS_EXTN_DIRECT_REF_LAYERS
+      if( pcSlice->getRefPic(RefPicList(iRefList), iRefIndex)->isILR(m_layerId) )
+      {
+#if POC_RESET_IDC_ENCODER
+        UInt refLayerId = pcSlice->getRefPic(RefPicList(iRefList), iRefIndex)->getLayerId();
+        UInt refLayerIdc = pcSlice->getReferenceLayerIdc(refLayerId);
+        assert( g_posScalingFactor[refLayerIdc][0] );
+        assert( g_posScalingFactor[refLayerIdc][1] );
+
+        printf( "%d(%d, {%1.2f, %1.2f}x)", pcSlice->getRefPOC(RefPicList(iRefList), iRefIndex), refLayerId, 65536.0/g_posScalingFactor[refLayerIdc][0], 65536.0/g_posScalingFactor[refLayerIdc][1] );
+#else
+        printf( "%d(%d)", pcSlice->getRefPOC(RefPicList(iRefList), iRefIndex)-pcSlice->getLastIDR(), pcSlice->getRefPic(RefPicList(iRefList), iRefIndex)->getLayerId() );
+#endif
+      }
+      else
+      {
+#if POC_RESET_IDC_ENCODER
+        printf ("%d", pcSlice->getRefPOC(RefPicList(iRefList), iRefIndex));
+#else
+        printf ("%d", pcSlice->getRefPOC(RefPicList(iRefList), iRefIndex)-pcSlice->getLastIDR());
+#endif
+      }
+#endif
+      if( pcSlice->getEnableTMVPFlag() && iRefList == 1 - pcSlice->getColFromL0Flag() && iRefIndex == pcSlice->getColRefIdx() )
+      {
+        printf( "c" );
+      }
+
+      printf( " " );
+#else
+      printf ("%d ", pcSlice->getRefPOC(RefPicList(iRefList), iRefIndex)-pcSlice->getLastIDR());
+#endif
+    }
+    printf("]");
+  }
+#if Q0048_CGS_3D_ASYMLUT
+  pcPic->setFrameBit( (Int)uibits );
+  if( m_layerId && pcSlice->getPPS()->getCGSFlag() )
+  {
+#if R0179_ENC_OPT_3DLUT_SIZE
+      m_Enc3DAsymLUTPicUpdate.update3DAsymLUTParam( &m_Enc3DAsymLUTPPS );
+#else
+    if( m_Enc3DAsymLUTPPS.getPPSBit() > 0 )
+      m_Enc3DAsymLUTPicUpdate.copy3DAsymLUT( &m_Enc3DAsymLUTPPS );
+#endif
+    m_Enc3DAsymLUTPicUpdate.updatePicCGSBits( pcSlice , m_Enc3DAsymLUTPPS.getPPSBit() );
+  }
+#endif
+
+  cscd.destroy();
+}
+
+Void TEncGOP::xCalculateInterlacedAddPSNR( TComPic* pcPicOrgFirstField, TComPic* pcPicOrgSecondField,
+                                           TComPicYuv* pcPicRecFirstField, TComPicYuv* pcPicRecSecondField,
+                                           const AccessUnit& accessUnit, Double dEncTime, const InputColourSpaceConversion conversion, const Bool printFrameMSE )
+{
+  Double  dPSNR[MAX_NUM_COMPONENT];
+  TComPic    *apcPicOrgFields[2]={pcPicOrgFirstField, pcPicOrgSecondField};
+  TComPicYuv *apcPicRecFields[2]={pcPicRecFirstField, pcPicRecSecondField};
+
+  for(Int i=0; i<MAX_NUM_COMPONENT; i++)
+  {
+    dPSNR[i]=0.0;
+  }
+
+  TComPicYuv cscd[2 /* first/second field */];
+  if (conversion!=IPCOLOURSPACE_UNCHANGED)
+  {
+    for(UInt fieldNum=0; fieldNum<2; fieldNum++)
+    {
+      TComPicYuv &reconField=*(apcPicRecFields[fieldNum]);
+      cscd[fieldNum].create(reconField.getWidth(COMPONENT_Y), reconField.getHeight(COMPONENT_Y), reconField.getChromaFormat(), g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth);
+      TVideoIOYuv::ColourSpaceConvert(reconField, cscd[fieldNum], conversion, g_bitDepth, false);
+      apcPicRecFields[fieldNum]=cscd+fieldNum;
+    }
+  }
+
+  //===== calculate PSNR =====
+  Double MSEyuvframe[MAX_NUM_COMPONENT] = {0, 0, 0};
+
+  assert(apcPicRecFields[0]->getChromaFormat()==apcPicRecFields[1]->getChromaFormat());
+  const UInt numValidComponents=apcPicRecFields[0]->getNumberValidComponents();
+
+  for(Int chan=0; chan<numValidComponents; chan++)
+  {
+    const ComponentID ch=ComponentID(chan);
+    assert(apcPicRecFields[0]->getWidth(ch)==apcPicRecFields[1]->getWidth(ch));
+    assert(apcPicRecFields[0]->getHeight(ch)==apcPicRecFields[1]->getHeight(ch));
+
+    UInt64 uiSSDtemp=0;
+    const Int   iWidth  = apcPicRecFields[0]->getWidth (ch) - (m_pcEncTop->getPad(0) >> apcPicRecFields[0]->getComponentScaleX(ch));
+    const Int   iHeight = apcPicRecFields[0]->getHeight(ch) - ((m_pcEncTop->getPad(1) >> 1) >> apcPicRecFields[0]->getComponentScaleY(ch));
+
+    Int   iSize   = iWidth*iHeight;
+
+    for(UInt fieldNum=0; fieldNum<2; fieldNum++)
+    {
+      TComPic *pcPic=apcPicOrgFields[fieldNum];
+      TComPicYuv *pcPicD=apcPicRecFields[fieldNum];
+
+      const Pel*  pOrg    = (conversion!=IPCOLOURSPACE_UNCHANGED) ? pcPic ->getPicYuvTrueOrg()->getAddr(ch) : pcPic ->getPicYuvOrg()->getAddr(ch);
+      Pel*  pRec    = pcPicD->getAddr(ch);
+      const Int   iStride = pcPicD->getStride(ch);
+
+
+      for(Int y = 0; y < iHeight; y++ )
+      {
+        for(Int x = 0; x < iWidth; x++ )
+        {
+          Intermediate_Int iDiff = (Intermediate_Int)( pOrg[x] - pRec[x] );
+          uiSSDtemp   += iDiff * iDiff;
+        }
+        pOrg += iStride;
+        pRec += iStride;
+      }
+    }
+    const Int maxval = 255 << (g_bitDepth[toChannelType(ch)] - 8);
+    const Double fRefValue = (Double) maxval * maxval * iSize*2;
+    dPSNR[ch]         = ( uiSSDtemp ? 10.0 * log10( fRefValue / (Double)uiSSDtemp ) : 999.99 );
+    MSEyuvframe[ch]   = (Double)uiSSDtemp/(iSize*2);
+  }
+
+  UInt uibits = 0; // the number of bits for the pair is not calculated here - instead the overall total is used elsewhere.
+
+  //===== add PSNR =====
+  m_gcAnalyzeAll_in.addResult (dPSNR, (Double)uibits, MSEyuvframe);
+
+  printf("\n                                      Interlaced frame %d: [Y %6.4lf dB    U %6.4lf dB    V %6.4lf dB]", pcPicOrgSecondField->getPOC()/2 , dPSNR[COMPONENT_Y], dPSNR[COMPONENT_Cb], dPSNR[COMPONENT_Cr] );
+  if (printFrameMSE)
+  {
+    printf(" [Y MSE %6.4lf  U MSE %6.4lf  V MSE %6.4lf]", MSEyuvframe[COMPONENT_Y], MSEyuvframe[COMPONENT_Cb], MSEyuvframe[COMPONENT_Cr] );
+  }
+
+  for(UInt fieldNum=0; fieldNum<2; fieldNum++)
+  {
+    cscd[fieldNum].destroy();
+  }
+}
+
+/** Function for deciding the nal_unit_type.
+ * \param pocCurr POC of the current picture
+ * \returns the nal unit type of the picture
+ * This function checks the configuration and returns the appropriate nal_unit_type for the picture.
+ */
+NalUnitType TEncGOP::getNalUnitType(Int pocCurr, Int lastIDR, Bool isField)
+{
+  if (pocCurr == 0)
+  {
+    return NAL_UNIT_CODED_SLICE_IDR_W_RADL;
+  }
+
+#if EFFICIENT_FIELD_IRAP
+  if(isField && pocCurr == 1)
+  {
+    // to avoid the picture becoming an IRAP
+    return NAL_UNIT_CODED_SLICE_TRAIL_R;
+  }
+#endif
+
+#if ALLOW_RECOVERY_POINT_AS_RAP
+  if(m_pcCfg->getDecodingRefreshType() != 3 && (pocCurr - isField) % m_pcCfg->getIntraPeriod() == 0)
+#else
+  if ((pocCurr - isField) % m_pcCfg->getIntraPeriod() == 0)
+#endif
+  {
+    if (m_pcCfg->getDecodingRefreshType() == 1)
+    {
+      return NAL_UNIT_CODED_SLICE_CRA;
+    }
+    else if (m_pcCfg->getDecodingRefreshType() == 2)
+    {
+      return NAL_UNIT_CODED_SLICE_IDR_W_RADL;
+    }
+  }
+
+#if POC_RESET_IDC_ENCODER
+  if(m_pocCraWithoutReset > 0 && this->m_associatedIRAPType == NAL_UNIT_CODED_SLICE_CRA)
+  {
+    if(pocCurr < m_pocCraWithoutReset)
+#else
+  if(m_pocCRA>0)
+  {
+    if(pocCurr<m_pocCRA)
+#endif
+    {
+      // 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
+  Int seiStartPos = 0;
+  for(AccessUnit::iterator 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->getAddr(COMPONENT_Y);
+  Pel* tempRec = Rec;
+  Int  stride = pcPicYuvRec->getStride(COMPONENT_Y);
+  UInt log2maxTB = pcPic->getSlice(0)->getSPS()->getQuadtreeTULog2MaxSize();
+  UInt maxTBsize = (1<<log2maxTB);
+  const UInt minBlockArtSize = 8;
+  const UInt picWidth = pcPicYuvRec->getWidth(COMPONENT_Y);
+  const UInt picHeight = pcPicYuvRec->getHeight(COMPONENT_Y);
+  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_bitDepth[CHANNEL_TYPE_LUMA]-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_bitDepth[CHANNEL_TYPE_LUMA]-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 P0123_ALPHA_CHANNEL_SEI
+SEIAlphaChannelInfo* TEncGOP::xCreateSEIAlphaChannelInfo()
+{
+  SEIAlphaChannelInfo *sei = new SEIAlphaChannelInfo();
+  sei->m_alphaChannelCancelFlag = m_pcCfg->getAlphaCancelFlag();
+  if(!sei->m_alphaChannelCancelFlag)
+  {
+    sei->m_alphaChannelUseIdc = m_pcCfg->getAlphaUseIdc();
+    sei->m_alphaChannelBitDepthMinus8 = m_pcCfg->getAlphaBitDepthMinus8();
+    sei->m_alphaTransparentValue = m_pcCfg->getAlphaTransparentValue();
+    sei->m_alphaOpaqueValue = m_pcCfg->getAlphaOpaqueValue();
+    sei->m_alphaChannelIncrFlag = m_pcCfg->getAlphaIncrementFlag();
+    sei->m_alphaChannelClipFlag = m_pcCfg->getAlphaClipFlag();
+    sei->m_alphaChannelClipTypeFlag = m_pcCfg->getAlphaClipTypeFlag();
+  }
+  return sei;
+}
+#endif
+#if Q0096_OVERLAY_SEI
+SEIOverlayInfo* TEncGOP::xCreateSEIOverlayInfo()
+{  
+  SEIOverlayInfo *sei = new SEIOverlayInfo();  
+  sei->m_overlayInfoCancelFlag = m_pcCfg->getOverlaySEICancelFlag();    
+  if ( !sei->m_overlayInfoCancelFlag )
+  {
+    sei->m_overlayContentAuxIdMinus128          = m_pcCfg->getOverlaySEIContentAuxIdMinus128(); 
+    sei->m_overlayLabelAuxIdMinus128            = m_pcCfg->getOverlaySEILabelAuxIdMinus128();  
+    sei->m_overlayAlphaAuxIdMinus128            = m_pcCfg->getOverlaySEIAlphaAuxIdMinus128(); 
+    sei->m_overlayElementLabelValueLengthMinus8 = m_pcCfg->getOverlaySEIElementLabelValueLengthMinus8(); 
+    sei->m_numOverlaysMinus1                    = m_pcCfg->getOverlaySEINumOverlaysMinus1();     
+    sei->m_overlayIdx                           = m_pcCfg->getOverlaySEIIdx();            
+    sei->m_languageOverlayPresentFlag           = m_pcCfg->getOverlaySEILanguagePresentFlag();
+    sei->m_overlayContentLayerId                = m_pcCfg->getOverlaySEIContentLayerId();   
+    sei->m_overlayLabelPresentFlag              = m_pcCfg->getOverlaySEILabelPresentFlag();   
+    sei->m_overlayLabelLayerId                  = m_pcCfg->getOverlaySEILabelLayerId();   
+    sei->m_overlayAlphaPresentFlag              = m_pcCfg->getOverlaySEIAlphaPresentFlag();   
+    sei->m_overlayAlphaLayerId                  = m_pcCfg->getOverlaySEIAlphaLayerId();   
+    sei->m_numOverlayElementsMinus1             = m_pcCfg->getOverlaySEINumElementsMinus1();
+    sei->m_overlayElementLabelMin               = m_pcCfg->getOverlaySEIElementLabelMin();
+    sei->m_overlayElementLabelMax               = m_pcCfg->getOverlaySEIElementLabelMax();    
+    sei->m_overlayLanguage.resize               ( sei->m_numOverlaysMinus1+1, NULL );
+    sei->m_overlayLanguageLength.resize         ( sei->m_numOverlaysMinus1+1 );
+    sei->m_overlayName.resize                   ( sei->m_numOverlaysMinus1+1, NULL );
+    sei->m_overlayNameLength.resize             ( sei->m_numOverlaysMinus1+1 );
+    sei->m_overlayElementName.resize            ( sei->m_numOverlaysMinus1+1 );
+    sei->m_overlayElementNameLength.resize      ( sei->m_numOverlaysMinus1+1 );  
+
+    Int i,j;
+    string strTmp;
+    Int nBytes;
+    assert( m_pcCfg->getOverlaySEILanguage().size()    == sei->m_numOverlaysMinus1+1 );
+    assert( m_pcCfg->getOverlaySEIName().size()        == sei->m_numOverlaysMinus1+1 );
+    assert( m_pcCfg->getOverlaySEIElementName().size() == sei->m_numOverlaysMinus1+1 );
+    
+    for ( i=0 ; i<=sei->m_numOverlaysMinus1; i++ )
+    {      
+      //language tag
+      if ( sei->m_languageOverlayPresentFlag[i] )
+      {                
+        strTmp = m_pcCfg->getOverlaySEILanguage()[i];
+        nBytes = (Int)m_pcCfg->getOverlaySEILanguage()[i].size();        
+        assert( nBytes>0 );
+        sei->m_overlayLanguage[i] = new UChar[nBytes];
+        memcpy(sei->m_overlayLanguage[i], strTmp.c_str(), nBytes);        
+        sei->m_overlayLanguageLength[i] = nBytes;        
+      }
+
+      //overlay name
+      strTmp = m_pcCfg->getOverlaySEIName()[i];
+      nBytes = (Int)m_pcCfg->getOverlaySEIName()[i].size();        
+      assert( nBytes>0 );
+      sei->m_overlayName[i] = new UChar[nBytes];      
+      memcpy(sei->m_overlayName[i], strTmp.c_str(), nBytes);        
+      sei->m_overlayNameLength[i] = nBytes;
+
+      //overlay element names
+      if ( sei->m_overlayLabelPresentFlag[i] )
+      {        
+        sei->m_overlayElementName[i].resize( sei->m_numOverlayElementsMinus1[i]+1, NULL );
+        sei->m_overlayElementNameLength[i].resize( sei->m_numOverlayElementsMinus1[i]+1 );
+        assert( m_pcCfg->getOverlaySEIElementName()[i].size() == sei->m_numOverlayElementsMinus1[i]+1 );        
+        for ( j=0 ; j<=sei->m_numOverlayElementsMinus1[i] ; j++)
+        {
+          strTmp = m_pcCfg->getOverlaySEIElementName()[i][j];
+          nBytes = (Int)m_pcCfg->getOverlaySEIElementName()[i][j].size();        
+          assert( nBytes>0 );
+          sei->m_overlayElementName[i][j] = new UChar[nBytes];
+          memcpy(sei->m_overlayElementName[i][j], strTmp.c_str(), nBytes);        
+          sei->m_overlayElementNameLength[i][j] = nBytes;
+        }
+      }
+    }
+  sei->m_overlayInfoPersistenceFlag = true;
+  }
+  return sei;
+}
+#endif
+
+#if Q0074_COLOUR_REMAPPING_SEI
+SEIColourRemappingInfo*  TEncGOP::xCreateSEIColourRemappingInfo()
+{
+  SEIColourRemappingInfo *seiColourRemappingInfo = new SEIColourRemappingInfo();
+  seiColourRemappingInfo->m_colourRemapId         = m_pcCfg->getCRISEIId();
+  seiColourRemappingInfo->m_colourRemapCancelFlag = m_pcCfg->getCRISEICancelFlag();
+  if( !seiColourRemappingInfo->m_colourRemapCancelFlag )
+  {
+    seiColourRemappingInfo->m_colourRemapPersistenceFlag            = m_pcCfg->getCRISEIPersistenceFlag();
+    seiColourRemappingInfo->m_colourRemapVideoSignalInfoPresentFlag = m_pcCfg->getCRISEIVideoSignalInfoPresentFlag();
+    if( seiColourRemappingInfo->m_colourRemapVideoSignalInfoPresentFlag )
+    {
+      seiColourRemappingInfo->m_colourRemapFullRangeFlag           = m_pcCfg->getCRISEIFullRangeFlag();
+      seiColourRemappingInfo->m_colourRemapPrimaries               = m_pcCfg->getCRISEIPrimaries();
+      seiColourRemappingInfo->m_colourRemapTransferFunction        = m_pcCfg->getCRISEITransferFunction();
+      seiColourRemappingInfo->m_colourRemapMatrixCoefficients      = m_pcCfg->getCRISEIMatrixCoefficients();
+    }
+    seiColourRemappingInfo->m_colourRemapInputBitDepth             = m_pcCfg->getCRISEIInputBitDepth();
+    seiColourRemappingInfo->m_colourRemapBitDepth                  = m_pcCfg->getCRISEIBitDepth();
+    for( Int c=0 ; c<3 ; c++ )
+    {
+      seiColourRemappingInfo->m_preLutNumValMinus1[c] = m_pcCfg->getCRISEIPreLutNumValMinus1(c);
+      if( seiColourRemappingInfo->m_preLutNumValMinus1[c]>0 )
+      {
+        seiColourRemappingInfo->m_preLutCodedValue[c].resize(seiColourRemappingInfo->m_preLutNumValMinus1[c]+1);
+        seiColourRemappingInfo->m_preLutTargetValue[c].resize(seiColourRemappingInfo->m_preLutNumValMinus1[c]+1);
+        for( Int i=0 ; i<=seiColourRemappingInfo->m_preLutNumValMinus1[c] ; i++)
+        {
+          seiColourRemappingInfo->m_preLutCodedValue[c][i]  = (m_pcCfg->getCRISEIPreLutCodedValue(c))[i];
+          seiColourRemappingInfo->m_preLutTargetValue[c][i] = (m_pcCfg->getCRISEIPreLutTargetValue(c))[i];
+        }
+      }
+    }
+    seiColourRemappingInfo->m_colourRemapMatrixPresentFlag = m_pcCfg->getCRISEIMatrixPresentFlag();
+    if( seiColourRemappingInfo->m_colourRemapMatrixPresentFlag )
+    {
+      seiColourRemappingInfo->m_log2MatrixDenom = m_pcCfg->getCRISEILog2MatrixDenom();
+      for( Int c=0 ; c<3 ; c++ )
+        for( Int i=0 ; i<3 ; i++ )
+          seiColourRemappingInfo->m_colourRemapCoeffs[c][i] = (m_pcCfg->getCRISEICoeffs(c))[i];
+    }
+    for( Int c=0 ; c<3 ; c++ )
+    {
+      seiColourRemappingInfo->m_postLutNumValMinus1[c] = m_pcCfg->getCRISEIPostLutNumValMinus1(c);
+      if( seiColourRemappingInfo->m_postLutNumValMinus1[c]>0 )
+      {
+        seiColourRemappingInfo->m_postLutCodedValue[c].resize(seiColourRemappingInfo->m_postLutNumValMinus1[c]+1);
+        seiColourRemappingInfo->m_postLutTargetValue[c].resize(seiColourRemappingInfo->m_postLutNumValMinus1[c]+1);
+        for( Int i=0 ; i<=seiColourRemappingInfo->m_postLutNumValMinus1[c] ; i++)
+        {
+          seiColourRemappingInfo->m_postLutCodedValue[c][i]  = (m_pcCfg->getCRISEIPostLutCodedValue(c))[i];
+          seiColourRemappingInfo->m_postLutTargetValue[c][i] = (m_pcCfg->getCRISEIPostLutTargetValue(c))[i];
+        }
+      }
+    }
+  }
+  return seiColourRemappingInfo;
+}
+#endif
+
+#if SVC_EXTENSION
+#if LAYERS_NOT_PRESENT_SEI
+SEILayersNotPresent* TEncGOP::xCreateSEILayersNotPresent ()
+{
+  UInt i = 0;
+  SEILayersNotPresent *seiLayersNotPresent = new SEILayersNotPresent(); 
+  seiLayersNotPresent->m_activeVpsId = m_pcCfg->getVPS()->getVPSId(); 
+  seiLayersNotPresent->m_vpsMaxLayers = m_pcCfg->getVPS()->getMaxLayers();
+  for ( ; i < seiLayersNotPresent->m_vpsMaxLayers; i++)
+  {
+    seiLayersNotPresent->m_layerNotPresentFlag[i] = true; 
+  }
+  for ( ; i < MAX_LAYERS; i++)
+  {
+    seiLayersNotPresent->m_layerNotPresentFlag[i] = false; 
+  }
+  return seiLayersNotPresent;
+}
+#endif
+
+#if N0383_IL_CONSTRAINED_TILE_SETS_SEI
+SEIInterLayerConstrainedTileSets* TEncGOP::xCreateSEIInterLayerConstrainedTileSets()
+{
+  SEIInterLayerConstrainedTileSets *seiInterLayerConstrainedTileSets = new SEIInterLayerConstrainedTileSets();
+  seiInterLayerConstrainedTileSets->m_ilAllTilesExactSampleValueMatchFlag = false;
+  seiInterLayerConstrainedTileSets->m_ilOneTilePerTileSetFlag = false;
+  if (!seiInterLayerConstrainedTileSets->m_ilOneTilePerTileSetFlag)
+  {
+    seiInterLayerConstrainedTileSets->m_ilNumSetsInMessageMinus1 = m_pcCfg->getIlNumSetsInMessage() - 1;
+    if (seiInterLayerConstrainedTileSets->m_ilNumSetsInMessageMinus1)
+    {
+      seiInterLayerConstrainedTileSets->m_skippedTileSetPresentFlag = m_pcCfg->getSkippedTileSetPresentFlag();
+    }
+    else
+    {
+      seiInterLayerConstrainedTileSets->m_skippedTileSetPresentFlag = false;
+    }
+    seiInterLayerConstrainedTileSets->m_ilNumSetsInMessageMinus1 += seiInterLayerConstrainedTileSets->m_skippedTileSetPresentFlag ? 1 : 0;
+    for (UInt i = 0; i < m_pcCfg->getIlNumSetsInMessage(); i++)
+    {
+      seiInterLayerConstrainedTileSets->m_ilctsId[i] = i;
+      seiInterLayerConstrainedTileSets->m_ilNumTileRectsInSetMinus1[i] = 0;
+      for( UInt j = 0; j <= seiInterLayerConstrainedTileSets->m_ilNumTileRectsInSetMinus1[i]; j++)
+      {
+        seiInterLayerConstrainedTileSets->m_ilTopLeftTileIndex[i][j]     = m_pcCfg->getTopLeftTileIndex(i);
+        seiInterLayerConstrainedTileSets->m_ilBottomRightTileIndex[i][j] = m_pcCfg->getBottomRightTileIndex(i);
+      }
+      seiInterLayerConstrainedTileSets->m_ilcIdc[i] = m_pcCfg->getIlcIdc(i);
+      if (seiInterLayerConstrainedTileSets->m_ilAllTilesExactSampleValueMatchFlag)
+      {
+        seiInterLayerConstrainedTileSets->m_ilExactSampleValueMatchFlag[i] = false;
+      }
+    }
+  }
+
+  return seiInterLayerConstrainedTileSets;
+}
+
+Void TEncGOP::xBuildTileSetsMap(TComPicSym* picSym)
+{
+  Int numCUs = picSym->getFrameWidthInCtus() * picSym->getFrameHeightInCtus();
+
+  for (Int i = 0; i < numCUs; i++)
+  {
+    picSym->setTileSetIdxMap(i, -1, 0, false);
+  }
+
+  for (Int i = 0; i < m_pcCfg->getIlNumSetsInMessage(); i++)
+  {
+    const TComTile* topLeftTile     = picSym->getTComTile(m_pcCfg->getTopLeftTileIndex(i));
+    TComTile* bottomRightTile = picSym->getTComTile(m_pcCfg->getBottomRightTileIndex(i));
+    Int tileSetLeftEdgePosInCU = topLeftTile->getRightEdgePosInCtus() - topLeftTile->getTileWidthInCtus() + 1;
+    Int tileSetRightEdgePosInCU = bottomRightTile->getRightEdgePosInCtus();
+    Int tileSetTopEdgePosInCU = topLeftTile->getBottomEdgePosInCtus() - topLeftTile->getTileHeightInCtus() + 1;
+    Int tileSetBottomEdgePosInCU = bottomRightTile->getBottomEdgePosInCtus();
+    assert(tileSetLeftEdgePosInCU < tileSetRightEdgePosInCU && tileSetTopEdgePosInCU < tileSetBottomEdgePosInCU);
+    for (Int j = tileSetTopEdgePosInCU; j <= tileSetBottomEdgePosInCU; j++)
+    {
+      for (Int k = tileSetLeftEdgePosInCU; k <= tileSetRightEdgePosInCU; k++)
+      {
+        picSym->setTileSetIdxMap(j * picSym->getFrameWidthInCtus() + k, i, m_pcCfg->getIlcIdc(i), false);
+      }
+    }
+  }
+  
+  if (m_pcCfg->getSkippedTileSetPresentFlag())
+  {
+    Int skippedTileSetIdx = m_pcCfg->getIlNumSetsInMessage();
+    for (Int i = 0; i < numCUs; i++)
+    {
+      if (picSym->getTileSetIdxMap(i) < 0)
+      {
+        picSym->setTileSetIdxMap(i, skippedTileSetIdx, 0, true);
+      }
+    }
+  }
+}
+#endif
+
+
+#if POC_RESET_IDC_ENCODER
+Void TEncGOP::determinePocResetIdc(Int const pocCurr, TComSlice *const slice)
+{
+  // If one picture in the AU is IDR, and another picture is not IDR, set the poc_reset_idc to 1 or 2
+  // If BL picture in the AU is IDR, and another picture is not IDR, set the poc_reset_idc to 2
+  // If BL picture is IRAP, and another picture is non-IRAP, then the poc_reset_idc is equal to 1 or 2.
+#if P0297_VPS_POC_LSB_ALIGNED_FLAG
+  slice->setPocMsbNeeded(false);
+#endif
+  if( slice->getSliceIdx() == 0 ) // First slice - compute, copy for other slices
+  {
+    Int needReset = false;
+    Int resetDueToBL = false;
+    if( slice->getVPS()->getMaxLayers() > 1 )
+    {
+      // If IRAP is refreshed in this access unit for base layer
+      if( (m_ppcTEncTop[0]->getGOPEncoder()->getIntraRefreshType() == 1 || m_ppcTEncTop[0]->getGOPEncoder()->getIntraRefreshType() == 2)
+        && ( pocCurr % m_ppcTEncTop[0]->getGOPEncoder()->getIntraRefreshInterval() == 0 )
+        )
+      {
+        // Check if the IRAP refresh interval of any layer does not match that of the base layer
+        for(Int i = 1; i < slice->getVPS()->getMaxLayers(); i++)
+        {
+          Bool refreshIntervalFlag = ( pocCurr % m_ppcTEncTop[i]->getGOPEncoder()->getIntraRefreshInterval() == 0 );
+          Bool refreshTypeFlag     = ( m_ppcTEncTop[0]->getGOPEncoder()->getIntraRefreshType() == m_ppcTEncTop[i]->getGOPEncoder()->getIntraRefreshType() );
+          if( !(refreshIntervalFlag && refreshTypeFlag) )
+          {
+            needReset = true;
+            resetDueToBL = true;
+            break;
+          }
+        }
+      }
+    }
+    
+    if( !needReset )// No need reset due to base layer IRAP
+    {
+      // Check if EL IDRs results in POC Reset
+      for(Int i = 1; i < slice->getVPS()->getMaxLayers() && !needReset; i++)
+      {
+        Bool idrFlag = ( (m_ppcTEncTop[i]->getGOPEncoder()->getIntraRefreshType() == 2) 
+                        && ( pocCurr % m_ppcTEncTop[i]->getGOPEncoder()->getIntraRefreshInterval() == 0 )
+                        );
+        for(Int j = 0; j < slice->getVPS()->getMaxLayers(); j++)
+        {
+          if( j == i )
+          {
+            continue;
+          }
+
+          Bool idrOtherPicFlag = ( (m_ppcTEncTop[j]->getGOPEncoder()->getIntraRefreshType() == 2) 
+                                  && ( pocCurr % m_ppcTEncTop[j]->getGOPEncoder()->getIntraRefreshInterval() == 0 )
+                                  );
+
+          if( idrFlag != idrOtherPicFlag )
+          {
+            needReset = true;
+            break;
+          }
+        }
+      }
+    }
+    if( needReset )
+    {
+      if( m_ppcTEncTop[0]->getGOPEncoder()->getIntraRefreshType() == 2 )  // BL IDR refresh, assuming BL picture present
+      {
+        if( resetDueToBL )
+        {
+          slice->setPocResetIdc( 2 ); // Full reset needed
+#if P0297_VPS_POC_LSB_ALIGNED_FLAG
+          if (slice->getVPS()->getVpsPocLsbAlignedFlag() && slice->getVPS()->getNumDirectRefLayers(slice->getLayerId()) == 0)
+          {
+            slice->setPocMsbNeeded(true);  // Force msb writing
+          }
+#endif
+        }
+        else
+        {
+          slice->setPocResetIdc( 1 ); // Due to IDR in EL
+        }
+      }
+      else
+      {
+        slice->setPocResetIdc( 1 ); // Only MSB reset
+      }
+
+      // Start a new POC reset period
+      if (m_layerId == 0)   // Assuming BL picture is always present at encoder; for other AU structures, need to change this
+      {
+        Int periodId = rand() % 64;
+        m_lastPocPeriodId = (periodId == m_lastPocPeriodId) ? (periodId + 1) % 64 : periodId ;
+
+#if P0297_VPS_POC_LSB_ALIGNED_FLAG
+        for (UInt i = 0; i < MAX_LAYERS; i++)
+        {
+          m_ppcTEncTop[i]->setPocDecrementedInDPBFlag(false);
+        }
+#endif
+      }
+      else
+      {
+        m_lastPocPeriodId = m_ppcTEncTop[0]->getGOPEncoder()->getLastPocPeriodId();
+      }
+      slice->setPocResetPeriodId(m_lastPocPeriodId);
+    }
+    else
+    {
+      slice->setPocResetIdc( 0 );
+    }
+  }
+}
+
+Void TEncGOP::updatePocValuesOfPics(Int const pocCurr, TComSlice *const slice)
+{
+#if P0297_VPS_POC_LSB_ALIGNED_FLAG
+  UInt affectedLayerList[MAX_NUM_LAYER_IDS];
+  Int  numAffectedLayers;
+
+  affectedLayerList[0] = m_layerId;
+  numAffectedLayers = 1;
+
+  if (m_pcEncTop->getVPS()->getVpsPocLsbAlignedFlag())
+  {
+    for (UInt j = 0; j < m_pcEncTop->getVPS()->getNumPredictedLayers(m_layerId); j++)
+    {
+      affectedLayerList[j + 1] = m_pcEncTop->getVPS()->getPredictedLayerId(m_layerId, j);
+    }
+    numAffectedLayers = m_pcEncTop->getVPS()->getNumPredictedLayers(m_layerId) + 1;
+  }
+#endif
+
+  Int pocAdjustValue = pocCurr - m_pcEncTop->getPocAdjustmentValue();
+
+  // New POC reset period
+  Int maxPocLsb, pocLsbVal, pocMsbDelta, pocLsbDelta, deltaPocVal;
+
+  maxPocLsb   = 1 << slice->getSPS()->getBitsForPOC();
+
+#if P0297_VPS_POC_LSB_ALIGNED_FLAG
+  Int adjustedPocValue = pocCurr;
+
+  if (m_pcEncTop->getFirstPicInLayerDecodedFlag())
+  {
+#endif
+
+  pocLsbVal   = (slice->getPocResetIdc() == 3)
+                ? slice->getPocLsbVal()
+                : pocAdjustValue % maxPocLsb; 
+  pocMsbDelta = pocAdjustValue - pocLsbVal;
+  pocLsbDelta = (slice->getPocResetIdc() == 2 || ( slice->getPocResetIdc() == 3 && slice->getFullPocResetFlag() )) 
+                ? pocLsbVal 
+                : 0; 
+  deltaPocVal = pocMsbDelta  + pocLsbDelta;
+
+#if P0297_VPS_POC_LSB_ALIGNED_FLAG
+  Int origDeltaPocVal = deltaPocVal;  // original value needed when updating POC adjustment value
+
+  if (slice->getPocMsbNeeded())  // IDR picture in base layer, non-IDR picture in other layers, poc_lsb_aligned_flag = 1
+  {
+    if (slice->getLayerId() == 0)
+    {
+      Int highestPoc = INT_MIN;
+      // Find greatest POC in DPB for layer 0
+      for (TComList<TComPic*>::iterator iterPic = m_pcEncTop->getListPic()->begin(); iterPic != m_pcEncTop->getListPic()->end(); ++iterPic)
+      {
+        TComPic *dpbPic = *iterPic;
+        if (dpbPic->getReconMark() && dpbPic->getLayerId() == 0 && dpbPic->getPOC() > highestPoc)
+        {
+          highestPoc = dpbPic->getPOC();
+        }
+      }
+      deltaPocVal = (highestPoc - (highestPoc & (maxPocLsb - 1))) + 1*maxPocLsb;
+      m_pcEncTop->setCurrPocMsb(deltaPocVal);
+    }
+    else
+    {
+      deltaPocVal = m_ppcTEncTop[0]->getCurrPocMsb();  // copy from base layer
+    }
+    slice->setPocMsbVal(deltaPocVal);
+  }
+
+  for (UInt layerIdx = 0; layerIdx < numAffectedLayers; layerIdx++)
+  {
+    UInt lIdx = slice->getVPS()->getLayerIdxInVps(affectedLayerList[layerIdx]);
+
+    if (!m_ppcTEncTop[lIdx]->getPocDecrementedInDPBFlag())
+    {
+      m_ppcTEncTop[lIdx]->setPocDecrementedInDPBFlag(true);
+
+      // Decrement value of associatedIrapPoc of the TEncGop object
+      m_ppcTEncTop[lIdx]->getGOPEncoder()->m_associatedIRAPPOC -= deltaPocVal;
+
+      // Decrememnt the value of m_pocCRA
+      m_ppcTEncTop[lIdx]->getGOPEncoder()->m_pocCRA -= deltaPocVal;
+
+      TComList<TComPic*>::iterator  iterPic = m_ppcTEncTop[lIdx]->getListPic()->begin();
+      while (iterPic != m_ppcTEncTop[lIdx]->getListPic()->end())
+#else
+  // Decrement value of associatedIrapPoc of the TEncGop object
+  this->m_associatedIRAPPOC -= deltaPocVal;
+
+  // Decrememnt the value of m_pocCRA
+  this->m_pocCRA -= deltaPocVal;
+
+  // Iterate through all pictures in the DPB
+  TComList<TComPic*>::iterator  iterPic = getListPic()->begin();  
+  while( iterPic != getListPic()->end() )
+#endif
+  {
+    TComPic *dpbPic = *iterPic;
+    
+    if( dpbPic->getReconMark() )
+    {
+      for(Int i = dpbPic->getNumAllocatedSlice() - 1; i >= 0; i--)
+      {
+        TComSlice *dpbPicSlice = dpbPic->getSlice( i );
+        TComReferencePictureSet *dpbPicRps = dpbPicSlice->getRPS();
+
+        // Decrement POC of slice
+        dpbPicSlice->setPOC( dpbPicSlice->getPOC() - deltaPocVal );
+
+        // Decrement POC value stored in the RPS of each such slice
+        for( Int j = dpbPicRps->getNumberOfPictures() - 1; j >= 0; j-- )
+        {
+          dpbPicRps->setPOC( j, dpbPicRps->getPOC(j) - deltaPocVal );
+        }
+
+        // Decrement value of refPOC
+        dpbPicSlice->decrementRefPocValues( deltaPocVal );
+
+        // Update value of associatedIrapPoc of each slice
+        dpbPicSlice->setAssociatedIRAPPOC( dpbPicSlice->getAssociatedIRAPPOC() - deltaPocVal );
+
+#if P0297_VPS_POC_LSB_ALIGNED_FLAG
+        if (slice->getPocMsbNeeded())
+        {
+          // this delta value is needed when computing delta POCs in reference picture set initialization
+          dpbPicSlice->setPocResetDeltaPoc(dpbPicSlice->getPocResetDeltaPoc() + (deltaPocVal - pocLsbVal));
+        }
+#endif
+      }
+    }
+    iterPic++;
+  }
+#if P0297_VPS_POC_LSB_ALIGNED_FLAG
+    }
+  }
+#endif
+
+  // Actual POC value before reset
+#if P0297_VPS_POC_LSB_ALIGNED_FLAG
+  adjustedPocValue = pocCurr - m_pcEncTop->getPocAdjustmentValue();
+#else
+  Int adjustedPocValue = pocCurr - m_pcEncTop->getPocAdjustmentValue();
+#endif
+
+  // Set MSB value before reset
+  Int tempLsbVal = adjustedPocValue & (maxPocLsb - 1);
+#if P0297_VPS_POC_LSB_ALIGNED_FLAG
+  if (!slice->getPocMsbNeeded())  // set poc msb normally if special msb handling is not needed
+  {
+#endif
+    slice->setPocMsbVal(adjustedPocValue - tempLsbVal);
+#if P0297_VPS_POC_LSB_ALIGNED_FLAG
+  }
+#endif
+
+  // Set LSB value before reset - this is needed in the case of resetIdc = 2
+  slice->setPicOrderCntLsb( tempLsbVal );
+
+  // Cumulative delta
+#if P0297_VPS_POC_LSB_ALIGNED_FLAG
+  deltaPocVal = origDeltaPocVal;  // restore deltaPoc for correct adjustment value update
+#endif
+  m_pcEncTop->setPocAdjustmentValue( m_pcEncTop->getPocAdjustmentValue() + deltaPocVal );
+
+#if P0297_VPS_POC_LSB_ALIGNED_FLAG
+  }
+#endif
+
+  // New LSB value, after reset
+  adjustedPocValue = pocCurr - m_pcEncTop->getPocAdjustmentValue();
+  Int newLsbVal = adjustedPocValue & (maxPocLsb - 1);
+
+  // Set value of POC current picture after RESET
+  if( slice->getPocResetIdc() == 1 )
+  {
+    slice->setPOC( newLsbVal );
+  }
+  else if( slice->getPocResetIdc() == 2 )
+  {
+    slice->setPOC( 0 );
+  }
+  else if( slice->getPocResetIdc() == 3 )
+  {
+    Int picOrderCntMsb = slice->getCurrMsb( newLsbVal, 
+                                        slice->getFullPocResetFlag() ? 0 : slice->getPocLsbVal(), 
+                                        0,
+                                        maxPocLsb );
+    slice->setPOC( picOrderCntMsb + newLsbVal );
+  }
+  else
+  {
+    assert(0);
+  }
+}
+#endif
+
+
+#if O0164_MULTI_LAYER_HRD
+#if VPS_VUI_BSP_HRD_PARAMS
+SEIScalableNesting* TEncGOP::xCreateBspNestingSEI(TComSlice *pcSlice, Int olsIdx, Int partitioningSchemeIdx, Int bspIdx)
+#else
+SEIScalableNesting* TEncGOP::xCreateBspNestingSEI(TComSlice *pcSlice)
+#endif
+{
+  SEIScalableNesting *seiScalableNesting = new SEIScalableNesting();
+  SEIBspInitialArrivalTime *seiBspInitialArrivalTime = new SEIBspInitialArrivalTime();
+  SEIBspNesting *seiBspNesting = new SEIBspNesting();
+  SEIBufferingPeriod *seiBufferingPeriod = new SEIBufferingPeriod();
+
+  // Scalable nesting SEI
+
+  seiScalableNesting->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
+  seiScalableNesting->m_nestingOpFlag                 = 1;
+  seiScalableNesting->m_defaultOpFlag                 = 0;
+  seiScalableNesting->m_nestingNumOpsMinus1           = 0;      //nesting_num_ops_minus1
+#if VPS_VUI_BSP_HRD_PARAMS
+  seiScalableNesting->m_nestingOpIdx[0]               = pcSlice->getVPS()->getOutputLayerSetIdx(olsIdx);
+  seiScalableNesting->m_nestingMaxTemporalIdPlus1[0]  = 6 + 1;
+#else
+  seiScalableNesting->m_nestingOpIdx[0]               = 1;
+#endif
+  seiScalableNesting->m_allLayersFlag                 = 0;
+  seiScalableNesting->m_nestingNoOpMaxTemporalIdPlus1 = 6 + 1;  //nesting_no_op_max_temporal_id_plus1
+  seiScalableNesting->m_nestingNumLayersMinus1        = 1 - 1;  //nesting_num_layers_minus1
+  seiScalableNesting->m_nestingLayerId[0]             = 0;
+  seiScalableNesting->m_callerOwnsSEIs                = true;
+
+  // Bitstream partition nesting SEI
+
+  seiBspNesting->m_bspIdx = 0;
+  seiBspNesting->m_callerOwnsSEIs = true;
+
+  // Buffering period SEI
+
+  UInt uiInitialCpbRemovalDelay = (90000/2);                      // 0.5 sec
+  seiBufferingPeriod->m_initialCpbRemovalDelay      [0][0]     = uiInitialCpbRemovalDelay;
+  seiBufferingPeriod->m_initialCpbRemovalDelayOffset[0][0]     = uiInitialCpbRemovalDelay;
+  seiBufferingPeriod->m_initialCpbRemovalDelay      [0][1]     = uiInitialCpbRemovalDelay;
+  seiBufferingPeriod->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 );
+  seiBufferingPeriod->m_initialAltCpbRemovalDelay      [0][0]  = uiInitialCpbRemovalDelay;
+  seiBufferingPeriod->m_initialAltCpbRemovalDelayOffset[0][0]  = uiInitialCpbRemovalDelay;
+  seiBufferingPeriod->m_initialAltCpbRemovalDelay      [0][1]  = uiInitialCpbRemovalDelay;
+  seiBufferingPeriod->m_initialAltCpbRemovalDelayOffset[0][1]  = uiInitialCpbRemovalDelay;
+
+  seiBufferingPeriod->m_rapCpbParamsPresentFlag              = 0;
+  //for the concatenation, it can be set to one during splicing.
+  seiBufferingPeriod->m_concatenationFlag = 0;
+  //since the temporal layer HRD is not ready, we assumed it is fixed
+  seiBufferingPeriod->m_auCpbRemovalDelayDelta = 1;
+  seiBufferingPeriod->m_cpbDelayOffset = 0;
+  seiBufferingPeriod->m_dpbDelayOffset = 0;
+
+  // Intial arrival time SEI message
+
+  seiBspInitialArrivalTime->m_nalInitialArrivalDelay[0] = 0;
+  seiBspInitialArrivalTime->m_vclInitialArrivalDelay[0] = 0;
+
+
+  seiBspNesting->m_nestedSEIs.push_back(seiBufferingPeriod);
+  seiBspNesting->m_nestedSEIs.push_back(seiBspInitialArrivalTime);
+#if VPS_VUI_BSP_HRD_PARAMS
+  seiBspNesting->m_bspIdx = bspIdx;
+  seiBspNesting->m_seiOlsIdx = olsIdx;
+  seiBspNesting->m_seiPartitioningSchemeIdx = partitioningSchemeIdx;
+#endif
+  seiScalableNesting->m_nestedSEIs.push_back(seiBspNesting); // BSP nesting SEI is contained in scalable nesting SEI
+
+  return seiScalableNesting;
+}
+#endif
+
+#if Q0048_CGS_3D_ASYMLUT
+Void TEncGOP::xDetermin3DAsymLUT( TComSlice * pSlice , TComPic * pCurPic , UInt refLayerIdc , TEncCfg * pCfg , Bool bSignalPPS )
+{
+  Int nCGSFlag = pSlice->getPPS()->getCGSFlag();
+  m_Enc3DAsymLUTPPS.setPPSBit( 0 );
+  Double dErrorUpdatedPPS = 0 , dErrorPPS = 0;
+
+#if R0179_ENC_OPT_3DLUT_SIZE
+  Int nTLthres = m_pcCfg->getCGSLutSizeRDO() ? 2:7;
+  Double dFrameLambda; 
+#if FULL_NBIT
+  Int    SHIFT_QP = 12 + 6 * (pSlice->getBitDepthY() - 8);
+#else
+  Int    SHIFT_QP = 12; 
+#endif 
+  Int QP = pSlice->getSliceQp();
+
+  // set frame lambda
+  dFrameLambda = 0.68 * pow (2, (QP  - SHIFT_QP) / 3.0) * (m_pcCfg->getGOPSize() > 1 && pSlice->isInterB()? 2 : 1);
+
+  if(m_pcCfg->getCGSLutSizeRDO() == 1 && (!bSignalPPS && (pSlice->getDepth() < nTLthres))) 
+    dErrorUpdatedPPS = m_Enc3DAsymLUTPicUpdate.derive3DAsymLUT( pSlice , pCurPic , refLayerIdc , pCfg , bSignalPPS , m_pcEncTop->getElRapSliceTypeB(), dFrameLambda );
+  else if (pSlice->getDepth() >= nTLthres)
+    dErrorUpdatedPPS = MAX_DOUBLE;
+  else // if (m_pcCfg->getCGSLutSizeRDO() = 0 || bSignalPPS)
+#endif   
+    dErrorUpdatedPPS = m_Enc3DAsymLUTPicUpdate.derive3DAsymLUT( pSlice , pCurPic , refLayerIdc , pCfg , bSignalPPS , m_pcEncTop->getElRapSliceTypeB() );
+
+
+  if( bSignalPPS )
+  {
+    m_Enc3DAsymLUTPPS.copy3DAsymLUT( &m_Enc3DAsymLUTPicUpdate );
+    pSlice->setCGSOverWritePPS( 1 ); // regular PPS update
+  }
+  else if( nCGSFlag )
+  {
+#if R0179_ENC_OPT_3DLUT_SIZE
+    if(pSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_RASL_R || pSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_RASL_N) 
+    {
+      pSlice->setCGSOverWritePPS( 0 ); 
+    }
+    else if (pSlice->getDepth() >= nTLthres) 
+    {
+      pSlice->setCGSOverWritePPS( 0 ); 
+    }
+    else
+    {
+#endif    
+      dErrorPPS = m_Enc3DAsymLUTPPS.estimateDistWithCur3DAsymLUT( pCurPic , refLayerIdc );
+      Double dFactor = pCfg->getIntraPeriod() == 1 ? 0.99 : 0.9;
+
+#if R0179_ENC_OPT_3DLUT_SIZE 
+      if( m_pcCfg->getCGSLutSizeRDO() )
+      {
+        dErrorPPS = dErrorPPS/m_Enc3DAsymLUTPicUpdate.getDistFactor(pSlice->getSliceType(), pSlice->getDepth()); 
+      }
+#endif
+      pSlice->setCGSOverWritePPS( dErrorUpdatedPPS < dFactor * dErrorPPS );
+#if R0179_ENC_OPT_3DLUT_SIZE
+    }
+#endif
+    if( pSlice->getCGSOverWritePPS() )
+    {
+      m_Enc3DAsymLUTPPS.copy3DAsymLUT( &m_Enc3DAsymLUTPicUpdate );
+    }
+  }
+  pSlice->getPPS()->setCGSOutputBitDepthY( m_Enc3DAsymLUTPPS.getOutputBitDepthY() );
+  pSlice->getPPS()->setCGSOutputBitDepthC( m_Enc3DAsymLUTPPS.getOutputBitDepthC() );
+}
+
+Void TEncGOP::downScalePic( TComPicYuv* pcYuvSrc, TComPicYuv* pcYuvDest)
+{
+  Int inputBitDepth  = g_bitDepthLayer[CHANNEL_TYPE_LUMA][m_layerId];
+  Int outputBitDepth = g_bitDepthLayer[CHANNEL_TYPE_CHROMA][m_layerId];
+  {
+    pcYuvSrc->setBorderExtension(false);
+    pcYuvSrc->extendPicBorder   (); // extend the border.
+    pcYuvSrc->setBorderExtension(false);
+
+    Int iWidth  = pcYuvSrc->getWidth(COMPONENT_Y);
+    Int iHeight = pcYuvSrc->getHeight(COMPONENT_Y); 
+
+    if(!m_temp)
+    {
+      initDs(iWidth, iHeight, m_pcCfg->getIntraPeriod()>1);
+    }
+
+    filterImg(pcYuvSrc->getAddr(COMPONENT_Y),  pcYuvSrc->getStride(COMPONENT_Y),  pcYuvDest->getAddr(COMPONENT_Y),  pcYuvDest->getStride(COMPONENT_Y),  iHeight,    iWidth,    inputBitDepth-outputBitDepth, 0);
+    filterImg(pcYuvSrc->getAddr(COMPONENT_Cb), pcYuvSrc->getStride(COMPONENT_Cb), pcYuvDest->getAddr(COMPONENT_Cb), pcYuvDest->getStride(COMPONENT_Cb), iHeight>>1, iWidth>>1, inputBitDepth-outputBitDepth, 1);
+    filterImg(pcYuvSrc->getAddr(COMPONENT_Cr), pcYuvSrc->getStride(COMPONENT_Cr), pcYuvDest->getAddr(COMPONENT_Cr), pcYuvDest->getStride(COMPONENT_Cr), iHeight>>1, iWidth>>1, inputBitDepth-outputBitDepth, 2);  
+  }
+}
+const Int TEncGOP::m_phase_filter_0_t0[4][13]={
+  {0,  2,  -3,  -9,   6,  39,  58,  39,   6,  -9,  -3,  2,  0},  
+  {0, 0,  0,  -2,  8,-20, 116, 34, -10,  2,  0, 0,  0},                      //{0,  1,  -1,  -8,  -1,  31,  57,  47,  13,  -7,  -5,  1,  0},  //
+  {0,  1,   0,  -7,  -5,  22,  53,  53,  22,  -5,  -7,  0,  1},  
+  {0,  0,   1,  -5,  -7,  13,  47,  57,  31,  -1,  -8,-1,  1}  
+};
+
+const Int TEncGOP::m_phase_filter_0_t1[4][13]={
+  {0,  4,  0,  -12, 0,  40,  64,  40, 0, -12,  0,  4,  0},
+  {0, 0,  0,  -2,  8,-20, 116,34,-10,  2,  0, 0,  0},                      //{0,  1,  -1,  -8,  -1,  31,  57,  47,  13,  -7,  -5,  1,  0},  //
+  {0,  1,   0,  -7,  -5,  22,  53,  53,  22,  -5,  -7,  0,  1},  
+  {0,  0,   1,  -5,  -7,  13,  47,  57,  31,  -1,  -8,-1,  1}  
+};
+const Int TEncGOP::m_phase_filter_0_t1_chroma[4][13]={
+  {0,  0,  0,   0,  0,   0,  128, 0,  0,  0,  0,  0,  0},
+  {0, 0,  0,  -2,  8,-20, 116,34,-10,  2,  0, 0,  0},                      //{0,  1,  -1,  -8,  -1,  31,  57,  47,  13,  -7,  -5,  1,  0},  //
+  {0,  1,   0,  -7,  -5,  22,  53,  53,  22,  -5,  -7,  0,  1},  
+  {0,  0,   1,  -5,  -7,  13,  47,  57,  31,  -1,  -8,-1,  1}  
+};
+
+const Int TEncGOP::m_phase_filter_1[8][13]={
+  {0,   0,  5,  -6,  -10,37,  76,  37,-10,   -6, 5,  0,   0},    
+  {0,  -1,  5,  -3,  -12,29,  75,  45,  -7,   -8, 5,  0,   0},    
+  {0,  -1,  4,  -1,  -13,22,  73,  52,  -3,  -10, 4,  1,   0},    
+  {0,  -1,  4,   1,  -13,14,  70,  59,   2,  -12, 3,  2,  -1},  
+  {0,  -1,  3,   2,  -13, 8,  65,  65,   8,  -13, 2,  3,  -1},    
+  {0,  -1,  2,   3,  -12, 2,  59,  70,  14,  -13, 1,  4,  -1},    
+  {0,   0,  1,   4,  -10,-3,  52,  73,  22,  -13,-1,  4,  -1},    
+  {0,   0,  0,   5,   -8,-7,  45,  75,  29,  -12,-3,  5,  -1}    
+};
+
+#if CGS_GCC_NO_VECTORIZATION  
+#ifdef __GNUC__
+#define GCC_VERSION (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
+#if GCC_VERSION > 40600
+__attribute__((optimize("no-tree-vectorize")))
+#endif
+#endif
+#endif
+Void TEncGOP::filterImg(
+    Pel           *src,
+    Int           iSrcStride,
+    Pel           *dst,
+    Int           iDstStride,
+    Int           height1,  
+    Int           width1,  
+    Int           shift,
+    Int           plane)
+{
+  Int length = m_iTap;
+  Int height2,width2;
+  Int k,iSum;
+  Int i0, div_i0, i1;
+  Int j0, div_j0, j1;
+  const Int *p_filter;
+  Pel *p_src, *p_dst;
+  Pel *p_src_line, *p_dst_line;
+  Int **p_temp, *p_tmp;
+  Int shift2 = 2*7+shift;
+  Int shift_round = (1 << (shift2 - 1));
+  Int iMax = (1<<(g_bitDepth[CHANNEL_TYPE_LUMA]-shift))-1;
+  height2 = (height1 * m_iM) / m_iN;
+  width2  = (width1  * m_iM) / m_iN;
+
+  m_phase_filter = plane? m_phase_filter_chroma : m_phase_filter_luma;
+
+  // horizontal filtering
+  p_src_line = src;
+  for(j1 = 0; j1 < height1; j1++)
+  {
+    i0=-m_iN;
+    p_tmp = m_temp[j1];
+    
+    for(i1 = 0; i1 < width2; i1++)
+    {
+      i0      += m_iN;
+      div_i0   = (i0 / m_iM);
+      p_src    =  p_src_line + ( div_i0 - (length >> 1));
+      p_filter = m_phase_filter[i0 - div_i0 * m_iM]; // phase_filter[i0 % M]
+      iSum     = 0;
+      for(k = 0; k < length; k++)
+      {
+        iSum += (*p_src++) * (*p_filter++);
+      }
+      *p_tmp++ = iSum;
+    }
+    p_src_line +=  iSrcStride;
+  }
+
+  // pad temp (vertical)
+  for (k=-(length>>1); k<0; k++)
+  {
+    memcpy(m_temp[k], m_temp[0], width2*sizeof(Int));
+  }
+  for (k=height1; k<(height1+(length>>1)); k++)
+  {
+    memcpy(m_temp[k], m_temp[k-1], (width2)* sizeof(Int));
+  }
+
+  // vertical filtering
+  j0 = (plane == 0) ? -m_iN : -(m_iN-1);
+  
+  p_dst_line = dst;
+  for(j1 = 0; j1 < height2; j1++)
+  {
+    j0      += m_iN;
+    div_j0   = (j0 / m_iM);
+    p_dst = p_dst_line;
+    p_temp   = &m_temp[div_j0 - (length>>1)];
+    p_filter = m_phase_filter[j0 - div_j0 * m_iM]; // phase_filter[j0 % M]
+    for(i1 = 0; i1 < width2;i1++)
+    {
+      iSum=0;
+      for(k = 0; k < length; k++)
+      {
+        iSum += p_temp[k][i1] * p_filter[k];
+      }
+      iSum=((iSum + shift_round) >> shift2);
+      *p_dst++ = (Short)(iSum > iMax ? iMax : (iSum < 0 ? 0 : iSum));
+    }
+    p_dst_line += iDstStride;
+  }
+}
+
+Void TEncGOP::initDs(Int iWidth, Int iHeight, Int iType)
+{
+  m_iTap = 13;
+  if(g_posScalingFactor[0][0] == (1<<15))
+  {
+    m_iM = 4;
+    m_iN = 8;
+    m_phase_filter_luma = iType? m_phase_filter_0_t1 : m_phase_filter_0_t0;
+    m_phase_filter_chroma = m_phase_filter_0_t1_chroma; 
+  }
+  else
+  {
+    m_iM = 8;
+    m_iN = 12;
+    m_phase_filter_luma = m_phase_filter_chroma =  m_phase_filter_1;
+    m_phase_filter = m_phase_filter_1;
+  }
+
+  get_mem2DintWithPad (&m_temp, iHeight, iWidth*m_iM/m_iN,   m_iTap>>1, 0);
+}
+
+Int TEncGOP::get_mem2DintWithPad(Int ***array2D, Int dim0, Int dim1, Int iPadY, Int iPadX)
+{
+  Int i;
+  Int *curr = NULL;
+  Int iHeight, iWidth;
+
+  iHeight = dim0+2*iPadY;
+  iWidth = dim1+2*iPadX;
+  (*array2D) = (Int**)malloc(iHeight*sizeof(Int*));
+  *(*array2D) = (Int* )xMalloc(Int, iHeight*iWidth);
+
+  (*array2D)[0] += iPadX;
+  curr = (*array2D)[0];
+  for(i = 1 ; i < iHeight; i++)
+  {
+    curr += iWidth;
+    (*array2D)[i] = curr;
+  }
+  (*array2D) = &((*array2D)[iPadY]);
+
+  return 0;
+}
+
+Void TEncGOP::free_mem2DintWithPad(Int **array2D, Int iPadY, Int iPadX)
+{
+  if (array2D)
+  {
+    if (*array2D)
+    {
+      xFree(array2D[-iPadY]-iPadX);
+    }
+    else 
+    {
+      printf("free_mem2DintWithPad: trying to free unused memory\r\nPress Any Key\r\n");
+    }
+
+    free (&array2D[-iPadY]);
+  } 
+  else
+  {
+    printf("free_mem2DintWithPad: trying to free unused memory\r\nPress Any Key\r\n");
+  }
+}
+#endif
+
+#if R0071_IRAP_EOS_CROSS_LAYER_IMPACTS
+Void TEncGOP::xCheckLayerReset(TComSlice *slice)
+{
+  Bool layerResetFlag;
+  Int dolLayerId;
+
+  if (slice->isIRAP() && slice->getLayerId() > 0)
+  {
+    if (m_prevPicHasEos)
+    {
+      layerResetFlag = true;
+      dolLayerId = slice->getLayerId();
+    }
+    else if ((slice->isCRA() && slice->getHandleCraAsBlaFlag()) || (slice->isIDR() && slice->getCrossLayerBLAFlag()) || slice->isBLA())
+    {
+      layerResetFlag = true;
+      dolLayerId = slice->getLayerId();
+    }
+    else
+    {
+      layerResetFlag = false;
+    }
+
+    if (layerResetFlag)
+    {
+      for (Int i = 0; i < slice->getVPS()->getNumPredictedLayers(dolLayerId); i++)
+      {
+        Int iLayerId = slice->getVPS()->getPredictedLayerId(dolLayerId, i);
+        m_ppcTEncTop[slice->getVPS()->getLayerIdxInVps(iLayerId)]->setLayerInitializedFlag(false);
+        m_ppcTEncTop[slice->getVPS()->getLayerIdxInVps(iLayerId)]->setFirstPicInLayerDecodedFlag(false);
+      }
+
+      // Each picture that is in the DPB and has nuh_layer_id equal to dolLayerId is marked as "unused for reference".
+      for (TComList<TComPic*>::iterator pic = m_ppcTEncTop[slice->getVPS()->getLayerIdxInVps(dolLayerId)]->getListPic()->begin(); pic != m_ppcTEncTop[slice->getVPS()->getLayerIdxInVps(dolLayerId)]->getListPic()->end(); pic++)
+      {
+        if ((*pic)->getSlice(0)->getPOC() != slice->getPOC())
+        {
+          (*pic)->getSlice(0)->setReferenced(false);
+        }
+      }
+
+      // Each picture that is in DPB and has nuh_layer_id equal to any value of IdPredictedLayer[dolLayerId][i]
+      // for the values of i in range of 0 to NumPredictedLayers[dolLayerId] - 1, inclusive, is marked as "unused for reference"
+      for (UInt i = 0; i < slice->getVPS()->getNumPredictedLayers(dolLayerId); i++)
+      {
+        UInt predLId = slice->getVPS()->getPredictedLayerId(dolLayerId, i);
+        for (TComList<TComPic*>::iterator pic = m_ppcTEncTop[slice->getVPS()->getLayerIdxInVps(predLId)]->getListPic()->begin(); pic != m_ppcTEncTop[slice->getVPS()->getLayerIdxInVps(predLId)]->getListPic()->end(); pic++)
+        {
+          if ((*pic)->getSlice(0)->getPOC() != slice->getPOC())
+          {
+            (*pic)->getSlice(0)->setReferenced(false);
+          }
+        }
+      }
+    }
+  }
+}
+
+Void TEncGOP::xSetNoRaslOutputFlag(TComSlice *slice)
+{
+  if (slice->isIRAP())
+  {
+    m_noRaslOutputFlag = slice->getHandleCraAsBlaFlag();  // default value
+    if (slice->isIDR() || slice->isBLA() || m_bFirst || m_prevPicHasEos)
+    {
+      m_noRaslOutputFlag = true;
+    }
+    else if (!m_ppcTEncTop[slice->getVPS()->getLayerIdxInVps(m_layerId)]->getLayerInitializedFlag())
+    {
+      Bool refLayersInitialized = true;
+      for (UInt j = 0; j < slice->getVPS()->getNumDirectRefLayers(m_layerId); j++)
+      {
+        UInt refLayerId = slice->getVPS()->getRefLayerId(m_layerId, j);
+        if (!m_ppcTEncTop[slice->getVPS()->getLayerIdxInVps(refLayerId)]->getLayerInitializedFlag())
+        {
+          refLayersInitialized = false;
+        }
+      }
+      if (refLayersInitialized)
+      {
+        m_noRaslOutputFlag = true;
+      }
+    }
+  }
+}
+
+Void TEncGOP::xSetLayerInitializedFlag(TComSlice *slice)
+{
+  if (slice->isIRAP() && m_noRaslOutputFlag)
+  {
+    if (m_layerId == 0)
+    {
+      m_ppcTEncTop[slice->getVPS()->getLayerIdxInVps(m_layerId)]->setLayerInitializedFlag(true);
+    }
+    else if (!m_ppcTEncTop[slice->getVPS()->getLayerIdxInVps(m_layerId)]->getLayerInitializedFlag() && slice->getVPS()->getNumDirectRefLayers(m_layerId) == 0)
+    {
+      m_ppcTEncTop[slice->getVPS()->getLayerIdxInVps(m_layerId)]->setLayerInitializedFlag(true);
+    }
+    else if (!m_ppcTEncTop[slice->getVPS()->getLayerIdxInVps(m_layerId)]->getLayerInitializedFlag())
+    {
+      Bool refLayersInitialized = true;
+      for (UInt j = 0; j < slice->getVPS()->getNumDirectRefLayers(m_layerId); j++)
+      {
+        UInt refLayerId = slice->getVPS()->getRefLayerId(m_layerId, j);
+        if (!m_ppcTEncTop[slice->getVPS()->getLayerIdxInVps(refLayerId)]->getLayerInitializedFlag())
+        {
+          refLayersInitialized = false;
+        }
+      }
+      if (refLayersInitialized)
+      {
+        m_ppcTEncTop[slice->getVPS()->getLayerIdxInVps(m_layerId)]->setLayerInitializedFlag(true);
+      }
+    }
+  }
+}
+#endif // R0071_IRAP_EOS_CROSS_LAYER_IMPACTS
+
+#endif //SVC_EXTENSION
+
+//! \}
Index: /tags/SHM-9.0/source/Lib/TLibEncoder/TEncGOP.h
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibEncoder/TEncGOP.h	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibEncoder/TEncGOP.h	(revision 1088)
@@ -0,0 +1,300 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TEncGOP.h
+    \brief    GOP encoder class (header)
+*/
+
+#ifndef __TENCGOP__
+#define __TENCGOP__
+
+#include <list>
+
+#include <stdlib.h>
+
+#include "TLibCommon/TComList.h"
+#include "TLibCommon/TComPic.h"
+#include "TLibCommon/TComBitCounter.h"
+#include "TLibCommon/TComLoopFilter.h"
+#include "TLibCommon/AccessUnit.h"
+#include "TEncSampleAdaptiveOffset.h"
+#include "TEncSlice.h"
+#include "TEncEntropy.h"
+#include "TEncCavlc.h"
+#include "TEncSbac.h"
+#include "SEIwrite.h"
+#if Q0048_CGS_3D_ASYMLUT
+#include "TEnc3DAsymLUT.h"
+#endif
+
+#include "TEncAnalyze.h"
+#include "TEncRateCtrl.h"
+#include <vector>
+
+//! \ingroup TLibEncoder
+//! \{
+
+class TEncTop;
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+class TEncGOP
+{
+private:
+  //  Data
+  Bool                    m_bLongtermTestPictureHasBeenCoded;
+  Bool                    m_bLongtermTestPictureHasBeenCoded2;
+  UInt                    m_numLongTermRefPicSPS;
+  UInt                    m_ltRefPicPocLsbSps[MAX_NUM_LONG_TERM_REF_PICS];
+  Bool                    m_ltRefPicUsedByCurrPicFlag[MAX_NUM_LONG_TERM_REF_PICS];
+  Int                     m_iLastIDR;
+  Int                     m_iGopSize;
+  Int                     m_iNumPicCoded;
+  Bool                    m_bFirst;
+#if ALLOW_RECOVERY_POINT_AS_RAP
+  Int                     m_iLastRecoveryPicPOC;
+#endif
+
+  //  Access channel
+  TEncTop*                m_pcEncTop;
+  TEncCfg*                m_pcCfg;
+  TEncSlice*              m_pcSliceEncoder;
+  TComList<TComPic*>*     m_pcListPic;
+
+  TEncEntropy*            m_pcEntropyCoder;
+  TEncCavlc*              m_pcCavlcCoder;
+  TEncSbac*               m_pcSbacCoder;
+  TEncBinCABAC*           m_pcBinCABAC;
+  TComLoopFilter*         m_pcLoopFilter;
+
+  SEIWriter               m_seiWriter;
+
+  //--Adaptive Loop filter
+  TEncSampleAdaptiveOffset*  m_pcSAO;
+  TEncRateCtrl*           m_pcRateCtrl;
+  // indicate sequence first
+  Bool                    m_bSeqFirst;
+
+  // clean decoding refresh
+  Bool                    m_bRefreshPending;
+  Int                     m_pocCRA;
+  NalUnitType             m_associatedIRAPType;
+  Int                     m_associatedIRAPPOC;
+
+  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;
+
+#if POC_RESET_IDC_ENCODER
+  Int                     m_pocCraWithoutReset;
+  Int                     m_associatedIrapPocBeforeReset;
+#endif
+#if SVC_EXTENSION
+  UInt                    m_layerId;      
+  TEncTop**               m_ppcTEncTop;
+  TEncSearch*             m_pcPredSearch;                       ///< encoder search class
+#if Q0048_CGS_3D_ASYMLUT
+  TEnc3DAsymLUT           m_Enc3DAsymLUTPicUpdate;
+  TEnc3DAsymLUT           m_Enc3DAsymLUTPPS;
+  TComPicYuv*             m_pColorMappedPic;
+
+  Int m_iTap;
+  const Int (*m_phase_filter)[13];
+  const Int (*m_phase_filter_luma)[13];
+  const Int (*m_phase_filter_chroma)[13];
+  Int m_iM, m_iN;
+  static const Int m_phase_filter_0_t0[4][13];
+  static const Int m_phase_filter_0_t1[4][13];
+  static const Int m_phase_filter_0_t1_chroma[4][13];
+  static const Int m_phase_filter_1[8][13];
+  Int   **m_temp;
+#endif
+#if POC_RESET_IDC_ENCODER
+  Int   m_lastPocPeriodId;
+#endif
+#if R0071_IRAP_EOS_CROSS_LAYER_IMPACTS
+  Bool  m_noRaslOutputFlag;
+  Bool  m_prevPicHasEos;
+#endif
+#endif
+  
+public:
+  TEncGOP();
+  virtual ~TEncGOP();
+  
+#if SVC_EXTENSION
+  Void  create      ( UInt layerId );
+#else
+  Void  create      ();
+#endif
+  Void  destroy     ();
+
+  Void  init        ( TEncTop* pcTEncTop );
+#if SVC_EXTENSION  
+  Void  compressGOP ( Int iPicIdInGOP, Int iPOCLast, Int iNumPicRcvd, TComList<TComPic*>& rcListPic, TComList<TComPicYuv*>& rcListPicYuvRec,
+                      std::list<AccessUnit>& accessUnitsInGOP, Bool isField, Bool isTff, const InputColourSpaceConversion snr_conversion, const Bool printFrameMSE );
+#else
+  Void  compressGOP ( Int iPOCLast, Int iNumPicRcvd, TComList<TComPic*>& rcListPic, TComList<TComPicYuv*>& rcListPicYuvRec,
+                      std::list<AccessUnit>& accessUnitsInGOP, Bool isField, Bool isTff, const InputColourSpaceConversion snr_conversion, const Bool printFrameMSE );
+#endif
+  Void  xAttachSliceDataToNalUnit (OutputNALUnit& rNalu, TComOutputBitstream* pcBitstreamRedirect);
+
+
+  Int   getGOPSize()          { return  m_iGopSize;  }
+
+  TComList<TComPic*>*   getListPic()      { return m_pcListPic; }
+  
+#if !SVC_EXTENSION
+  Void  printOutSummary      ( UInt uiNumAllPicCoded, Bool isField, const Bool printMSEBasedSNR, const Bool printSequenceMSE );
+#endif
+  Void  preLoopFilterPicAll  ( TComPic* pcPic, UInt64& ruiDist );
+
+  TEncSlice*  getSliceEncoder()   { return m_pcSliceEncoder; }
+  NalUnitType getNalUnitType( Int pocCurr, Int lastIdr, Bool isField );
+  Void arrangeLongtermPicturesInRPS(TComSlice *, TComList<TComPic*>& );
+
+#if POC_RESET_IDC_ENCODER
+  Void  determinePocResetIdc( Int const pocCurr, TComSlice *const slice);
+  Int   getIntraRefreshInterval()  { return m_pcCfg->getIntraPeriod(); }
+  Int   getIntraRefreshType()      { return m_pcCfg->getDecodingRefreshType(); }  
+  Int   getLastPocPeriodId()      { return m_lastPocPeriodId; }
+  Void  setLastPocPeriodId(Int x) { m_lastPocPeriodId = x;    }
+  Void  updatePocValuesOfPics( Int const pocCurr, TComSlice *const slice);
+#endif
+
+protected:
+  TEncRateCtrl* getRateCtrl()       { return m_pcRateCtrl;  }
+
+protected:
+
+  Void  xInitGOP          ( Int iPOCLast, Int iNumPicRcvd, TComList<TComPic*>& rcListPic, TComList<TComPicYuv*>& rcListPicYuvRecOut, Bool isField );
+  Void  xGetBuffer        ( TComList<TComPic*>& rcListPic, TComList<TComPicYuv*>& rcListPicYuvRecOut, Int iNumPicRcvd, Int iTimeOffset, TComPic*& rpcPic, TComPicYuv*& rpcPicYuvRecOut, Int pocCurr, Bool isField );
+
+  Void  xCalculateAddPSNR          ( TComPic* pcPic, TComPicYuv* pcPicD, const AccessUnit&, Double dEncTime, const InputColourSpaceConversion snr_conversion, const Bool printFrameMSE );
+  Void  xCalculateInterlacedAddPSNR( TComPic* pcPicOrgFirstField, TComPic* pcPicOrgSecondField,
+                                     TComPicYuv* pcPicRecFirstField, TComPicYuv* pcPicRecSecondField,
+                                     const AccessUnit& accessUnit, Double dEncTime, const InputColourSpaceConversion snr_conversion, const Bool printFrameMSE );
+
+  UInt64 xFindDistortionFrame (TComPicYuv* pcPic0, TComPicYuv* pcPic1);
+
+  Double xCalculateRVM();
+
+  SEIActiveParameterSets*           xCreateSEIActiveParameterSets (TComSPS *sps);
+  SEIFramePacking*                  xCreateSEIFramePacking();
+  SEISegmentedRectFramePacking*     xCreateSEISegmentedRectFramePacking();
+  SEIDisplayOrientation*            xCreateSEIDisplayOrientation();
+  SEIToneMappingInfo*               xCreateSEIToneMappingInfo();
+  SEITempMotionConstrainedTileSets* xCreateSEITempMotionConstrainedTileSets ();
+  SEIKneeFunctionInfo*              xCreateSEIKneeFunctionInfo();
+  SEIChromaSamplingFilterHint*      xCreateSEIChromaSamplingFilterHint(Bool bChromaLocInfoPresent, Int iHorFilterIndex, Int iVerFilterIdc);
+
+  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;
+  }
+  Void dblMetric( TComPic* pcPic, UInt uiNumSlices );
+
+#if Q0074_COLOUR_REMAPPING_SEI
+  SEIColourRemappingInfo* xCreateSEIColourRemappingInfo();
+#endif
+#if SVC_EXTENSION
+#if LAYERS_NOT_PRESENT_SEI
+  SEILayersNotPresent*    xCreateSEILayersNotPresent ();
+#endif
+#if N0383_IL_CONSTRAINED_TILE_SETS_SEI
+  Void xBuildTileSetsMap(TComPicSym* picSym);
+  SEIInterLayerConstrainedTileSets* xCreateSEIInterLayerConstrainedTileSets();
+#endif
+#if O0164_MULTI_LAYER_HRD
+#if VPS_VUI_BSP_HRD_PARAMS
+  SEIScalableNesting* xCreateBspNestingSEI(TComSlice *pcSlice, Int olsIdx, Int partitioningSchemeIdx, Int bspIdx);
+#else
+  SEIScalableNesting* xCreateBspNestingSEI(TComSlice *pcSlice);
+#endif
+#endif
+#if P0123_ALPHA_CHANNEL_SEI
+  SEIAlphaChannelInfo* xCreateSEIAlphaChannelInfo();
+#endif
+#if Q0096_OVERLAY_SEI
+  SEIOverlayInfo* xCreateSEIOverlayInfo();
+#endif
+#if Q0048_CGS_3D_ASYMLUT
+  Void xDetermin3DAsymLUT( TComSlice * pSlice , TComPic * pCurPic , UInt refLayerIdc , TEncCfg * pCfg , Bool bSignalPPS );
+  Void downScalePic( TComPicYuv* pcYuvSrc, TComPicYuv* pcYuvDest);
+  Void downScaleComponent2x2( const Pel* pSrc, Pel* pDest, const Int iSrcStride, const Int iDestStride, const Int iSrcWidth, const Int iSrcHeight, const Int inputBitDepth, const Int outputBitDepth );
+  inline Short  xClip( Short x , Int bitdepth );
+  Void initDs(Int iWidth, Int iHeight, Int iType);
+  Void filterImg(
+    Pel           *src,
+    Int           iSrcStride,
+    Pel           *dst,
+    Int           iDstStride,
+    Int           height1,  
+    Int           width1,  
+    Int           shift,
+    Int           plane);
+
+  Int get_mem2DintWithPad(Int ***array2D, Int dim0, Int dim1, Int iPadY, Int iPadX);
+  Void free_mem2DintWithPad(Int **array2D, Int iPadY, Int iPadX);
+#endif
+#if R0071_IRAP_EOS_CROSS_LAYER_IMPACTS
+  Void xCheckLayerReset(TComSlice *slice);
+  Void xSetNoRaslOutputFlag(TComSlice *slice);
+  Void xSetLayerInitializedFlag(TComSlice *slice);
+#endif
+#endif //SVC_EXTENSION
+};// END CLASS DEFINITION TEncGOP
+
+//! \}
+
+#endif // __TENCGOP__
+
Index: /tags/SHM-9.0/source/Lib/TLibEncoder/TEncPic.cpp
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibEncoder/TEncPic.cpp	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibEncoder/TEncPic.cpp	(revision 1088)
@@ -0,0 +1,165 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TEncPic.cpp
+    \brief    class of picture which includes side information for encoder
+*/
+
+#include "TEncPic.h"
+
+//! \ingroup TLibEncoder
+//! \{
+
+/** Constructor
+ */
+TEncQPAdaptationUnit::TEncQPAdaptationUnit()
+: m_dActivity(0.0)
+{
+}
+
+/** Destructor
+ */
+TEncQPAdaptationUnit::~TEncQPAdaptationUnit()
+{
+}
+
+/** Constructor
+ */
+TEncPicQPAdaptationLayer::TEncPicQPAdaptationLayer()
+: m_uiAQPartWidth(0)
+, m_uiAQPartHeight(0)
+, m_uiNumAQPartInWidth(0)
+, m_uiNumAQPartInHeight(0)
+, m_acTEncAQU(NULL)
+, m_dAvgActivity(0.0)
+{
+}
+
+/** Destructor
+ */
+TEncPicQPAdaptationLayer::~TEncPicQPAdaptationLayer()
+{
+  destroy();
+}
+
+/** Initialize member variables
+ * \param iWidth Picture width
+ * \param iHeight Picture height
+ * \param uiAQPartWidth Width of unit block for analyzing local image characteristics
+ * \param uiAQPartHeight Height of unit block for analyzing local image characteristics
+ * \return Void
+ */
+Void TEncPicQPAdaptationLayer::create( Int iWidth, Int iHeight, UInt uiAQPartWidth, UInt uiAQPartHeight )
+{
+  m_uiAQPartWidth = uiAQPartWidth;
+  m_uiAQPartHeight = uiAQPartHeight;
+  m_uiNumAQPartInWidth = (iWidth + m_uiAQPartWidth-1) / m_uiAQPartWidth;
+  m_uiNumAQPartInHeight = (iHeight + m_uiAQPartHeight-1) / m_uiAQPartHeight;
+  m_acTEncAQU = new TEncQPAdaptationUnit[ m_uiNumAQPartInWidth * m_uiNumAQPartInHeight ];
+}
+
+/** Clean up
+ * \return Void
+ */
+Void TEncPicQPAdaptationLayer::destroy()
+{
+  if (m_acTEncAQU)
+  {
+    delete[] m_acTEncAQU;
+    m_acTEncAQU = NULL;
+  }
+}
+
+/** Constructor
+ */
+TEncPic::TEncPic()
+: m_acAQLayer(NULL)
+, m_uiMaxAQDepth(0)
+{
+}
+
+/** Destructor
+ */
+TEncPic::~TEncPic()
+{
+  destroy();
+}
+
+/** Initialize member variables
+ * \param iWidth Picture width
+ * \param iHeight Picture height
+ * \param uiMaxWidth Maximum CU width
+ * \param uiMaxHeight Maximum CU height
+ * \param uiMaxDepth Maximum CU depth
+ * \param uiMaxAQDepth Maximum depth of unit block for assigning QP adaptive to local image characteristics
+ * \param bIsVirtual
+ * \return Void
+ */
+
+#if SVC_EXTENSION
+Void TEncPic::create( Int iWidth, Int iHeight, ChromaFormat chromaFormat, UInt uiMaxWidth, UInt uiMaxHeight, UInt uiMaxDepth, UInt uiMaxAQDepth,  
+                      Window &conformanceWindow, Window &defaultDisplayWindow, Int *numReorderPics, TComSPS* pcSps, Bool bIsVirtual )
+{
+  TComPic::create( iWidth, iHeight, chromaFormat, uiMaxWidth, uiMaxHeight, uiMaxDepth,  
+                   conformanceWindow, defaultDisplayWindow, numReorderPics, pcSps, bIsVirtual );
+#else
+Void TEncPic::create( Int iWidth, Int iHeight, ChromaFormat chromaFormat, UInt uiMaxWidth, UInt uiMaxHeight, UInt uiMaxDepth, UInt uiMaxAQDepth,
+                      Window &conformanceWindow, Window &defaultDisplayWindow, Int *numReorderPics, Bool bIsVirtual )
+{
+  TComPic::create( iWidth, iHeight, chromaFormat, uiMaxWidth, uiMaxHeight, uiMaxDepth, conformanceWindow, defaultDisplayWindow, numReorderPics, bIsVirtual );
+#endif
+  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: /tags/SHM-9.0/source/Lib/TLibEncoder/TEncPic.h
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibEncoder/TEncPic.h	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibEncoder/TEncPic.h	(revision 1088)
@@ -0,0 +1,123 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     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"
+#if SVC_EXTENSION
+#include "TLibCommon/TComSlice.h"
+#endif
+//! \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();
+
+#if SVC_EXTENSION
+  Void          create( Int iWidth, Int iHeight, ChromaFormat chromaFormat, UInt uiMaxWidth, UInt uiMaxHeight, UInt uiMaxDepth, UInt uiMaxAQDepth,  
+                      Window &conformanceWindow, Window &defaultDisplayWindow, Int *numReorderPics, TComSPS* pcSps, Bool bIsVirtual=false );
+#else  //SVC_EXTENSION
+  Void          create( Int iWidth, Int iHeight, ChromaFormat chromaFormat, UInt uiMaxWidth, UInt uiMaxHeight, UInt uiMaxDepth, UInt uiMaxAQDepth,
+                          Window &conformanceWindow, Window &defaultDisplayWindow, Int *numReorderPics, Bool bIsVirtual = false );
+#endif //SVC_EXTENSION
+
+  virtual Void  destroy();
+
+  TEncPicQPAdaptationLayer* getAQLayer( UInt uiDepth )  { return &m_acAQLayer[uiDepth]; }
+  UInt                      getMaxAQDepth()             { return m_uiMaxAQDepth;        }
+};
+
+//! \}
+
+#endif // __TENCPIC__
Index: /tags/SHM-9.0/source/Lib/TLibEncoder/TEncPreanalyzer.cpp
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibEncoder/TEncPreanalyzer.cpp	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibEncoder/TEncPreanalyzer.cpp	(revision 1088)
@@ -0,0 +1,141 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TEncPreanalyzer.cpp
+    \brief    source picture analyzer class
+*/
+
+#include <cfloat>
+#include <algorithm>
+
+#include "TEncPreanalyzer.h"
+
+using namespace std;
+
+//! \ingroup TLibEncoder
+//! \{
+
+/** Constructor
+ */
+TEncPreanalyzer::TEncPreanalyzer()
+{
+}
+
+/** Destructor
+ */
+TEncPreanalyzer::~TEncPreanalyzer()
+{
+}
+
+/** Analyze source picture and compute local image characteristics used for QP adaptation
+ * \param pcEPic Picture object to be analyzed
+ * \return Void
+ */
+Void TEncPreanalyzer::xPreanalyze( TEncPic* pcEPic )
+{
+  TComPicYuv* pcPicYuv = pcEPic->getPicYuvOrg();
+  const Int iWidth = pcPicYuv->getWidth(COMPONENT_Y);
+  const Int iHeight = pcPicYuv->getHeight(COMPONENT_Y);
+  const Int iStride = pcPicYuv->getStride(COMPONENT_Y);
+
+  for ( UInt d = 0; d < pcEPic->getMaxAQDepth(); d++ )
+  {
+    const Pel* pLineY = pcPicYuv->getAddr(COMPONENT_Y);
+    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: /tags/SHM-9.0/source/Lib/TLibEncoder/TEncPreanalyzer.h
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibEncoder/TEncPreanalyzer.h	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibEncoder/TEncPreanalyzer.h	(revision 1088)
@@ -0,0 +1,62 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TEncPreanalyzer.h
+    \brief    source picture analyzer class (header)
+*/
+
+#ifndef __TENCPREANALYZER__
+#define __TENCPREANALYZER__
+
+#include "TEncPic.h"
+
+//! \ingroup TLibEncoder
+//! \{
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// Source picture analyzer class
+class TEncPreanalyzer
+{
+public:
+  TEncPreanalyzer();
+  virtual ~TEncPreanalyzer();
+
+  Void xPreanalyze( TEncPic* pcPic );
+};
+
+//! \}
+
+#endif // __TENCPREANALYZER__
Index: /tags/SHM-9.0/source/Lib/TLibEncoder/TEncRateCtrl.cpp
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibEncoder/TEncRateCtrl.cpp	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibEncoder/TEncRateCtrl.cpp	(revision 1088)
@@ -0,0 +1,1403 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TEncRateCtrl.cpp
+    \brief    Rate control manager class
+*/
+#include "TEncRateCtrl.h"
+#include "../TLibCommon/TComPic.h"
+#include "../TLibCommon/TComChromaFormat.h"
+
+#include <cmath>
+
+using namespace std;
+
+//sequence level
+TEncRCSeq::TEncRCSeq()
+{
+  m_totalFrames         = 0;
+  m_targetRate          = 0;
+  m_frameRate           = 0;
+  m_targetBits          = 0;
+  m_GOPSize             = 0;
+  m_picWidth            = 0;
+  m_picHeight           = 0;
+  m_LCUWidth            = 0;
+  m_LCUHeight           = 0;
+  m_numberOfLevel       = 0;
+  m_numberOfLCU         = 0;
+  m_averageBits         = 0;
+  m_bitsRatio           = NULL;
+  m_GOPID2Level         = NULL;
+  m_picPara             = NULL;
+  m_LCUPara             = NULL;
+  m_numberOfPixel       = 0;
+  m_framesLeft          = 0;
+  m_bitsLeft            = 0;
+  m_useLCUSeparateModel = false;
+  m_adaptiveBit         = 0;
+  m_lastLambda          = 0.0;
+}
+
+TEncRCSeq::~TEncRCSeq()
+{
+  destroy();
+}
+
+Void TEncRCSeq::create( Int totalFrames, Int targetBitrate, Int frameRate, Int GOPSize, Int picWidth, Int picHeight, Int LCUWidth, Int LCUHeight, Int numberOfLevel, Bool useLCUSeparateModel, Int adaptiveBit )
+{
+  destroy();
+  m_totalFrames         = totalFrames;
+  m_targetRate          = targetBitrate;
+  m_frameRate           = frameRate;
+  m_GOPSize             = GOPSize;
+  m_picWidth            = picWidth;
+  m_picHeight           = picHeight;
+  m_LCUWidth            = LCUWidth;
+  m_LCUHeight           = LCUHeight;
+  m_numberOfLevel       = numberOfLevel;
+  m_useLCUSeparateModel = useLCUSeparateModel;
+
+  m_numberOfPixel   = m_picWidth * m_picHeight;
+  m_targetBits      = (Int64)m_totalFrames * (Int64)m_targetRate / (Int64)m_frameRate;
+  m_seqTargetBpp = (Double)m_targetRate / (Double)m_frameRate / (Double)m_numberOfPixel;
+  if ( m_seqTargetBpp < 0.03 )
+  {
+    m_alphaUpdate = 0.01;
+    m_betaUpdate  = 0.005;
+  }
+  else if ( m_seqTargetBpp < 0.08 )
+  {
+    m_alphaUpdate = 0.05;
+    m_betaUpdate  = 0.025;
+  }
+  else if ( m_seqTargetBpp < 0.2 )
+  {
+    m_alphaUpdate = 0.1;
+    m_betaUpdate  = 0.05;
+  }
+  else if ( m_seqTargetBpp < 0.5 )
+  {
+    m_alphaUpdate = 0.2;
+    m_betaUpdate  = 0.1;
+  }
+  else
+  {
+    m_alphaUpdate = 0.4;
+    m_betaUpdate  = 0.2;
+  }
+
+  m_averageBits     = (Int)(m_targetBits / totalFrames);
+  Int picWidthInBU  = ( m_picWidth  % m_LCUWidth  ) == 0 ? m_picWidth  / m_LCUWidth  : m_picWidth  / m_LCUWidth  + 1;
+  Int picHeightInBU = ( m_picHeight % m_LCUHeight ) == 0 ? m_picHeight / m_LCUHeight : m_picHeight / m_LCUHeight + 1;
+  m_numberOfLCU     = picWidthInBU * picHeightInBU;
+
+  m_bitsRatio   = new Int[m_GOPSize];
+  for ( Int i=0; i<m_GOPSize; i++ )
+  {
+    m_bitsRatio[i] = 1;
+  }
+
+  m_GOPID2Level = new Int[m_GOPSize];
+  for ( Int i=0; i<m_GOPSize; i++ )
+  {
+    m_GOPID2Level[i] = 1;
+  }
+
+  m_picPara = new TRCParameter[m_numberOfLevel];
+  for ( Int i=0; i<m_numberOfLevel; i++ )
+  {
+    m_picPara[i].m_alpha = 0.0;
+    m_picPara[i].m_beta  = 0.0;
+  }
+
+  if ( m_useLCUSeparateModel )
+  {
+    m_LCUPara = new TRCParameter*[m_numberOfLevel];
+    for ( Int i=0; i<m_numberOfLevel; i++ )
+    {
+      m_LCUPara[i] = new TRCParameter[m_numberOfLCU];
+      for ( Int j=0; j<m_numberOfLCU; j++)
+      {
+        m_LCUPara[i][j].m_alpha = 0.0;
+        m_LCUPara[i][j].m_beta  = 0.0;
+      }
+    }
+  }
+
+  m_framesLeft = m_totalFrames;
+  m_bitsLeft   = m_targetBits;
+  m_adaptiveBit = adaptiveBit;
+  m_lastLambda = 0.0;
+}
+
+Void TEncRCSeq::destroy()
+{
+  if (m_bitsRatio != NULL)
+  {
+    delete[] m_bitsRatio;
+    m_bitsRatio = NULL;
+  }
+
+  if ( m_GOPID2Level != NULL )
+  {
+    delete[] m_GOPID2Level;
+    m_GOPID2Level = NULL;
+  }
+
+  if ( m_picPara != NULL )
+  {
+    delete[] m_picPara;
+    m_picPara = NULL;
+  }
+
+  if ( m_LCUPara != NULL )
+  {
+    for ( Int i=0; i<m_numberOfLevel; i++ )
+    {
+      delete[] m_LCUPara[i];
+    }
+    delete[] m_LCUPara;
+    m_LCUPara = NULL;
+  }
+}
+
+Void TEncRCSeq::initBitsRatio( Int bitsRatio[])
+{
+  for (Int i=0; i<m_GOPSize; i++)
+  {
+    m_bitsRatio[i] = bitsRatio[i];
+  }
+}
+
+Void TEncRCSeq::initGOPID2Level( Int GOPID2Level[] )
+{
+  for ( Int i=0; i<m_GOPSize; i++ )
+  {
+    m_GOPID2Level[i] = GOPID2Level[i];
+  }
+}
+
+Void TEncRCSeq::initPicPara( TRCParameter* picPara )
+{
+  assert( m_picPara != NULL );
+
+  if ( picPara == NULL )
+  {
+    for ( Int i=0; i<m_numberOfLevel; i++ )
+    {
+      if (i>0)
+      {
+        m_picPara[i].m_alpha = 3.2003;
+        m_picPara[i].m_beta  = -1.367;
+      }
+      else
+      {
+        m_picPara[i].m_alpha = ALPHA;
+        m_picPara[i].m_beta  = BETA2;
+      }
+    }
+  }
+  else
+  {
+    for ( Int i=0; i<m_numberOfLevel; i++ )
+    {
+      m_picPara[i] = picPara[i];
+    }
+  }
+}
+
+Void TEncRCSeq::initLCUPara( TRCParameter** LCUPara )
+{
+  if ( m_LCUPara == NULL )
+  {
+    return;
+  }
+  if ( LCUPara == NULL )
+  {
+    for ( Int i=0; i<m_numberOfLevel; i++ )
+    {
+      for ( Int j=0; j<m_numberOfLCU; j++)
+      {
+        m_LCUPara[i][j].m_alpha = m_picPara[i].m_alpha;
+        m_LCUPara[i][j].m_beta  = m_picPara[i].m_beta;
+      }
+    }
+  }
+  else
+  {
+    for ( Int i=0; i<m_numberOfLevel; i++ )
+    {
+      for ( Int j=0; j<m_numberOfLCU; j++)
+      {
+        m_LCUPara[i][j] = LCUPara[i][j];
+      }
+    }
+  }
+}
+
+Void TEncRCSeq::updateAfterPic ( Int bits )
+{
+  m_bitsLeft -= bits;
+  m_framesLeft--;
+}
+
+Void TEncRCSeq::setAllBitRatio( Double basicLambda, Double* equaCoeffA, Double* equaCoeffB )
+{
+  Int* bitsRatio = new Int[m_GOPSize];
+  for ( Int i=0; i<m_GOPSize; i++ )
+  {
+    bitsRatio[i] = (Int)( equaCoeffA[i] * pow( basicLambda, equaCoeffB[i] ) * m_numberOfPixel );
+  }
+  initBitsRatio( bitsRatio );
+  delete[] bitsRatio;
+}
+
+//GOP level
+TEncRCGOP::TEncRCGOP()
+{
+  m_encRCSeq  = NULL;
+  m_picTargetBitInGOP = NULL;
+  m_numPic     = 0;
+  m_targetBits = 0;
+  m_picLeft    = 0;
+  m_bitsLeft   = 0;
+}
+
+TEncRCGOP::~TEncRCGOP()
+{
+  destroy();
+}
+
+Void TEncRCGOP::create( TEncRCSeq* encRCSeq, Int numPic )
+{
+  destroy();
+  Int targetBits = xEstGOPTargetBits( encRCSeq, numPic );
+
+  if ( encRCSeq->getAdaptiveBits() > 0 && encRCSeq->getLastLambda() > 0.1 )
+  {
+    Double targetBpp = (Double)targetBits / encRCSeq->getNumPixel();
+    Double basicLambda = 0.0;
+    Double* lambdaRatio = new Double[encRCSeq->getGOPSize()];
+    Double* equaCoeffA = new Double[encRCSeq->getGOPSize()];
+    Double* equaCoeffB = new Double[encRCSeq->getGOPSize()];
+
+    if ( encRCSeq->getAdaptiveBits() == 1 )   // for GOP size =4, low delay case
+    {
+      if ( encRCSeq->getLastLambda() < 120.0 )
+      {
+        lambdaRatio[1] = 0.725 * log( encRCSeq->getLastLambda() ) + 0.5793;
+        lambdaRatio[0] = 1.3 * lambdaRatio[1];
+        lambdaRatio[2] = 1.3 * lambdaRatio[1];
+        lambdaRatio[3] = 1.0;
+      }
+      else
+      {
+        lambdaRatio[0] = 5.0;
+        lambdaRatio[1] = 4.0;
+        lambdaRatio[2] = 5.0;
+        lambdaRatio[3] = 1.0;
+      }
+    }
+    else if ( encRCSeq->getAdaptiveBits() == 2 )  // for GOP size = 8, random access case
+    {
+      if ( encRCSeq->getLastLambda() < 90.0 )
+      {
+        lambdaRatio[0] = 1.0;
+        lambdaRatio[1] = 0.725 * log( encRCSeq->getLastLambda() ) + 0.7963;
+        lambdaRatio[2] = 1.3 * lambdaRatio[1];
+        lambdaRatio[3] = 3.25 * lambdaRatio[1];
+        lambdaRatio[4] = 3.25 * lambdaRatio[1];
+        lambdaRatio[5] = 1.3  * lambdaRatio[1];
+        lambdaRatio[6] = 3.25 * lambdaRatio[1];
+        lambdaRatio[7] = 3.25 * lambdaRatio[1];
+      }
+      else
+      {
+        lambdaRatio[0] = 1.0;
+        lambdaRatio[1] = 4.0;
+        lambdaRatio[2] = 5.0;
+        lambdaRatio[3] = 12.3;
+        lambdaRatio[4] = 12.3;
+        lambdaRatio[5] = 5.0;
+        lambdaRatio[6] = 12.3;
+        lambdaRatio[7] = 12.3;
+      }
+    }
+
+    xCalEquaCoeff( encRCSeq, lambdaRatio, equaCoeffA, equaCoeffB, encRCSeq->getGOPSize() );
+    basicLambda = xSolveEqua( targetBpp, equaCoeffA, equaCoeffB, encRCSeq->getGOPSize() );
+    encRCSeq->setAllBitRatio( basicLambda, equaCoeffA, equaCoeffB );
+
+    delete []lambdaRatio;
+    delete []equaCoeffA;
+    delete []equaCoeffB;
+  }
+
+  m_picTargetBitInGOP = new Int[numPic];
+  Int i;
+  Int totalPicRatio = 0;
+  Int currPicRatio = 0;
+  for ( i=0; i<numPic; i++ )
+  {
+    totalPicRatio += encRCSeq->getBitRatio( i );
+  }
+  for ( i=0; i<numPic; i++ )
+  {
+    currPicRatio = encRCSeq->getBitRatio( i );
+    m_picTargetBitInGOP[i] = (Int)( ((Double)targetBits) * currPicRatio / totalPicRatio );
+  }
+
+  m_encRCSeq    = encRCSeq;
+  m_numPic       = numPic;
+  m_targetBits   = targetBits;
+  m_picLeft      = m_numPic;
+  m_bitsLeft     = m_targetBits;
+}
+
+Void TEncRCGOP::xCalEquaCoeff( TEncRCSeq* encRCSeq, Double* lambdaRatio, Double* equaCoeffA, Double* equaCoeffB, Int GOPSize )
+{
+  for ( Int i=0; i<GOPSize; i++ )
+  {
+    Int frameLevel = encRCSeq->getGOPID2Level(i);
+    Double alpha   = encRCSeq->getPicPara(frameLevel).m_alpha;
+    Double beta    = encRCSeq->getPicPara(frameLevel).m_beta;
+    equaCoeffA[i] = pow( 1.0/alpha, 1.0/beta ) * pow( lambdaRatio[i], 1.0/beta );
+    equaCoeffB[i] = 1.0/beta;
+  }
+}
+
+Double TEncRCGOP::xSolveEqua( Double targetBpp, Double* equaCoeffA, Double* equaCoeffB, Int GOPSize )
+{
+  Double solution = 100.0;
+  Double minNumber = 0.1;
+  Double maxNumber = 10000.0;
+  for ( Int i=0; i<g_RCIterationNum; i++ )
+  {
+    Double fx = 0.0;
+    for ( Int j=0; j<GOPSize; j++ )
+    {
+      fx += equaCoeffA[j] * pow( solution, equaCoeffB[j] );
+    }
+
+    if ( fabs( fx - targetBpp ) < 0.000001 )
+    {
+      break;
+    }
+
+    if ( fx > targetBpp )
+    {
+      minNumber = solution;
+      solution = ( solution + maxNumber ) / 2.0;
+    }
+    else
+    {
+      maxNumber = solution;
+      solution = ( solution + minNumber ) / 2.0;
+    }
+  }
+
+  solution = Clip3( 0.1, 10000.0, solution );
+  return solution;
+}
+
+Void TEncRCGOP::destroy()
+{
+  m_encRCSeq = NULL;
+  if ( m_picTargetBitInGOP != NULL )
+  {
+    delete[] m_picTargetBitInGOP;
+    m_picTargetBitInGOP = NULL;
+  }
+}
+
+Void TEncRCGOP::updateAfterPicture( Int bitsCost )
+{
+  m_bitsLeft -= bitsCost;
+  m_picLeft--;
+}
+
+Int TEncRCGOP::xEstGOPTargetBits( TEncRCSeq* encRCSeq, Int GOPSize )
+{
+  Int realInfluencePicture = min( g_RCSmoothWindowSize, encRCSeq->getFramesLeft() );
+  Int averageTargetBitsPerPic = (Int)( encRCSeq->getTargetBits() / encRCSeq->getTotalFrames() );
+  Int currentTargetBitsPerPic = (Int)( ( encRCSeq->getBitsLeft() - averageTargetBitsPerPic * (encRCSeq->getFramesLeft() - realInfluencePicture) ) / realInfluencePicture );
+  Int targetBits = currentTargetBitsPerPic * GOPSize;
+
+  if ( targetBits < 200 )
+  {
+    targetBits = 200;   // at least allocate 200 bits for one GOP
+  }
+
+  return targetBits;
+}
+
+//picture level
+TEncRCPic::TEncRCPic()
+{
+  m_encRCSeq = NULL;
+  m_encRCGOP = NULL;
+
+  m_frameLevel    = 0;
+  m_numberOfPixel = 0;
+  m_numberOfLCU   = 0;
+  m_targetBits    = 0;
+  m_estHeaderBits = 0;
+  m_estPicQP      = 0;
+  m_estPicLambda  = 0.0;
+
+  m_LCULeft       = 0;
+  m_bitsLeft      = 0;
+  m_pixelsLeft    = 0;
+
+  m_LCUs         = NULL;
+  m_picActualHeaderBits = 0;
+  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 );
+  }
+
+  targetBits  = Int( ((Double)GOPbitsLeft) * currPicRatio / totalPicRatio );
+
+  if ( targetBits < 100 )
+  {
+    targetBits = 100;   // at least allocate 100 bits for one picture
+  }
+
+  if ( m_encRCSeq->getFramesLeft() > 16 )
+  {
+    targetBits = Int( g_RCWeightPicRargetBitInBuffer * targetBits + g_RCWeightPicTargetBitInGOP * m_encRCGOP->getTargetBitInGOP( currPicPosition ) );
+  }
+
+  return targetBits;
+}
+
+Int TEncRCPic::xEstPicHeaderBits( list<TEncRCPic*>& listPreviousPictures, Int frameLevel )
+{
+  Int numPreviousPics   = 0;
+  Int totalPreviousBits = 0;
+
+  list<TEncRCPic*>::iterator it;
+  for ( it = listPreviousPictures.begin(); it != listPreviousPictures.end(); it++ )
+  {
+    if ( (*it)->getFrameLevel() == frameLevel )
+    {
+      totalPreviousBits += (*it)->getPicActualHeaderBits();
+      numPreviousPics++;
+    }
+  }
+
+  Int estHeaderBits = 0;
+  if ( numPreviousPics > 0 )
+  {
+    estHeaderBits = totalPreviousBits / numPreviousPics;
+  }
+
+  return estHeaderBits;
+}
+
+Void TEncRCPic::addToPictureLsit( list<TEncRCPic*>& listPreviousPictures )
+{
+  if ( listPreviousPictures.size() > g_RCMaxPicListSize )
+  {
+    TEncRCPic* p = listPreviousPictures.front();
+    listPreviousPictures.pop_front();
+    p->destroy();
+    delete p;
+  }
+
+  listPreviousPictures.push_back( this );
+}
+
+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;
+      m_LCUs[LCUIdx].m_bitWeight  = 1.0;
+      Int currWidth  = ( (i == picWidthInLCU -1) ? picWidth  - LCUWidth *(picWidthInLCU -1) : LCUWidth  );
+      Int currHeight = ( (j == picHeightInLCU-1) ? picHeight - LCUHeight*(picHeightInLCU-1) : LCUHeight );
+      m_LCUs[LCUIdx].m_numberOfPixel = currWidth * currHeight;
+    }
+  }
+  m_picActualHeaderBits = 0;
+  m_picActualBits       = 0;
+  m_picQP               = 0;
+  m_picLambda           = 0.0;
+}
+
+Void TEncRCPic::destroy()
+{
+  if( m_LCUs != NULL )
+  {
+    delete[] m_LCUs;
+    m_LCUs = NULL;
+  }
+  m_encRCSeq = NULL;
+  m_encRCGOP = NULL;
+}
+
+
+Double TEncRCPic::estimatePicLambda( list<TEncRCPic*>& listPreviousPictures, SliceType eSliceType)
+{
+  Double alpha         = m_encRCSeq->getPicPara( m_frameLevel ).m_alpha;
+  Double beta          = m_encRCSeq->getPicPara( m_frameLevel ).m_beta;
+  Double bpp       = (Double)m_targetBits/(Double)m_numberOfPixel;
+  Double estLambda;
+  if (eSliceType == I_SLICE)
+  {
+    estLambda = calculateLambdaIntra(alpha, beta, pow(m_totalCostIntra/(Double)m_numberOfPixel, BETA1), bpp);
+  }
+  else
+  {
+    estLambda = alpha * pow( bpp, beta );
+  }
+
+  Double lastLevelLambda = -1.0;
+  Double lastPicLambda   = -1.0;
+  Double lastValidLambda = -1.0;
+  list<TEncRCPic*>::iterator it;
+  for ( it = listPreviousPictures.begin(); it != listPreviousPictures.end(); it++ )
+  {
+    if ( (*it)->getFrameLevel() == m_frameLevel )
+    {
+      lastLevelLambda = (*it)->getPicActualLambda();
+    }
+    lastPicLambda     = (*it)->getPicActualLambda();
+
+    if ( lastPicLambda > 0.0 )
+    {
+      lastValidLambda = lastPicLambda;
+    }
+  }
+
+  if ( lastLevelLambda > 0.0 )
+  {
+    lastLevelLambda = Clip3( 0.1, 10000.0, lastLevelLambda );
+    estLambda = Clip3( lastLevelLambda * pow( 2.0, -3.0/3.0 ), lastLevelLambda * pow( 2.0, 3.0/3.0 ), estLambda );
+  }
+
+  if ( lastPicLambda > 0.0 )
+  {
+    lastPicLambda = Clip3( 0.1, 2000.0, lastPicLambda );
+    estLambda = Clip3( lastPicLambda * pow( 2.0, -10.0/3.0 ), lastPicLambda * pow( 2.0, 10.0/3.0 ), estLambda );
+  }
+  else if ( lastValidLambda > 0.0 )
+  {
+    lastValidLambda = Clip3( 0.1, 2000.0, lastValidLambda );
+    estLambda = Clip3( lastValidLambda * pow(2.0, -10.0/3.0), lastValidLambda * pow(2.0, 10.0/3.0), estLambda );
+  }
+  else
+  {
+    estLambda = Clip3( 0.1, 10000.0, estLambda );
+  }
+
+  if ( estLambda < 0.1 )
+  {
+    estLambda = 0.1;
+  }
+
+  m_estPicLambda = estLambda;
+
+  Double totalWeight = 0.0;
+  // initial BU bit allocation weight
+  for ( Int i=0; i<m_numberOfLCU; i++ )
+  {
+    Double alphaLCU, betaLCU;
+    if ( m_encRCSeq->getUseLCUSeparateModel() )
+    {
+      alphaLCU = m_encRCSeq->getLCUPara( m_frameLevel, i ).m_alpha;
+      betaLCU  = m_encRCSeq->getLCUPara( m_frameLevel, i ).m_beta;
+    }
+    else
+    {
+      alphaLCU = m_encRCSeq->getPicPara( m_frameLevel ).m_alpha;
+      betaLCU  = m_encRCSeq->getPicPara( m_frameLevel ).m_beta;
+    }
+
+    m_LCUs[i].m_bitWeight =  m_LCUs[i].m_numberOfPixel * pow( estLambda/alphaLCU, 1.0/betaLCU );
+
+    if ( m_LCUs[i].m_bitWeight < 0.01 )
+    {
+      m_LCUs[i].m_bitWeight = 0.01;
+    }
+    totalWeight += m_LCUs[i].m_bitWeight;
+  }
+  for ( Int i=0; i<m_numberOfLCU; i++ )
+  {
+    Double BUTargetBits = m_targetBits * m_LCUs[i].m_bitWeight / totalWeight;
+    m_LCUs[i].m_bitWeight = BUTargetBits;
+  }
+
+  return estLambda;
+}
+
+Int TEncRCPic::estimatePicQP( Double lambda, list<TEncRCPic*>& listPreviousPictures )
+{
+  Int QP = Int( 4.2005 * log( lambda ) + 13.7122 + 0.5 );
+
+  Int lastLevelQP = g_RCInvalidQPValue;
+  Int lastPicQP   = g_RCInvalidQPValue;
+  Int lastValidQP = g_RCInvalidQPValue;
+  list<TEncRCPic*>::iterator it;
+  for ( it = listPreviousPictures.begin(); it != listPreviousPictures.end(); it++ )
+  {
+    if ( (*it)->getFrameLevel() == m_frameLevel )
+    {
+      lastLevelQP = (*it)->getPicActualQP();
+    }
+    lastPicQP = (*it)->getPicActualQP();
+    if ( lastPicQP > g_RCInvalidQPValue )
+    {
+      lastValidQP = lastPicQP;
+    }
+  }
+
+  if ( lastLevelQP > g_RCInvalidQPValue )
+  {
+    QP = Clip3( lastLevelQP - 3, lastLevelQP + 3, QP );
+  }
+
+  if( lastPicQP > g_RCInvalidQPValue )
+  {
+    QP = Clip3( lastPicQP - 10, lastPicQP + 10, QP );
+  }
+  else if( lastValidQP > g_RCInvalidQPValue )
+  {
+    QP = Clip3( lastValidQP - 10, lastValidQP + 10, QP );
+  }
+
+  return QP;
+}
+
+Double TEncRCPic::getLCUTargetBpp(SliceType eSliceType)
+{
+  Int   LCUIdx    = getLCUCoded();
+  Double bpp      = -1.0;
+  Int avgBits     = 0;
+
+  if (eSliceType == I_SLICE)
+  {
+    Int noOfLCUsLeft = m_numberOfLCU - LCUIdx + 1;
+    Int bitrateWindow = min(4,noOfLCUsLeft);
+    Double MAD      = getLCU(LCUIdx).m_costIntra;
+
+    if (m_remainingCostIntra > 0.1 )
+    {
+      Double weightedBitsLeft = (m_bitsLeft*bitrateWindow+(m_bitsLeft-getLCU(LCUIdx).m_targetBitsLeft)*noOfLCUsLeft)/(Double)bitrateWindow;
+      avgBits = Int( MAD*weightedBitsLeft/m_remainingCostIntra );
+    }
+    else
+    {
+      avgBits = Int( m_bitsLeft / m_LCULeft );
+    }
+    m_remainingCostIntra -= MAD;
+  }
+  else
+  {
+    Double totalWeight = 0;
+    for ( Int i=LCUIdx; i<m_numberOfLCU; i++ )
+    {
+      totalWeight += m_LCUs[i].m_bitWeight;
+    }
+    Int realInfluenceLCU = min( g_RCLCUSmoothWindowSize, getLCULeft() );
+    avgBits = (Int)( m_LCUs[LCUIdx].m_bitWeight - ( totalWeight - m_bitsLeft ) / realInfluenceLCU + 0.5 );
+  }
+
+  if ( avgBits < 1 )
+  {
+    avgBits = 1;
+  }
+
+  bpp = ( Double )avgBits/( Double )m_LCUs[ LCUIdx ].m_numberOfPixel;
+  m_LCUs[ LCUIdx ].m_targetBits = avgBits;
+
+  return bpp;
+}
+
+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::updateAfterCTU( Int LCUIdx, Int bits, Int QP, Double lambda, Bool updateLCUParameter )
+{
+  m_LCUs[LCUIdx].m_actualBits = bits;
+  m_LCUs[LCUIdx].m_QP         = QP;
+  m_LCUs[LCUIdx].m_lambda     = lambda;
+
+  m_LCULeft--;
+  m_bitsLeft   -= bits;
+  m_pixelsLeft -= m_LCUs[LCUIdx].m_numberOfPixel;
+
+  if ( !updateLCUParameter )
+  {
+    return;
+  }
+
+  if ( !m_encRCSeq->getUseLCUSeparateModel() )
+  {
+    return;
+  }
+
+  Double alpha = m_encRCSeq->getLCUPara( m_frameLevel, LCUIdx ).m_alpha;
+  Double beta  = m_encRCSeq->getLCUPara( m_frameLevel, LCUIdx ).m_beta;
+
+  Int LCUActualBits   = m_LCUs[LCUIdx].m_actualBits;
+  Int LCUTotalPixels  = m_LCUs[LCUIdx].m_numberOfPixel;
+  Double bpp         = ( Double )LCUActualBits/( Double )LCUTotalPixels;
+  Double calLambda   = alpha * pow( bpp, beta );
+  Double inputLambda = m_LCUs[LCUIdx].m_lambda;
+
+  if( inputLambda < 0.01 || calLambda < 0.01 || bpp < 0.0001 )
+  {
+    alpha *= ( 1.0 - m_encRCSeq->getAlphaUpdate() / 2.0 );
+    beta  *= ( 1.0 - m_encRCSeq->getBetaUpdate() / 2.0 );
+
+    alpha = Clip3( g_RCAlphaMinValue, g_RCAlphaMaxValue, alpha );
+    beta  = Clip3( g_RCBetaMinValue,  g_RCBetaMaxValue,  beta  );
+
+    TRCParameter rcPara;
+    rcPara.m_alpha = alpha;
+    rcPara.m_beta  = beta;
+    m_encRCSeq->setLCUPara( m_frameLevel, LCUIdx, rcPara );
+
+    return;
+  }
+
+  calLambda = Clip3( inputLambda / 10.0, inputLambda * 10.0, calLambda );
+  alpha += m_encRCSeq->getAlphaUpdate() * ( log( inputLambda ) - log( calLambda ) ) * alpha;
+  Double lnbpp = log( bpp );
+  lnbpp = Clip3( -5.0, -0.1, lnbpp );
+  beta  += m_encRCSeq->getBetaUpdate() * ( log( inputLambda ) - log( calLambda ) ) * lnbpp;
+
+  alpha = Clip3( g_RCAlphaMinValue, g_RCAlphaMaxValue, alpha );
+  beta  = Clip3( g_RCBetaMinValue,  g_RCBetaMaxValue,  beta  );
+
+  TRCParameter rcPara;
+  rcPara.m_alpha = alpha;
+  rcPara.m_beta  = beta;
+  m_encRCSeq->setLCUPara( m_frameLevel, LCUIdx, rcPara );
+
+}
+
+Double TEncRCPic::calAverageQP()
+{
+  Int totalQPs = 0;
+  Int numTotalLCUs = 0;
+
+  Int i;
+  for ( i=0; i<m_numberOfLCU; i++ )
+  {
+    if ( m_LCUs[i].m_QP > 0 )
+    {
+      totalQPs += m_LCUs[i].m_QP;
+      numTotalLCUs++;
+    }
+  }
+
+  Double avgQP = 0.0;
+  if ( numTotalLCUs == 0 )
+  {
+    avgQP = g_RCInvalidQPValue;
+  }
+  else
+  {
+    avgQP = ((Double)totalQPs) / ((Double)numTotalLCUs);
+  }
+  return avgQP;
+}
+
+Double TEncRCPic::calAverageLambda()
+{
+  Double totalLambdas = 0.0;
+  Int numTotalLCUs = 0;
+
+  Int i;
+  for ( i=0; i<m_numberOfLCU; i++ )
+  {
+    if ( m_LCUs[i].m_lambda > 0.01 )
+    {
+      totalLambdas += log( m_LCUs[i].m_lambda );
+      numTotalLCUs++;
+    }
+  }
+
+  Double avgLambda;
+  if( numTotalLCUs == 0 )
+  {
+    avgLambda = -1.0;
+  }
+  else
+  {
+    avgLambda = pow( 2.7183, totalLambdas / numTotalLCUs );
+  }
+  return avgLambda;
+}
+
+
+Void TEncRCPic::updateAfterPicture( Int actualHeaderBits, Int actualTotalBits, Double averageQP, Double averageLambda, SliceType eSliceType)
+{
+  m_picActualHeaderBits = actualHeaderBits;
+  m_picActualBits       = actualTotalBits;
+  if ( averageQP > 0.0 )
+  {
+    m_picQP             = Int( averageQP + 0.5 );
+  }
+  else
+  {
+    m_picQP             = g_RCInvalidQPValue;
+  }
+  m_picLambda           = averageLambda;
+
+  Double alpha = m_encRCSeq->getPicPara( m_frameLevel ).m_alpha;
+  Double beta  = m_encRCSeq->getPicPara( m_frameLevel ).m_beta;
+
+  if (eSliceType == I_SLICE)
+  {
+    updateAlphaBetaIntra(&alpha, &beta);
+  }
+  else
+  {
+    // update parameters
+    Double picActualBits = ( Double )m_picActualBits;
+    Double picActualBpp  = picActualBits/(Double)m_numberOfPixel;
+    Double calLambda     = alpha * pow( picActualBpp, beta );
+    Double inputLambda   = m_picLambda;
+
+    if ( inputLambda < 0.01 || calLambda < 0.01 || picActualBpp < 0.0001 )
+    {
+      alpha *= ( 1.0 - m_encRCSeq->getAlphaUpdate() / 2.0 );
+      beta  *= ( 1.0 - m_encRCSeq->getBetaUpdate() / 2.0 );
+
+      alpha = Clip3( g_RCAlphaMinValue, g_RCAlphaMaxValue, alpha );
+      beta  = Clip3( g_RCBetaMinValue,  g_RCBetaMaxValue,  beta  );
+
+      TRCParameter rcPara;
+      rcPara.m_alpha = alpha;
+      rcPara.m_beta  = beta;
+      m_encRCSeq->setPicPara( m_frameLevel, rcPara );
+
+      return;
+    }
+
+    calLambda = Clip3( inputLambda / 10.0, inputLambda * 10.0, calLambda );
+    alpha += m_encRCSeq->getAlphaUpdate() * ( log( inputLambda ) - log( calLambda ) ) * alpha;
+    Double lnbpp = log( picActualBpp );
+    lnbpp = Clip3( -5.0, -0.1, lnbpp );
+
+    beta  += m_encRCSeq->getBetaUpdate() * ( log( inputLambda ) - log( calLambda ) ) * lnbpp;
+
+    alpha = Clip3( g_RCAlphaMinValue, g_RCAlphaMaxValue, alpha );
+    beta  = Clip3( g_RCBetaMinValue,  g_RCBetaMaxValue,  beta  );
+  }
+
+  TRCParameter rcPara;
+  rcPara.m_alpha = alpha;
+  rcPara.m_beta  = beta;
+
+  m_encRCSeq->setPicPara( m_frameLevel, rcPara );
+
+  if ( m_frameLevel == 1 )
+  {
+    Double currLambda = Clip3( 0.1, 10000.0, m_picLambda );
+    Double updateLastLambda = g_RCWeightHistoryLambda * m_encRCSeq->getLastLambda() + g_RCWeightCurrentLambda * currLambda;
+    m_encRCSeq->setLastLambda( updateLastLambda );
+  }
+}
+
+Int TEncRCPic::getRefineBitsForIntra( Int orgBits )
+{
+  Double alpha=0.25, beta=0.5582;
+  Int iIntraBits;
+
+  if (orgBits*40 < m_numberOfPixel)
+  {
+    alpha=0.25;
+  }
+  else
+  {
+    alpha=0.30;
+  }
+
+  iIntraBits = (Int)(alpha* pow(m_totalCostIntra*4.0/(Double)orgBits, beta)*(Double)orgBits+0.5);
+
+  return iIntraBits;
+}
+
+Double TEncRCPic::calculateLambdaIntra(Double alpha, Double beta, Double MADPerPixel, Double bitsPerPixel)
+{
+  return ( (alpha/256.0) * pow( MADPerPixel/bitsPerPixel, beta ) );
+}
+
+Void TEncRCPic::updateAlphaBetaIntra(Double *alpha, Double *beta)
+{
+  Double lnbpp = log(pow(m_totalCostIntra / (Double)m_numberOfPixel, BETA1));
+  Double diffLambda = (*beta)*(log((Double)m_picActualBits)-log((Double)m_targetBits));
+
+  diffLambda = Clip3(-0.125, 0.125, 0.25*diffLambda);
+  *alpha    =  (*alpha) * exp(diffLambda);
+  *beta     =  (*beta) + diffLambda / lnbpp;
+}
+
+
+Void TEncRCPic::getLCUInitTargetBits()
+{
+  Int iAvgBits     = 0;
+
+  m_remainingCostIntra = m_totalCostIntra;
+  for (Int i=m_numberOfLCU-1; i>=0; i--)
+  {
+    iAvgBits += Int(m_targetBits * getLCU(i).m_costIntra/m_totalCostIntra);
+    getLCU(i).m_targetBitsLeft = iAvgBits;
+  }
+}
+
+
+Double TEncRCPic::getLCUEstLambdaAndQP(Double bpp, Int clipPicQP, Int *estQP)
+{
+  Int   LCUIdx = getLCUCoded();
+
+  Double   alpha = m_encRCSeq->getPicPara( m_frameLevel ).m_alpha;
+  Double   beta  = m_encRCSeq->getPicPara( m_frameLevel ).m_beta;
+
+  Double costPerPixel = getLCU(LCUIdx).m_costIntra/(Double)getLCU(LCUIdx).m_numberOfPixel;
+  costPerPixel = pow(costPerPixel, BETA1);
+  Double estLambda = calculateLambdaIntra(alpha, beta, costPerPixel, bpp);
+
+  Int clipNeighbourQP = g_RCInvalidQPValue;
+  for (Int i=LCUIdx-1; i>=0; i--)
+  {
+    if ((getLCU(i)).m_QP > g_RCInvalidQPValue)
+    {
+      clipNeighbourQP = getLCU(i).m_QP;
+      break;
+    }
+  }
+
+  Int minQP = clipPicQP - 2;
+  Int maxQP = clipPicQP + 2;
+
+  if ( clipNeighbourQP > g_RCInvalidQPValue )
+  {
+    maxQP = min(clipNeighbourQP + 1, maxQP);
+    minQP = max(clipNeighbourQP - 1, minQP);
+  }
+
+  Double maxLambda=exp(((Double)(maxQP+0.49)-13.7122)/4.2005);
+  Double minLambda=exp(((Double)(minQP-0.49)-13.7122)/4.2005);
+
+  estLambda = Clip3(minLambda, maxLambda, estLambda);
+
+  *estQP = Int( 4.2005 * log(estLambda) + 13.7122 + 0.5 );
+  *estQP = Clip3(minQP, maxQP, *estQP);
+
+  return estLambda;
+}
+
+TEncRateCtrl::TEncRateCtrl()
+{
+  m_encRCSeq = NULL;
+  m_encRCGOP = NULL;
+  m_encRCPic = NULL;
+}
+
+TEncRateCtrl::~TEncRateCtrl()
+{
+  destroy();
+}
+
+Void TEncRateCtrl::destroy()
+{
+  if ( m_encRCSeq != NULL )
+  {
+    delete m_encRCSeq;
+    m_encRCSeq = NULL;
+  }
+  if ( m_encRCGOP != NULL )
+  {
+    delete m_encRCGOP;
+    m_encRCGOP = NULL;
+  }
+  while ( m_listRCPictures.size() > 0 )
+  {
+    TEncRCPic* p = m_listRCPictures.front();
+    m_listRCPictures.pop_front();
+    delete p;
+  }
+}
+
+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] )
+{
+  destroy();
+
+  Bool isLowdelay = true;
+  for ( Int i=0; i<GOPSize-1; i++ )
+  {
+    if ( GOPList[i].m_POC > GOPList[i+1].m_POC )
+    {
+      isLowdelay = false;
+      break;
+    }
+  }
+
+  Int numberOfLevel = 1;
+  Int adaptiveBit = 0;
+  if ( keepHierBits > 0 )
+  {
+    numberOfLevel = Int( log((Double)GOPSize)/log(2.0) + 0.5 ) + 1;
+  }
+  if ( !isLowdelay && GOPSize == 8 )
+  {
+    numberOfLevel = Int( log((Double)GOPSize)/log(2.0) + 0.5 ) + 1;
+  }
+  numberOfLevel++;    // intra picture
+  numberOfLevel++;    // non-reference picture
+
+
+  Int* bitsRatio;
+  bitsRatio = new Int[ GOPSize ];
+  for ( Int i=0; i<GOPSize; i++ )
+  {
+    bitsRatio[i] = 10;
+    if ( !GOPList[i].m_refPic )
+    {
+      bitsRatio[i] = 2;
+    }
+  }
+
+  if ( keepHierBits > 0 )
+  {
+    Double bpp = (Double)( targetBitrate / (Double)( frameRate*picWidth*picHeight ) );
+    if ( GOPSize == 4 && isLowdelay )
+    {
+      if ( bpp > 0.2 )
+      {
+        bitsRatio[0] = 2;
+        bitsRatio[1] = 3;
+        bitsRatio[2] = 2;
+        bitsRatio[3] = 6;
+      }
+      else if( bpp > 0.1 )
+      {
+        bitsRatio[0] = 2;
+        bitsRatio[1] = 3;
+        bitsRatio[2] = 2;
+        bitsRatio[3] = 10;
+      }
+      else if ( bpp > 0.05 )
+      {
+        bitsRatio[0] = 2;
+        bitsRatio[1] = 3;
+        bitsRatio[2] = 2;
+        bitsRatio[3] = 12;
+      }
+      else
+      {
+        bitsRatio[0] = 2;
+        bitsRatio[1] = 3;
+        bitsRatio[2] = 2;
+        bitsRatio[3] = 14;
+      }
+
+      if ( keepHierBits == 2 )
+      {
+        adaptiveBit = 1;
+      }
+    }
+    else if ( GOPSize == 8 && !isLowdelay )
+    {
+      if ( bpp > 0.2 )
+      {
+        bitsRatio[0] = 15;
+        bitsRatio[1] = 5;
+        bitsRatio[2] = 4;
+        bitsRatio[3] = 1;
+        bitsRatio[4] = 1;
+        bitsRatio[5] = 4;
+        bitsRatio[6] = 1;
+        bitsRatio[7] = 1;
+      }
+      else if ( bpp > 0.1 )
+      {
+        bitsRatio[0] = 20;
+        bitsRatio[1] = 6;
+        bitsRatio[2] = 4;
+        bitsRatio[3] = 1;
+        bitsRatio[4] = 1;
+        bitsRatio[5] = 4;
+        bitsRatio[6] = 1;
+        bitsRatio[7] = 1;
+      }
+      else if ( bpp > 0.05 )
+      {
+        bitsRatio[0] = 25;
+        bitsRatio[1] = 7;
+        bitsRatio[2] = 4;
+        bitsRatio[3] = 1;
+        bitsRatio[4] = 1;
+        bitsRatio[5] = 4;
+        bitsRatio[6] = 1;
+        bitsRatio[7] = 1;
+      }
+      else
+      {
+        bitsRatio[0] = 30;
+        bitsRatio[1] = 8;
+        bitsRatio[2] = 4;
+        bitsRatio[3] = 1;
+        bitsRatio[4] = 1;
+        bitsRatio[5] = 4;
+        bitsRatio[6] = 1;
+        bitsRatio[7] = 1;
+      }
+
+      if ( keepHierBits == 2 )
+      {
+        adaptiveBit = 2;
+      }
+    }
+    else
+    {
+      printf( "\n hierarchical bit allocation is not support for the specified coding structure currently.\n" );
+    }
+  }
+
+  Int* GOPID2Level = new Int[ GOPSize ];
+  for ( Int i=0; i<GOPSize; i++ )
+  {
+    GOPID2Level[i] = 1;
+    if ( !GOPList[i].m_refPic )
+    {
+      GOPID2Level[i] = 2;
+    }
+  }
+
+  if ( keepHierBits > 0 )
+  {
+    if ( GOPSize == 4 && isLowdelay )
+    {
+      GOPID2Level[0] = 3;
+      GOPID2Level[1] = 2;
+      GOPID2Level[2] = 3;
+      GOPID2Level[3] = 1;
+    }
+    else if ( GOPSize == 8 && !isLowdelay )
+    {
+      GOPID2Level[0] = 1;
+      GOPID2Level[1] = 2;
+      GOPID2Level[2] = 3;
+      GOPID2Level[3] = 4;
+      GOPID2Level[4] = 4;
+      GOPID2Level[5] = 3;
+      GOPID2Level[6] = 4;
+      GOPID2Level[7] = 4;
+    }
+  }
+
+  if ( !isLowdelay && GOPSize == 8 )
+  {
+    GOPID2Level[0] = 1;
+    GOPID2Level[1] = 2;
+    GOPID2Level[2] = 3;
+    GOPID2Level[3] = 4;
+    GOPID2Level[4] = 4;
+    GOPID2Level[5] = 3;
+    GOPID2Level[6] = 4;
+    GOPID2Level[7] = 4;
+  }
+
+  m_encRCSeq = new TEncRCSeq;
+  m_encRCSeq->create( totalFrames, targetBitrate, frameRate, GOPSize, picWidth, picHeight, LCUWidth, LCUHeight, numberOfLevel, useLCUSeparateModel, adaptiveBit );
+  m_encRCSeq->initBitsRatio( bitsRatio );
+  m_encRCSeq->initGOPID2Level( GOPID2Level );
+  m_encRCSeq->initPicPara();
+  if ( useLCUSeparateModel )
+  {
+    m_encRCSeq->initLCUPara();
+  }
+
+  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;
+}
+
Index: /tags/SHM-9.0/source/Lib/TLibEncoder/TEncRateCtrl.h
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibEncoder/TEncRateCtrl.h	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibEncoder/TEncRateCtrl.h	(revision 1088)
@@ -0,0 +1,335 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TEncRateCtrl.h
+    \brief    Rate control manager class
+*/
+
+#ifndef __TENCRATECTRL__
+#define __TENCRATECTRL__
+
+#if _MSC_VER > 1000
+#pragma once
+#endif // _MSC_VER > 1000
+
+
+#include "../TLibCommon/CommonDef.h"
+#include "../TLibCommon/TComDataCU.h"
+
+#include <vector>
+#include <algorithm>
+
+using namespace std;
+
+//! \ingroup TLibEncoder
+//! \{
+
+#include "../TLibEncoder/TEncCfg.h"
+#include <list>
+#include <cassert>
+
+const Int g_RCInvalidQPValue = -999;
+const Int g_RCSmoothWindowSize = 40;
+const Int g_RCMaxPicListSize = 32;
+const Double g_RCWeightPicTargetBitInGOP    = 0.9;
+const Double g_RCWeightPicRargetBitInBuffer = 1.0 - g_RCWeightPicTargetBitInGOP;
+const Int g_RCIterationNum = 20;
+const Double g_RCWeightHistoryLambda = 0.5;
+const Double g_RCWeightCurrentLambda = 1.0 - g_RCWeightHistoryLambda;
+const Int g_RCLCUSmoothWindowSize = 4;
+const Double g_RCAlphaMinValue = 0.05;
+const Double g_RCAlphaMaxValue = 500.0;
+const Double g_RCBetaMinValue  = -3.0;
+const Double g_RCBetaMaxValue  = -0.1;
+
+#define ALPHA     6.7542;
+#define BETA1     1.2517
+#define BETA2     1.7860
+
+struct TRCLCU
+{
+  Int m_actualBits;
+  Int m_QP;     // QP of skip mode is set to g_RCInvalidQPValue
+  Int m_targetBits;
+  Double m_lambda;
+  Double m_bitWeight;
+  Int m_numberOfPixel;
+  Double m_costIntra;
+  Int m_targetBitsLeft;
+};
+
+struct TRCParameter
+{
+  Double m_alpha;
+  Double m_beta;
+};
+
+class TEncRCSeq
+{
+public:
+  TEncRCSeq();
+  ~TEncRCSeq();
+
+public:
+  Void create( Int totalFrames, Int targetBitrate, Int frameRate, Int GOPSize, Int picWidth, Int picHeight, Int LCUWidth, Int LCUHeight, Int numberOfLevel, Bool useLCUSeparateModel, Int adaptiveBit );
+  Void destroy();
+  Void initBitsRatio( Int bitsRatio[] );
+  Void initGOPID2Level( Int GOPID2Level[] );
+  Void initPicPara( TRCParameter* picPara  = NULL );    // NULL to initial with default value
+  Void initLCUPara( TRCParameter** LCUPara = NULL );    // NULL to initial with default value
+  Void updateAfterPic ( Int bits );
+  Void setAllBitRatio( Double basicLambda, Double* equaCoeffA, Double* equaCoeffB );
+
+public:
+  Int  getTotalFrames()                 { return m_totalFrames; }
+  Int  getTargetRate()                  { return m_targetRate; }
+  Int  getFrameRate()                   { return m_frameRate; }
+  Int  getGOPSize()                     { return m_GOPSize; }
+  Int  getPicWidth()                    { return m_picWidth; }
+  Int  getPicHeight()                   { return m_picHeight; }
+  Int  getLCUWidth()                    { return m_LCUWidth; }
+  Int  getLCUHeight()                   { return m_LCUHeight; }
+  Int  getNumberOfLevel()               { return m_numberOfLevel; }
+  Int  getAverageBits()                 { return m_averageBits; }
+  Int  getLeftAverageBits()             { assert( m_framesLeft > 0 ); return (Int)(m_bitsLeft / m_framesLeft); }
+  Bool getUseLCUSeparateModel()         { return m_useLCUSeparateModel; }
+
+  Int  getNumPixel()                    { return m_numberOfPixel; }
+  Int64  getTargetBits()                { return m_targetBits; }
+  Int  getNumberOfLCU()                 { return m_numberOfLCU; }
+  Int* getBitRatio()                    { return m_bitsRatio; }
+  Int  getBitRatio( Int idx )           { assert( idx<m_GOPSize); return m_bitsRatio[idx]; }
+  Int* getGOPID2Level()                 { return m_GOPID2Level; }
+  Int  getGOPID2Level( Int ID )         { assert( ID < m_GOPSize ); return m_GOPID2Level[ID]; }
+  TRCParameter*  getPicPara()                                   { return m_picPara; }
+  TRCParameter   getPicPara( Int level )                        { assert( level < m_numberOfLevel ); return m_picPara[level]; }
+  Void           setPicPara( Int level, TRCParameter para )     { assert( level < m_numberOfLevel ); m_picPara[level] = para; }
+  TRCParameter** getLCUPara()                                   { return m_LCUPara; }
+  TRCParameter*  getLCUPara( Int level )                        { assert( level < m_numberOfLevel ); return m_LCUPara[level]; }
+  TRCParameter   getLCUPara( Int level, Int LCUIdx )            { assert( LCUIdx  < m_numberOfLCU ); return getLCUPara(level)[LCUIdx]; }
+  Void           setLCUPara( Int level, Int LCUIdx, TRCParameter para ) { assert( level < m_numberOfLevel ); assert( LCUIdx  < m_numberOfLCU ); m_LCUPara[level][LCUIdx] = para; }
+
+  Int  getFramesLeft()                  { return m_framesLeft; }
+  Int64  getBitsLeft()                  { return m_bitsLeft; }
+
+  Double getSeqBpp()                    { return m_seqTargetBpp; }
+  Double getAlphaUpdate()               { return m_alphaUpdate; }
+  Double getBetaUpdate()                { return m_betaUpdate; }
+
+  Int    getAdaptiveBits()              { return m_adaptiveBit;  }
+  Double getLastLambda()                { return m_lastLambda;   }
+  Void   setLastLambda( Double lamdba ) { m_lastLambda = lamdba; }
+
+private:
+  Int m_totalFrames;
+  Int m_targetRate;
+  Int m_frameRate;
+  Int m_GOPSize;
+  Int m_picWidth;
+  Int m_picHeight;
+  Int m_LCUWidth;
+  Int m_LCUHeight;
+  Int m_numberOfLevel;
+  Int m_averageBits;
+
+  Int m_numberOfPixel;
+  Int64 m_targetBits;
+  Int m_numberOfLCU;
+  Int* m_bitsRatio;
+  Int* m_GOPID2Level;
+  TRCParameter*  m_picPara;
+  TRCParameter** m_LCUPara;
+
+  Int m_framesLeft;
+  Int64 m_bitsLeft;
+  Double m_seqTargetBpp;
+  Double m_alphaUpdate;
+  Double m_betaUpdate;
+  Bool m_useLCUSeparateModel;
+
+  Int m_adaptiveBit;
+  Double m_lastLambda;
+};
+
+class TEncRCGOP
+{
+public:
+  TEncRCGOP();
+  ~TEncRCGOP();
+
+public:
+  Void create( TEncRCSeq* encRCSeq, Int numPic );
+  Void destroy();
+  Void updateAfterPicture( Int bitsCost );
+
+private:
+  Int  xEstGOPTargetBits( TEncRCSeq* encRCSeq, Int GOPSize );
+  Void   xCalEquaCoeff( TEncRCSeq* encRCSeq, Double* lambdaRatio, Double* equaCoeffA, Double* equaCoeffB, Int GOPSize );
+  Double xSolveEqua( Double targetBpp, Double* equaCoeffA, Double* equaCoeffB, Int GOPSize );
+
+public:
+  TEncRCSeq* getEncRCSeq()        { return m_encRCSeq; }
+  Int  getNumPic()                { return m_numPic;}
+  Int  getTargetBits()            { return m_targetBits; }
+  Int  getPicLeft()               { return m_picLeft; }
+  Int  getBitsLeft()              { return m_bitsLeft; }
+  Int  getTargetBitInGOP( Int i ) { return m_picTargetBitInGOP[i]; }
+
+private:
+  TEncRCSeq* m_encRCSeq;
+  Int* m_picTargetBitInGOP;
+  Int m_numPic;
+  Int m_targetBits;
+  Int m_picLeft;
+  Int m_bitsLeft;
+};
+
+class TEncRCPic
+{
+public:
+  TEncRCPic();
+  ~TEncRCPic();
+
+public:
+  Void create( TEncRCSeq* encRCSeq, TEncRCGOP* encRCGOP, Int frameLevel, list<TEncRCPic*>& listPreviousPictures );
+  Void destroy();
+
+  Int    estimatePicQP    ( Double lambda, list<TEncRCPic*>& listPreviousPictures );
+  Int    getRefineBitsForIntra(Int orgBits);
+  Double calculateLambdaIntra(Double alpha, Double beta, Double MADPerPixel, Double bitsPerPixel);
+  Double estimatePicLambda( list<TEncRCPic*>& listPreviousPictures, SliceType eSliceType);
+
+  Void   updateAlphaBetaIntra(Double *alpha, Double *beta);
+
+  Double getLCUTargetBpp(SliceType eSliceType);
+  Double getLCUEstLambdaAndQP(Double bpp, Int clipPicQP, Int *estQP);
+  Double getLCUEstLambda( Double bpp );
+  Int    getLCUEstQP( Double lambda, Int clipPicQP );
+
+  Void updateAfterCTU( Int LCUIdx, Int bits, Int QP, Double lambda, Bool updateLCUParameter = true );
+  Void updateAfterPicture( Int actualHeaderBits, Int actualTotalBits, Double averageQP, Double averageLambda, SliceType eSliceType);
+
+  Void addToPictureLsit( list<TEncRCPic*>& listPreviousPictures );
+  Double calAverageQP();
+  Double calAverageLambda();
+
+private:
+  Int xEstPicTargetBits( TEncRCSeq* encRCSeq, TEncRCGOP* encRCGOP );
+  Int xEstPicHeaderBits( list<TEncRCPic*>& listPreviousPictures, Int frameLevel );
+
+public:
+  TEncRCSeq*      getRCSequence()                         { return m_encRCSeq; }
+  TEncRCGOP*      getRCGOP()                              { return m_encRCGOP; }
+
+  Int  getFrameLevel()                                    { return m_frameLevel; }
+  Int  getNumberOfPixel()                                 { return m_numberOfPixel; }
+  Int  getNumberOfLCU()                                   { return m_numberOfLCU; }
+  Int  getTargetBits()                                    { return m_targetBits; }
+  Int  getEstHeaderBits()                                 { return m_estHeaderBits; }
+  Int  getLCULeft()                                       { return m_LCULeft; }
+  Int  getBitsLeft()                                      { return m_bitsLeft; }
+  Int  getPixelsLeft()                                    { return m_pixelsLeft; }
+  Int  getBitsCoded()                                     { return m_targetBits - m_estHeaderBits - m_bitsLeft; }
+  Int  getLCUCoded()                                      { return m_numberOfLCU - m_LCULeft; }
+  TRCLCU* getLCU()                                        { return m_LCUs; }
+  TRCLCU& getLCU( Int LCUIdx )                            { return m_LCUs[LCUIdx]; }
+  Int  getPicActualHeaderBits()                           { return m_picActualHeaderBits; }
+  Void setTargetBits( Int bits )                          { m_targetBits = bits; m_bitsLeft = bits;}
+  Void setTotalIntraCost(Double cost)                     { m_totalCostIntra = cost; }
+  Void getLCUInitTargetBits();
+
+  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
+  Double m_totalCostIntra;
+  Double m_remainingCostIntra;
+  Int m_picActualBits;          // the whole picture, including header
+  Int m_picQP;                  // in integer form
+  Double m_picLambda;
+};
+
+class TEncRateCtrl
+{
+public:
+  TEncRateCtrl();
+  ~TEncRateCtrl();
+
+public:
+  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] );
+  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;
+};
+
+#endif
+
+
Index: /tags/SHM-9.0/source/Lib/TLibEncoder/TEncSampleAdaptiveOffset.cpp
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibEncoder/TEncSampleAdaptiveOffset.cpp	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibEncoder/TEncSampleAdaptiveOffset.cpp	(revision 1088)
@@ -0,0 +1,1395 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ \file     TEncSampleAdaptiveOffset.cpp
+ \brief       estimation part of sample adaptive offset class
+ */
+#include "TEncSampleAdaptiveOffset.h"
+#include <string.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <math.h>
+
+//! \ingroup TLibEncoder
+//! \{
+
+
+/** rounding with IBDI
+ * \param  x
+ */
+inline Double xRoundIbdi2(Int bitDepth, Double x)
+{
+  return ((x)>0) ? (Int)(((Int)(x)+(1<<(bitDepth-8-1)))/(1<<(bitDepth-8))) : ((Int)(((Int)(x)-(1<<(bitDepth-8-1)))/(1<<(bitDepth-8))));
+}
+
+inline Double xRoundIbdi(Int bitDepth, Double x)
+{
+  return (bitDepth > 8 ? xRoundIbdi2(bitDepth, (x)) : ((x)>=0 ? ((Int)((x)+0.5)) : ((Int)((x)-0.5)))) ;
+}
+
+
+TEncSampleAdaptiveOffset::TEncSampleAdaptiveOffset()
+{
+  m_pppcRDSbacCoder = NULL;
+  m_pcRDGoOnSbacCoder = NULL;
+  m_pppcBinCoderCABAC = NULL;
+  m_statData = NULL;
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+  m_preDBFstatData = NULL;
+#endif
+}
+
+TEncSampleAdaptiveOffset::~TEncSampleAdaptiveOffset()
+{
+  destroyEncData();
+}
+
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+Void TEncSampleAdaptiveOffset::createEncData(Bool isPreDBFSamplesUsed)
+#else
+Void TEncSampleAdaptiveOffset::createEncData()
+#endif
+{
+
+  //cabac coder for RDO
+  m_pppcRDSbacCoder = new TEncSbac* [NUM_SAO_CABACSTATE_LABELS];
+#if FAST_BIT_EST
+  m_pppcBinCoderCABAC = new TEncBinCABACCounter* [NUM_SAO_CABACSTATE_LABELS];
+#else
+  m_pppcBinCoderCABAC = new TEncBinCABAC* [NUM_SAO_CABACSTATE_LABELS];
+#endif
+
+  for(Int cs=0; cs < NUM_SAO_CABACSTATE_LABELS; cs++)
+  {
+    m_pppcRDSbacCoder[cs] = new TEncSbac;
+#if FAST_BIT_EST
+    m_pppcBinCoderCABAC[cs] = new TEncBinCABACCounter;
+#else
+    m_pppcBinCoderCABAC[cs] = new TEncBinCABAC;
+#endif
+    m_pppcRDSbacCoder   [cs]->init( m_pppcBinCoderCABAC [cs] );
+  }
+
+
+  //statistics
+  m_statData = new SAOStatData**[m_numCTUsPic];
+  for(Int i=0; i< m_numCTUsPic; i++)
+  {
+    m_statData[i] = new SAOStatData*[MAX_NUM_COMPONENT];
+    for(Int compIdx=0; compIdx < MAX_NUM_COMPONENT; compIdx++)
+    {
+      m_statData[i][compIdx] = new SAOStatData[NUM_SAO_NEW_TYPES];
+    }
+  }
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+  if(isPreDBFSamplesUsed)
+  {
+    m_preDBFstatData = new SAOStatData**[m_numCTUsPic];
+    for(Int i=0; i< m_numCTUsPic; i++)
+    {
+      m_preDBFstatData[i] = new SAOStatData*[MAX_NUM_COMPONENT];
+      for(Int compIdx=0; compIdx < MAX_NUM_COMPONENT; compIdx++)
+      {
+        m_preDBFstatData[i][compIdx] = new SAOStatData[NUM_SAO_NEW_TYPES];
+      }
+    }
+
+  }
+#endif
+
+#if SAO_ENCODING_CHOICE
+  ::memset(m_saoDisabledRate, 0, sizeof(m_saoDisabledRate));
+#endif
+
+  for(Int typeIdc=0; typeIdc < NUM_SAO_NEW_TYPES; typeIdc++)
+  {
+    m_skipLinesR[COMPONENT_Y ][typeIdc]= 5;
+    m_skipLinesR[COMPONENT_Cb][typeIdc]= m_skipLinesR[COMPONENT_Cr][typeIdc]= 3;
+
+    m_skipLinesB[COMPONENT_Y ][typeIdc]= 4;
+    m_skipLinesB[COMPONENT_Cb][typeIdc]= m_skipLinesB[COMPONENT_Cr][typeIdc]= 2;
+
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+    if(isPreDBFSamplesUsed)
+    {
+      switch(typeIdc)
+      {
+      case SAO_TYPE_EO_0:
+        {
+          m_skipLinesR[COMPONENT_Y ][typeIdc]= 5;
+          m_skipLinesR[COMPONENT_Cb][typeIdc]= m_skipLinesR[COMPONENT_Cr][typeIdc]= 3;
+
+          m_skipLinesB[COMPONENT_Y ][typeIdc]= 3;
+          m_skipLinesB[COMPONENT_Cb][typeIdc]= m_skipLinesB[COMPONENT_Cr][typeIdc]= 1;
+        }
+        break;
+      case SAO_TYPE_EO_90:
+        {
+          m_skipLinesR[COMPONENT_Y ][typeIdc]= 4;
+          m_skipLinesR[COMPONENT_Cb][typeIdc]= m_skipLinesR[COMPONENT_Cr][typeIdc]= 2;
+
+          m_skipLinesB[COMPONENT_Y ][typeIdc]= 4;
+          m_skipLinesB[COMPONENT_Cb][typeIdc]= m_skipLinesB[COMPONENT_Cr][typeIdc]= 2;
+        }
+        break;
+      case SAO_TYPE_EO_135:
+      case SAO_TYPE_EO_45:
+        {
+          m_skipLinesR[COMPONENT_Y ][typeIdc]= 5;
+          m_skipLinesR[COMPONENT_Cb][typeIdc]= m_skipLinesR[COMPONENT_Cr][typeIdc]= 3;
+
+          m_skipLinesB[COMPONENT_Y ][typeIdc]= 4;
+          m_skipLinesB[COMPONENT_Cb][typeIdc]= m_skipLinesB[COMPONENT_Cr][typeIdc]= 2;
+        }
+        break;
+      case SAO_TYPE_BO:
+        {
+          m_skipLinesR[COMPONENT_Y ][typeIdc]= 4;
+          m_skipLinesR[COMPONENT_Cb][typeIdc]= m_skipLinesR[COMPONENT_Cr][typeIdc]= 2;
+
+          m_skipLinesB[COMPONENT_Y ][typeIdc]= 3;
+          m_skipLinesB[COMPONENT_Cb][typeIdc]= m_skipLinesB[COMPONENT_Cr][typeIdc]= 1;
+        }
+        break;
+      default:
+        {
+          printf("Not a supported type");
+          assert(0);
+          exit(-1);
+        }
+      }
+    }
+#endif
+  }
+
+}
+
+Void TEncSampleAdaptiveOffset::destroyEncData()
+{
+  if(m_pppcRDSbacCoder != NULL)
+  {
+    for (Int cs = 0; cs < NUM_SAO_CABACSTATE_LABELS; cs ++ )
+    {
+      delete m_pppcRDSbacCoder[cs];
+    }
+    delete[] m_pppcRDSbacCoder; m_pppcRDSbacCoder = NULL;
+  }
+
+  if(m_pppcBinCoderCABAC != NULL)
+  {
+    for (Int cs = 0; cs < NUM_SAO_CABACSTATE_LABELS; cs ++ )
+    {
+      delete m_pppcBinCoderCABAC[cs];
+    }
+    delete[] m_pppcBinCoderCABAC; m_pppcBinCoderCABAC = NULL;
+  }
+
+  if(m_statData != NULL)
+  {
+    for(Int i=0; i< m_numCTUsPic; i++)
+    {
+      for(Int compIdx=0; compIdx< MAX_NUM_COMPONENT; compIdx++)
+      {
+        delete[] m_statData[i][compIdx];
+      }
+      delete[] m_statData[i];
+    }
+    delete[] m_statData; m_statData = NULL;
+  }
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+  if(m_preDBFstatData != NULL)
+  {
+    for(Int i=0; i< m_numCTUsPic; i++)
+    {
+      for(Int compIdx=0; compIdx< MAX_NUM_COMPONENT; compIdx++)
+      {
+        delete[] m_preDBFstatData[i][compIdx];
+      }
+      delete[] m_preDBFstatData[i];
+    }
+    delete[] m_preDBFstatData; m_preDBFstatData = NULL;
+  }
+
+#endif
+}
+
+Void TEncSampleAdaptiveOffset::initRDOCabacCoder(TEncSbac* pcRDGoOnSbacCoder, TComSlice* pcSlice)
+{
+  m_pcRDGoOnSbacCoder = pcRDGoOnSbacCoder;
+  m_pcRDGoOnSbacCoder->setSlice(pcSlice);
+  m_pcRDGoOnSbacCoder->resetEntropy();
+  m_pcRDGoOnSbacCoder->resetBits();
+
+  m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[SAO_CABACSTATE_PIC_INIT]);
+}
+
+
+
+Void TEncSampleAdaptiveOffset::SAOProcess(TComPic* pPic, Bool* sliceEnabled, const Double *lambdas
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+                                         , Bool isPreDBFSamplesUsed
+#endif
+                                          )
+{
+  TComPicYuv* orgYuv= pPic->getPicYuvOrg();
+  TComPicYuv* resYuv= pPic->getPicYuvRec();
+  memcpy(m_lambda, lambdas, sizeof(m_lambda));
+  TComPicYuv* srcYuv = m_tempPicYuv;
+  resYuv->copyToPic(srcYuv);
+  srcYuv->setBorderExtension(false);
+  srcYuv->extendPicBorder();
+
+  //collect statistics
+  getStatistics(m_statData, orgYuv, srcYuv, pPic);
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+  if(isPreDBFSamplesUsed)
+  {
+    addPreDBFStatistics(m_statData);
+  }
+#endif
+  //slice on/off
+  decidePicParams(sliceEnabled, pPic->getSlice(0)->getDepth());
+
+  //block on/off
+  SAOBlkParam* reconParams = new SAOBlkParam[m_numCTUsPic]; //temporary parameter buffer for storing reconstructed SAO parameters
+  decideBlkParams(pPic, sliceEnabled, m_statData, srcYuv, resYuv, reconParams, pPic->getPicSym()->getSAOBlkParam());
+  delete[] reconParams;
+}
+
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+Void TEncSampleAdaptiveOffset::getPreDBFStatistics(TComPic* pPic)
+{
+  getStatistics(m_preDBFstatData, pPic->getPicYuvOrg(), pPic->getPicYuvRec(), pPic, true);
+}
+
+Void TEncSampleAdaptiveOffset::addPreDBFStatistics(SAOStatData*** blkStats)
+{
+  for(Int n=0; n< m_numCTUsPic; n++)
+  {
+    for(Int compIdx=0; compIdx < MAX_NUM_COMPONENT; compIdx++)
+    {
+      for(Int typeIdc=0; typeIdc < NUM_SAO_NEW_TYPES; typeIdc++)
+      {
+        blkStats[n][compIdx][typeIdc] += m_preDBFstatData[n][compIdx][typeIdc];
+      }
+    }
+  }
+}
+
+#endif
+
+Void TEncSampleAdaptiveOffset::getStatistics(SAOStatData*** blkStats, TComPicYuv* orgYuv, TComPicYuv* srcYuv, TComPic* pPic
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+                          , Bool isCalculatePreDeblockSamples
+#endif
+                          )
+{
+  Bool isLeftAvail,isRightAvail,isAboveAvail,isBelowAvail,isAboveLeftAvail,isAboveRightAvail,isBelowLeftAvail,isBelowRightAvail;
+
+  const Int numberOfComponents = getNumberValidComponents(m_chromaFormatIDC);
+
+  for(Int ctuRsAddr= 0; ctuRsAddr < m_numCTUsPic; ctuRsAddr++)
+  {
+    Int yPos   = (ctuRsAddr / m_numCTUInWidth)*m_maxCUHeight;
+    Int xPos   = (ctuRsAddr % m_numCTUInWidth)*m_maxCUWidth;
+    Int height = (yPos + m_maxCUHeight > m_picHeight)?(m_picHeight- yPos):m_maxCUHeight;
+    Int width  = (xPos + m_maxCUWidth  > m_picWidth )?(m_picWidth - xPos):m_maxCUWidth;
+
+    pPic->getPicSym()->deriveLoopFilterBoundaryAvailibility(ctuRsAddr, isLeftAvail,isRightAvail,isAboveAvail,isBelowAvail,isAboveLeftAvail,isAboveRightAvail,isBelowLeftAvail,isBelowRightAvail);
+
+    //NOTE: The number of skipped lines during gathering CTU statistics depends on the slice boundary availabilities.
+    //For simplicity, here only picture boundaries are considered.
+
+    isRightAvail      = (xPos + m_maxCUWidth  < m_picWidth );
+    isBelowAvail      = (yPos + m_maxCUHeight < m_picHeight);
+    isBelowRightAvail = (isRightAvail && isBelowAvail);
+    isBelowLeftAvail  = ((xPos > 0) && (isBelowAvail));
+    isAboveRightAvail = ((yPos > 0) && (isRightAvail));
+
+    for(Int compIdx = 0; compIdx < numberOfComponents; compIdx++)
+    {
+      const ComponentID component = ComponentID(compIdx);
+
+      const UInt componentScaleX = getComponentScaleX(component, pPic->getChromaFormat());
+      const UInt componentScaleY = getComponentScaleY(component, pPic->getChromaFormat());
+
+      Int  srcStride  = srcYuv->getStride(component);
+      Pel* srcBlk     = srcYuv->getAddr(component) + ((yPos >> componentScaleY) * srcStride) + (xPos >> componentScaleX);
+
+      Int  orgStride  = orgYuv->getStride(component);
+      Pel* orgBlk     = orgYuv->getAddr(component) + ((yPos >> componentScaleY) * orgStride) + (xPos >> componentScaleX);
+
+      getBlkStats(component, blkStats[ctuRsAddr][component]
+                , srcBlk, orgBlk, srcStride, orgStride, (width  >> componentScaleX), (height >> componentScaleY)
+                , isLeftAvail,  isRightAvail, isAboveAvail, isBelowAvail, isAboveLeftAvail, isAboveRightAvail, isBelowLeftAvail, isBelowRightAvail
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+                , isCalculatePreDeblockSamples
+#endif
+                );
+
+    }
+  }
+}
+
+Void TEncSampleAdaptiveOffset::decidePicParams(Bool* sliceEnabled, Int picTempLayer)
+{
+  //decide sliceEnabled[compIdx]
+  const Int numberOfComponents = getNumberValidComponents(m_chromaFormatIDC);
+  for (Int compIdx = 0; compIdx < MAX_NUM_COMPONENT; compIdx++)
+  {
+    sliceEnabled[compIdx] = false;
+  }
+
+  for (Int compIdx = 0; compIdx < numberOfComponents; compIdx++)
+  {
+    // reset flags & counters
+    sliceEnabled[compIdx] = true;
+
+#if SAO_ENCODING_CHOICE
+#if SAO_ENCODING_CHOICE_CHROMA
+    // decide slice-level on/off based on previous results
+    if( (picTempLayer > 0)
+      && (m_saoDisabledRate[compIdx][picTempLayer-1] > ((compIdx==COMPONENT_Y) ? SAO_ENCODING_RATE : SAO_ENCODING_RATE_CHROMA)) )
+    {
+      sliceEnabled[compIdx] = false;
+    }
+#else
+    // decide slice-level on/off based on previous results
+    if( (picTempLayer > 0)
+      && (m_saoDisabledRate[COMPONENT_Y][0] > SAO_ENCODING_RATE) )
+    {
+      sliceEnabled[compIdx] = false;
+    }
+#endif
+#endif
+  }
+}
+
+Int64 TEncSampleAdaptiveOffset::getDistortion(ComponentID compIdx, Int typeIdc, Int typeAuxInfo, Int* invQuantOffset, SAOStatData& statData)
+{
+  Int64 dist        = 0;
+  Int shift         = 2 * DISTORTION_PRECISION_ADJUSTMENT(g_bitDepth[toChannelType(compIdx)] - 8);
+
+  switch(typeIdc)
+  {
+    case SAO_TYPE_EO_0:
+    case SAO_TYPE_EO_90:
+    case SAO_TYPE_EO_135:
+    case SAO_TYPE_EO_45:
+      {
+        for (Int offsetIdx=0; offsetIdx<NUM_SAO_EO_CLASSES; offsetIdx++)
+        {
+          dist += estSaoDist( statData.count[offsetIdx], invQuantOffset[offsetIdx], statData.diff[offsetIdx], shift);
+        }
+      }
+      break;
+    case SAO_TYPE_BO:
+      {
+        for (Int offsetIdx=typeAuxInfo; offsetIdx<typeAuxInfo+4; offsetIdx++)
+        {
+          Int bandIdx = offsetIdx % NUM_SAO_BO_CLASSES ;
+          dist += estSaoDist( statData.count[bandIdx], invQuantOffset[bandIdx], statData.diff[bandIdx], shift);
+        }
+      }
+      break;
+    default:
+      {
+        printf("Not a supported type");
+        assert(0);
+        exit(-1);
+      }
+  }
+
+  return dist;
+}
+
+inline Int64 TEncSampleAdaptiveOffset::estSaoDist(Int64 count, Int64 offset, Int64 diffSum, Int shift)
+{
+  return (( count*offset*offset-diffSum*offset*2 ) >> shift);
+}
+
+
+inline Int TEncSampleAdaptiveOffset::estIterOffset(Int typeIdx, Int classIdx, Double lambda, Int offsetInput, Int64 count, Int64 diffSum, Int shift, Int bitIncrease, Int64& bestDist, Double& bestCost, Int offsetTh )
+{
+  Int iterOffset, tempOffset;
+  Int64 tempDist, tempRate;
+  Double tempCost, tempMinCost;
+  Int offsetOutput = 0;
+  iterOffset = offsetInput;
+  // Assuming sending quantized value 0 results in zero offset and sending the value zero needs 1 bit. entropy coder can be used to measure the exact rate here.
+  tempMinCost = lambda;
+  while (iterOffset != 0)
+  {
+    // Calculate the bits required for signaling the offset
+    tempRate = (typeIdx == SAO_TYPE_BO) ? (abs((Int)iterOffset)+2) : (abs((Int)iterOffset)+1);
+    if (abs((Int)iterOffset)==offsetTh) //inclusive
+    {
+      tempRate --;
+    }
+    // Do the dequantization before distortion calculation
+    tempOffset  = iterOffset << bitIncrease;
+    tempDist    = estSaoDist( count, tempOffset, diffSum, shift);
+    tempCost    = ((Double)tempDist + lambda * (Double) tempRate);
+    if(tempCost < tempMinCost)
+    {
+      tempMinCost = tempCost;
+      offsetOutput = iterOffset;
+      bestDist = tempDist;
+      bestCost = tempCost;
+    }
+    iterOffset = (iterOffset > 0) ? (iterOffset-1):(iterOffset+1);
+  }
+  return offsetOutput;
+}
+
+Void TEncSampleAdaptiveOffset::deriveOffsets(ComponentID compIdx, Int typeIdc, SAOStatData& statData, Int* quantOffsets, Int& typeAuxInfo)
+{
+  Int bitDepth = g_bitDepth[toChannelType(compIdx)];
+  Int shift    = 2 * DISTORTION_PRECISION_ADJUSTMENT(bitDepth-8);
+#if SVC_EXTENSION
+  Int offsetTh = getSaoMaxOffsetQVal()[compIdx];  //inclusive
+#else
+  Int offsetTh = g_saoMaxOffsetQVal[compIdx];  //inclusive
+#endif
+
+  ::memset(quantOffsets, 0, sizeof(Int)*MAX_NUM_SAO_CLASSES);
+
+  //derive initial offsets
+  Int numClasses = (typeIdc == SAO_TYPE_BO)?((Int)NUM_SAO_BO_CLASSES):((Int)NUM_SAO_EO_CLASSES);
+  for(Int classIdx=0; classIdx< numClasses; classIdx++)
+  {
+    if( (typeIdc != SAO_TYPE_BO) && (classIdx==SAO_CLASS_EO_PLAIN)  )
+    {
+      continue; //offset will be zero
+    }
+
+    if(statData.count[classIdx] == 0)
+    {
+      continue; //offset will be zero
+    }
+
+    quantOffsets[classIdx] = (Int) xRoundIbdi(bitDepth, (Double)( statData.diff[classIdx]<<(bitDepth-8))
+                                                                  /
+                                                          (Double)( statData.count[classIdx]<< m_offsetStepLog2[compIdx])
+                                               );
+    quantOffsets[classIdx] = Clip3(-offsetTh, offsetTh, quantOffsets[classIdx]);
+  }
+
+  // adjust offsets
+  switch(typeIdc)
+  {
+    case SAO_TYPE_EO_0:
+    case SAO_TYPE_EO_90:
+    case SAO_TYPE_EO_135:
+    case SAO_TYPE_EO_45:
+      {
+        Int64 classDist;
+        Double classCost;
+        for(Int classIdx=0; classIdx<NUM_SAO_EO_CLASSES; classIdx++)
+        {
+          if(classIdx==SAO_CLASS_EO_FULL_VALLEY && quantOffsets[classIdx] < 0) quantOffsets[classIdx] =0;
+          if(classIdx==SAO_CLASS_EO_HALF_VALLEY && quantOffsets[classIdx] < 0) quantOffsets[classIdx] =0;
+          if(classIdx==SAO_CLASS_EO_HALF_PEAK   && quantOffsets[classIdx] > 0) quantOffsets[classIdx] =0;
+          if(classIdx==SAO_CLASS_EO_FULL_PEAK   && quantOffsets[classIdx] > 0) quantOffsets[classIdx] =0;
+
+          if( quantOffsets[classIdx] != 0 ) //iterative adjustment only when derived offset is not zero
+          {
+            quantOffsets[classIdx] = estIterOffset( typeIdc, classIdx, m_lambda[compIdx], quantOffsets[classIdx], statData.count[classIdx], statData.diff[classIdx], shift, m_offsetStepLog2[compIdx], classDist , classCost , offsetTh );
+          }
+        }
+
+        typeAuxInfo =0;
+      }
+      break;
+    case SAO_TYPE_BO:
+      {
+        Int64  distBOClasses[NUM_SAO_BO_CLASSES];
+        Double costBOClasses[NUM_SAO_BO_CLASSES];
+        ::memset(distBOClasses, 0, sizeof(Int64)*NUM_SAO_BO_CLASSES);
+        for(Int classIdx=0; classIdx< NUM_SAO_BO_CLASSES; classIdx++)
+        {
+          costBOClasses[classIdx]= m_lambda[compIdx];
+          if( quantOffsets[classIdx] != 0 ) //iterative adjustment only when derived offset is not zero
+          {
+            quantOffsets[classIdx] = estIterOffset( typeIdc, classIdx, m_lambda[compIdx], quantOffsets[classIdx], statData.count[classIdx], statData.diff[classIdx], shift, m_offsetStepLog2[compIdx], distBOClasses[classIdx], costBOClasses[classIdx], offsetTh );
+          }
+        }
+
+        //decide the starting band index
+        Double minCost = MAX_DOUBLE, cost;
+        for(Int band=0; band< NUM_SAO_BO_CLASSES- 4+ 1; band++)
+        {
+          cost  = costBOClasses[band  ];
+          cost += costBOClasses[band+1];
+          cost += costBOClasses[band+2];
+          cost += costBOClasses[band+3];
+
+          if(cost < minCost)
+          {
+            minCost = cost;
+            typeAuxInfo = band;
+          }
+        }
+        //clear those unused classes
+        Int clearQuantOffset[NUM_SAO_BO_CLASSES];
+        ::memset(clearQuantOffset, 0, sizeof(Int)*NUM_SAO_BO_CLASSES);
+        for(Int i=0; i< 4; i++)
+        {
+          Int band = (typeAuxInfo+i)%NUM_SAO_BO_CLASSES;
+          clearQuantOffset[band] = quantOffsets[band];
+        }
+        ::memcpy(quantOffsets, clearQuantOffset, sizeof(Int)*NUM_SAO_BO_CLASSES);
+      }
+      break;
+    default:
+      {
+        printf("Not a supported type");
+        assert(0);
+        exit(-1);
+      }
+
+  }
+
+
+}
+
+Void TEncSampleAdaptiveOffset::deriveModeNewRDO(Int ctuRsAddr, SAOBlkParam* mergeList[NUM_SAO_MERGE_TYPES], Bool* sliceEnabled, SAOStatData*** blkStats, SAOBlkParam& modeParam, Double& modeNormCost, TEncSbac** cabacCoderRDO, Int inCabacLabel)
+{
+  Double minCost, cost;
+  UInt previousWrittenBits;
+  const Int numberOfComponents = getNumberValidComponents(m_chromaFormatIDC);
+
+  Int64 dist[MAX_NUM_COMPONENT], modeDist[MAX_NUM_COMPONENT];
+  SAOOffset testOffset[MAX_NUM_COMPONENT];
+  Int invQuantOffset[MAX_NUM_SAO_CLASSES];
+  for(Int comp=0; comp < MAX_NUM_COMPONENT; comp++)
+  {
+    modeDist[comp] = 0;
+  }
+
+  //pre-encode merge flags
+  modeParam[COMPONENT_Y].modeIdc = SAO_MODE_OFF;
+  m_pcRDGoOnSbacCoder->load(cabacCoderRDO[inCabacLabel]);
+#if SVC_EXTENSION
+  m_pcRDGoOnSbacCoder->codeSAOBlkParam(modeParam, getSaoMaxOffsetQVal(), sliceEnabled, (mergeList[SAO_MERGE_LEFT]!= NULL), (mergeList[SAO_MERGE_ABOVE]!= NULL), true);
+#else
+  m_pcRDGoOnSbacCoder->codeSAOBlkParam(modeParam, sliceEnabled, (mergeList[SAO_MERGE_LEFT]!= NULL), (mergeList[SAO_MERGE_ABOVE]!= NULL), true);
+#endif
+  m_pcRDGoOnSbacCoder->store(cabacCoderRDO[SAO_CABACSTATE_BLK_MID]);
+
+    //------ luma --------//
+  {
+    ComponentID compIdx = COMPONENT_Y;
+    //"off" case as initial cost
+    modeParam[compIdx].modeIdc = SAO_MODE_OFF;
+    m_pcRDGoOnSbacCoder->resetBits();
+#if SVC_EXTENSION
+    m_pcRDGoOnSbacCoder->codeSAOOffsetParam(compIdx, modeParam[compIdx], sliceEnabled[compIdx], getSaoMaxOffsetQVal());
+#else
+    m_pcRDGoOnSbacCoder->codeSAOOffsetParam(compIdx, modeParam[compIdx], sliceEnabled[compIdx]);
+#endif
+    modeDist[compIdx] = 0;
+    minCost= m_lambda[compIdx]*((Double)m_pcRDGoOnSbacCoder->getNumberOfWrittenBits());
+    m_pcRDGoOnSbacCoder->store(cabacCoderRDO[SAO_CABACSTATE_BLK_TEMP]);
+    if(sliceEnabled[compIdx])
+    {
+      for(Int typeIdc=0; typeIdc< NUM_SAO_NEW_TYPES; typeIdc++)
+      {
+        testOffset[compIdx].modeIdc = SAO_MODE_NEW;
+        testOffset[compIdx].typeIdc = typeIdc;
+
+        //derive coded offset
+        deriveOffsets(compIdx, typeIdc, blkStats[ctuRsAddr][compIdx][typeIdc], testOffset[compIdx].offset, testOffset[compIdx].typeAuxInfo);
+
+        //inversed quantized offsets
+        invertQuantOffsets(compIdx, typeIdc, testOffset[compIdx].typeAuxInfo, invQuantOffset, testOffset[compIdx].offset);
+
+        //get distortion
+        dist[compIdx] = getDistortion(compIdx, testOffset[compIdx].typeIdc, testOffset[compIdx].typeAuxInfo, invQuantOffset, blkStats[ctuRsAddr][compIdx][typeIdc]);
+
+        //get rate
+        m_pcRDGoOnSbacCoder->load(cabacCoderRDO[SAO_CABACSTATE_BLK_MID]);
+        m_pcRDGoOnSbacCoder->resetBits();
+#if SVC_EXTENSION
+        m_pcRDGoOnSbacCoder->codeSAOOffsetParam(compIdx, testOffset[compIdx], sliceEnabled[compIdx], getSaoMaxOffsetQVal());
+#else
+        m_pcRDGoOnSbacCoder->codeSAOOffsetParam(compIdx, testOffset[compIdx], sliceEnabled[compIdx]);
+#endif
+        Int rate = m_pcRDGoOnSbacCoder->getNumberOfWrittenBits();
+        cost = (Double)dist[compIdx] + m_lambda[compIdx]*((Double)rate);
+        if(cost < minCost)
+        {
+          minCost = cost;
+          modeDist[compIdx] = dist[compIdx];
+          modeParam[compIdx]= testOffset[compIdx];
+          m_pcRDGoOnSbacCoder->store(cabacCoderRDO[SAO_CABACSTATE_BLK_TEMP]);
+        }
+      }
+    }
+    m_pcRDGoOnSbacCoder->load(cabacCoderRDO[SAO_CABACSTATE_BLK_TEMP]);
+    m_pcRDGoOnSbacCoder->store(cabacCoderRDO[SAO_CABACSTATE_BLK_MID]);
+  }
+
+  //------ chroma --------//
+//"off" case as initial cost
+  cost = 0;
+  previousWrittenBits = 0;
+  m_pcRDGoOnSbacCoder->resetBits();
+  for(UInt componentIndex = COMPONENT_Cb; componentIndex < numberOfComponents; componentIndex++)
+  {
+    const ComponentID component = ComponentID(componentIndex);
+
+    modeParam[component].modeIdc = SAO_MODE_OFF;
+    modeDist [component]         = 0;
+
+#if SVC_EXTENSION
+    m_pcRDGoOnSbacCoder->codeSAOOffsetParam(component, modeParam[component], sliceEnabled[component], getSaoMaxOffsetQVal());
+#else
+    m_pcRDGoOnSbacCoder->codeSAOOffsetParam(component, modeParam[component], sliceEnabled[component]);
+#endif
+
+    const UInt currentWrittenBits = m_pcRDGoOnSbacCoder->getNumberOfWrittenBits();
+    cost += m_lambda[component] * (currentWrittenBits - previousWrittenBits);
+    previousWrittenBits = currentWrittenBits;
+  }
+
+  minCost = cost;
+
+  //doesn't need to store cabac status here since the whole CTU parameters will be re-encoded at the end of this function
+
+  for(Int typeIdc=0; typeIdc< NUM_SAO_NEW_TYPES; typeIdc++)
+  {
+    m_pcRDGoOnSbacCoder->load(cabacCoderRDO[SAO_CABACSTATE_BLK_MID]);
+    m_pcRDGoOnSbacCoder->resetBits();
+    previousWrittenBits = 0;
+    cost = 0;
+
+    for(UInt componentIndex = COMPONENT_Cb; componentIndex < numberOfComponents; componentIndex++)
+    {
+      const ComponentID component = ComponentID(componentIndex);
+      if(!sliceEnabled[component])
+      {
+        testOffset[component].modeIdc = SAO_MODE_OFF;
+        dist[component]= 0;
+        continue;
+      }
+      testOffset[component].modeIdc = SAO_MODE_NEW;
+      testOffset[component].typeIdc = typeIdc;
+
+      //derive offset & get distortion
+      deriveOffsets(component, typeIdc, blkStats[ctuRsAddr][component][typeIdc], testOffset[component].offset, testOffset[component].typeAuxInfo);
+      invertQuantOffsets(component, typeIdc, testOffset[component].typeAuxInfo, invQuantOffset, testOffset[component].offset);
+      dist[component] = getDistortion(component, typeIdc, testOffset[component].typeAuxInfo, invQuantOffset, blkStats[ctuRsAddr][component][typeIdc]);
+
+#if SVC_EXTENSION
+      m_pcRDGoOnSbacCoder->codeSAOOffsetParam(component, testOffset[component], sliceEnabled[component], getSaoMaxOffsetQVal());
+#else
+      m_pcRDGoOnSbacCoder->codeSAOOffsetParam(component, testOffset[component], sliceEnabled[component]);
+#endif
+
+      const UInt currentWrittenBits = m_pcRDGoOnSbacCoder->getNumberOfWrittenBits();
+      cost += dist[component] + (m_lambda[component] * (currentWrittenBits - previousWrittenBits));
+      previousWrittenBits = currentWrittenBits;
+    }
+
+    if(cost < minCost)
+    {
+      minCost = cost;
+      for(UInt componentIndex = COMPONENT_Cb; componentIndex < numberOfComponents; componentIndex++)
+      {
+        modeDist[componentIndex]  = dist[componentIndex];
+        modeParam[componentIndex] = testOffset[componentIndex];
+      }
+    }
+
+  } // SAO_TYPE loop
+
+  //----- re-gen rate & normalized cost----//
+  modeNormCost = 0;
+  for(UInt componentIndex = COMPONENT_Y; componentIndex < numberOfComponents; componentIndex++)
+  {
+    modeNormCost += (Double)modeDist[componentIndex] / m_lambda[componentIndex];
+  }
+
+  m_pcRDGoOnSbacCoder->load(cabacCoderRDO[inCabacLabel]);
+  m_pcRDGoOnSbacCoder->resetBits();
+#if SVC_EXTENSION
+  m_pcRDGoOnSbacCoder->codeSAOBlkParam(modeParam, getSaoMaxOffsetQVal(), sliceEnabled, (mergeList[SAO_MERGE_LEFT]!= NULL), (mergeList[SAO_MERGE_ABOVE]!= NULL), false);
+#else
+  m_pcRDGoOnSbacCoder->codeSAOBlkParam(modeParam, sliceEnabled, (mergeList[SAO_MERGE_LEFT]!= NULL), (mergeList[SAO_MERGE_ABOVE]!= NULL), false);
+#endif
+  modeNormCost += (Double)m_pcRDGoOnSbacCoder->getNumberOfWrittenBits();
+}
+
+Void TEncSampleAdaptiveOffset::deriveModeMergeRDO(Int ctuRsAddr, SAOBlkParam* mergeList[NUM_SAO_MERGE_TYPES], Bool* sliceEnabled, SAOStatData*** blkStats, SAOBlkParam& modeParam, Double& modeNormCost, TEncSbac** cabacCoderRDO, Int inCabacLabel)
+{
+  modeNormCost = MAX_DOUBLE;
+
+  Double cost;
+  SAOBlkParam testBlkParam;
+  const Int numberOfComponents = getNumberValidComponents(m_chromaFormatIDC);
+
+  for(Int mergeType=0; mergeType< NUM_SAO_MERGE_TYPES; mergeType++)
+  {
+    if(mergeList[mergeType] == NULL)
+    {
+      continue;
+    }
+
+    testBlkParam = *(mergeList[mergeType]);
+    //normalized distortion
+    Double normDist=0;
+    for(Int compIdx = 0; compIdx < numberOfComponents; compIdx++)
+    {
+      testBlkParam[compIdx].modeIdc = SAO_MODE_MERGE;
+      testBlkParam[compIdx].typeIdc = mergeType;
+
+      SAOOffset& mergedOffsetParam = (*(mergeList[mergeType]))[compIdx];
+
+      if( mergedOffsetParam.modeIdc != SAO_MODE_OFF)
+      {
+        //offsets have been reconstructed. Don't call inversed quantization function.
+        normDist += (((Double)getDistortion(ComponentID(compIdx), mergedOffsetParam.typeIdc, mergedOffsetParam.typeAuxInfo, mergedOffsetParam.offset, blkStats[ctuRsAddr][compIdx][mergedOffsetParam.typeIdc]))
+                       /m_lambda[compIdx]
+                    );
+      }
+
+    }
+
+    //rate
+    m_pcRDGoOnSbacCoder->load(cabacCoderRDO[inCabacLabel]);
+    m_pcRDGoOnSbacCoder->resetBits();
+#if SVC_EXTENSION
+    m_pcRDGoOnSbacCoder->codeSAOBlkParam(testBlkParam, getSaoMaxOffsetQVal(), sliceEnabled, (mergeList[SAO_MERGE_LEFT]!= NULL), (mergeList[SAO_MERGE_ABOVE]!= NULL), false);
+#else
+    m_pcRDGoOnSbacCoder->codeSAOBlkParam(testBlkParam, sliceEnabled, (mergeList[SAO_MERGE_LEFT]!= NULL), (mergeList[SAO_MERGE_ABOVE]!= NULL), false);
+#endif
+    Int rate = m_pcRDGoOnSbacCoder->getNumberOfWrittenBits();
+
+    cost = normDist+(Double)rate;
+
+    if(cost < modeNormCost)
+    {
+      modeNormCost = cost;
+      modeParam    = testBlkParam;
+      m_pcRDGoOnSbacCoder->store(cabacCoderRDO[SAO_CABACSTATE_BLK_TEMP]);
+    }
+  }
+
+  m_pcRDGoOnSbacCoder->load(cabacCoderRDO[SAO_CABACSTATE_BLK_TEMP]);
+}
+
+Void TEncSampleAdaptiveOffset::decideBlkParams(TComPic* pic, Bool* sliceEnabled, SAOStatData*** blkStats, TComPicYuv* srcYuv, TComPicYuv* resYuv, SAOBlkParam* reconParams, SAOBlkParam* codedParams)
+{
+  Bool allBlksDisabled = true;
+  const Int numberOfComponents = getNumberValidComponents(m_chromaFormatIDC);
+  for(Int compId = COMPONENT_Y; compId < numberOfComponents; compId++)
+  {
+    if (sliceEnabled[compId])
+      allBlksDisabled = false;
+  }
+
+  m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[ SAO_CABACSTATE_PIC_INIT ]);
+
+  SAOBlkParam modeParam;
+  Double minCost, modeCost;
+
+
+#if RD_TEST_SAO_DISABLE_AT_PICTURE_LEVEL
+  Double totalCost = 0;
+#endif
+
+  for(Int ctuRsAddr=0; ctuRsAddr< m_numCTUsPic; ctuRsAddr++)
+  {
+    if(allBlksDisabled)
+    {
+      codedParams[ctuRsAddr].reset();
+      continue;
+    }
+
+    m_pcRDGoOnSbacCoder->store(m_pppcRDSbacCoder[ SAO_CABACSTATE_BLK_CUR ]);
+
+    //get merge list
+    SAOBlkParam* mergeList[NUM_SAO_MERGE_TYPES] = { NULL };
+    getMergeList(pic, ctuRsAddr, reconParams, mergeList);
+
+    minCost = MAX_DOUBLE;
+    for(Int mode=0; mode < NUM_SAO_MODES; mode++)
+    {
+      switch(mode)
+      {
+      case SAO_MODE_OFF:
+        {
+          continue; //not necessary, since all-off case will be tested in SAO_MODE_NEW case.
+        }
+        break;
+      case SAO_MODE_NEW:
+        {
+          deriveModeNewRDO(ctuRsAddr, mergeList, sliceEnabled, blkStats, modeParam, modeCost, m_pppcRDSbacCoder, SAO_CABACSTATE_BLK_CUR);
+
+        }
+        break;
+      case SAO_MODE_MERGE:
+        {
+          deriveModeMergeRDO(ctuRsAddr, mergeList, sliceEnabled, blkStats , modeParam, modeCost, m_pppcRDSbacCoder, SAO_CABACSTATE_BLK_CUR);
+        }
+        break;
+      default:
+        {
+          printf("Not a supported SAO mode\n");
+          assert(0);
+          exit(-1);
+        }
+      }
+
+      if(modeCost < minCost)
+      {
+        minCost = modeCost;
+        codedParams[ctuRsAddr] = modeParam;
+        m_pcRDGoOnSbacCoder->store(m_pppcRDSbacCoder[ SAO_CABACSTATE_BLK_NEXT ]);
+      }
+    } //mode
+
+#if RD_TEST_SAO_DISABLE_AT_PICTURE_LEVEL
+    totalCost += minCost;
+#endif
+
+    m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[ SAO_CABACSTATE_BLK_NEXT ]);
+
+    //apply reconstructed offsets
+    reconParams[ctuRsAddr] = codedParams[ctuRsAddr];
+    reconstructBlkSAOParam(reconParams[ctuRsAddr], mergeList);
+    offsetCTU(ctuRsAddr, srcYuv, resYuv, reconParams[ctuRsAddr], pic);
+  } //ctuRsAddr
+
+#if RD_TEST_SAO_DISABLE_AT_PICTURE_LEVEL
+  if (!allBlksDisabled && (totalCost >= 0)) //SAO is not beneficial - disable it
+  {
+    for(Int ctuRsAddr = 0; ctuRsAddr < m_numCTUsPic; ctuRsAddr++)
+    {
+      codedParams[ctuRsAddr].reset();
+    }
+
+    for (UInt componentIndex = 0; componentIndex < MAX_NUM_COMPONENT; componentIndex++)
+    {
+      sliceEnabled[componentIndex] = false;
+    }
+
+    m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[ SAO_CABACSTATE_PIC_INIT ]);
+  }
+#endif
+
+#if SAO_ENCODING_CHOICE
+  Int picTempLayer = pic->getSlice(0)->getDepth();
+  Int numCtusForSAOOff[MAX_NUM_COMPONENT];
+
+  for (Int compIdx = 0; compIdx < numberOfComponents; compIdx++)
+  {
+    numCtusForSAOOff[compIdx] = 0;
+    for(Int ctuRsAddr=0; ctuRsAddr< m_numCTUsPic; ctuRsAddr++)
+    {
+      if( reconParams[ctuRsAddr][compIdx].modeIdc == SAO_MODE_OFF)
+      {
+        numCtusForSAOOff[compIdx]++;
+      }
+    }
+  }
+#if SAO_ENCODING_CHOICE_CHROMA
+  for (Int compIdx = 0; compIdx < numberOfComponents; compIdx++)
+  {
+    m_saoDisabledRate[compIdx][picTempLayer] = (Double)numCtusForSAOOff[compIdx]/(Double)m_numCTUsPic;
+  }
+#else
+  if (picTempLayer == 0)
+  {
+    m_saoDisabledRate[COMPONENT_Y][0] = (Double)(numCtusForSAOOff[COMPONENT_Y]+numCtusForSAOOff[COMPONENT_Cb]+numCtusForSAOOff[COMPONENT_Cr])/(Double)(m_numCTUsPic*3);
+  }
+#endif
+#endif
+}
+
+
+Void TEncSampleAdaptiveOffset::getBlkStats(ComponentID compIdx, SAOStatData* statsDataTypes
+                        , Pel* srcBlk, Pel* orgBlk, Int srcStride, Int orgStride, Int width, Int height
+                        , Bool isLeftAvail,  Bool isRightAvail, Bool isAboveAvail, Bool isBelowAvail, Bool isAboveLeftAvail, Bool isAboveRightAvail, Bool isBelowLeftAvail, Bool isBelowRightAvail
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+                        , Bool isCalculatePreDeblockSamples
+#endif
+                        )
+{
+  if(m_lineBufWidth != m_maxCUWidth)
+  {
+    m_lineBufWidth = m_maxCUWidth;
+
+    if (m_signLineBuf1) delete[] m_signLineBuf1; m_signLineBuf1 = NULL;
+    m_signLineBuf1 = new Char[m_lineBufWidth+1];
+
+    if (m_signLineBuf2) delete[] m_signLineBuf2; m_signLineBuf2 = NULL;
+    m_signLineBuf2 = new Char[m_lineBufWidth+1];
+  }
+
+  Int x,y, startX, startY, endX, endY, edgeType, firstLineStartX, firstLineEndX;
+  Char signLeft, signRight, signDown;
+  Int64 *diff, *count;
+  Pel *srcLine, *orgLine;
+  Int* skipLinesR = m_skipLinesR[compIdx];
+  Int* skipLinesB = m_skipLinesB[compIdx];
+
+  for(Int typeIdx=0; typeIdx< NUM_SAO_NEW_TYPES; typeIdx++)
+  {
+    SAOStatData& statsData= statsDataTypes[typeIdx];
+    statsData.reset();
+
+    srcLine = srcBlk;
+    orgLine = orgBlk;
+    diff    = statsData.diff;
+    count   = statsData.count;
+    switch(typeIdx)
+    {
+    case SAO_TYPE_EO_0:
+      {
+        diff +=2;
+        count+=2;
+        endY   = (isBelowAvail) ? (height - skipLinesB[typeIdx]) : height;
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+        startX = (!isCalculatePreDeblockSamples) ? (isLeftAvail  ? 0 : 1)
+                                                 : (isRightAvail ? (width - skipLinesR[typeIdx]) : (width - 1))
+                                                 ;
+#else
+        startX = isLeftAvail ? 0 : 1;
+#endif
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+        endX   = (!isCalculatePreDeblockSamples) ? (isRightAvail ? (width - skipLinesR[typeIdx]) : (width - 1))
+                                                 : (isRightAvail ? width : (width - 1))
+                                                 ;
+#else
+        endX   = isRightAvail ? (width - skipLinesR[typeIdx]): (width - 1);
+#endif
+        for (y=0; y<endY; y++)
+        {
+          signLeft = (Char)sgn(srcLine[startX] - srcLine[startX-1]);
+          for (x=startX; x<endX; x++)
+          {
+            signRight =  (Char)sgn(srcLine[x] - srcLine[x+1]);
+            edgeType  =  signRight + signLeft;
+            signLeft  = -signRight;
+
+            diff [edgeType] += (orgLine[x] - srcLine[x]);
+            count[edgeType] ++;
+          }
+          srcLine  += srcStride;
+          orgLine  += orgStride;
+        }
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+        if(isCalculatePreDeblockSamples)
+        {
+          if(isBelowAvail)
+          {
+            startX = isLeftAvail  ? 0 : 1;
+            endX   = isRightAvail ? width : (width -1);
+
+            for(y=0; y<skipLinesB[typeIdx]; y++)
+            {
+              signLeft = (Char)sgn(srcLine[startX] - srcLine[startX-1]);
+              for (x=startX; x<endX; x++)
+              {
+                signRight =  (Char)sgn(srcLine[x] - srcLine[x+1]);
+                edgeType  =  signRight + signLeft;
+                signLeft  = -signRight;
+
+                diff [edgeType] += (orgLine[x] - srcLine[x]);
+                count[edgeType] ++;
+              }
+              srcLine  += srcStride;
+              orgLine  += orgStride;
+            }
+          }
+        }
+#endif
+      }
+      break;
+    case SAO_TYPE_EO_90:
+      {
+        diff +=2;
+        count+=2;
+        Char *signUpLine = m_signLineBuf1;
+
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+        startX = (!isCalculatePreDeblockSamples) ? 0
+                                                 : (isRightAvail ? (width - skipLinesR[typeIdx]) : width)
+                                                 ;
+#endif
+        startY = isAboveAvail ? 0 : 1;
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+        endX   = (!isCalculatePreDeblockSamples) ? (isRightAvail ? (width - skipLinesR[typeIdx]) : width)
+                                                 : width
+                                                 ;
+#else
+        endX   = isRightAvail ? (width - skipLinesR[typeIdx]) : width ;
+#endif
+        endY   = isBelowAvail ? (height - skipLinesB[typeIdx]) : (height - 1);
+        if (!isAboveAvail)
+        {
+          srcLine += srcStride;
+          orgLine += orgStride;
+        }
+
+        Pel* srcLineAbove = srcLine - srcStride;
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+        for (x=startX; x<endX; x++)
+#else
+        for (x=0; x< endX; x++)
+#endif
+        {
+          signUpLine[x] = (Char)sgn(srcLine[x] - srcLineAbove[x]);
+        }
+
+        Pel* srcLineBelow;
+        for (y=startY; y<endY; y++)
+        {
+          srcLineBelow = srcLine + srcStride;
+
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+          for (x=startX; x<endX; x++)
+#else
+          for (x=0; x<endX; x++)
+#endif
+          {
+            signDown  = (Char)sgn(srcLine[x] - srcLineBelow[x]); 
+            edgeType  = signDown + signUpLine[x];
+            signUpLine[x]= -signDown;
+
+            diff [edgeType] += (orgLine[x] - srcLine[x]);
+            count[edgeType] ++;
+          }
+          srcLine += srcStride;
+          orgLine += orgStride;
+        }
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+        if(isCalculatePreDeblockSamples)
+        {
+          if(isBelowAvail)
+          {
+            startX = 0;
+            endX   = width;
+
+            for(y=0; y<skipLinesB[typeIdx]; y++)
+            {
+              srcLineBelow = srcLine + srcStride;
+              srcLineAbove = srcLine - srcStride;
+
+              for (x=startX; x<endX; x++)
+              {
+                edgeType = sgn(srcLine[x] - srcLineBelow[x]) + sgn(srcLine[x] - srcLineAbove[x]);
+                diff [edgeType] += (orgLine[x] - srcLine[x]);
+                count[edgeType] ++;
+              }
+              srcLine  += srcStride;
+              orgLine  += orgStride;
+            }
+          }
+        }
+#endif
+
+      }
+      break;
+    case SAO_TYPE_EO_135:
+      {
+        diff +=2;
+        count+=2;
+        Char *signUpLine, *signDownLine, *signTmpLine;
+
+        signUpLine  = m_signLineBuf1;
+        signDownLine= m_signLineBuf2;
+
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+        startX = (!isCalculatePreDeblockSamples) ? (isLeftAvail  ? 0 : 1)
+                                                 : (isRightAvail ? (width - skipLinesR[typeIdx]) : (width - 1))
+                                                 ;
+#else
+        startX = isLeftAvail ? 0 : 1 ;
+#endif
+
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+        endX   = (!isCalculatePreDeblockSamples) ? (isRightAvail ? (width - skipLinesR[typeIdx]): (width - 1))
+                                                 : (isRightAvail ? width : (width - 1))
+                                                 ;
+#else
+        endX   = isRightAvail ? (width - skipLinesR[typeIdx]): (width - 1);
+#endif
+        endY   = isBelowAvail ? (height - skipLinesB[typeIdx]) : (height - 1);
+
+        //prepare 2nd line's upper sign
+        Pel* srcLineBelow = srcLine + srcStride;
+        for (x=startX; x<endX+1; x++)
+        {
+          signUpLine[x] = (Char)sgn(srcLineBelow[x] - srcLine[x-1]);
+        }
+
+        //1st line
+        Pel* srcLineAbove = srcLine - srcStride;
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+        firstLineStartX = (!isCalculatePreDeblockSamples) ? (isAboveLeftAvail ? 0    : 1) : startX;
+        firstLineEndX   = (!isCalculatePreDeblockSamples) ? (isAboveAvail     ? endX : 1) : endX;
+#else
+        firstLineStartX = isAboveLeftAvail ? 0    : 1;
+        firstLineEndX   = isAboveAvail     ? endX : 1;
+#endif
+        for(x=firstLineStartX; x<firstLineEndX; x++)
+        {
+          edgeType = sgn(srcLine[x] - srcLineAbove[x-1]) - signUpLine[x+1];
+          diff [edgeType] += (orgLine[x] - srcLine[x]);
+          count[edgeType] ++;
+        }
+        srcLine  += srcStride;
+        orgLine  += orgStride;
+
+
+        //middle lines
+        for (y=1; y<endY; y++)
+        {
+          srcLineBelow = srcLine + srcStride;
+
+          for (x=startX; x<endX; x++)
+          {
+            signDown = (Char)sgn(srcLine[x] - srcLineBelow[x+1]);
+            edgeType = signDown + signUpLine[x];
+            diff [edgeType] += (orgLine[x] - srcLine[x]);
+            count[edgeType] ++;
+
+            signDownLine[x+1] = -signDown;
+          }
+          signDownLine[startX] = (Char)sgn(srcLineBelow[startX] - srcLine[startX-1]);
+
+          signTmpLine  = signUpLine;
+          signUpLine   = signDownLine;
+          signDownLine = signTmpLine;
+
+          srcLine += srcStride;
+          orgLine += orgStride;
+        }
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+        if(isCalculatePreDeblockSamples)
+        {
+          if(isBelowAvail)
+          {
+            startX = isLeftAvail  ? 0     : 1 ;
+            endX   = isRightAvail ? width : (width -1);
+
+            for(y=0; y<skipLinesB[typeIdx]; y++)
+            {
+              srcLineBelow = srcLine + srcStride;
+              srcLineAbove = srcLine - srcStride;
+
+              for (x=startX; x< endX; x++)
+              {
+                edgeType = sgn(srcLine[x] - srcLineBelow[x+1]) + sgn(srcLine[x] - srcLineAbove[x-1]);
+                diff [edgeType] += (orgLine[x] - srcLine[x]);
+                count[edgeType] ++;
+              }
+              srcLine  += srcStride;
+              orgLine  += orgStride;
+            }
+          }
+        }
+#endif
+      }
+      break;
+    case SAO_TYPE_EO_45:
+      {
+        diff +=2;
+        count+=2;
+        Char *signUpLine = m_signLineBuf1+1;
+
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+        startX = (!isCalculatePreDeblockSamples) ? (isLeftAvail  ? 0 : 1)
+                                                 : (isRightAvail ? (width - skipLinesR[typeIdx]) : (width - 1))
+                                                 ;
+#else
+        startX = isLeftAvail ? 0 : 1;
+#endif
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+        endX   = (!isCalculatePreDeblockSamples) ? (isRightAvail ? (width - skipLinesR[typeIdx]) : (width - 1))
+                                                 : (isRightAvail ? width : (width - 1))
+                                                 ;
+#else
+        endX   = isRightAvail ? (width - skipLinesR[typeIdx]) : (width - 1);
+#endif
+        endY   = isBelowAvail ? (height - skipLinesB[typeIdx]) : (height - 1);
+
+        //prepare 2nd line upper sign
+        Pel* srcLineBelow = srcLine + srcStride;
+        for (x=startX-1; x<endX; x++)
+        {
+          signUpLine[x] = (Char)sgn(srcLineBelow[x] - srcLine[x+1]);
+        }
+
+
+        //first line
+        Pel* srcLineAbove = srcLine - srcStride;
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+        firstLineStartX = (!isCalculatePreDeblockSamples) ? (isAboveAvail ? startX : endX)
+                                                          : startX
+                                                          ;
+        firstLineEndX   = (!isCalculatePreDeblockSamples) ? ((!isRightAvail && isAboveRightAvail) ? width : endX)
+                                                          : endX
+                                                          ;
+#else
+        firstLineStartX = isAboveAvail ? startX : endX;
+        firstLineEndX   = (!isRightAvail && isAboveRightAvail) ? width : endX;
+#endif
+        for(x=firstLineStartX; x<firstLineEndX; x++)
+        {
+          edgeType = sgn(srcLine[x] - srcLineAbove[x+1]) - signUpLine[x-1];
+          diff [edgeType] += (orgLine[x] - srcLine[x]);
+          count[edgeType] ++;
+        }
+
+        srcLine += srcStride;
+        orgLine += orgStride;
+
+        //middle lines
+        for (y=1; y<endY; y++)
+        {
+          srcLineBelow = srcLine + srcStride;
+
+          for(x=startX; x<endX; x++)
+          {
+            signDown = (Char)sgn(srcLine[x] - srcLineBelow[x-1]);
+            edgeType = signDown + signUpLine[x];
+
+            diff [edgeType] += (orgLine[x] - srcLine[x]);
+            count[edgeType] ++;
+
+            signUpLine[x-1] = -signDown;
+          }
+          signUpLine[endX-1] = (Char)sgn(srcLineBelow[endX-1] - srcLine[endX]);
+          srcLine  += srcStride;
+          orgLine  += orgStride;
+        }
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+        if(isCalculatePreDeblockSamples)
+        {
+          if(isBelowAvail)
+          {
+            startX = isLeftAvail  ? 0     : 1 ;
+            endX   = isRightAvail ? width : (width -1);
+
+            for(y=0; y<skipLinesB[typeIdx]; y++)
+            {
+              srcLineBelow = srcLine + srcStride;
+              srcLineAbove = srcLine - srcStride;
+
+              for (x=startX; x<endX; x++)
+              {
+                edgeType = sgn(srcLine[x] - srcLineBelow[x-1]) + sgn(srcLine[x] - srcLineAbove[x+1]);
+                diff [edgeType] += (orgLine[x] - srcLine[x]);
+                count[edgeType] ++;
+              }
+              srcLine  += srcStride;
+              orgLine  += orgStride;
+            }
+          }
+        }
+#endif
+      }
+      break;
+    case SAO_TYPE_BO:
+      {
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+        startX = (!isCalculatePreDeblockSamples)?0
+                                                :( isRightAvail?(width- skipLinesR[typeIdx]):width)
+                                                ;
+        endX   = (!isCalculatePreDeblockSamples)?(isRightAvail ? (width - skipLinesR[typeIdx]) : width )
+                                                :width
+                                                ;
+#else
+        endX = isRightAvail ? (width- skipLinesR[typeIdx]) : width;
+#endif
+        endY = isBelowAvail ? (height- skipLinesB[typeIdx]) : height;
+        Int shiftBits = g_bitDepth[toChannelType(compIdx)] - NUM_SAO_BO_CLASSES_LOG2;
+        for (y=0; y< endY; y++)
+        {
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+          for (x=startX; x< endX; x++)
+#else
+          for (x=0; x< endX; x++)
+#endif
+          {
+
+            Int bandIdx= srcLine[x] >> shiftBits;
+            diff [bandIdx] += (orgLine[x] - srcLine[x]);
+            count[bandIdx] ++;
+          }
+          srcLine += srcStride;
+          orgLine += orgStride;
+        }
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+        if(isCalculatePreDeblockSamples)
+        {
+          if(isBelowAvail)
+          {
+            startX = 0;
+            endX   = width;
+
+            for(y= 0; y< skipLinesB[typeIdx]; y++)
+            {
+              for (x=startX; x< endX; x++)
+              {
+                Int bandIdx= srcLine[x] >> shiftBits;
+                diff [bandIdx] += (orgLine[x] - srcLine[x]);
+                count[bandIdx] ++;
+              }
+              srcLine  += srcStride;
+              orgLine  += orgStride;
+
+            }
+
+          }
+        }
+#endif
+      }
+      break;
+    default:
+      {
+        printf("Not a supported SAO types\n");
+        assert(0);
+        exit(-1);
+      }
+    }
+  }
+}
+
+
+//! \}
Index: /tags/SHM-9.0/source/Lib/TLibEncoder/TEncSampleAdaptiveOffset.h
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibEncoder/TEncSampleAdaptiveOffset.h	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibEncoder/TEncSampleAdaptiveOffset.h	(revision 1088)
@@ -0,0 +1,168 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ \file     TEncSampleAdaptiveOffset.h
+ \brief    estimation part of sample adaptive offset class (header)
+ */
+
+#ifndef __TENCSAMPLEADAPTIVEOFFSET__
+#define __TENCSAMPLEADAPTIVEOFFSET__
+
+#include "TLibCommon/TComSampleAdaptiveOffset.h"
+#include "TLibCommon/TComPic.h"
+
+#include "TEncEntropy.h"
+#include "TEncSbac.h"
+#include "TLibCommon/TComBitCounter.h"
+
+//! \ingroup TLibEncoder
+//! \{
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+enum SAOCabacStateLablesRDO //CABAC state labels
+{
+  SAO_CABACSTATE_PIC_INIT =0,
+  SAO_CABACSTATE_BLK_CUR,
+  SAO_CABACSTATE_BLK_NEXT,
+  SAO_CABACSTATE_BLK_MID,
+  SAO_CABACSTATE_BLK_TEMP,
+  NUM_SAO_CABACSTATE_LABELS
+};
+
+struct SAOStatData //data structure for SAO statistics
+{
+  Int64 diff[MAX_NUM_SAO_CLASSES];
+  Int64 count[MAX_NUM_SAO_CLASSES];
+
+  SAOStatData(){}
+  ~SAOStatData(){}
+  Void reset()
+  {
+    ::memset(diff, 0, sizeof(Int64)*MAX_NUM_SAO_CLASSES);
+    ::memset(count, 0, sizeof(Int64)*MAX_NUM_SAO_CLASSES);
+  }
+  const SAOStatData& operator=(const SAOStatData& src)
+  {
+    ::memcpy(diff, src.diff, sizeof(Int64)*MAX_NUM_SAO_CLASSES);
+    ::memcpy(count, src.count, sizeof(Int64)*MAX_NUM_SAO_CLASSES);
+    return *this;
+  }
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+  const SAOStatData& operator+= (const SAOStatData& src)
+  {
+    for(Int i=0; i< MAX_NUM_SAO_CLASSES; i++)
+    {
+      diff[i] += src.diff[i];
+      count[i] += src.count[i];
+    }
+    return *this;
+  }
+#endif
+};
+
+class TEncSampleAdaptiveOffset : public TComSampleAdaptiveOffset
+{
+public:
+  TEncSampleAdaptiveOffset();
+  virtual ~TEncSampleAdaptiveOffset();
+
+  //interface
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+  Void createEncData(Bool isPreDBFSamplesUsed);
+#else
+  Void createEncData();
+#endif
+  Void destroyEncData();
+  Void initRDOCabacCoder(TEncSbac* pcRDGoOnSbacCoder, TComSlice* pcSlice) ;
+  Void SAOProcess(TComPic* pPic, Bool* sliceEnabled, const Double *lambdas
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+                , Bool isPreDBFSamplesUsed
+#endif
+                );
+public: //methods
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+  Void getPreDBFStatistics(TComPic* pPic);
+#endif
+private: //methods
+  Void getStatistics(SAOStatData*** blkStats, TComPicYuv* orgYuv, TComPicYuv* srcYuv,TComPic* pPic
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+                   , Bool isCalculatePreDeblockSamples = false
+#endif
+                   );
+  Void decidePicParams(Bool* sliceEnabled, Int picTempLayer);
+  Void decideBlkParams(TComPic* pic, Bool* sliceEnabled, SAOStatData*** blkStats, TComPicYuv* srcYuv, TComPicYuv* resYuv, SAOBlkParam* reconParams, SAOBlkParam* codedParams);
+  Void getBlkStats(ComponentID compIdx, SAOStatData* statsDataTypes, Pel* srcBlk, Pel* orgBlk, Int srcStride, Int orgStride, Int width, Int height, Bool isLeftAvail,  Bool isRightAvail, Bool isAboveAvail, Bool isBelowAvail, Bool isAboveLeftAvail, Bool isAboveRightAvail, Bool isBelowLeftAvail, Bool isBelowRightAvail
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+                  , Bool isCalculatePreDeblockSamples
+#endif
+                  );
+  Void deriveModeNewRDO(Int ctuRsAddr, SAOBlkParam* mergeList[NUM_SAO_MERGE_TYPES], Bool* sliceEnabled, SAOStatData*** blkStats, SAOBlkParam& modeParam, Double& modeNormCost, TEncSbac** cabacCoderRDO, Int inCabacLabel);
+  Void deriveModeMergeRDO(Int ctuRsAddr, SAOBlkParam* mergeList[NUM_SAO_MERGE_TYPES], Bool* sliceEnabled, SAOStatData*** blkStats, SAOBlkParam& modeParam, Double& modeNormCost, TEncSbac** cabacCoderRDO, Int inCabacLabel);
+  Int64 getDistortion(ComponentID compIdx, Int typeIdc, Int typeAuxInfo, Int* offsetVal, SAOStatData& statData);
+  Void deriveOffsets(ComponentID compIdx, Int typeIdc, SAOStatData& statData, Int* quantOffsets, Int& typeAuxInfo);
+  inline Int64 estSaoDist(Int64 count, Int64 offset, Int64 diffSum, Int shift);
+  inline Int estIterOffset(Int typeIdx, Int classIdx, Double lambda, Int offsetInput, Int64 count, Int64 diffSum, Int shift, Int bitIncrease, Int64& bestDist, Double& bestCost, Int offsetTh );
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+  Void addPreDBFStatistics(SAOStatData*** blkStats);
+#endif
+private: //members
+  //for RDO
+  TEncSbac**             m_pppcRDSbacCoder;
+  TEncSbac*              m_pcRDGoOnSbacCoder;
+#if FAST_BIT_EST
+  TEncBinCABACCounter**  m_pppcBinCoderCABAC;
+#else
+  TEncBinCABAC**         m_pppcBinCoderCABAC;
+#endif
+  Double                 m_lambda[MAX_NUM_COMPONENT];
+
+  //statistics
+  SAOStatData***         m_statData; //[ctu][comp][classes]
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+  SAOStatData***         m_preDBFstatData;
+#endif
+#if SAO_ENCODING_CHOICE
+  Double                 m_saoDisabledRate[MAX_NUM_COMPONENT][MAX_TLAYER];
+#endif
+  Int                    m_skipLinesR[MAX_NUM_COMPONENT][NUM_SAO_NEW_TYPES];
+  Int                    m_skipLinesB[MAX_NUM_COMPONENT][NUM_SAO_NEW_TYPES];
+};
+
+
+//! \}
+
+#endif
Index: /tags/SHM-9.0/source/Lib/TLibEncoder/TEncSbac.cpp
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibEncoder/TEncSbac.cpp	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibEncoder/TEncSbac.cpp	(revision 1088)
@@ -0,0 +1,2038 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TEncSbac.cpp
+    \brief    SBAC encoder class
+*/
+
+#include "TEncTop.h"
+#include "TEncSbac.h"
+#include "TLibCommon/TComTU.h"
+
+#include <map>
+#include <algorithm>
+
+#if ENVIRONMENT_VARIABLE_DEBUG_AND_TEST
+#include "../TLibCommon/Debug.h"
+#endif
+
+
+//! \ingroup TLibEncoder
+//! \{
+
+// ====================================================================================================================
+// Constructor / destructor / create / destroy
+// ====================================================================================================================
+
+TEncSbac::TEncSbac()
+// new structure here
+: m_pcBitIf                            ( NULL )
+, m_pcSlice                            ( NULL )
+, m_pcBinIf                            ( 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)
+, 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,             NUM_QT_CBF_CTX_SETS,    NUM_QT_CBF_CTX_PER_SET               , 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,             NUM_CTX_LAST_FLAG_SETS, NUM_CTX_LAST_FLAG_XY                 , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCuCtxLastY                        ( 1,             NUM_CTX_LAST_FLAG_SETS, NUM_CTX_LAST_FLAG_XY                 , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCUOneSCModel                      ( 1,             1,                      NUM_ONE_FLAG_CTX                     , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCUAbsSCModel                      ( 1,             1,                      NUM_ABS_FLAG_CTX                     , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cMVPIdxSCModel                     ( 1,             1,                      NUM_MVP_IDX_CTX                      , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cSaoMergeSCModel                   ( 1,             1,                      NUM_SAO_MERGE_FLAG_CTX               , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cSaoTypeIdxSCModel                 ( 1,             1,                      NUM_SAO_TYPE_IDX_CTX                 , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cTransformSkipSCModel              ( 1,             MAX_NUM_CHANNEL_TYPE,   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)
+, m_explicitRdpcmFlagSCModel           ( 1,             MAX_NUM_CHANNEL_TYPE,   NUM_EXPLICIT_RDPCM_FLAG_CTX          , m_contextModels + m_numContextModels, m_numContextModels)
+, m_explicitRdpcmDirSCModel            ( 1,             MAX_NUM_CHANNEL_TYPE,   NUM_EXPLICIT_RDPCM_DIR_CTX           , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCrossComponentPredictionSCModel   ( 1,             1,                      NUM_CROSS_COMPONENT_PREDICTION_CTX   , m_contextModels + m_numContextModels, m_numContextModels)
+, m_ChromaQpAdjFlagSCModel             ( 1,             1,                      NUM_CHROMA_QP_ADJ_FLAG_CTX           , m_contextModels + m_numContextModels, m_numContextModels)
+, m_ChromaQpAdjIdcSCModel              ( 1,             1,                      NUM_CHROMA_QP_ADJ_IDC_CTX            , m_contextModels + m_numContextModels, m_numContextModels)
+{
+  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);
+  m_cCUPartSizeSCModel.initBuffer                 ( eSliceType, iQp, (UChar*)INIT_PART_SIZE );
+  m_cCUPredModeSCModel.initBuffer                 ( eSliceType, iQp, (UChar*)INIT_PRED_MODE );
+  m_cCUIntraPredSCModel.initBuffer                ( eSliceType, iQp, (UChar*)INIT_INTRA_PRED_MODE );
+  m_cCUChromaPredSCModel.initBuffer               ( eSliceType, iQp, (UChar*)INIT_CHROMA_PRED_MODE );
+  m_cCUInterDirSCModel.initBuffer                 ( eSliceType, iQp, (UChar*)INIT_INTER_DIR );
+  m_cCUMvdSCModel.initBuffer                      ( eSliceType, iQp, (UChar*)INIT_MVD );
+  m_cCURefPicSCModel.initBuffer                   ( eSliceType, iQp, (UChar*)INIT_REF_PIC );
+  m_cCUDeltaQpSCModel.initBuffer                  ( eSliceType, iQp, (UChar*)INIT_DQP );
+  m_cCUQtCbfSCModel.initBuffer                    ( eSliceType, iQp, (UChar*)INIT_QT_CBF );
+  m_cCUQtRootCbfSCModel.initBuffer                ( eSliceType, iQp, (UChar*)INIT_QT_ROOT_CBF );
+  m_cCUSigCoeffGroupSCModel.initBuffer            ( eSliceType, iQp, (UChar*)INIT_SIG_CG_FLAG );
+  m_cCUSigSCModel.initBuffer                      ( eSliceType, iQp, (UChar*)INIT_SIG_FLAG );
+  m_cCuCtxLastX.initBuffer                        ( eSliceType, iQp, (UChar*)INIT_LAST );
+  m_cCuCtxLastY.initBuffer                        ( eSliceType, iQp, (UChar*)INIT_LAST );
+  m_cCUOneSCModel.initBuffer                      ( eSliceType, iQp, (UChar*)INIT_ONE_FLAG );
+  m_cCUAbsSCModel.initBuffer                      ( eSliceType, iQp, (UChar*)INIT_ABS_FLAG );
+  m_cMVPIdxSCModel.initBuffer                     ( eSliceType, iQp, (UChar*)INIT_MVP_IDX );
+  m_cCUTransSubdivFlagSCModel.initBuffer          ( eSliceType, iQp, (UChar*)INIT_TRANS_SUBDIV_FLAG );
+  m_cSaoMergeSCModel.initBuffer                   ( eSliceType, iQp, (UChar*)INIT_SAO_MERGE_FLAG );
+  m_cSaoTypeIdxSCModel.initBuffer                 ( eSliceType, iQp, (UChar*)INIT_SAO_TYPE_IDX );
+  m_cTransformSkipSCModel.initBuffer              ( eSliceType, iQp, (UChar*)INIT_TRANSFORMSKIP_FLAG );
+  m_CUTransquantBypassFlagSCModel.initBuffer      ( eSliceType, iQp, (UChar*)INIT_CU_TRANSQUANT_BYPASS_FLAG );
+  m_explicitRdpcmFlagSCModel.initBuffer           ( eSliceType, iQp, (UChar*)INIT_EXPLICIT_RDPCM_FLAG);
+  m_explicitRdpcmDirSCModel.initBuffer            ( eSliceType, iQp, (UChar*)INIT_EXPLICIT_RDPCM_DIR);
+  m_cCrossComponentPredictionSCModel.initBuffer   ( eSliceType, iQp, (UChar*)INIT_CROSS_COMPONENT_PREDICTION  );
+  m_ChromaQpAdjFlagSCModel.initBuffer             ( eSliceType, iQp, (UChar*)INIT_CHROMA_QP_ADJ_FLAG );
+  m_ChromaQpAdjIdcSCModel.initBuffer              ( eSliceType, iQp, (UChar*)INIT_CHROMA_QP_ADJ_IDC );
+
+  for (UInt statisticIndex = 0; statisticIndex < RExt__GOLOMB_RICE_ADAPTATION_STATISTICS_SETS ; statisticIndex++)
+  {
+    m_golombRiceAdaptationStatistics[statisticIndex] = 0;
+  }
+
+  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);
+      curCost += m_cCUPartSizeSCModel.calcCost                 ( curSliceType, qp, (UChar*)INIT_PART_SIZE );
+      curCost += m_cCUPredModeSCModel.calcCost                 ( curSliceType, qp, (UChar*)INIT_PRED_MODE );
+      curCost += m_cCUIntraPredSCModel.calcCost                ( curSliceType, qp, (UChar*)INIT_INTRA_PRED_MODE );
+      curCost += m_cCUChromaPredSCModel.calcCost               ( curSliceType, qp, (UChar*)INIT_CHROMA_PRED_MODE );
+      curCost += m_cCUInterDirSCModel.calcCost                 ( curSliceType, qp, (UChar*)INIT_INTER_DIR );
+      curCost += m_cCUMvdSCModel.calcCost                      ( curSliceType, qp, (UChar*)INIT_MVD );
+      curCost += m_cCURefPicSCModel.calcCost                   ( curSliceType, qp, (UChar*)INIT_REF_PIC );
+      curCost += m_cCUDeltaQpSCModel.calcCost                  ( curSliceType, qp, (UChar*)INIT_DQP );
+      curCost += m_cCUQtCbfSCModel.calcCost                    ( curSliceType, qp, (UChar*)INIT_QT_CBF );
+      curCost += m_cCUQtRootCbfSCModel.calcCost                ( curSliceType, qp, (UChar*)INIT_QT_ROOT_CBF );
+      curCost += m_cCUSigCoeffGroupSCModel.calcCost            ( curSliceType, qp, (UChar*)INIT_SIG_CG_FLAG );
+      curCost += m_cCUSigSCModel.calcCost                      ( curSliceType, qp, (UChar*)INIT_SIG_FLAG );
+      curCost += m_cCuCtxLastX.calcCost                        ( curSliceType, qp, (UChar*)INIT_LAST );
+      curCost += m_cCuCtxLastY.calcCost                        ( curSliceType, qp, (UChar*)INIT_LAST );
+      curCost += m_cCUOneSCModel.calcCost                      ( curSliceType, qp, (UChar*)INIT_ONE_FLAG );
+      curCost += m_cCUAbsSCModel.calcCost                      ( curSliceType, qp, (UChar*)INIT_ABS_FLAG );
+      curCost += m_cMVPIdxSCModel.calcCost                     ( curSliceType, qp, (UChar*)INIT_MVP_IDX );
+      curCost += m_cCUTransSubdivFlagSCModel.calcCost          ( curSliceType, qp, (UChar*)INIT_TRANS_SUBDIV_FLAG );
+      curCost += m_cSaoMergeSCModel.calcCost                   ( curSliceType, qp, (UChar*)INIT_SAO_MERGE_FLAG );
+      curCost += m_cSaoTypeIdxSCModel.calcCost                 ( curSliceType, qp, (UChar*)INIT_SAO_TYPE_IDX );
+      curCost += m_cTransformSkipSCModel.calcCost              ( curSliceType, qp, (UChar*)INIT_TRANSFORMSKIP_FLAG );
+      curCost += m_CUTransquantBypassFlagSCModel.calcCost      ( curSliceType, qp, (UChar*)INIT_CU_TRANSQUANT_BYPASS_FLAG );
+      curCost += m_explicitRdpcmFlagSCModel.calcCost           ( curSliceType, qp, (UChar*)INIT_EXPLICIT_RDPCM_FLAG);
+      curCost += m_explicitRdpcmDirSCModel.calcCost            ( curSliceType, qp, (UChar*)INIT_EXPLICIT_RDPCM_DIR);
+      curCost += m_cCrossComponentPredictionSCModel.calcCost   ( curSliceType, qp, (UChar*)INIT_CROSS_COMPONENT_PREDICTION );
+      curCost += m_ChromaQpAdjFlagSCModel.calcCost             ( curSliceType, qp, (UChar*)INIT_CHROMA_QP_ADJ_FLAG );
+      curCost += m_ChromaQpAdjIdcSCModel.calcCost              ( curSliceType, qp, (UChar*)INIT_CHROMA_QP_ADJ_IDC );
+
+      if (curCost < bestCost)
+      {
+        bestSliceType = curSliceType;
+        bestCost      = curCost;
+      }
+    }
+    m_pcSlice->getPPS()->setEncCABACTableIdx( bestSliceType );
+  }
+  else
+  {
+    m_pcSlice->getPPS()->setEncCABACTableIdx( I_SLICE );
+  }
+}
+
+Void TEncSbac::codeVPS( TComVPS* pcVPS )
+{
+  assert (0);
+  return;
+}
+
+Void TEncSbac::codeSPS( TComSPS* pcSPS )
+{
+  assert (0);
+  return;
+}
+
+Void TEncSbac::codePPS( TComPPS* pcPPS 
+#if Q0048_CGS_3D_ASYMLUT
+  , TEnc3DAsymLUT * pc3DAsymLUT
+#endif
+  )
+{
+  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, const Bool useLimitedPrefixLength, const ChannelType channelType )
+{
+  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 if (useLimitedPrefixLength)
+  {
+    const UInt maximumPrefixLength = (32 - (COEF_REMAIN_BIN_REDUCTION + g_maxTrDynamicRange[channelType]));
+
+    UInt prefixLength = 0;
+    UInt suffixLength = MAX_UINT;
+    UInt codeValue    = (symbol >> rParam) - COEF_REMAIN_BIN_REDUCTION;
+
+    if (codeValue >= ((1 << maximumPrefixLength) - 1))
+    {
+      prefixLength = maximumPrefixLength;
+      suffixLength = g_maxTrDynamicRange[channelType] - rParam;
+    }
+    else
+    {
+      while (codeValue > ((2 << prefixLength) - 2))
+      {
+        prefixLength++;
+      }
+
+      suffixLength = prefixLength + 1; //+1 for the separator bit
+    }
+
+    const UInt suffix = codeValue - ((1 << prefixLength) - 1);
+
+    const UInt totalPrefixLength = prefixLength + COEF_REMAIN_BIN_REDUCTION;
+    const UInt prefix            = (1 << totalPrefixLength) - 1;
+    const UInt rParamBitMask     = (1 << rParam) - 1;
+
+    m_pcBinIf->encodeBinsEP(  prefix,                                        totalPrefixLength      ); //prefix
+    m_pcBinIf->encodeBinsEP(((suffix << rParam) | (symbol & rParamBitMask)), (suffixLength + rParam)); //separator, suffix, and rParam bits
+  }
+  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);
+  }
+}
+
+// SBAC RD
+Void  TEncSbac::load ( const TEncSbac* pSrc)
+{
+  this->xCopyFrom(pSrc);
+}
+
+Void  TEncSbac::loadIntraDirMode( const TEncSbac* pSrc, const ChannelType chType )
+{
+  m_pcBinIf->copyState( pSrc->m_pcBinIf );
+  if (isLuma(chType))
+    this->m_cCUIntraPredSCModel      .copyFrom( &pSrc->m_cCUIntraPredSCModel       );
+  else
+    this->m_cCUChromaPredSCModel     .copyFrom( &pSrc->m_cCUChromaPredSCModel      );
+}
+
+
+Void  TEncSbac::store( TEncSbac* pDest) const
+{
+  pDest->xCopyFrom( this );
+}
+
+
+Void TEncSbac::xCopyFrom( const TEncSbac* pSrc )
+{
+  m_pcBinIf->copyState( pSrc->m_pcBinIf );
+  xCopyContextsFrom(pSrc);
+}
+
+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);
+}
+
+Void TEncSbac::codePartSize( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  PartSize eSize         = pcCU->getPartitionSize( uiAbsPartIdx );
+
+  if ( pcCU->isIntra( uiAbsPartIdx ) )
+  {
+    if( uiDepth == g_uiMaxCUDepth - g_uiAddCUDepth )
+    {
+      m_pcBinIf->encodeBin( eSize == SIZE_2Nx2N? 1 : 0, m_cCUPartSizeSCModel.get( 0, 0, 0 ) );
+    }
+    return;
+  }
+
+  switch(eSize)
+  {
+    case SIZE_2Nx2N:
+    {
+      m_pcBinIf->encodeBin( 1, m_cCUPartSizeSCModel.get( 0, 0, 0) );
+      break;
+    }
+    case SIZE_2NxN:
+    case SIZE_2NxnU:
+    case SIZE_2NxnD:
+    {
+      m_pcBinIf->encodeBin( 0, m_cCUPartSizeSCModel.get( 0, 0, 0) );
+      m_pcBinIf->encodeBin( 1, m_cCUPartSizeSCModel.get( 0, 0, 1) );
+      if ( pcCU->getSlice()->getSPS()->getAMPAcc( uiDepth ) )
+      {
+        if (eSize == SIZE_2NxN)
+        {
+          m_pcBinIf->encodeBin(1, m_cCUPartSizeSCModel.get( 0, 0, 3 ));
+        }
+        else
+        {
+          m_pcBinIf->encodeBin(0, m_cCUPartSizeSCModel.get( 0, 0, 3 ));
+          m_pcBinIf->encodeBinEP((eSize == SIZE_2NxnU? 0: 1));
+        }
+      }
+      break;
+    }
+    case SIZE_Nx2N:
+    case SIZE_nLx2N:
+    case SIZE_nRx2N:
+    {
+      m_pcBinIf->encodeBin( 0, m_cCUPartSizeSCModel.get( 0, 0, 0) );
+      m_pcBinIf->encodeBin( 0, m_cCUPartSizeSCModel.get( 0, 0, 1) );
+
+      if( uiDepth == g_uiMaxCUDepth - g_uiAddCUDepth && !( pcCU->getWidth(uiAbsPartIdx) == 8 && pcCU->getHeight(uiAbsPartIdx) == 8 ) )
+      {
+        m_pcBinIf->encodeBin( 1, m_cCUPartSizeSCModel.get( 0, 0, 2) );
+      }
+
+      if ( pcCU->getSlice()->getSPS()->getAMPAcc( uiDepth ) )
+      {
+        if (eSize == SIZE_Nx2N)
+        {
+          m_pcBinIf->encodeBin(1, m_cCUPartSizeSCModel.get( 0, 0, 3 ));
+        }
+        else
+        {
+          m_pcBinIf->encodeBin(0, m_cCUPartSizeSCModel.get( 0, 0, 3 ));
+          m_pcBinIf->encodeBinEP((eSize == SIZE_nLx2N? 0: 1));
+        }
+      }
+      break;
+    }
+    case SIZE_NxN:
+    {
+      if( uiDepth == g_uiMaxCUDepth - g_uiAddCUDepth && !( pcCU->getWidth(uiAbsPartIdx) == 8 && pcCU->getHeight(uiAbsPartIdx) == 8 ) )
+      {
+        m_pcBinIf->encodeBin( 0, m_cCUPartSizeSCModel.get( 0, 0, 0) );
+        m_pcBinIf->encodeBin( 0, m_cCUPartSizeSCModel.get( 0, 0, 1) );
+        m_pcBinIf->encodeBin( 0, m_cCUPartSizeSCModel.get( 0, 0, 2) );
+      }
+      break;
+    }
+    default:
+    {
+      assert(0);
+      break;
+    }
+  }
+}
+
+
+/** code prediction mode
+ * \param pcCU
+ * \param uiAbsPartIdx
+ * \returns Void
+ */
+Void TEncSbac::codePredMode( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  // get context function is here
+  m_pcBinIf->encodeBin( pcCU->isIntra( uiAbsPartIdx ) ? 1 : 0, m_cCUPredModeSCModel.get( 0, 0, 0 ) );
+}
+
+Void TEncSbac::codeCUTransquantBypassFlag( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  UInt uiSymbol = pcCU->getCUTransquantBypass(uiAbsPartIdx);
+  m_pcBinIf->encodeBin( uiSymbol, m_CUTransquantBypassFlagSCModel.get( 0, 0, 0 ) );
+}
+
+/** 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 ) );
+  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");
+}
+
+/** 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 ) );
+
+  DTRACE_CABAC_VL( g_nSymbolCounter++ );
+  DTRACE_CABAC_T( "\tMergeFlag: " );
+  DTRACE_CABAC_V( uiSymbol );
+  DTRACE_CABAC_T( "\tAddress: " );
+  DTRACE_CABAC_V( pcCU->getCtuRsAddr() );
+  DTRACE_CABAC_T( "\tuiAbsPartIdx: " );
+  DTRACE_CABAC_V( uiAbsPartIdx );
+  DTRACE_CABAC_T( "\n" );
+}
+
+/** 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;
+      }
+    }
+  }
+  DTRACE_CABAC_VL( g_nSymbolCounter++ );
+  DTRACE_CABAC_T( "\tparseMergeIndex()" );
+  DTRACE_CABAC_T( "\tuiMRGIdx= " );
+  DTRACE_CABAC_V( pcCU->getMergeIndex( uiAbsPartIdx ) );
+  DTRACE_CABAC_T( "\n" );
+}
+
+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 );
+  m_pcBinIf->encodeBin( uiCurrSplitFlag, m_cCUSplitFlagSCModel.get( 0, 0, uiCtx ) );
+  DTRACE_CABAC_VL( g_nSymbolCounter++ )
+  DTRACE_CABAC_T( "\tSplitFlag\n" )
+  return;
+}
+
+Void TEncSbac::codeTransformSubdivFlag( UInt uiSymbol, UInt uiCtx )
+{
+  m_pcBinIf->encodeBin( uiSymbol, m_cCUTransSubdivFlagSCModel.get( 0, 0, uiCtx ) );
+  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" )
+}
+
+
+Void TEncSbac::codeIntraDirLumaAng( TComDataCU* pcCU, UInt absPartIdx, Bool isMultiple)
+{
+  UInt dir[4],j;
+  Int preds[4][NUM_MOST_PROBABLE_MODES] = {{-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()->getNumPartitionsInCtu() >> ( pcCU->getDepth(absPartIdx) << 1 ) ) >> 2;
+  for (j=0;j<partNum;j++)
+  {
+    dir[j] = pcCU->getIntraDir( CHANNEL_TYPE_LUMA, absPartIdx+partOffset*j );
+    predNum[j] = pcCU->getIntraDirPredictor(absPartIdx+partOffset*j, preds[j], COMPONENT_Y);
+    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 ) );
+  }
+  for (j=0;j<partNum;j++)
+  {
+    if(predIdx[j] != -1)
+    {
+      m_pcBinIf->encodeBinEP( predIdx[j] ? 1 : 0 );
+      if (predIdx[j])
+      {
+        m_pcBinIf->encodeBinEP( predIdx[j]-1 );
+      }
+    }
+    else
+    {
+      assert(predNum[j]>=3); // It is currently always 3!
+      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 );
+    }
+  }
+  return;
+}
+
+Void TEncSbac::codeIntraDirChroma( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  UInt uiIntraDirChroma = pcCU->getIntraDir( CHANNEL_TYPE_CHROMA, uiAbsPartIdx );
+
+  if( uiIntraDirChroma == DM_CHROMA_IDX )
+  {
+    m_pcBinIf->encodeBin( 0, m_cCUChromaPredSCModel.get( 0, 0, 0 ) );
+  }
+  else
+  {
+    m_pcBinIf->encodeBin( 1, m_cCUChromaPredSCModel.get( 0, 0, 0 ) );
+
+    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->encodeBinsEP( uiIntraDirChroma, 2 );
+  }
+
+  return;
+}
+
+
+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 ) );
+  }
+
+  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;
+      }
+    }
+  }
+  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::codeCrossComponentPrediction( TComTU &rTu, ComponentID compID )
+{
+  TComDataCU *pcCU = rTu.getCU();
+
+  if( isLuma(compID) || !pcCU->getSlice()->getPPS()->getUseCrossComponentPrediction() ) return;
+
+  const UInt uiAbsPartIdx = rTu.GetAbsPartIdxTU();
+
+  if (!pcCU->isIntra(uiAbsPartIdx) || (pcCU->getIntraDir( CHANNEL_TYPE_CHROMA, uiAbsPartIdx ) == DM_CHROMA_IDX))
+  {
+    DTRACE_CABAC_VL( g_nSymbolCounter++ )
+    DTRACE_CABAC_T("\tparseCrossComponentPrediction()")
+    DTRACE_CABAC_T( "\tAddr=" )
+    DTRACE_CABAC_V( compID )
+    DTRACE_CABAC_T( "\tuiAbsPartIdx=" )
+    DTRACE_CABAC_V( uiAbsPartIdx )
+
+    Int alpha = pcCU->getCrossComponentPredictionAlpha( uiAbsPartIdx, compID );
+    ContextModel *pCtx = m_cCrossComponentPredictionSCModel.get(0, 0) + ((compID == COMPONENT_Cr) ? (NUM_CROSS_COMPONENT_PREDICTION_CTX >> 1) : 0);
+    m_pcBinIf->encodeBin(((alpha != 0) ? 1 : 0), pCtx[0]);
+
+    if (alpha != 0)
+    {
+      static const Int log2AbsAlphaMinus1Table[8] = { 0, 1, 1, 2, 2, 2, 3, 3 };
+      assert(abs(alpha) <= 8);
+
+      if (abs(alpha)>1)
+      {
+        m_pcBinIf->encodeBin(1, pCtx[1]);
+        xWriteUnaryMaxSymbol( log2AbsAlphaMinus1Table[abs(alpha) - 1] - 1, (pCtx + 2), 1, 2 );
+      }
+      else
+      {
+        m_pcBinIf->encodeBin(0, pCtx[1]);
+      }
+      m_pcBinIf->encodeBin( ((alpha < 0) ? 1 : 0), pCtx[4] );
+    }
+    DTRACE_CABAC_T( "\tAlpha=" )
+    DTRACE_CABAC_V( pcCU->getCrossComponentPredictionAlpha( uiAbsPartIdx, compID ) )
+    DTRACE_CABAC_T( "\n" )
+  }
+}
+
+Void TEncSbac::codeDeltaQP( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  Int iDQp  = pcCU->getQP( uiAbsPartIdx ) - pcCU->getRefQP( uiAbsPartIdx );
+  
+#if REPN_FORMAT_IN_VPS  
+  Int qpBdOffsetY =  pcCU->getSlice()->getQpBDOffsetY();
+#else
+  Int qpBdOffsetY =  pcCU->getSlice()->getSPS()->getQpBDOffset(CHANNEL_TYPE_LUMA);
+#endif
+  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;
+}
+
+/** code chroma qp adjustment, converting from the internal table representation
+ * \returns Void
+ */
+Void TEncSbac::codeChromaQpAdjustment( TComDataCU* cu, UInt absPartIdx )
+{
+  Int internalIdc = cu->getChromaQpAdj( absPartIdx );
+  Int tableSize = cu->getSlice()->getPPS()->getChromaQpAdjTableSize();
+  /* internal_idc == 0 => flag = 0
+   * internal_idc > 1 => code idc value (if table size warrents) */
+  m_pcBinIf->encodeBin( internalIdc > 0, m_ChromaQpAdjFlagSCModel.get( 0, 0, 0 ) );
+
+  if (internalIdc > 0 && tableSize > 1)
+  {
+    xWriteUnaryMaxSymbol( internalIdc - 1, &m_ChromaQpAdjIdcSCModel.get( 0, 0, 0 ), 0, tableSize - 1 );
+  }
+}
+
+Void TEncSbac::codeQtCbf( TComTU &rTu, const ComponentID compID, const Bool lowestLevel )
+{
+  TComDataCU* pcCU = rTu.getCU();
+
+  const UInt absPartIdx   = rTu.GetAbsPartIdxTU(compID);
+  const UInt TUDepth      = rTu.GetTransformDepthRel();
+        UInt uiCtx        = pcCU->getCtxQtCbf( rTu, toChannelType(compID) );
+  const UInt contextSet   = toChannelType(compID);
+
+  const UInt width        = rTu.getRect(compID).width;
+  const UInt height       = rTu.getRect(compID).height;
+  const Bool canQuadSplit = (width >= (MIN_TU_SIZE * 2)) && (height >= (MIN_TU_SIZE * 2));
+
+  //             Since the CBF for chroma is coded at the highest level possible, if sub-TUs are
+  //             to be coded for a 4x8 chroma TU, their CBFs must be coded at the highest 4x8 level
+  //             (i.e. where luma TUs are 8x8 rather than 4x4)
+  //    ___ ___
+  //   |   |   | <- 4 x (8x8 luma + 4x8 4:2:2 chroma)
+  //   |___|___|    each quadrant has its own chroma CBF
+  //   |   |   | _ _ _ _
+  //   |___|___|        |
+  //   <--16--->        V
+  //                   _ _
+  //                  |_|_| <- 4 x 4x4 luma + 1 x 4x8 4:2:2 chroma
+  //                  |_|_|    no chroma CBF is coded - instead the parent CBF is inherited
+  //                  <-8->    if sub-TUs are present, their CBFs had to be coded at the parent level
+
+  const UInt lowestTUDepth = TUDepth + ((!lowestLevel && !canQuadSplit) ? 1 : 0); //unsplittable TUs inherit their parent's CBF
+
+  if ((width != height) && (lowestLevel || !canQuadSplit)) //if sub-TUs are present
+  {
+    const UInt subTUDepth        = lowestTUDepth + 1;                      //if this is the lowest level of the TU-tree, the sub-TUs are directly below. Otherwise, this must be the level above the lowest level (as specified above)
+    const UInt partIdxesPerSubTU = rTu.GetAbsPartIdxNumParts(compID) >> 1;
+
+    for (UInt subTU = 0; subTU < 2; subTU++)
+    {
+      const UInt subTUAbsPartIdx = absPartIdx + (subTU * partIdxesPerSubTU);
+      const UInt uiCbf           = pcCU->getCbf(subTUAbsPartIdx, compID, subTUDepth);
+
+      m_pcBinIf->encodeBin(uiCbf, m_cCUQtCbfSCModel.get(0, contextSet, uiCtx));
+
+      DTRACE_CABAC_VL( g_nSymbolCounter++ )
+      DTRACE_CABAC_T( "\tparseQtCbf()" )
+      DTRACE_CABAC_T( "\tsub-TU=" )
+      DTRACE_CABAC_V( subTU )
+      DTRACE_CABAC_T( "\tsymbol=" )
+      DTRACE_CABAC_V( uiCbf )
+      DTRACE_CABAC_T( "\tctx=" )
+      DTRACE_CABAC_V( uiCtx )
+      DTRACE_CABAC_T( "\tetype=" )
+      DTRACE_CABAC_V( compID )
+      DTRACE_CABAC_T( "\tuiAbsPartIdx=" )
+      DTRACE_CABAC_V( subTUAbsPartIdx )
+      DTRACE_CABAC_T( "\n" )
+    }
+  }
+  else
+  {
+    const UInt uiCbf = pcCU->getCbf( absPartIdx, compID, lowestTUDepth );
+    m_pcBinIf->encodeBin( uiCbf , m_cCUQtCbfSCModel.get( 0, contextSet, uiCtx ) );
+
+
+    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( compID )
+    DTRACE_CABAC_T( "\tuiAbsPartIdx=" )
+    DTRACE_CABAC_V( rTu.GetAbsPartIdxTU(compID) )
+    DTRACE_CABAC_T( "\n" )
+  }
+}
+
+
+Void TEncSbac::codeTransformSkipFlags (TComTU &rTu, ComponentID component )
+{
+  TComDataCU* pcCU=rTu.getCU();
+  const UInt uiAbsPartIdx=rTu.GetAbsPartIdxTU();
+
+  if (pcCU->getCUTransquantBypass(uiAbsPartIdx))
+  {
+    return;
+  }
+
+  if (!TUCompRectHasAssociatedTransformSkipFlag(rTu.getRect(component), pcCU->getSlice()->getPPS()->getTransformSkipLog2MaxSize()))
+  {
+    return;
+  }
+
+  UInt useTransformSkip = pcCU->getTransformSkip( uiAbsPartIdx,component);
+  m_pcBinIf->encodeBin( useTransformSkip, m_cTransformSkipSCModel.get( 0, toChannelType(component), 0 ) );
+
+  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->getCtuRsAddr() )
+  DTRACE_CABAC_T( "\tetype=" )
+  DTRACE_CABAC_V( component )
+  DTRACE_CABAC_T( "\tuiAbsPartIdx=" )
+  DTRACE_CABAC_V( rTu.GetAbsPartIdxTU() )
+  DTRACE_CABAC_T( "\n" )
+}
+
+
+/** 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 (writePCMSampleFlag)
+  {
+    m_pcBinIf->encodePCMAlignBits();
+
+    const UInt minCoeffSizeY = pcCU->getPic()->getMinCUWidth() * pcCU->getPic()->getMinCUHeight();
+    const UInt offsetY       = minCoeffSizeY * uiAbsPartIdx;
+    for (UInt ch=0; ch < pcCU->getPic()->getNumberValidComponents(); ch++)
+    {
+      const ComponentID compID = ComponentID(ch);
+      const UInt offset = offsetY >> (pcCU->getPic()->getComponentScaleX(compID) + pcCU->getPic()->getComponentScaleY(compID));
+      Pel * pPCMSample  = pcCU->getPCMSample(compID) + offset;
+      const UInt width  = pcCU->getWidth (uiAbsPartIdx) >> pcCU->getPic()->getComponentScaleX(compID);
+      const UInt height = pcCU->getHeight(uiAbsPartIdx) >> pcCU->getPic()->getComponentScaleY(compID);
+      const UInt sampleBits = pcCU->getSlice()->getSPS()->getPCMBitDepth(toChannelType(compID));
+      for (UInt y=0; y<height; y++)
+      {
+        for (UInt x=0; x<width; x++)
+        {
+          UInt sample = pPCMSample[x];
+          m_pcBinIf->xWritePCMCode(sample, sampleBits);
+        }
+        pPCMSample += width;
+      }
+    }
+
+    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 ) );
+  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" )
+}
+
+Void TEncSbac::codeQtCbfZero( TComTU & rTu, const ChannelType chType )
+{
+  // 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 = rTu.getCU()->getCtxQtCbf( rTu, chType );
+
+  m_pcBinIf->encodeBin( uiCbf , m_cCUQtCbfSCModel.get( 0, chType, 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, ComponentID component, UInt uiScanIdx )
+{
+  // swap
+  if( uiScanIdx == SCAN_VER )
+  {
+    swap( uiPosX, uiPosY );
+    swap( width,  height );
+  }
+
+  UInt uiCtxLast;
+  UInt uiGroupIdxX    = g_uiGroupIdx[ uiPosX ];
+  UInt uiGroupIdxY    = g_uiGroupIdx[ uiPosY ];
+
+  ContextModel *pCtxX = m_cCuCtxLastX.get( 0, toChannelType(component) );
+  ContextModel *pCtxY = m_cCuCtxLastY.get( 0, toChannelType(component) );
+
+  Int blkSizeOffsetX, blkSizeOffsetY, shiftX, shiftY;
+  getLastSignificantContextParameters(component, width, height, blkSizeOffsetX, blkSizeOffsetY, shiftX, shiftY);
+
+  //------------------
+
+  // 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) ) );
+  }
+
+  // EP-coded part
+
+  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( TComTU &rTu, TCoeff* pcCoef, const ComponentID compID )
+{
+  TComDataCU* pcCU=rTu.getCU();
+  const UInt uiAbsPartIdx=rTu.GetAbsPartIdxTU(compID);
+  const TComRectangle &tuRect=rTu.getRect(compID);
+  const UInt uiWidth=tuRect.width;
+  const UInt uiHeight=tuRect.height;
+
+  DTRACE_CABAC_VL( g_nSymbolCounter++ )
+  DTRACE_CABAC_T( "\tparseCoeffNxN()\teType=" )
+  DTRACE_CABAC_V( compID )
+  DTRACE_CABAC_T( "\twidth=" )
+  DTRACE_CABAC_V( uiWidth )
+  DTRACE_CABAC_T( "\theight=" )
+  DTRACE_CABAC_V( uiHeight )
+  DTRACE_CABAC_T( "\tdepth=" )
+//  DTRACE_CABAC_V( rTu.GetTransformDepthTotalAdj(compID) )
+  DTRACE_CABAC_V( rTu.GetTransformDepthTotal() )
+  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->getCtuRsAddr() )
+  DTRACE_CABAC_T( "\tinCU-X=" )
+//  DTRACE_CABAC_V( g_auiRasterToPelX[ g_auiZscanToRaster[uiAbsPartIdx] ] )
+  DTRACE_CABAC_V( g_auiRasterToPelX[ g_auiZscanToRaster[rTu.GetAbsPartIdxTU(compID)] ] )
+  DTRACE_CABAC_T( "\tinCU-Y=" )
+// DTRACE_CABAC_V( g_auiRasterToPelY[ g_auiZscanToRaster[uiAbsPartIdx] ] )
+  DTRACE_CABAC_V( g_auiRasterToPelY[ g_auiZscanToRaster[rTu.GetAbsPartIdxTU(compID)] ] )
+  DTRACE_CABAC_T( "\tpredmode=" )
+  DTRACE_CABAC_V(  pcCU->getPredictionMode( uiAbsPartIdx ) )
+  DTRACE_CABAC_T( "\n" )
+
+  //--------------------------------------------------------------------------------------------------
+
+  if( uiWidth > m_pcSlice->getSPS()->getMaxTrSize() )
+  {
+    std::cerr << "ERROR: codeCoeffNxN was passed a TU with dimensions larger than the maximum allowed size" << std::endl;
+    assert(false);
+    exit(1);
+  }
+
+  // compute number of significant coefficients
+  UInt uiNumSig = TEncEntropy::countNonZeroCoeffs(pcCoef, uiWidth * uiHeight);
+
+  if ( uiNumSig == 0 )
+  {
+    std::cerr << "ERROR: codeCoeffNxN called for empty TU!" << std::endl;
+    assert(false);
+    exit(1);
+  }
+
+  //--------------------------------------------------------------------------------------------------
+
+  //set parameters
+
+  const ChannelType  chType            = toChannelType(compID);
+  const UInt         uiLog2BlockWidth  = g_aucConvertToBit[ uiWidth  ] + 2;
+  const UInt         uiLog2BlockHeight = g_aucConvertToBit[ uiHeight ] + 2;
+
+  const ChannelType  channelType       = toChannelType(compID);
+  const Bool         extendedPrecision = pcCU->getSlice()->getSPS()->getUseExtendedPrecision();
+
+  const Bool         alignCABACBeforeBypass = pcCU->getSlice()->getSPS()->getAlignCABACBeforeBypass();
+
+  Bool beValid;
+
+  {
+    Int uiIntraMode = -1;
+    const Bool       bIsLuma = isLuma(compID);
+    Int isIntra = pcCU->isIntra(uiAbsPartIdx) ? 1 : 0;
+    if ( isIntra )
+    {
+      uiIntraMode = pcCU->getIntraDir( toChannelType(compID), uiAbsPartIdx );
+
+      uiIntraMode = (uiIntraMode==DM_CHROMA_IDX && !bIsLuma) ? pcCU->getIntraDir(CHANNEL_TYPE_LUMA, getChromasCorrespondingPULumaIdx(uiAbsPartIdx, rTu.GetChromaFormat())) : uiIntraMode;
+      uiIntraMode = ((rTu.GetChromaFormat() == CHROMA_422) && !bIsLuma) ? g_chroma422IntraAngleMappingTable[uiIntraMode] : uiIntraMode;
+    }
+
+    Int transformSkip = pcCU->getTransformSkip( uiAbsPartIdx,compID) ? 1 : 0;
+    Bool rdpcm_lossy = ( transformSkip && isIntra && ( (uiIntraMode == HOR_IDX) || (uiIntraMode == VER_IDX) ) ) && pcCU->isRDPCMEnabled(uiAbsPartIdx);
+
+    if ( (pcCU->getCUTransquantBypass(uiAbsPartIdx)) || rdpcm_lossy )
+    {
+      beValid = false;
+      if ( (!pcCU->isIntra(uiAbsPartIdx)) && pcCU->isRDPCMEnabled(uiAbsPartIdx))
+        codeExplicitRdpcmMode( rTu, compID);
+    }
+    else
+    {
+      beValid = pcCU->getSlice()->getPPS()->getSignHideFlag() > 0;
+    }
+  }
+
+  //--------------------------------------------------------------------------------------------------
+
+  if(pcCU->getSlice()->getPPS()->getUseTransformSkip())
+  {
+    codeTransformSkipFlags(rTu, compID);
+    if(pcCU->getTransformSkip(uiAbsPartIdx, compID) && !pcCU->isIntra(uiAbsPartIdx) && pcCU->isRDPCMEnabled(uiAbsPartIdx))
+    {
+      //  This TU has coefficients and is transform skipped. Check whether is inter coded and if yes encode the explicit RDPCM mode
+      codeExplicitRdpcmMode( rTu, compID);
+
+      if(pcCU->getExplicitRdpcmMode(compID, uiAbsPartIdx) != RDPCM_OFF)
+      {
+        //  Sign data hiding is avoided for horizontal and vertical explicit RDPCM modes
+        beValid = false;
+      }
+    }
+  }
+
+  //--------------------------------------------------------------------------------------------------
+
+  const Bool  bUseGolombRiceParameterAdaptation = pcCU->getSlice()->getSPS()->getUseGolombRiceParameterAdaptation();
+        UInt &currentGolombRiceStatistic        = m_golombRiceAdaptationStatistics[rTu.getGolombRiceStatisticsIndex(compID)];
+
+  //select scans
+  TUEntropyCodingParameters codingParameters;
+  getTUEntropyCodingParameters(codingParameters, rTu, compID);
+
+  //----- encode significance map -----
+
+  // Find position of last coefficient
+  Int scanPosLast = -1;
+  Int posLast;
+
+
+  UInt uiSigCoeffGroupFlag[ MLS_GRP_NUM ];
+
+  memset( uiSigCoeffGroupFlag, 0, sizeof(UInt) * MLS_GRP_NUM );
+  do
+  {
+    posLast = codingParameters.scan[ ++scanPosLast ];
+
+    if( pcCoef[ posLast ] != 0 )
+    {
+      // get L1 sig map
+      UInt uiPosY   = posLast >> uiLog2BlockWidth;
+      UInt uiPosX   = posLast - ( uiPosY << uiLog2BlockWidth );
+
+      UInt uiBlkIdx = (codingParameters.widthInGroups * (uiPosY >> MLS_CG_LOG2_HEIGHT)) + (uiPosX >> MLS_CG_LOG2_WIDTH);
+      uiSigCoeffGroupFlag[ uiBlkIdx ] = 1;
+
+      uiNumSig--;
+    }
+  }
+  while ( uiNumSig > 0 );
+
+  // Code position of last coefficient
+  Int posLastY = posLast >> uiLog2BlockWidth;
+  Int posLastX = posLast - ( posLastY << uiLog2BlockWidth );
+  codeLastSignificantXY(posLastX, posLastY, uiWidth, uiHeight, compID, codingParameters.scanType);
+
+  //===== code significance flag =====
+  ContextModel * const baseCoeffGroupCtx = m_cCUSigCoeffGroupSCModel.get( 0, chType );
+  ContextModel * const baseCtx = m_cCUSigSCModel.get( 0, 0 ) + getSignificanceMapContextOffset(compID);
+
+  const Int  iLastScanSet  = scanPosLast >> MLS_CG_SIZE;
+
+  UInt c1                  = 1;
+  UInt uiGoRiceParam       = 0;
+  Int  iScanPosSig         = scanPosLast;
+
+  for( Int iSubSet = iLastScanSet; iSubSet >= 0; iSubSet-- )
+  {
+    Int numNonZero = 0;
+    Int  iSubPos   = iSubSet << MLS_CG_SIZE;
+    uiGoRiceParam  = currentGolombRiceStatistic / RExt__GOLOMB_RICE_INCREMENT_DIVISOR;
+    Bool updateGolombRiceStatistics = bUseGolombRiceParameterAdaptation; //leave the statistics at 0 when not using the adaptation system
+    UInt coeffSigns = 0;
+
+    Int absCoeff[1 << MLS_CG_SIZE];
+
+    Int lastNZPosInCG  = -1;
+    Int firstNZPosInCG = 1 << MLS_CG_SIZE;
+
+    Bool escapeDataPresentInGroup = false;
+
+    if( iScanPosSig == scanPosLast )
+    {
+      absCoeff[ 0 ] = Int(abs( pcCoef[ posLast ] ));
+      coeffSigns    = ( pcCoef[ posLast ] < 0 );
+      numNonZero    = 1;
+      lastNZPosInCG  = iScanPosSig;
+      firstNZPosInCG = iScanPosSig;
+      iScanPosSig--;
+    }
+
+    // encode significant_coeffgroup_flag
+    Int iCGBlkPos = codingParameters.scanCG[ iSubSet ];
+    Int iCGPosY   = iCGBlkPos / codingParameters.widthInGroups;
+    Int iCGPosX   = iCGBlkPos - (iCGPosY * codingParameters.widthInGroups);
+
+    if( iSubSet == iLastScanSet || iSubSet == 0)
+    {
+      uiSigCoeffGroupFlag[ iCGBlkPos ] = 1;
+    }
+    else
+    {
+      UInt uiSigCoeffGroup   = (uiSigCoeffGroupFlag[ iCGBlkPos ] != 0);
+      UInt uiCtxSig  = TComTrQuant::getSigCoeffGroupCtxInc( uiSigCoeffGroupFlag, iCGPosX, iCGPosY, codingParameters.widthInGroups, codingParameters.heightInGroups );
+      m_pcBinIf->encodeBin( uiSigCoeffGroup, baseCoeffGroupCtx[ uiCtxSig ] );
+    }
+
+    // encode significant_coeff_flag
+    if( uiSigCoeffGroupFlag[ iCGBlkPos ] )
+    {
+      const Int patternSigCtx = TComTrQuant::calcPatternSigCtx(uiSigCoeffGroupFlag, iCGPosX, iCGPosY, codingParameters.widthInGroups, codingParameters.heightInGroups);
+
+      UInt uiBlkPos, uiSig, uiCtxSig;
+      for( ; iScanPosSig >= iSubPos; iScanPosSig-- )
+      {
+        uiBlkPos  = codingParameters.scan[ iScanPosSig ];
+        uiSig     = (pcCoef[ uiBlkPos ] != 0);
+        if( iScanPosSig > iSubPos || iSubSet == 0 || numNonZero )
+        {
+          uiCtxSig  = TComTrQuant::getSigCtxInc( patternSigCtx, codingParameters, iScanPosSig, uiLog2BlockWidth, uiLog2BlockHeight, chType );
+          m_pcBinIf->encodeBin( uiSig, baseCtx[ uiCtxSig ] );
+        }
+        if( uiSig )
+        {
+          absCoeff[ numNonZero ] = Int(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 );
+
+      const UInt uiCtxSet = getContextSetIndex(compID, iSubSet, (c1 == 0));
+      c1 = 1;
+
+      ContextModel *baseCtxMod = m_cCUOneSCModel.get( 0, 0 ) + (NUM_ONE_FLAG_CTX_PER_SET * 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 a greater-than-one has been encountered already this group
+          {
+            escapeDataPresentInGroup = true;
+          }
+        }
+        else if( (c1 < 3) && (c1 > 0) )
+        {
+          c1++;
+        }
+      }
+
+      if (c1 == 0)
+      {
+        baseCtxMod = m_cCUAbsSCModel.get( 0, 0 ) + (NUM_ABS_FLAG_CTX_PER_SET * uiCtxSet);
+        if ( firstC2FlagIdx != -1)
+        {
+          UInt symbol = absCoeff[ firstC2FlagIdx ] > 2;
+          m_pcBinIf->encodeBin( symbol, baseCtxMod[0] );
+          if (symbol != 0)
+          {
+            escapeDataPresentInGroup = true;
+          }
+        }
+      }
+
+      escapeDataPresentInGroup = escapeDataPresentInGroup || (numNonZero > C1FLAG_NUMBER);
+
+      if (escapeDataPresentInGroup && alignCABACBeforeBypass)
+      {
+        m_pcBinIf->align();
+      }
+
+      if( beValid && signHidden )
+      {
+        m_pcBinIf->encodeBinsEP( (coeffSigns >> 1), numNonZero-1 );
+      }
+      else
+      {
+        m_pcBinIf->encodeBinsEP( coeffSigns, numNonZero );
+      }
+
+      Int iFirstCoeff2 = 1;
+      if (escapeDataPresentInGroup)
+      {
+        for ( Int idx = 0; idx < numNonZero; idx++ )
+        {
+          UInt baseLevel  = (idx < C1FLAG_NUMBER)? (2 + iFirstCoeff2 ) : 1;
+
+          if( absCoeff[ idx ] >= baseLevel)
+          {
+            const UInt escapeCodeValue = absCoeff[idx] - baseLevel;
+
+            xWriteCoefRemainExGolomb( escapeCodeValue, uiGoRiceParam, extendedPrecision, channelType );
+
+            if (absCoeff[idx] > (3 << uiGoRiceParam))
+            {
+              uiGoRiceParam = bUseGolombRiceParameterAdaptation ? (uiGoRiceParam + 1) : (std::min<UInt>((uiGoRiceParam + 1), 4));
+            }
+
+            if (updateGolombRiceStatistics)
+            {
+              const UInt initialGolombRiceParameter = currentGolombRiceStatistic / RExt__GOLOMB_RICE_INCREMENT_DIVISOR;
+
+              if (escapeCodeValue >= (3 << initialGolombRiceParameter))
+              {
+                currentGolombRiceStatistic++;
+              }
+              else if (((escapeCodeValue * 2) < (1 << initialGolombRiceParameter)) && (currentGolombRiceStatistic > 0))
+              {
+                currentGolombRiceStatistic--;
+              }
+
+              updateGolombRiceStatistics = false;
+            }
+          }
+
+          if(absCoeff[ idx ] >= 2)
+          {
+            iFirstCoeff2 = 0;
+          }
+        }
+      }
+    }
+  }
+#if ENVIRONMENT_VARIABLE_DEBUG_AND_TEST
+  printSBACCoeffData(posLastX, posLastY, uiWidth, uiHeight, compID, uiAbsPartIdx, codingParameters.scanType, pcCoef, g_bFinalEncode);
+#endif
+
+  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 )
+{
+  m_pcBinIf->encodeBin(((uiCode == 0) ? 0 : 1),  m_cSaoMergeSCModel.get( 0, 0, 0 ));
+}
+
+/** Code SAO type index
+ * \param uiCode
+ */
+Void TEncSbac::codeSaoTypeIdx       ( UInt uiCode)
+{
+  if (uiCode == 0)
+  {
+    m_pcBinIf->encodeBin( 0, m_cSaoTypeIdxSCModel.get( 0, 0, 0 ) );
+  }
+  else
+  {
+    m_pcBinIf->encodeBin( 1, m_cSaoTypeIdxSCModel.get( 0, 0, 0 ) );
+    m_pcBinIf->encodeBinEP( uiCode == 1 ? 0 : 1 );
+  }
+}
+#if SVC_EXTENSION
+Void TEncSbac::codeSAOOffsetParam(ComponentID compIdx, SAOOffset& ctbParam, Bool sliceEnabled, UInt* saoMaxOffsetQVal)
+#else
+Void TEncSbac::codeSAOOffsetParam(ComponentID compIdx, SAOOffset& ctbParam, Bool sliceEnabled)
+#endif
+{
+  UInt uiSymbol;
+  if(!sliceEnabled)
+  {
+    assert(ctbParam.modeIdc == SAO_MODE_OFF);
+    return;
+  }
+  const Bool bIsFirstCompOfChType = (getFirstComponentOfChannel(toChannelType(compIdx)) == compIdx);
+
+  //type
+  if(bIsFirstCompOfChType)
+  {
+    //sao_type_idx_luma or sao_type_idx_chroma
+    if(ctbParam.modeIdc == SAO_MODE_OFF)
+    {
+      uiSymbol =0;
+    }
+    else if(ctbParam.typeIdc == SAO_TYPE_BO) //BO
+    {
+      uiSymbol = 1;
+    }
+    else
+    {
+      assert(ctbParam.typeIdc < SAO_TYPE_START_BO); //EO
+      uiSymbol = 2;
+    }
+    codeSaoTypeIdx(uiSymbol);
+  }
+
+  if(ctbParam.modeIdc == SAO_MODE_NEW)
+  {
+    Int numClasses = (ctbParam.typeIdc == SAO_TYPE_BO)?4:NUM_SAO_EO_CLASSES;
+    Int offset[4];
+    Int k=0;
+    for(Int i=0; i< numClasses; i++)
+    {
+      if(ctbParam.typeIdc != SAO_TYPE_BO && i == SAO_CLASS_EO_PLAIN)
+      {
+        continue;
+      }
+      Int classIdx = (ctbParam.typeIdc == SAO_TYPE_BO)?(  (ctbParam.typeAuxInfo+i)% NUM_SAO_BO_CLASSES   ):i;
+      offset[k] = ctbParam.offset[classIdx];
+      k++;
+    }
+
+    for(Int i=0; i< 4; i++)
+    {
+#if SVC_EXTENSION
+      codeSaoMaxUvlc((offset[i]<0)?(-offset[i]):(offset[i]),  saoMaxOffsetQVal[compIdx] ); //sao_offset_abs
+#else
+      codeSaoMaxUvlc((offset[i]<0)?(-offset[i]):(offset[i]),  g_saoMaxOffsetQVal[compIdx] ); //sao_offset_abs
+#endif
+    }
+
+
+    if(ctbParam.typeIdc == SAO_TYPE_BO)
+    {
+      for(Int i=0; i< 4; i++)
+      {
+        if(offset[i] != 0)
+        {
+          codeSAOSign((offset[i]< 0)?1:0);
+        }
+      }
+
+      codeSaoUflc(NUM_SAO_BO_CLASSES_LOG2, ctbParam.typeAuxInfo ); //sao_band_position
+    }
+    else //EO
+    {
+      if(bIsFirstCompOfChType)
+      {
+        assert(ctbParam.typeIdc - SAO_TYPE_START_EO >=0);
+        codeSaoUflc(NUM_SAO_EO_TYPES_LOG2, ctbParam.typeIdc - SAO_TYPE_START_EO ); //sao_eo_class_luma or sao_eo_class_chroma
+      }
+    }
+
+  }
+}
+
+
+Void TEncSbac::codeSAOBlkParam(SAOBlkParam& saoBlkParam
+#if SVC_EXTENSION
+                              , UInt* saoMaxOffsetQVal
+#endif
+                              , Bool* sliceEnabled
+                              , Bool leftMergeAvail
+                              , Bool aboveMergeAvail
+                              , Bool onlyEstMergeInfo // = false
+                              )
+{
+
+  Bool isLeftMerge = false;
+  Bool isAboveMerge= false;
+
+  if(leftMergeAvail)
+  {
+    isLeftMerge = ((saoBlkParam[COMPONENT_Y].modeIdc == SAO_MODE_MERGE) && (saoBlkParam[COMPONENT_Y].typeIdc == SAO_MERGE_LEFT));
+    codeSaoMerge( isLeftMerge?1:0  ); //sao_merge_left_flag
+  }
+
+  if( aboveMergeAvail && !isLeftMerge)
+  {
+    isAboveMerge = ((saoBlkParam[COMPONENT_Y].modeIdc == SAO_MODE_MERGE) && (saoBlkParam[COMPONENT_Y].typeIdc == SAO_MERGE_ABOVE));
+    codeSaoMerge( isAboveMerge?1:0  ); //sao_merge_left_flag
+  }
+
+  if(onlyEstMergeInfo)
+  {
+    return; //only for RDO
+  }
+
+  if(!isLeftMerge && !isAboveMerge) //not merge mode
+  {
+    for(Int compIdx=0; compIdx < MAX_NUM_COMPONENT; compIdx++)
+    {
+#if SVC_EXTENSION
+      codeSAOOffsetParam(ComponentID(compIdx), saoBlkParam[compIdx], sliceEnabled[compIdx], saoMaxOffsetQVal);
+#else
+      codeSAOOffsetParam(ComponentID(compIdx), saoBlkParam[compIdx], sliceEnabled[compIdx]);
+#endif
+    }
+  }
+}
+
+/*!
+ ****************************************************************************
+ * \brief
+ *   estimate bit cost for CBP, significant map and significant coefficients
+ ****************************************************************************
+ */
+Void TEncSbac::estBit( estBitsSbacStruct* pcEstBitsSbac, Int width, Int height, ChannelType chType )
+{
+  estCBFBit( pcEstBitsSbac );
+
+  estSignificantCoeffGroupMapBit( pcEstBitsSbac, chType );
+
+  // encode significance map
+  estSignificantMapBit( pcEstBitsSbac, width, height, chType );
+
+  // encode last significant position
+  estLastSignificantPositionBit( pcEstBitsSbac, width, height, chType );
+
+  // encode significant coefficients
+  estSignificantCoefficientsBit( pcEstBitsSbac, chType );
+
+  memcpy(pcEstBitsSbac->golombRiceAdaptationStatistics, m_golombRiceAdaptationStatistics, (sizeof(UInt) * RExt__GOLOMB_RICE_ADAPTATION_STATISTICS_SETS));
+}
+
+/*!
+ ****************************************************************************
+ * \brief
+ *    estimate bit cost for each CBP bit
+ ****************************************************************************
+ */
+Void TEncSbac::estCBFBit( estBitsSbacStruct* pcEstBitsSbac )
+{
+  ContextModel *pCtx = m_cCUQtCbfSCModel.get( 0 );
+
+  for( UInt uiCtxInc = 0; uiCtxInc < (NUM_QT_CBF_CTX_SETS * NUM_QT_CBF_CTX_PER_SET); 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, ChannelType chType )
+{
+  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, chType, ctxIdx ).getEntropyBits( uiBin );
+    }
+  }
+}
+
+
+/*!
+ ****************************************************************************
+ * \brief
+ *    estimate SAMBAC bit cost for significant coefficient map
+ ****************************************************************************
+ */
+Void TEncSbac::estSignificantMapBit( estBitsSbacStruct* pcEstBitsSbac, Int width, Int height, ChannelType chType )
+{
+  //--------------------------------------------------------------------------------------------------
+
+  //set up the number of channels and context variables
+
+  const UInt firstComponent = ((isLuma(chType)) ? (COMPONENT_Y) : (COMPONENT_Cb));
+  const UInt lastComponent  = ((isLuma(chType)) ? (COMPONENT_Y) : (COMPONENT_Cb));
+
+  //----------------------------------------------------------
+
+  Int firstCtx = MAX_INT;
+  Int numCtx   = MAX_INT;
+
+  if      ((width == 4) && (height == 4))
+  {
+    firstCtx = significanceMapContextSetStart[chType][CONTEXT_TYPE_4x4];
+    numCtx   = significanceMapContextSetSize [chType][CONTEXT_TYPE_4x4];
+  }
+  else if ((width == 8) && (height == 8))
+  {
+    firstCtx = significanceMapContextSetStart[chType][CONTEXT_TYPE_8x8];
+    numCtx   = significanceMapContextSetSize [chType][CONTEXT_TYPE_8x8];
+  }
+  else
+  {
+    firstCtx = significanceMapContextSetStart[chType][CONTEXT_TYPE_NxN];
+    numCtx   = significanceMapContextSetSize [chType][CONTEXT_TYPE_NxN];
+  }
+
+  //--------------------------------------------------------------------------------------------------
+
+  //fill the data for the significace map
+
+  for (UInt component = firstComponent; component <= lastComponent; component++)
+  {
+    const UInt contextOffset = getSignificanceMapContextOffset(ComponentID(component));
+
+    if (firstCtx > 0)
+    {
+      for( UInt bin = 0; bin < 2; bin++ ) //always get the DC
+      {
+        pcEstBitsSbac->significantBits[ contextOffset ][ bin ] = m_cCUSigSCModel.get( 0, 0, contextOffset ).getEntropyBits( bin );
+      }
+    }
+
+    // This could be made optional, but would require this function to have knowledge of whether the
+    // TU is transform-skipped or transquant-bypassed and whether the SPS flag is set
+    for( UInt bin = 0; bin < 2; bin++ )
+    {
+      const Int ctxIdx = significanceMapContextSetStart[chType][CONTEXT_TYPE_SINGLE];
+      pcEstBitsSbac->significantBits[ contextOffset + ctxIdx ][ bin ] = m_cCUSigSCModel.get( 0, 0, (contextOffset + ctxIdx) ).getEntropyBits( bin );
+    }
+
+    for ( Int ctxIdx = firstCtx; ctxIdx < firstCtx + numCtx; ctxIdx++ )
+    {
+      for( UInt uiBin = 0; uiBin < 2; uiBin++ )
+      {
+        pcEstBitsSbac->significantBits[ contextOffset + ctxIdx ][ uiBin ] = m_cCUSigSCModel.get(  0, 0, (contextOffset + ctxIdx) ).getEntropyBits( uiBin );
+      }
+    }
+  }
+
+  //--------------------------------------------------------------------------------------------------
+}
+
+
+/*!
+ ****************************************************************************
+ * \brief
+ *    estimate bit cost of significant coefficient
+ ****************************************************************************
+ */
+
+Void TEncSbac::estLastSignificantPositionBit( estBitsSbacStruct* pcEstBitsSbac, Int width, Int height, ChannelType chType )
+{
+  //--------------------------------------------------------------------------------------------------.
+
+  //set up the number of channels
+
+  const UInt firstComponent = ((isLuma(chType)) ? (COMPONENT_Y) : (COMPONENT_Cb));
+  const UInt lastComponent  = ((isLuma(chType)) ? (COMPONENT_Y) : (COMPONENT_Cb));
+
+  //--------------------------------------------------------------------------------------------------
+
+  //fill the data for the last-significant-coefficient position
+
+  for (UInt componentIndex = firstComponent; componentIndex <= lastComponent; componentIndex++)
+  {
+    const ComponentID component = ComponentID(componentIndex);
+
+    Int iBitsX = 0, iBitsY = 0;
+
+    Int blkSizeOffsetX, blkSizeOffsetY, shiftX, shiftY;
+    getLastSignificantContextParameters(ComponentID(component), width, height, blkSizeOffsetX, blkSizeOffsetY, shiftX, shiftY);
+
+    Int ctx;
+
+    const ChannelType channelType = toChannelType(ComponentID(component));
+
+    ContextModel *const pCtxX = m_cCuCtxLastX.get( 0, channelType );
+    ContextModel *const pCtxY = m_cCuCtxLastY.get( 0, channelType );
+    Int          *const lastXBitsArray = pcEstBitsSbac->lastXBits[channelType];
+    Int          *const lastYBitsArray = pcEstBitsSbac->lastYBits[channelType];
+
+    //------------------------------------------------
+
+    //X-coordinate
+
+    for (ctx = 0; ctx < g_uiGroupIdx[ width - 1 ]; ctx++)
+    {
+      Int ctxOffset = blkSizeOffsetX + (ctx >>shiftX);
+      lastXBitsArray[ ctx ] = iBitsX + pCtxX[ ctxOffset ].getEntropyBits( 0 );
+      iBitsX += pCtxX[ ctxOffset ].getEntropyBits( 1 );
+    }
+
+    lastXBitsArray[ctx] = iBitsX;
+
+    //------------------------------------------------
+
+    //Y-coordinate
+
+    for (ctx = 0; ctx < g_uiGroupIdx[ height - 1 ]; ctx++)
+    {
+      Int ctxOffset = blkSizeOffsetY + (ctx >>shiftY);
+      lastYBitsArray[ ctx ] = iBitsY + pCtxY[ ctxOffset ].getEntropyBits( 0 );
+      iBitsY += pCtxY[ ctxOffset ].getEntropyBits( 1 );
+    }
+
+    lastYBitsArray[ctx] = iBitsY;
+
+  } //end of component loop
+
+  //--------------------------------------------------------------------------------------------------
+}
+
+
+/*!
+ ****************************************************************************
+ * \brief
+ *    estimate bit cost of significant coefficient
+ ****************************************************************************
+ */
+Void TEncSbac::estSignificantCoefficientsBit( estBitsSbacStruct* pcEstBitsSbac, ChannelType chType )
+{
+  ContextModel *ctxOne = m_cCUOneSCModel.get(0, 0);
+  ContextModel *ctxAbs = m_cCUAbsSCModel.get(0, 0);
+
+  const UInt oneStartIndex = ((isLuma(chType)) ? (0)                     : (NUM_ONE_FLAG_CTX_LUMA));
+  const UInt oneStopIndex  = ((isLuma(chType)) ? (NUM_ONE_FLAG_CTX_LUMA) : (NUM_ONE_FLAG_CTX));
+  const UInt absStartIndex = ((isLuma(chType)) ? (0)                     : (NUM_ABS_FLAG_CTX_LUMA));
+  const UInt absStopIndex  = ((isLuma(chType)) ? (NUM_ABS_FLAG_CTX_LUMA) : (NUM_ABS_FLAG_CTX));
+
+  for (Int ctxIdx = oneStartIndex; ctxIdx < oneStopIndex; ctxIdx++)
+  {
+    pcEstBitsSbac->m_greaterOneBits[ ctxIdx ][ 0 ] = ctxOne[ ctxIdx ].getEntropyBits( 0 );
+    pcEstBitsSbac->m_greaterOneBits[ ctxIdx ][ 1 ] = ctxOne[ ctxIdx ].getEntropyBits( 1 );
+  }
+
+  for (Int ctxIdx = absStartIndex; ctxIdx < absStopIndex; 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( const TEncSbac* pSrc )
+{
+  memcpy(m_contextModels, pSrc->m_contextModels, m_numContextModels*sizeof(m_contextModels[0]));
+  memcpy(m_golombRiceAdaptationStatistics, pSrc->m_golombRiceAdaptationStatistics, (sizeof(UInt) * RExt__GOLOMB_RICE_ADAPTATION_STATISTICS_SETS));
+}
+
+Void  TEncSbac::loadContexts ( const TEncSbac* pSrc)
+{
+  xCopyContextsFrom(pSrc);
+}
+
+/** Performs CABAC encoding of the explicit RDPCM mode
+ * \param rTu current TU data structure
+ * \param compID component identifier
+ */
+Void TEncSbac::codeExplicitRdpcmMode( TComTU &rTu, const ComponentID compID )
+{
+  TComDataCU *cu = rTu.getCU();
+  const TComRectangle &rect = rTu.getRect(compID);
+  const UInt absPartIdx   = rTu.GetAbsPartIdxTU(compID);
+  const UInt tuHeight = g_aucConvertToBit[rect.height];
+  const UInt tuWidth  = g_aucConvertToBit[rect.width];
+
+  assert(tuHeight == tuWidth);
+  assert(tuHeight < 4);
+
+  UInt explicitRdpcmMode = cu->getExplicitRdpcmMode(compID, absPartIdx);
+
+  if( explicitRdpcmMode == RDPCM_OFF )
+  {
+    m_pcBinIf->encodeBin (0, m_explicitRdpcmFlagSCModel.get (0, toChannelType(compID), 0));
+  }
+  else if( explicitRdpcmMode == RDPCM_HOR || explicitRdpcmMode == RDPCM_VER )
+  {
+    m_pcBinIf->encodeBin (1, m_explicitRdpcmFlagSCModel.get (0, toChannelType(compID), 0));
+    if(explicitRdpcmMode == RDPCM_HOR)
+    {
+      m_pcBinIf->encodeBin ( 0, m_explicitRdpcmDirSCModel.get(0, toChannelType(compID), 0));
+    }
+    else
+    {
+      m_pcBinIf->encodeBin ( 1, m_explicitRdpcmDirSCModel.get(0, toChannelType(compID), 0));
+    }
+  }
+  else
+  {
+    assert(0);
+  }
+}
+
+#if POC_RESET_IDC_SIGNALLING
+Void  TEncSbac::codeSliceHeaderExtn( TComSlice* pSlice, Int shBitsWrittenTillNow )
+{
+  assert (0);
+  return;
+}
+#endif
+
+//! \}
Index: /tags/SHM-9.0/source/Lib/TLibEncoder/TEncSbac.h
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibEncoder/TEncSbac.h	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibEncoder/TEncSbac.h	(revision 1088)
@@ -0,0 +1,239 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TEncSbac.h
+    \brief    Context-adaptive entropy encoder class (header)
+*/
+
+#ifndef __TENCSBAC__
+#define __TENCSBAC__
+
+#if _MSC_VER > 1000
+#pragma once
+#endif // _MSC_VER > 1000
+
+#include "TLibCommon/TComBitStream.h"
+#include "TLibCommon/ContextTables.h"
+#include "TLibCommon/ContextModel.h"
+#include "TLibCommon/ContextModel3DBuffer.h"
+#include "TEncEntropy.h"
+#include "TEncBinCoder.h"
+#include "TEncBinCoderCABAC.h"
+#if FAST_BIT_EST
+#include "TEncBinCoderCABACCounter.h"
+#endif
+
+class TEncTop;
+
+//! \ingroup TLibEncoder
+//! \{
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// SBAC encoder class
+class TEncSbac : public TEncEntropyIf
+{
+public:
+  TEncSbac();
+  virtual ~TEncSbac();
+
+  Void  init                   ( TEncBinIf* p )  { m_pcBinIf = p; }
+  Void  uninit                 ()                { m_pcBinIf = 0; }
+
+  //  Virtual list
+  Void  resetEntropy           ();
+  Void  determineCabacInitIdx  ();
+  Void  setBitstream           ( TComBitIf* p )  { m_pcBitIf = p; m_pcBinIf->init( p ); }
+  Void  setSlice               ( TComSlice* p )  { m_pcSlice = p;                       }
+
+  Void  load                   ( const TEncSbac* pSrc  );
+  Void  loadIntraDirMode       ( const TEncSbac* pScr, const ChannelType chType  );
+  Void  store                  ( TEncSbac* pDest ) const;
+  Void  loadContexts           ( const TEncSbac* pSrc  );
+  Void  resetBits              ()                { m_pcBinIf->resetBits(); m_pcBitIf->resetBits(); }
+  UInt  getNumberOfWrittenBits ()                { return m_pcBinIf->getNumWrittenBits(); }
+  //--SBAC RD
+
+  Void  codeVPS                ( TComVPS* pcVPS );
+  Void  codeSPS                ( TComSPS* pcSPS     );
+  Void  codePPS                ( TComPPS* pcPPS     
+#if Q0048_CGS_3D_ASYMLUT
+    , TEnc3DAsymLUT * pc3DAsymLUT
+#endif
+    );
+  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;};
+
+#if SVC_EXTENSION
+#if POC_RESET_IDC_SIGNALLING
+  Void  codeSliceHeaderExtn     ( TComSlice* pSlice, Int shBitsWrittenTillNow );
+#endif  
+  Void codeSAOOffsetParam(ComponentID compIdx, SAOOffset& ctbParam, Bool sliceEnabled, UInt* saoMaxOffsetQVal);
+  Void codeSAOBlkParam(SAOBlkParam& saoBlkParam
+                    , UInt* saoMaxOffsetQVal
+                    , Bool* sliceEnabled
+                    , Bool leftMergeAvail
+                    , Bool aboveMergeAvail
+                    , Bool onlyEstMergeInfo = false
+                    );
+#else
+  Void codeSAOOffsetParam(ComponentID compIdx, SAOOffset& ctbParam, Bool sliceEnabled);
+  Void codeSAOBlkParam(SAOBlkParam& saoBlkParam
+                    , Bool* sliceEnabled
+                    , Bool leftMergeAvail
+                    , Bool aboveMergeAvail
+                    , Bool onlyEstMergeInfo = false
+                    );
+#endif  
+
+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, const Bool useLimitedPrefixLength, const ChannelType channelType );
+
+  Void  xCopyFrom            ( const TEncSbac* pSrc );
+  Void  xCopyContextsFrom    ( const 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;
+
+  //--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 );
+  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               ( TComTU & rTu, const ComponentID compID, const Bool lowestLevel );
+  Void codeQtRootCbf           ( TComDataCU* pcCU, UInt uiAbsPartIdx );
+  Void codeQtCbfZero           ( TComTU &rTu, const ChannelType chType );
+  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 codeCrossComponentPrediction( TComTU &rTu, ComponentID compID );
+
+  Void codeDeltaQP             ( TComDataCU* pcCU, UInt uiAbsPartIdx );
+  Void codeChromaQpAdjustment  ( TComDataCU* cu, UInt absPartIdx );
+
+  Void codeLastSignificantXY ( UInt uiPosX, UInt uiPosY, Int width, Int height, ComponentID component, UInt uiScanIdx );
+  Void codeCoeffNxN            ( TComTU &rTu, TCoeff* pcCoef, const ComponentID compID );
+  Void codeTransformSkipFlags ( TComTU &rTu, ComponentID component );
+
+  // -------------------------------------------------------------------------------------------------------------------
+  // for RD-optimizatioon
+  // -------------------------------------------------------------------------------------------------------------------
+
+  Void estBit               (estBitsSbacStruct* pcEstBitsSbac, Int width, Int height, ChannelType chType);
+  Void estCBFBit                     ( estBitsSbacStruct* pcEstBitsSbac );
+  Void estSignificantCoeffGroupMapBit( estBitsSbacStruct* pcEstBitsSbac, ChannelType chType );
+  Void estSignificantMapBit          ( estBitsSbacStruct* pcEstBitsSbac, Int width, Int height, ChannelType chType );
+  Void estLastSignificantPositionBit ( estBitsSbacStruct* pcEstBitsSbac, Int width, Int height, ChannelType chType );
+  Void estSignificantCoefficientsBit ( estBitsSbacStruct* pcEstBitsSbac, ChannelType chType );
+
+  Void codeExplicitRdpcmMode            ( TComTU &rTu, const ComponentID compID );
+
+
+  TEncBinIf* getEncBinIf()  { return m_pcBinIf; }
+private:
+  ContextModel         m_contextModels[MAX_NUM_CTX_MOD];
+  Int                  m_numContextModels;
+  ContextModel3DBuffer m_cCUSplitFlagSCModel;
+  ContextModel3DBuffer m_cCUSkipFlagSCModel;
+  ContextModel3DBuffer m_cCUMergeFlagExtSCModel;
+  ContextModel3DBuffer m_cCUMergeIdxExtSCModel;
+  ContextModel3DBuffer m_cCUPartSizeSCModel;
+  ContextModel3DBuffer m_cCUPredModeSCModel;
+  ContextModel3DBuffer m_cCUIntraPredSCModel;
+  ContextModel3DBuffer m_cCUChromaPredSCModel;
+  ContextModel3DBuffer m_cCUDeltaQpSCModel;
+  ContextModel3DBuffer m_cCUInterDirSCModel;
+  ContextModel3DBuffer m_cCURefPicSCModel;
+  ContextModel3DBuffer m_cCUMvdSCModel;
+  ContextModel3DBuffer m_cCUQtCbfSCModel;
+  ContextModel3DBuffer m_cCUTransSubdivFlagSCModel;
+  ContextModel3DBuffer m_cCUQtRootCbfSCModel;
+
+  ContextModel3DBuffer m_cCUSigCoeffGroupSCModel;
+  ContextModel3DBuffer m_cCUSigSCModel;
+  ContextModel3DBuffer m_cCuCtxLastX;
+  ContextModel3DBuffer m_cCuCtxLastY;
+  ContextModel3DBuffer m_cCUOneSCModel;
+  ContextModel3DBuffer m_cCUAbsSCModel;
+
+  ContextModel3DBuffer m_cMVPIdxSCModel;
+
+  ContextModel3DBuffer m_cSaoMergeSCModel;
+  ContextModel3DBuffer m_cSaoTypeIdxSCModel;
+  ContextModel3DBuffer m_cTransformSkipSCModel;
+  ContextModel3DBuffer m_CUTransquantBypassFlagSCModel;
+  ContextModel3DBuffer m_explicitRdpcmFlagSCModel;
+  ContextModel3DBuffer m_explicitRdpcmDirSCModel;
+  ContextModel3DBuffer m_cCrossComponentPredictionSCModel;
+
+  ContextModel3DBuffer m_ChromaQpAdjFlagSCModel;
+  ContextModel3DBuffer m_ChromaQpAdjIdcSCModel;
+
+  UInt m_golombRiceAdaptationStatistics[RExt__GOLOMB_RICE_ADAPTATION_STATISTICS_SETS];
+};
+
+//! \}
+
+#endif // !defined(AFX_TENCSBAC_H__DDA7CDC4_EDE3_4015_9D32_2156249C82AA__INCLUDED_)
Index: /tags/SHM-9.0/source/Lib/TLibEncoder/TEncSearch.cpp
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibEncoder/TEncSearch.cpp	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibEncoder/TEncSearch.cpp	(revision 1088)
@@ -0,0 +1,6175 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TEncSearch.cpp
+ \brief    encoder search class
+ */
+
+#include "TLibCommon/TypeDef.h"
+#include "TLibCommon/TComRom.h"
+#include "TLibCommon/TComMotionInfo.h"
+#include "TEncSearch.h"
+#include "TLibCommon/TComTU.h"
+#include "TLibCommon/Debug.h"
+#include <math.h>
+#include <limits>
+
+
+//! \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
+};
+
+static Void offsetSubTUCBFs(TComTU &rTu, const ComponentID compID)
+{
+        TComDataCU *pcCU              = rTu.getCU();
+  const UInt        uiTrDepth         = rTu.GetTransformDepthRel();
+  const UInt        uiAbsPartIdx      = rTu.GetAbsPartIdxTU(compID);
+  const UInt        partIdxesPerSubTU = rTu.GetAbsPartIdxNumParts(compID) >> 1;
+
+  //move the CBFs down a level and set the parent CBF
+
+  UChar subTUCBF[2];
+  UChar combinedSubTUCBF = 0;
+
+  for (UInt subTU = 0; subTU < 2; subTU++)
+  {
+    const UInt subTUAbsPartIdx = uiAbsPartIdx + (subTU * partIdxesPerSubTU);
+
+    subTUCBF[subTU]   = pcCU->getCbf(subTUAbsPartIdx, compID, uiTrDepth);
+    combinedSubTUCBF |= subTUCBF[subTU];
+  }
+
+  for (UInt subTU = 0; subTU < 2; subTU++)
+  {
+    const UInt subTUAbsPartIdx = uiAbsPartIdx + (subTU * partIdxesPerSubTU);
+    const UChar compositeCBF = (subTUCBF[subTU] << 1) | combinedSubTUCBF;
+
+    pcCU->setCbfPartRange((compositeCBF << uiTrDepth), compID, subTUAbsPartIdx, partIdxesPerSubTU);
+  }
+}
+
+
+TEncSearch::TEncSearch()
+{
+  for (UInt ch=0; ch<MAX_NUM_COMPONENT; ch++)
+  {
+    m_ppcQTTempCoeff[ch]                           = NULL;
+    m_pcQTTempCoeff[ch]                            = NULL;
+#if ADAPTIVE_QP_SELECTION
+    m_ppcQTTempArlCoeff[ch]                        = NULL;
+    m_pcQTTempArlCoeff[ch]                         = NULL;
+#endif
+    m_puhQTTempCbf[ch]                             = NULL;
+    m_phQTTempCrossComponentPredictionAlpha[ch]    = NULL;
+    m_pSharedPredTransformSkip[ch]                 = NULL;
+    m_pcQTTempTUCoeff[ch]                          = NULL;
+#if ADAPTIVE_QP_SELECTION
+    m_ppcQTTempTUArlCoeff[ch]                      = NULL;
+#endif
+    m_puhQTTempTransformSkipFlag[ch]               = NULL;
+  }
+  m_puhQTTempTrIdx                                 = NULL;
+  m_pcQTTempTComYuv                                = NULL;
+  m_pcEncCfg                                       = NULL;
+  m_pcEntropyCoder                                 = NULL;
+  m_pTempPel                                       = 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 ch=0; ch<MAX_NUM_COMPONENT; ch++)
+    {
+      for (UInt layer = 0; layer < uiNumLayersAllocated; layer++)
+      {
+        delete[] m_ppcQTTempCoeff[ch][layer];
+#if ADAPTIVE_QP_SELECTION
+        delete[] m_ppcQTTempArlCoeff[ch][layer];
+#endif
+      }
+      delete[] m_ppcQTTempCoeff[ch];
+      delete[] m_pcQTTempCoeff[ch];
+      delete[] m_puhQTTempCbf[ch];
+#if ADAPTIVE_QP_SELECTION
+      delete[] m_ppcQTTempArlCoeff[ch];
+      delete[] m_pcQTTempArlCoeff[ch];
+#endif
+    }
+
+    for( UInt layer = 0; layer < uiNumLayersAllocated; layer++ )
+    {
+      m_pcQTTempTComYuv[layer].destroy();
+    }
+  }
+
+  delete[] m_puhQTTempTrIdx;
+  delete[] m_pcQTTempTComYuv;
+
+  for (UInt ch=0; ch<MAX_NUM_COMPONENT; ch++)
+  {
+    delete[] m_pSharedPredTransformSkip[ch];
+    delete[] m_pcQTTempTUCoeff[ch];
+#if ADAPTIVE_QP_SELECTION
+    delete[] m_ppcQTTempTUArlCoeff[ch];
+#endif
+    delete[] m_phQTTempCrossComponentPredictionAlpha[ch];
+    delete[] m_puhQTTempTransformSkipFlag[ch];
+  }
+  m_pcQTTempTransformSkipTComYuv.destroy();
+
+  m_tmpYuvPred.destroy();
+}
+
+
+
+
+Void TEncSearch::init(TEncCfg*      pcEncCfg,
+                      TComTrQuant*  pcTrQuant,
+                      Int           iSearchRange,
+                      Int           bipredSearchRange,
+                      Int           iFastSearch,
+                      Int           iMaxDeltaQP,
+                      TEncEntropy*  pcEntropyCoder,
+                      TComRdCost*   pcRdCost,
+                      TEncSbac*** pppcRDSbacCoder,
+                      TEncSbac*   pcRDGoOnSbacCoder
+                      )
+{
+  m_pcEncCfg             = pcEncCfg;
+  m_pcTrQuant            = pcTrQuant;
+  m_iSearchRange         = iSearchRange;
+  m_bipredSearchRange    = bipredSearchRange;
+  m_iFastSearch          = iFastSearch;
+  m_iMaxDeltaQP          = iMaxDeltaQP;
+  m_pcEntropyCoder       = pcEntropyCoder;
+  m_pcRdCost             = pcRdCost;
+
+  m_pppcRDSbacCoder     = pppcRDSbacCoder;
+  m_pcRDGoOnSbacCoder   = pcRDGoOnSbacCoder;
+
+  for (UInt iDir = 0; iDir < MAX_NUM_REF_LIST_ADAPT_SR; iDir++)
+  {
+    for (UInt iRefIdx = 0; iRefIdx < MAX_IDX_ADAPT_SR; iRefIdx++)
+    {
+      m_aaiAdaptSR[iDir][iRefIdx] = iSearchRange;
+    }
+  }
+
+  m_puiDFilter = s_auiDFilter + 4;
+
+  // initialize motion cost
+  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;
+    }
+  }
+
+  const ChromaFormat cform=pcEncCfg->getChromaFormatIdc();
+  initTempBuff(cform);
+
+  m_pTempPel = new Pel[g_uiMaxCUWidth*g_uiMaxCUHeight];
+
+  const UInt uiNumLayersToAllocate = pcEncCfg->getQuadtreeTULog2MaxSize()-pcEncCfg->getQuadtreeTULog2MinSize()+1;
+  const UInt uiNumPartitions = 1<<(g_uiMaxCUDepth<<1);
+  for (UInt ch=0; ch<MAX_NUM_COMPONENT; ch++)
+  {
+    const UInt csx=::getComponentScaleX(ComponentID(ch), cform);
+    const UInt csy=::getComponentScaleY(ComponentID(ch), cform);
+    m_ppcQTTempCoeff[ch] = new TCoeff* [uiNumLayersToAllocate];
+    m_pcQTTempCoeff[ch]   = new TCoeff [(g_uiMaxCUWidth*g_uiMaxCUHeight)>>(csx+csy)   ];
+#if ADAPTIVE_QP_SELECTION
+    m_ppcQTTempArlCoeff[ch]  = new TCoeff*[uiNumLayersToAllocate];
+    m_pcQTTempArlCoeff[ch]   = new TCoeff [(g_uiMaxCUWidth*g_uiMaxCUHeight)>>(csx+csy)   ];
+#endif
+    m_puhQTTempCbf[ch] = new UChar  [uiNumPartitions];
+
+    for (UInt layer = 0; layer < uiNumLayersToAllocate; layer++)
+    {
+      m_ppcQTTempCoeff[ch][layer] = new TCoeff[(g_uiMaxCUWidth*g_uiMaxCUHeight)>>(csx+csy)];
+#if ADAPTIVE_QP_SELECTION
+      m_ppcQTTempArlCoeff[ch][layer]  = new TCoeff[(g_uiMaxCUWidth*g_uiMaxCUHeight)>>(csx+csy) ];
+#endif
+    }
+
+    m_phQTTempCrossComponentPredictionAlpha[ch]    = new Char  [uiNumPartitions];
+    m_pSharedPredTransformSkip[ch]                 = new Pel   [MAX_CU_SIZE*MAX_CU_SIZE];
+    m_pcQTTempTUCoeff[ch]                          = new TCoeff[MAX_CU_SIZE*MAX_CU_SIZE];
+#if ADAPTIVE_QP_SELECTION
+    m_ppcQTTempTUArlCoeff[ch]                      = new TCoeff[MAX_CU_SIZE*MAX_CU_SIZE];
+#endif
+    m_puhQTTempTransformSkipFlag[ch]               = new UChar [uiNumPartitions];
+  }
+  m_puhQTTempTrIdx   = new UChar  [uiNumPartitions];
+  m_pcQTTempTComYuv  = new TComYuv[uiNumLayersToAllocate];
+  for( UInt ui = 0; ui < uiNumLayersToAllocate; ++ui )
+  {
+    m_pcQTTempTComYuv[ui].create( g_uiMaxCUWidth, g_uiMaxCUHeight, pcEncCfg->getChromaFormatIdc() );
+  }
+  m_pcQTTempTransformSkipTComYuv.create( g_uiMaxCUWidth, g_uiMaxCUHeight, pcEncCfg->getChromaFormatIdc() );
+  m_tmpYuvPred.create(MAX_CU_SIZE, MAX_CU_SIZE, pcEncCfg->getChromaFormatIdc());
+}
+
+#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) */  \
+
+
+#define SEL_SEARCH_CONFIGURATION                                                                                 \
+  const Bool bTestOtherPredictedMV    = 1;                                                                       \
+  const Bool bTestZeroVector          = 1;                                                                       \
+  const Bool bEnableRasterSearch      = 1;                                                                       \
+  const Bool bAlwaysRasterSearch      = 0;  /* ===== 1: BETTER but factor 15x slower ===== */                    \
+  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) */   \
+  const UInt uiSearchRange            = m_iSearchRange;                                                          \
+  const Int  uiSearchRangeInitial     = m_iSearchRange >> 2;                                                     \
+  const Int  uiSearchStep             = 4;                                                                       \
+  const Int  iMVDistThresh            = 8;                                                                       \
+
+
+
+__inline Void TEncSearch::xTZSearchHelp( TComPattern* pcPatternKey, IntTZSearchStruct& rcStruct, const Int iSearchX, const Int iSearchY, const UChar ucPointNr, const UInt uiDistance )
+{
+  Distortion  uiSad = 0;
+
+  Pel*  piRefSrch;
+
+  piRefSrch = rcStruct.piRefY + iSearchY * rcStruct.iYStride + iSearchX;
+
+  //-- jclee for using the SAD function pointer
+  m_pcRdCost->setDistParam( pcPatternKey, piRefSrch, rcStruct.iYStride,  m_cDistParam );
+
+  if(m_pcEncCfg->getFastSearch() != SELECTIVE)
+  {
+    // 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(COMPONENT_Y);
+
+  // distortion
+  m_cDistParam.bitDepth = g_bitDepth[CHANNEL_TYPE_LUMA];
+  if(m_pcEncCfg->getFastSearch() == SELECTIVE)
+  {
+    Int isubShift = 0;
+    // motion cost
+    UInt uiBitCost = m_pcRdCost->getCost( iSearchX, iSearchY );
+
+    if ( m_cDistParam.iRows > 32 )
+      m_cDistParam.iSubShift = 4;
+    else if ( m_cDistParam.iRows > 16 )
+      m_cDistParam.iSubShift = 3;
+    else if ( m_cDistParam.iRows > 8 )
+      m_cDistParam.iSubShift = 2;
+    else
+      m_cDistParam.iSubShift = 1;
+
+    Distortion uiTempSad = m_cDistParam.DistFunc( &m_cDistParam );
+    if((uiTempSad + uiBitCost) < rcStruct.uiBestSad)
+    {
+      uiSad += uiTempSad >>  m_cDistParam.iSubShift;
+      while(m_cDistParam.iSubShift > 0)
+      {
+        isubShift         = m_cDistParam.iSubShift -1;
+        m_cDistParam.pOrg = pcPatternKey->getROIY() + (pcPatternKey->getPatternLStride() << isubShift);
+        m_cDistParam.pCur = piRefSrch + (rcStruct.iYStride << isubShift);
+        uiTempSad = m_cDistParam.DistFunc( &m_cDistParam );
+        uiSad += uiTempSad >>  m_cDistParam.iSubShift;
+        if(((uiSad << isubShift) + uiBitCost) > rcStruct.uiBestSad)
+          break;
+
+        m_cDistParam.iSubShift--;
+      }
+
+      if(m_cDistParam.iSubShift == 0)
+      {
+        uiSad += uiBitCost;
+        if( uiSad < rcStruct.uiBestSad )
+        {
+          rcStruct.uiBestSad      = uiSad;
+          rcStruct.iBestX         = iSearchX;
+          rcStruct.iBestY         = iSearchY;
+          rcStruct.uiBestDistance = uiDistance;
+          rcStruct.uiBestRound    = 0;
+          rcStruct.ucPointNr      = ucPointNr;
+        }
+      }
+    }
+  }
+  else
+  {
+    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
+}
+
+
+
+
+
+//<--
+
+Distortion TEncSearch::xPatternRefinement( TComPattern* pcPatternKey,
+                                           TComMv baseRefMv,
+                                           Int iFrac, TComMv& rcMvFrac,
+                                           Bool bAllowUseOfHadamard
+                                         )
+{
+  Distortion  uiDist;
+  Distortion  uiDistBest  = std::numeric_limits<Distortion>::max();
+  UInt        uiDirecBest = 0;
+
+  Pel*  piRefPos;
+  Int iRefStride = m_filteredBlock[0][0].getStride(COMPONENT_Y);
+
+  m_pcRdCost->setDistParam( pcPatternKey, m_filteredBlock[0][0].getAddr(COMPONENT_Y), iRefStride, 1, m_cDistParam, m_pcEncCfg->getUseHADME() && bAllowUseOfHadamard );
+
+  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 ].getAddr(COMPONENT_Y);
+    if ( horVal == 2 && ( verVal & 1 ) == 0 )
+    {
+      piRefPos += 1;
+    }
+    if ( ( horVal & 1 ) == 0 && verVal == 2 )
+    {
+      piRefPos += iRefStride;
+    }
+    cMvTest = pcMvRefine[i];
+    cMvTest += rcMvFrac;
+
+    setDistParamComp(COMPONENT_Y);
+
+    m_cDistParam.pCur = piRefPos;
+    m_cDistParam.bitDepth = g_bitDepth[CHANNEL_TYPE_LUMA];
+    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(TComTU      &rTu,
+                            Bool         bLuma,
+                            Bool         bChroma )
+{
+  TComDataCU* pcCU=rTu.getCU();
+  const UInt uiAbsPartIdx         = rTu.GetAbsPartIdxTU();
+  const UInt uiTrDepth            = rTu.GetTransformDepthRel();
+  const UInt uiTrMode             = pcCU->getTransformIdx( uiAbsPartIdx );
+  const UInt uiSubdiv             = ( uiTrMode > uiTrDepth ? 1 : 0 );
+  const UInt uiLog2LumaTrafoSize  = rTu.GetLog2LumaTrSize();
+
+  if( pcCU->isIntra(0) && pcCU->getPartitionSize(0) == SIZE_NxN && uiTrDepth == 0 )
+  {
+    assert( uiSubdiv );
+  }
+  else if( uiLog2LumaTrafoSize > pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() )
+  {
+    assert( uiSubdiv );
+  }
+  else if( uiLog2LumaTrafoSize == pcCU->getSlice()->getSPS()->getQuadtreeTULog2MinSize() )
+  {
+    assert( !uiSubdiv );
+  }
+  else if( uiLog2LumaTrafoSize == pcCU->getQuadtreeTULog2MinSizeInCU(uiAbsPartIdx) )
+  {
+    assert( !uiSubdiv );
+  }
+  else
+  {
+    assert( uiLog2LumaTrafoSize > pcCU->getQuadtreeTULog2MinSizeInCU(uiAbsPartIdx) );
+    if( bLuma )
+    {
+      m_pcEntropyCoder->encodeTransformSubdivFlag( uiSubdiv, 5 - uiLog2LumaTrafoSize );
+    }
+  }
+
+  if ( bChroma )
+  {
+    const UInt numberValidComponents = getNumberValidComponents(rTu.GetChromaFormat());
+    for (UInt ch=COMPONENT_Cb; ch<numberValidComponents; ch++)
+    {
+      const ComponentID compID=ComponentID(ch);
+      if( rTu.ProcessingAllQuadrants(compID) && (uiTrDepth==0 || pcCU->getCbf( uiAbsPartIdx, compID, uiTrDepth-1 ) ))
+        m_pcEntropyCoder->encodeQtCbf(rTu, compID, (uiSubdiv == 0));
+    }
+  }
+
+  if( uiSubdiv )
+  {
+    TComTURecurse tuRecurse(rTu, false);
+    do
+    {
+      xEncSubdivCbfQT( tuRecurse, bLuma, bChroma );
+    } while (tuRecurse.nextSection(rTu));
+  }
+  else
+  {
+    //===== Cbfs =====
+    if( bLuma )
+    {
+      m_pcEntropyCoder->encodeQtCbf( rTu, COMPONENT_Y, true );
+    }
+  }
+}
+
+
+
+
+Void
+TEncSearch::xEncCoeffQT(TComTU &rTu,
+                        const ComponentID  component,
+                        Bool         bRealCoeff )
+{
+  TComDataCU* pcCU=rTu.getCU();
+  const UInt uiAbsPartIdx = rTu.GetAbsPartIdxTU();
+  const UInt uiTrDepth=rTu.GetTransformDepthRel();
+
+  const UInt  uiTrMode        = pcCU->getTransformIdx( uiAbsPartIdx );
+  const UInt  uiSubdiv        = ( uiTrMode > uiTrDepth ? 1 : 0 );
+
+  if( uiSubdiv )
+  {
+    TComTURecurse tuRecurseChild(rTu, false);
+    do
+    {
+      xEncCoeffQT( tuRecurseChild, component, bRealCoeff );
+    } while (tuRecurseChild.nextSection(rTu) );
+  }
+  else if (rTu.ProcessComponentSection(component))
+  {
+    //===== coefficients =====
+    const UInt  uiLog2TrafoSize = rTu.GetLog2LumaTrSize();
+    UInt    uiCoeffOffset   = rTu.getCoefficientOffset(component);
+    UInt    uiQTLayer       = pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() - uiLog2TrafoSize;
+    TCoeff* pcCoeff         = bRealCoeff ? pcCU->getCoeff(component) : m_ppcQTTempCoeff[component][uiQTLayer];
+
+    if (isChroma(component) && (pcCU->getCbf( rTu.GetAbsPartIdxTU(), COMPONENT_Y, uiTrMode ) != 0) && pcCU->getSlice()->getPPS()->getUseCrossComponentPrediction() )
+    {
+      m_pcEntropyCoder->encodeCrossComponentPrediction( rTu, component );
+    }
+
+    m_pcEntropyCoder->encodeCoeffNxN( rTu, pcCoeff+uiCoeffOffset, component );
+  }
+}
+
+
+
+
+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 && (uiAbsPartIdx%uiQNumParts)==0) m_pcEntropyCoder->encodeIntraDirModeLuma ( pcCU, uiAbsPartIdx );
+    }
+  }
+
+  if( bChroma )
+  {
+    if( pcCU->getPartitionSize(0) == SIZE_2Nx2N || !enable4ChromaPUsInIntraNxNCU(pcCU->getPic()->getChromaFormat()))
+    {
+      if(uiAbsPartIdx==0)
+      {
+         m_pcEntropyCoder->encodeIntraDirModeChroma ( pcCU, uiAbsPartIdx );
+      }
+    }
+    else
+    {
+      UInt uiQNumParts = pcCU->getTotalNumPart() >> 2;
+      assert(uiTrDepth>0);
+      if ((uiAbsPartIdx%uiQNumParts)==0)
+      {
+        m_pcEntropyCoder->encodeIntraDirModeChroma ( pcCU, uiAbsPartIdx );
+      }
+    }
+  }
+}
+
+
+
+
+UInt
+TEncSearch::xGetIntraBitsQT(TComTU &rTu,
+                            Bool         bLuma,
+                            Bool         bChroma,
+                            Bool         bRealCoeff /* just for test */ )
+{
+  TComDataCU* pcCU=rTu.getCU();
+  const UInt uiAbsPartIdx = rTu.GetAbsPartIdxTU();
+  const UInt uiTrDepth=rTu.GetTransformDepthRel();
+  m_pcEntropyCoder->resetBits();
+  xEncIntraHeader ( pcCU, uiTrDepth, uiAbsPartIdx, bLuma, bChroma );
+  xEncSubdivCbfQT ( rTu, bLuma, bChroma );
+
+  if( bLuma )
+  {
+    xEncCoeffQT   ( rTu, COMPONENT_Y,      bRealCoeff );
+  }
+  if( bChroma )
+  {
+    xEncCoeffQT   ( rTu, COMPONENT_Cb,  bRealCoeff );
+    xEncCoeffQT   ( rTu, COMPONENT_Cr,  bRealCoeff );
+  }
+  UInt   uiBits = m_pcEntropyCoder->getNumberOfWrittenBits();
+
+  return uiBits;
+}
+
+UInt TEncSearch::xGetIntraBitsQTChroma(TComTU &rTu,
+                                       ComponentID compID,
+                                       Bool         bRealCoeff /* just for test */ )
+{
+  m_pcEntropyCoder->resetBits();
+  xEncCoeffQT   ( rTu, compID,  bRealCoeff );
+  UInt   uiBits = m_pcEntropyCoder->getNumberOfWrittenBits();
+  return uiBits;
+}
+
+Void TEncSearch::xIntraCodingTUBlock(       TComYuv*    pcOrgYuv,
+                                            TComYuv*    pcPredYuv,
+                                            TComYuv*    pcResiYuv,
+                                            Pel         resiLuma[NUMBER_OF_STORED_RESIDUAL_TYPES][MAX_CU_SIZE * MAX_CU_SIZE],
+                                      const Bool        checkCrossCPrediction,
+                                            Distortion& ruiDist,
+                                      const ComponentID compID,
+                                            TComTU&     rTu
+                                      DEBUG_STRING_FN_DECLARE(sDebug)
+                                           ,Int         default0Save1Load2
+                                     )
+{
+  if (!rTu.ProcessComponentSection(compID)) return;
+  const Bool       bIsLuma = isLuma(compID);
+  const TComRectangle &rect= rTu.getRect(compID);
+  TComDataCU *pcCU=rTu.getCU();
+  const UInt uiAbsPartIdx=rTu.GetAbsPartIdxTU();
+
+  const UInt uiTrDepth=rTu.GetTransformDepthRelAdj(compID);
+  const UInt uiFullDepth   = rTu.GetTransformDepthTotal();
+  const UInt uiLog2TrSize  = rTu.GetLog2LumaTrSize();
+  const ChromaFormat chFmt = pcOrgYuv->getChromaFormat();
+  const ChannelType chType = toChannelType(compID);
+
+  const UInt    uiWidth           = rect.width;
+  const UInt    uiHeight          = rect.height;
+  const UInt    uiStride          = pcOrgYuv ->getStride (compID);
+        Pel*    piOrg             = pcOrgYuv ->getAddr( compID, uiAbsPartIdx );
+        Pel*    piPred            = pcPredYuv->getAddr( compID, uiAbsPartIdx );
+        Pel*    piResi            = pcResiYuv->getAddr( compID, uiAbsPartIdx );
+        Pel*    piReco            = pcPredYuv->getAddr( compID, uiAbsPartIdx );
+  const UInt    uiQTLayer           = pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() - uiLog2TrSize;
+        Pel*    piRecQt           = m_pcQTTempTComYuv[ uiQTLayer ].getAddr( compID, uiAbsPartIdx );
+  const UInt    uiRecQtStride     = m_pcQTTempTComYuv[ uiQTLayer ].getStride(compID);
+  const UInt    uiZOrder            = pcCU->getZorderIdxInCtu() + uiAbsPartIdx;
+        Pel*    piRecIPred        = pcCU->getPic()->getPicYuvRec()->getAddr( compID, pcCU->getCtuRsAddr(), uiZOrder );
+        UInt    uiRecIPredStride  = pcCU->getPic()->getPicYuvRec()->getStride  ( compID );
+        TCoeff* pcCoeff           = m_ppcQTTempCoeff[compID][uiQTLayer] + rTu.getCoefficientOffset(compID);
+        Bool    useTransformSkip  = pcCU->getTransformSkip(uiAbsPartIdx, compID);
+
+#if ADAPTIVE_QP_SELECTION
+        TCoeff*    pcArlCoeff     = m_ppcQTTempArlCoeff[compID][ uiQTLayer ] + rTu.getCoefficientOffset(compID);
+#endif
+
+  const UInt uiChPredMode         = pcCU->getIntraDir( chType, uiAbsPartIdx );
+  const UInt uiChCodedMode        = (uiChPredMode==DM_CHROMA_IDX && !bIsLuma) ? pcCU->getIntraDir(CHANNEL_TYPE_LUMA, getChromasCorrespondingPULumaIdx(uiAbsPartIdx, chFmt)) : uiChPredMode;
+  const UInt uiChFinalMode        = ((chFmt == CHROMA_422)       && !bIsLuma) ? g_chroma422IntraAngleMappingTable[uiChCodedMode] : uiChCodedMode;
+
+  const Int         blkX                                 = g_auiRasterToPelX[ g_auiZscanToRaster[ uiAbsPartIdx ] ];
+  const Int         blkY                                 = g_auiRasterToPelY[ g_auiZscanToRaster[ uiAbsPartIdx ] ];
+  const Int         bufferOffset                         = blkX + (blkY * MAX_CU_SIZE);
+        Pel  *const encoderLumaResidual                  = resiLuma[RESIDUAL_ENCODER_SIDE ] + bufferOffset;
+        Pel  *const reconstructedLumaResidual            = resiLuma[RESIDUAL_RECONSTRUCTED] + bufferOffset;
+  const Bool        bUseCrossCPrediction                 = isChroma(compID) && (uiChPredMode == DM_CHROMA_IDX) && checkCrossCPrediction;
+  const Bool        bUseReconstructedResidualForEstimate = m_pcEncCfg->getUseReconBasedCrossCPredictionEstimate();
+        Pel *const  lumaResidualForEstimate              = bUseReconstructedResidualForEstimate ? reconstructedLumaResidual : encoderLumaResidual;
+
+#ifdef DEBUG_STRING
+  const Int debugPredModeMask=DebugStringGetPredModeMask(MODE_INTRA);
+#endif
+
+  //===== init availability pattern =====
+  Bool  bAboveAvail = false;
+  Bool  bLeftAvail  = false;
+
+  DEBUG_STRING_NEW(sTemp)
+
+#ifndef DEBUG_STRING
+  if( default0Save1Load2 != 2 )
+#endif
+  {
+    const Bool bUseFilteredPredictions=TComPrediction::filteringIntraReferenceSamples(compID, uiChFinalMode, uiWidth, uiHeight, chFmt, pcCU->getSlice()->getSPS()->getDisableIntraReferenceSmoothing());
+
+    initAdiPatternChType( rTu, bAboveAvail, bLeftAvail, compID, bUseFilteredPredictions DEBUG_STRING_PASS_INTO(sDebug) );
+
+    //===== get prediction signal =====
+    predIntraAng( compID, uiChFinalMode, piOrg, uiStride, piPred, uiStride, rTu, bAboveAvail, bLeftAvail, bUseFilteredPredictions );
+
+    // save prediction
+    if( default0Save1Load2 == 1 )
+    {
+      Pel*  pPred   = piPred;
+      Pel*  pPredBuf = m_pSharedPredTransformSkip[compID];
+      Int k = 0;
+      for( UInt uiY = 0; uiY < uiHeight; uiY++ )
+      {
+        for( UInt uiX = 0; uiX < uiWidth; uiX++ )
+        {
+          pPredBuf[ k ++ ] = pPred[ uiX ];
+        }
+        pPred += uiStride;
+      }
+    }
+  }
+#ifndef DEBUG_STRING
+  else
+  {
+    // load prediction
+    Pel*  pPred   = piPred;
+    Pel*  pPredBuf = m_pSharedPredTransformSkip[compID];
+    Int k = 0;
+    for( UInt uiY = 0; uiY < uiHeight; uiY++ )
+    {
+      for( UInt uiX = 0; uiX < uiWidth; uiX++ )
+      {
+        pPred[ uiX ] = pPredBuf[ k ++ ];
+      }
+      pPred += uiStride;
+    }
+  }
+#endif
+
+  //===== 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;
+    }
+  }
+
+  if (pcCU->getSlice()->getPPS()->getUseCrossComponentPrediction())
+  {
+    if (bUseCrossCPrediction)
+    {
+      if (xCalcCrossComponentPredictionAlpha( rTu, compID, lumaResidualForEstimate, piResi, uiWidth, uiHeight, MAX_CU_SIZE, uiStride ) == 0) return;
+      TComTrQuant::crossComponentPrediction ( rTu, compID, reconstructedLumaResidual, piResi, piResi, uiWidth, uiHeight, MAX_CU_SIZE, uiStride, uiStride, false );
+    }
+    else if (isLuma(compID) && !bUseReconstructedResidualForEstimate)
+    {
+      xStoreCrossComponentPredictionResult( encoderLumaResidual, piResi, rTu, 0, 0, MAX_CU_SIZE, uiStride );
+    }
+  }
+
+  //===== 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, uiHeight, chType );
+  }
+
+  //--- transform and quantization ---
+  TCoeff uiAbsSum = 0;
+  if (bIsLuma)
+  {
+    pcCU       ->setTrIdxSubParts ( uiTrDepth, uiAbsPartIdx, uiFullDepth );
+  }
+
+  const QpParam cQP(*pcCU, compID);
+
+#if RDOQ_CHROMA_LAMBDA
+  m_pcTrQuant->selectLambda     (compID);
+#endif
+
+  m_pcTrQuant->transformNxN     ( rTu, compID, piResi, uiStride, pcCoeff,
+#if ADAPTIVE_QP_SELECTION
+    pcArlCoeff,
+#endif
+    uiAbsSum, cQP
+    );
+
+  //--- inverse transform ---
+
+#ifdef DEBUG_STRING
+  if ( (uiAbsSum > 0) || (DebugOptionList::DebugString_InvTran.getInt()&debugPredModeMask) )
+#else
+  if ( uiAbsSum > 0 )
+#endif
+  {
+    m_pcTrQuant->invTransformNxN ( rTu, compID, piResi, uiStride, pcCoeff, cQP DEBUG_STRING_PASS_INTO_OPTIONAL(&sDebug, (DebugOptionList::DebugString_InvTran.getInt()&debugPredModeMask)) );
+  }
+  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;
+    const UInt clipbd=g_bitDepth[chType];
+
+    if (pcCU->getSlice()->getPPS()->getUseCrossComponentPrediction())
+    {
+      if (bUseCrossCPrediction)
+      {
+        TComTrQuant::crossComponentPrediction( rTu, compID, reconstructedLumaResidual, piResi, piResi, uiWidth, uiHeight, MAX_CU_SIZE, uiStride, uiStride, true );
+      }
+      else if (isLuma(compID))
+      {
+        xStoreCrossComponentPredictionResult( reconstructedLumaResidual, piResi, rTu, 0, 0, MAX_CU_SIZE, uiStride );
+      }
+    }
+
+ #ifdef DEBUG_STRING
+    std::stringstream ss(stringstream::out);
+    const Bool bDebugPred=((DebugOptionList::DebugString_Pred.getInt()&debugPredModeMask) && DEBUG_STRING_CHANNEL_CONDITION(compID));
+    const Bool bDebugResi=((DebugOptionList::DebugString_Resi.getInt()&debugPredModeMask) && DEBUG_STRING_CHANNEL_CONDITION(compID));
+    const Bool bDebugReco=((DebugOptionList::DebugString_Reco.getInt()&debugPredModeMask) && DEBUG_STRING_CHANNEL_CONDITION(compID));
+
+    if (bDebugPred || bDebugResi || bDebugReco)
+    {
+      ss << "###: " << "CompID: " << compID << " pred mode (ch/fin): " << uiChPredMode << "/" << uiChFinalMode << " absPartIdx: " << rTu.GetAbsPartIdxTU() << "\n";
+      for( UInt uiY = 0; uiY < uiHeight; uiY++ )
+      {
+        ss << "###: ";
+        if (bDebugPred)
+        {
+          ss << " - pred: ";
+          for( UInt uiX = 0; uiX < uiWidth; uiX++ )
+          {
+            ss << pPred[ uiX ] << ", ";
+          }
+        }
+        if (bDebugResi) ss << " - resi: ";
+        for( UInt uiX = 0; uiX < uiWidth; uiX++ )
+        {
+          if (bDebugResi) ss << pResi[ uiX ] << ", ";
+          pReco    [ uiX ] = Pel(ClipBD<Int>( Int(pPred[uiX]) + Int(pResi[uiX]), clipbd ));
+          pRecQt   [ uiX ] = pReco[ uiX ];
+          pRecIPred[ uiX ] = pReco[ uiX ];
+        }
+        if (bDebugReco)
+        {
+          ss << " - reco: ";
+          for( UInt uiX = 0; uiX < uiWidth; uiX++ )
+          {
+            ss << pReco[ uiX ] << ", ";
+          }
+        }
+        pPred     += uiStride;
+        pResi     += uiStride;
+        pReco     += uiStride;
+        pRecQt    += uiRecQtStride;
+        pRecIPred += uiRecIPredStride;
+        ss << "\n";
+      }
+      DEBUG_STRING_APPEND(sDebug, ss.str())
+    }
+    else
+#endif
+    {
+
+      for( UInt uiY = 0; uiY < uiHeight; uiY++ )
+      {
+        for( UInt uiX = 0; uiX < uiWidth; uiX++ )
+        {
+          pReco    [ uiX ] = Pel(ClipBD<Int>( Int(pPred[uiX]) + Int(pResi[uiX]), clipbd ));
+          pRecQt   [ uiX ] = pReco[ uiX ];
+          pRecIPred[ uiX ] = pReco[ uiX ];
+        }
+        pPred     += uiStride;
+        pResi     += uiStride;
+        pReco     += uiStride;
+        pRecQt    += uiRecQtStride;
+        pRecIPred += uiRecIPredStride;
+      }
+    }
+  }
+
+  //===== update distortion =====
+  ruiDist += m_pcRdCost->getDistPart( g_bitDepth[chType], piReco, uiStride, piOrg, uiStride, uiWidth, uiHeight, compID );
+}
+
+
+
+
+
+Void
+TEncSearch::xRecurIntraCodingQT(Bool        bLumaOnly,
+                                TComYuv*    pcOrgYuv,
+                                TComYuv*    pcPredYuv,
+                                TComYuv*    pcResiYuv,
+                                Pel         resiLuma[NUMBER_OF_STORED_RESIDUAL_TYPES][MAX_CU_SIZE * MAX_CU_SIZE],
+                                Distortion& ruiDistY,
+                                Distortion& ruiDistC,
+#if HHI_RQT_INTRA_SPEEDUP
+                                Bool        bCheckFirst,
+#endif
+                                Double&     dRDCost,
+                                TComTU&     rTu
+                                DEBUG_STRING_FN_DECLARE(sDebug))
+{
+  TComDataCU   *pcCU          = rTu.getCU();
+  const UInt    uiAbsPartIdx  = rTu.GetAbsPartIdxTU();
+  const UInt    uiFullDepth   = rTu.GetTransformDepthTotal();
+  const UInt    uiTrDepth     = rTu.GetTransformDepthRel();
+  const UInt    uiLog2TrSize  = rTu.GetLog2LumaTrSize();
+        Bool    bCheckFull    = ( uiLog2TrSize  <= pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() );
+        Bool    bCheckSplit   = ( uiLog2TrSize  >  pcCU->getQuadtreeTULog2MinSizeInCU(uiAbsPartIdx) );
+  const UInt    numValidComp  = (bLumaOnly) ? 1 : pcOrgYuv->getNumberValidComponents();
+
+        Pel     resiLumaSplit [NUMBER_OF_STORED_RESIDUAL_TYPES][MAX_CU_SIZE * MAX_CU_SIZE];
+        Pel     resiLumaSingle[NUMBER_OF_STORED_RESIDUAL_TYPES][MAX_CU_SIZE * MAX_CU_SIZE];
+
+        Bool    bMaintainResidual[NUMBER_OF_STORED_RESIDUAL_TYPES];
+        for (UInt residualTypeIndex = 0; residualTypeIndex < NUMBER_OF_STORED_RESIDUAL_TYPES; residualTypeIndex++)
+        {
+          bMaintainResidual[residualTypeIndex] = true; //assume true unless specified otherwise
+        }
+
+        bMaintainResidual[RESIDUAL_ENCODER_SIDE] = !(m_pcEncCfg->getUseReconBasedCrossCPredictionEstimate());
+
+#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
+  Double     dSingleCost                        = MAX_DOUBLE;
+  Distortion uiSingleDist[MAX_NUM_CHANNEL_TYPE] = {0,0};
+  UInt       uiSingleCbf[MAX_NUM_COMPONENT]     = {0,0,0};
+  Bool       checkTransformSkip  = pcCU->getSlice()->getPPS()->getUseTransformSkip();
+  Int        bestModeId[MAX_NUM_COMPONENT] = { 0, 0, 0};
+  checkTransformSkip           &= TUCompRectHasAssociatedTransformSkipFlag(rTu.getRect(COMPONENT_Y), pcCU->getSlice()->getPPS()->getTransformSkipLog2MaxSize());
+  checkTransformSkip           &= (!pcCU->getCUTransquantBypass(0));
+
+  if ( m_pcEncCfg->getUseTransformSkipFast() )
+  {
+    checkTransformSkip       &= (pcCU->getPartitionSize(uiAbsPartIdx)==SIZE_NxN);
+  }
+
+  if( bCheckFull )
+  {
+    if(checkTransformSkip == true)
+    {
+      //----- store original entropy coding status -----
+      m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[ uiFullDepth ][ CI_QT_TRAFO_ROOT ] );
+
+      Distortion singleDistTmp[MAX_NUM_CHANNEL_TYPE]  = { 0, 0 };
+      UInt       singleCbfTmp[MAX_NUM_COMPONENT]      = { 0, 0, 0 };
+      Double     singleCostTmp                        = 0;
+      Int        firstCheckId                         = 0;
+
+      for(Int modeId = firstCheckId; modeId < 2; modeId ++)
+      {
+        DEBUG_STRING_NEW(sModeString)
+        Int  default0Save1Load2 = 0;
+        singleDistTmp[0]=singleDistTmp[1]=0;
+        if(modeId == firstCheckId)
+        {
+          default0Save1Load2 = 1;
+        }
+        else
+        {
+          default0Save1Load2 = 2;
+        }
+
+        for(UInt ch=COMPONENT_Y; ch<numValidComp; ch++)
+        {
+          const ComponentID compID = ComponentID(ch);
+          if (rTu.ProcessComponentSection(compID))
+          {
+            const UInt totalAdjustedDepthChan = rTu.GetTransformDepthTotalAdj(compID);
+            pcCU->setTransformSkipSubParts ( modeId, compID, uiAbsPartIdx, totalAdjustedDepthChan );
+
+            xIntraCodingTUBlock( pcOrgYuv, pcPredYuv, pcResiYuv, resiLumaSingle, false, singleDistTmp[toChannelType(compID)], compID, rTu DEBUG_STRING_PASS_INTO(sModeString), default0Save1Load2 );
+          }
+          singleCbfTmp[compID] = pcCU->getCbf( uiAbsPartIdx, compID, uiTrDepth );
+        }
+        //----- determine rate and r-d cost -----
+        if(modeId == 1 && singleCbfTmp[COMPONENT_Y] == 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( rTu, true, !bLumaOnly, false );
+          singleCostTmp     = m_pcRdCost->calcRdCost( uiSingleBits, singleDistTmp[CHANNEL_TYPE_LUMA] + singleDistTmp[CHANNEL_TYPE_CHROMA] );
+        }
+        if(singleCostTmp < dSingleCost)
+        {
+          DEBUG_STRING_SWAP(sDebug, sModeString)
+          dSingleCost   = singleCostTmp;
+          uiSingleDist[CHANNEL_TYPE_LUMA] = singleDistTmp[CHANNEL_TYPE_LUMA];
+          uiSingleDist[CHANNEL_TYPE_CHROMA] = singleDistTmp[CHANNEL_TYPE_CHROMA];
+          for (UInt ch=0; ch<MAX_NUM_COMPONENT; ch++)
+            uiSingleCbf[ch] = singleCbfTmp[ch];
+
+          bestModeId[COMPONENT_Y] = modeId;
+          if(bestModeId[COMPONENT_Y] == firstCheckId)
+          {
+            xStoreIntraResultQT(COMPONENT_Y, bLumaOnly?COMPONENT_Y:COMPONENT_Cr, rTu );
+            m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[ uiFullDepth ][ CI_TEMP_BEST ] );
+          }
+
+          if (pcCU->getSlice()->getPPS()->getUseCrossComponentPrediction())
+          {
+            const Int xOffset = rTu.getRect( COMPONENT_Y ).x0;
+            const Int yOffset = rTu.getRect( COMPONENT_Y ).y0;
+            for (UInt storedResidualIndex = 0; storedResidualIndex < NUMBER_OF_STORED_RESIDUAL_TYPES; storedResidualIndex++)
+            {
+              if (bMaintainResidual[storedResidualIndex])
+              {
+                xStoreCrossComponentPredictionResult(resiLuma[storedResidualIndex], resiLumaSingle[storedResidualIndex], rTu, xOffset, yOffset, MAX_CU_SIZE, MAX_CU_SIZE);
+              }
+            }
+          }
+        }
+        if (modeId == firstCheckId)
+        {
+          m_pcRDGoOnSbacCoder->load ( m_pppcRDSbacCoder[ uiFullDepth ][ CI_QT_TRAFO_ROOT ] );
+        }
+      }
+
+      for(UInt ch=COMPONENT_Y; ch<numValidComp; ch++)
+      {
+        const ComponentID compID=ComponentID(ch);
+        if (rTu.ProcessComponentSection(compID))
+        {
+          const UInt totalAdjustedDepthChan   = rTu.GetTransformDepthTotalAdj(compID);
+          pcCU ->setTransformSkipSubParts ( bestModeId[COMPONENT_Y], compID, uiAbsPartIdx, totalAdjustedDepthChan );
+        }
+      }
+
+      if(bestModeId[COMPONENT_Y] == firstCheckId)
+      {
+        xLoadIntraResultQT(COMPONENT_Y, bLumaOnly?COMPONENT_Y:COMPONENT_Cr, rTu );
+        for(UInt ch=COMPONENT_Y; ch< numValidComp; ch++)
+        {
+          const ComponentID compID=ComponentID(ch);
+          if (rTu.ProcessComponentSection(compID))
+            pcCU->setCbfSubParts  ( uiSingleCbf[compID] << uiTrDepth, compID, uiAbsPartIdx, rTu.GetTransformDepthTotalAdj(compID) );
+        }
+
+        m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[ uiFullDepth ][ CI_TEMP_BEST ] );
+      }
+
+      if( !bLumaOnly )
+      {
+        bestModeId[COMPONENT_Cb] = bestModeId[COMPONENT_Cr] = bestModeId[COMPONENT_Y];
+        if (rTu.ProcessComponentSection(COMPONENT_Cb) && bestModeId[COMPONENT_Y] == 1)
+        {
+          //In order not to code TS flag when cbf is zero, the case for TS with cbf being zero is forbidden.
+          for (UInt ch=COMPONENT_Cb; ch<numValidComp; ch++)
+          {
+            if (uiSingleCbf[ch] == 0)
+            {
+              const ComponentID compID=ComponentID(ch);
+              const UInt totalAdjustedDepthChan = rTu.GetTransformDepthTotalAdj(compID);
+              pcCU ->setTransformSkipSubParts ( 0, compID, uiAbsPartIdx, totalAdjustedDepthChan);
+              bestModeId[ch] = 0;
+            }
+          }
+        }
+      }
+    }
+    else
+    {
+      //----- store original entropy coding status -----
+      if( bCheckSplit )
+      {
+        m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[ uiFullDepth ][ CI_QT_TRAFO_ROOT ] );
+      }
+      //----- code luma/chroma block with given intra prediction mode and store Cbf-----
+      dSingleCost   = 0.0;
+      for (UInt ch=COMPONENT_Y; ch<numValidComp; ch++)
+      {
+        const ComponentID compID = ComponentID(ch);
+
+        if (rTu.ProcessComponentSection(compID))
+        {
+          const UInt totalAdjustedDepthChan   = rTu.GetTransformDepthTotalAdj(compID);
+          pcCU ->setTransformSkipSubParts ( 0, compID, uiAbsPartIdx, totalAdjustedDepthChan );
+        }
+
+        xIntraCodingTUBlock( pcOrgYuv, pcPredYuv, pcResiYuv, resiLumaSingle, false, uiSingleDist[toChannelType(compID)], compID, rTu DEBUG_STRING_PASS_INTO(sDebug));
+
+        if( bCheckSplit )
+        {
+          uiSingleCbf[compID] = pcCU->getCbf( uiAbsPartIdx, compID, uiTrDepth );
+        }
+      }
+      //----- determine rate and r-d cost -----
+      UInt uiSingleBits = xGetIntraBitsQT( rTu, true, !bLumaOnly, false );
+
+      if(m_pcEncCfg->getRDpenalty() && (uiLog2TrSize==5) && !isIntraSlice)
+      {
+        uiSingleBits=uiSingleBits*4;
+      }
+
+      dSingleCost       = m_pcRdCost->calcRdCost( uiSingleBits, uiSingleDist[CHANNEL_TYPE_LUMA] + uiSingleDist[CHANNEL_TYPE_CHROMA] );
+
+      if (pcCU->getSlice()->getPPS()->getUseCrossComponentPrediction())
+      {
+        const Int xOffset = rTu.getRect( COMPONENT_Y ).x0;
+        const Int yOffset = rTu.getRect( COMPONENT_Y ).y0;
+        for (UInt storedResidualIndex = 0; storedResidualIndex < NUMBER_OF_STORED_RESIDUAL_TYPES; storedResidualIndex++)
+        {
+          if (bMaintainResidual[storedResidualIndex])
+          {
+            xStoreCrossComponentPredictionResult(resiLuma[storedResidualIndex], resiLumaSingle[storedResidualIndex], rTu, xOffset, yOffset, MAX_CU_SIZE, MAX_CU_SIZE);
+          }
+        }
+      }
+    }
+  }
+
+  if( bCheckSplit )
+  {
+    //----- store full entropy coding status, load original entropy coding status -----
+    if( bCheckFull )
+    {
+      m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[ uiFullDepth ][ CI_QT_TRAFO_TEST ] );
+      m_pcRDGoOnSbacCoder->load ( m_pppcRDSbacCoder[ uiFullDepth ][ CI_QT_TRAFO_ROOT ] );
+    }
+    else
+    {
+      m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[ uiFullDepth ][ CI_QT_TRAFO_ROOT ] );
+    }
+    //----- code splitted block -----
+    Double     dSplitCost                         = 0.0;
+    Distortion uiSplitDist[MAX_NUM_CHANNEL_TYPE]  = {0,0};
+    UInt       uiSplitCbf[MAX_NUM_COMPONENT]      = {0,0,0};
+
+    TComTURecurse tuRecurseChild(rTu, false);
+    DEBUG_STRING_NEW(sSplit)
+    do
+    {
+      DEBUG_STRING_NEW(sChild)
+#if HHI_RQT_INTRA_SPEEDUP
+      xRecurIntraCodingQT( bLumaOnly, pcOrgYuv, pcPredYuv, pcResiYuv, resiLumaSplit, uiSplitDist[0], uiSplitDist[1], bCheckFirst, dSplitCost, tuRecurseChild DEBUG_STRING_PASS_INTO(sChild) );
+#else
+      xRecurIntraCodingQT( bLumaOnly, pcOrgYuv, pcPredYuv, pcResiYuv, resiLumaSplit, uiSplitDist[0], uiSplitDist[1], dSplitCost, tuRecurseChild DEBUG_STRING_PASS_INTO(sChild) );
+#endif
+      DEBUG_STRING_APPEND(sSplit, sChild)
+      for(UInt ch=0; ch<numValidComp; ch++)
+      {
+        uiSplitCbf[ch] |= pcCU->getCbf( tuRecurseChild.GetAbsPartIdxTU(), ComponentID(ch), tuRecurseChild.GetTransformDepthRel() );
+      }
+    } while (tuRecurseChild.nextSection(rTu) );
+
+    UInt    uiPartsDiv     = rTu.GetAbsPartIdxNumParts();
+    for(UInt ch=COMPONENT_Y; ch<numValidComp; ch++)
+    {
+      if (uiSplitCbf[ch])
+      {
+        const UInt flag=1<<uiTrDepth;
+        const ComponentID compID=ComponentID(ch);
+        UChar *pBase=pcCU->getCbf( compID );
+        for( UInt uiOffs = 0; uiOffs < uiPartsDiv; uiOffs++ )
+        {
+          pBase[ uiAbsPartIdx + uiOffs ] |= flag;
+        }
+      }
+    }
+    //----- restore context states -----
+    m_pcRDGoOnSbacCoder->load ( m_pppcRDSbacCoder[ uiFullDepth ][ CI_QT_TRAFO_ROOT ] );
+    
+    //----- determine rate and r-d cost -----
+    UInt uiSplitBits = xGetIntraBitsQT( rTu, true, !bLumaOnly, false );
+    dSplitCost       = m_pcRdCost->calcRdCost( uiSplitBits, uiSplitDist[CHANNEL_TYPE_LUMA] + uiSplitDist[CHANNEL_TYPE_CHROMA] );
+
+    //===== compare and set best =====
+    if( dSplitCost < dSingleCost )
+    {
+      //--- update cost ---
+      DEBUG_STRING_SWAP(sSplit, sDebug)
+      ruiDistY += uiSplitDist[CHANNEL_TYPE_LUMA];
+      ruiDistC += uiSplitDist[CHANNEL_TYPE_CHROMA];
+      dRDCost  += dSplitCost;
+
+      if (pcCU->getSlice()->getPPS()->getUseCrossComponentPrediction())
+      {
+        const Int xOffset = rTu.getRect( COMPONENT_Y ).x0;
+        const Int yOffset = rTu.getRect( COMPONENT_Y ).y0;
+        for (UInt storedResidualIndex = 0; storedResidualIndex < NUMBER_OF_STORED_RESIDUAL_TYPES; storedResidualIndex++)
+        {
+          if (bMaintainResidual[storedResidualIndex])
+          {
+            xStoreCrossComponentPredictionResult(resiLuma[storedResidualIndex], resiLumaSplit[storedResidualIndex], rTu, xOffset, yOffset, MAX_CU_SIZE, MAX_CU_SIZE);
+          }
+        }
+      }
+
+      return;
+    }
+
+    //----- set entropy coding status -----
+    m_pcRDGoOnSbacCoder->load ( m_pppcRDSbacCoder[ uiFullDepth ][ CI_QT_TRAFO_TEST ] );
+
+    //--- set transform index and Cbf values ---
+    pcCU->setTrIdxSubParts( uiTrDepth, uiAbsPartIdx, uiFullDepth );
+    for(UInt ch=0; ch<numValidComp; ch++)
+    {
+      const ComponentID compID=ComponentID(ch);
+      const TComRectangle &tuRect=rTu.getRect(compID);
+      const UInt totalAdjustedDepthChan   = rTu.GetTransformDepthTotalAdj(compID);
+      pcCU->setCbfSubParts  ( uiSingleCbf[compID] << uiTrDepth, compID, uiAbsPartIdx, totalAdjustedDepthChan );
+      pcCU ->setTransformSkipSubParts  ( bestModeId[compID], compID, uiAbsPartIdx, totalAdjustedDepthChan );
+
+      //--- set reconstruction for next intra prediction blocks ---
+      const UInt  uiQTLayer   = pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() - uiLog2TrSize;
+      const UInt  uiZOrder    = pcCU->getZorderIdxInCtu() + uiAbsPartIdx;
+      const UInt  uiWidth     = tuRect.width;
+      const UInt  uiHeight    = tuRect.height;
+      Pel*  piSrc       = m_pcQTTempTComYuv[ uiQTLayer ].getAddr( compID, uiAbsPartIdx );
+      UInt  uiSrcStride = m_pcQTTempTComYuv[ uiQTLayer ].getStride  ( compID );
+      Pel*  piDes       = pcCU->getPic()->getPicYuvRec()->getAddr( compID, pcCU->getCtuRsAddr(), uiZOrder );
+      UInt  uiDesStride = pcCU->getPic()->getPicYuvRec()->getStride  ( compID );
+
+      for( UInt uiY = 0; uiY < uiHeight; uiY++, piSrc += uiSrcStride, piDes += uiDesStride )
+      {
+        for( UInt uiX = 0; uiX < uiWidth; uiX++ )
+        {
+          piDes[ uiX ] = piSrc[ uiX ];
+        }
+      }
+    }
+  }
+  ruiDistY += uiSingleDist[CHANNEL_TYPE_LUMA];
+  ruiDistC += uiSingleDist[CHANNEL_TYPE_CHROMA];
+  dRDCost  += dSingleCost;
+}
+
+
+Void
+TEncSearch::xSetIntraResultQT(Bool        bLumaOnly,
+                              TComYuv*    pcRecoYuv,
+                              TComTU     &rTu)
+{
+  TComDataCU *pcCU        = rTu.getCU();
+  const UInt uiTrDepth    = rTu.GetTransformDepthRel();
+  const UInt uiAbsPartIdx = rTu.GetAbsPartIdxTU();
+  UInt uiTrMode     = pcCU->getTransformIdx( uiAbsPartIdx );
+  if(  uiTrMode == uiTrDepth )
+  {
+    UInt uiLog2TrSize = rTu.GetLog2LumaTrSize();
+    UInt uiQTLayer    = pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() - uiLog2TrSize;
+
+    Bool bSkipChroma = !rTu.ProcessChannelSection(CHANNEL_TYPE_CHROMA);
+
+    //===== copy transform coefficients =====
+
+    const UInt numChannelsToProcess = (bLumaOnly || bSkipChroma) ? 1 : ::getNumberValidComponents(pcCU->getPic()->getChromaFormat());
+    for (UInt ch=0; ch<numChannelsToProcess; ch++)
+    {
+      const ComponentID compID = ComponentID(ch);
+      const TComRectangle &tuRect=rTu.getRect(compID);
+      const UInt coeffOffset = rTu.getCoefficientOffset(compID);
+      const UInt numCoeffInBlock = tuRect.width * tuRect.height;
+
+      if (numCoeffInBlock!=0)
+      {
+        const TCoeff* srcCoeff = m_ppcQTTempCoeff[compID][uiQTLayer] + coeffOffset;
+        TCoeff* destCoeff      = pcCU->getCoeff(compID) + coeffOffset;
+        ::memcpy( destCoeff, srcCoeff, sizeof(TCoeff)*numCoeffInBlock );
+#if ADAPTIVE_QP_SELECTION
+        const TCoeff* srcArlCoeff = m_ppcQTTempArlCoeff[compID][ uiQTLayer ] + coeffOffset;
+        TCoeff* destArlCoeff      = pcCU->getArlCoeff (compID)               + coeffOffset;
+        ::memcpy( destArlCoeff, srcArlCoeff, sizeof( TCoeff ) * numCoeffInBlock );
+#endif
+        m_pcQTTempTComYuv[ uiQTLayer ].copyPartToPartComponent( compID, pcRecoYuv, uiAbsPartIdx, tuRect.width, tuRect.height );
+      }
+    } // End of channel loop
+
+  }
+  else
+  {
+    TComTURecurse tuRecurseChild(rTu, false);
+    do
+    {
+      xSetIntraResultQT( bLumaOnly, pcRecoYuv, tuRecurseChild );
+    } while (tuRecurseChild.nextSection(rTu));
+  }
+}
+
+
+Void
+TEncSearch::xStoreIntraResultQT(const ComponentID first,
+                                const ComponentID lastIncl,
+                                      TComTU &rTu )
+{
+  TComDataCU *pcCU=rTu.getCU();
+  const UInt uiTrDepth = rTu.GetTransformDepthRel();
+  const UInt uiAbsPartIdx = rTu.GetAbsPartIdxTU();
+  const UInt uiTrMode     = pcCU->getTransformIdx( uiAbsPartIdx );
+  if (  first==COMPONENT_Y || uiTrMode == uiTrDepth )
+  {
+    assert(uiTrMode == uiTrDepth);
+    const UInt uiLog2TrSize = rTu.GetLog2LumaTrSize();
+    const UInt uiQTLayer    = pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() - uiLog2TrSize;
+
+
+    for(UInt compID_=first; compID_<=lastIncl; compID_++)
+    {
+      ComponentID compID=ComponentID(compID_);
+      if (rTu.ProcessComponentSection(compID))
+      {
+        const TComRectangle &tuRect=rTu.getRect(compID);
+
+        //===== copy transform coefficients =====
+        const UInt uiNumCoeff    = tuRect.width * tuRect.height;
+        TCoeff* pcCoeffSrc = m_ppcQTTempCoeff[compID] [ uiQTLayer ] + rTu.getCoefficientOffset(compID);
+        TCoeff* pcCoeffDst = m_pcQTTempTUCoeff[compID];
+
+        ::memcpy( pcCoeffDst, pcCoeffSrc, sizeof( TCoeff ) * uiNumCoeff );
+#if ADAPTIVE_QP_SELECTION
+        TCoeff* pcArlCoeffSrc = m_ppcQTTempArlCoeff[compID] [ uiQTLayer ] + rTu.getCoefficientOffset(compID);
+        TCoeff* pcArlCoeffDst = m_ppcQTTempTUArlCoeff[compID];
+        ::memcpy( pcArlCoeffDst, pcArlCoeffSrc, sizeof( TCoeff ) * uiNumCoeff );
+#endif
+        //===== copy reconstruction =====
+        m_pcQTTempTComYuv[ uiQTLayer ].copyPartToPartComponent( compID, &m_pcQTTempTransformSkipTComYuv, uiAbsPartIdx, tuRect.width, tuRect.height );
+      }
+    }
+  }
+}
+
+
+Void
+TEncSearch::xLoadIntraResultQT(const ComponentID first,
+                               const ComponentID lastIncl,
+                                     TComTU &rTu)
+{
+  TComDataCU *pcCU=rTu.getCU();
+  const UInt uiTrDepth = rTu.GetTransformDepthRel();
+  const UInt uiAbsPartIdx = rTu.GetAbsPartIdxTU();
+  const UInt uiTrMode     = pcCU->getTransformIdx( uiAbsPartIdx );
+  if (  first==COMPONENT_Y || uiTrMode == uiTrDepth )
+  {
+    assert(uiTrMode == uiTrDepth);
+    const UInt uiLog2TrSize = rTu.GetLog2LumaTrSize();
+    const UInt uiQTLayer    = pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() - uiLog2TrSize;
+    const UInt uiZOrder     = pcCU->getZorderIdxInCtu() + uiAbsPartIdx;
+
+    for(UInt compID_=first; compID_<=lastIncl; compID_++)
+    {
+      ComponentID compID=ComponentID(compID_);
+      if (rTu.ProcessComponentSection(compID))
+      {
+        const TComRectangle &tuRect=rTu.getRect(compID);
+
+        //===== copy transform coefficients =====
+        const UInt uiNumCoeff = tuRect.width * tuRect.height;
+        TCoeff* pcCoeffDst = m_ppcQTTempCoeff[compID] [ uiQTLayer ] + rTu.getCoefficientOffset(compID);
+        TCoeff* pcCoeffSrc = m_pcQTTempTUCoeff[compID];
+
+        ::memcpy( pcCoeffDst, pcCoeffSrc, sizeof( TCoeff ) * uiNumCoeff );
+#if ADAPTIVE_QP_SELECTION
+        TCoeff* pcArlCoeffDst = m_ppcQTTempArlCoeff[compID] [ uiQTLayer ] + rTu.getCoefficientOffset(compID);
+        TCoeff* pcArlCoeffSrc = m_ppcQTTempTUArlCoeff[compID];
+        ::memcpy( pcArlCoeffDst, pcArlCoeffSrc, sizeof( TCoeff ) * uiNumCoeff );
+#endif
+        //===== copy reconstruction =====
+        m_pcQTTempTransformSkipTComYuv.copyPartToPartComponent( compID, &m_pcQTTempTComYuv[ uiQTLayer ], uiAbsPartIdx, tuRect.width, tuRect.height );
+
+        Pel*    piRecIPred        = pcCU->getPic()->getPicYuvRec()->getAddr( compID, pcCU->getCtuRsAddr(), uiZOrder );
+        UInt    uiRecIPredStride  = pcCU->getPic()->getPicYuvRec()->getStride (compID);
+        Pel*    piRecQt           = m_pcQTTempTComYuv[ uiQTLayer ].getAddr( compID, uiAbsPartIdx );
+        UInt    uiRecQtStride     = m_pcQTTempTComYuv[ uiQTLayer ].getStride  (compID);
+        UInt    uiWidth           = tuRect.width;
+        UInt    uiHeight          = tuRect.height;
+        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::xStoreCrossComponentPredictionResult(       Pel    *pResiDst,
+                                                  const Pel    *pResiSrc,
+                                                        TComTU &rTu,
+                                                  const Int     xOffset,
+                                                  const Int     yOffset,
+                                                  const Int     strideDst,
+                                                  const Int     strideSrc )
+{
+  const Pel *pSrc = pResiSrc + yOffset * strideSrc + xOffset;
+        Pel *pDst = pResiDst + yOffset * strideDst + xOffset;
+
+  for( Int y = 0; y < rTu.getRect( COMPONENT_Y ).height; y++ )
+  {
+    ::memcpy( pDst, pSrc, sizeof(Pel) * rTu.getRect( COMPONENT_Y ).width );
+    pDst += strideDst;
+    pSrc += strideSrc;
+  }
+}
+
+Char
+TEncSearch::xCalcCrossComponentPredictionAlpha(       TComTU &rTu,
+                                                const ComponentID compID,
+                                                const Pel*        piResiL,
+                                                const Pel*        piResiC,
+                                                const Int         width,
+                                                const Int         height,
+                                                const Int         strideL,
+                                                const Int         strideC )
+{
+  const Pel *pResiL = piResiL;
+  const Pel *pResiC = piResiC;
+
+        TComDataCU *pCU = rTu.getCU();
+  const Int  absPartIdx = rTu.GetAbsPartIdxTU( compID );
+  const Int diffBitDepth = pCU->getSlice()->getSPS()->getDifferentialLumaChromaBitDepth();
+
+  Char alpha = 0;
+  Int SSxy  = 0;
+  Int SSxx  = 0;
+
+  for( UInt uiY = 0; uiY < height; uiY++ )
+  {
+    for( UInt uiX = 0; uiX < width; uiX++ )
+    {
+      const Pel scaledResiL = rightShift( pResiL[ uiX ], diffBitDepth );
+      SSxy += ( scaledResiL * pResiC[ uiX ] );
+      SSxx += ( scaledResiL * scaledResiL   );
+    }
+
+    pResiL += strideL;
+    pResiC += strideC;
+  }
+
+  if( SSxx != 0 )
+  {
+    Double dAlpha = SSxy / Double( SSxx );
+    alpha = Char(Clip3<Int>(-16, 16, (Int)(dAlpha * 16)));
+
+    static const Char alphaQuant[17] = {0, 1, 1, 2, 2, 2, 4, 4, 4, 4, 4, 4, 8, 8, 8, 8, 8};
+
+    alpha = (alpha < 0) ? -alphaQuant[Int(-alpha)] : alphaQuant[Int(alpha)];
+  }
+  pCU->setCrossComponentPredictionAlphaPartRange( alpha, compID, absPartIdx, rTu.GetAbsPartIdxNumParts( compID ) );
+
+  return alpha;
+}
+
+Void
+TEncSearch::xRecurIntraChromaCodingQT(TComYuv*    pcOrgYuv,
+                                      TComYuv*    pcPredYuv,
+                                      TComYuv*    pcResiYuv,
+                                      Pel         resiLuma[NUMBER_OF_STORED_RESIDUAL_TYPES][MAX_CU_SIZE * MAX_CU_SIZE],
+                                      Distortion& ruiDist,
+                                      TComTU&     rTu
+                                      DEBUG_STRING_FN_DECLARE(sDebug))
+{
+  TComDataCU         *pcCU                  = rTu.getCU();
+  const UInt          uiTrDepth             = rTu.GetTransformDepthRel();
+  const UInt          uiAbsPartIdx          = rTu.GetAbsPartIdxTU();
+  const ChromaFormat  format                = rTu.GetChromaFormat();
+  UInt                uiTrMode              = pcCU->getTransformIdx( uiAbsPartIdx );
+  const UInt          numberValidComponents = getNumberValidComponents(format);
+
+  if(  uiTrMode == uiTrDepth )
+  {
+    if (!rTu.ProcessChannelSection(CHANNEL_TYPE_CHROMA)) return;
+
+    const UInt uiFullDepth = rTu.GetTransformDepthTotal();
+
+    Bool checkTransformSkip = pcCU->getSlice()->getPPS()->getUseTransformSkip();
+    checkTransformSkip &= TUCompRectHasAssociatedTransformSkipFlag(rTu.getRect(COMPONENT_Cb), pcCU->getSlice()->getPPS()->getTransformSkipLog2MaxSize());
+
+    if ( m_pcEncCfg->getUseTransformSkipFast() )
+    {
+      checkTransformSkip &= TUCompRectHasAssociatedTransformSkipFlag(rTu.getRect(COMPONENT_Y), pcCU->getSlice()->getPPS()->getTransformSkipLog2MaxSize());
+
+      if (checkTransformSkip)
+      {
+        Int nbLumaSkip = 0;
+        const UInt maxAbsPartIdxSub=uiAbsPartIdx + (rTu.ProcessingAllQuadrants(COMPONENT_Cb)?1:4);
+        for(UInt absPartIdxSub = uiAbsPartIdx; absPartIdxSub < maxAbsPartIdxSub; absPartIdxSub ++)
+        {
+          nbLumaSkip += pcCU->getTransformSkip(absPartIdxSub, COMPONENT_Y);
+        }
+        checkTransformSkip &= (nbLumaSkip > 0);
+      }
+    }
+
+
+    for (UInt ch=COMPONENT_Cb; ch<numberValidComponents; ch++)
+    {
+      const ComponentID compID = ComponentID(ch);
+      DEBUG_STRING_NEW(sDebugBestMode)
+
+      //use RDO to decide whether Cr/Cb takes TS
+      m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[uiFullDepth][CI_QT_TRAFO_ROOT] );
+
+      const Bool splitIntoSubTUs = rTu.getRect(compID).width != rTu.getRect(compID).height;
+
+      TComTURecurse TUIterator(rTu, false, (splitIntoSubTUs ? TComTU::VERTICAL_SPLIT : TComTU::DONT_SPLIT), true, compID);
+
+      const UInt partIdxesPerSubTU = TUIterator.GetAbsPartIdxNumParts(compID);
+
+      do
+      {
+        const UInt subTUAbsPartIdx   = TUIterator.GetAbsPartIdxTU(compID);
+
+        Double     dSingleCost               = MAX_DOUBLE;
+        Int        bestModeId                = 0;
+        Distortion singleDistC               = 0;
+        UInt       singleCbfC                = 0;
+        Distortion singleDistCTmp            = 0;
+        Double     singleCostTmp             = 0;
+        UInt       singleCbfCTmp             = 0;
+        Char       bestCrossCPredictionAlpha = 0;
+        Int        bestTransformSkipMode     = 0;
+
+        const Bool checkCrossComponentPrediction =    (pcCU->getIntraDir(CHANNEL_TYPE_CHROMA, subTUAbsPartIdx) == DM_CHROMA_IDX)
+                                                   &&  pcCU->getSlice()->getPPS()->getUseCrossComponentPrediction()
+                                                   && (pcCU->getCbf(subTUAbsPartIdx,  COMPONENT_Y, uiTrDepth) != 0);
+
+        const Int  crossCPredictionModesToTest = checkCrossComponentPrediction ? 2 : 1;
+        const Int  transformSkipModesToTest    = checkTransformSkip            ? 2 : 1;
+        const Int  totalModesToTest            = crossCPredictionModesToTest * transformSkipModesToTest;
+              Int  currModeId                  = 0;
+              Int  default0Save1Load2          = 0;
+
+        for(Int transformSkipModeId = 0; transformSkipModeId < transformSkipModesToTest; transformSkipModeId++)
+        {
+          for(Int crossCPredictionModeId = 0; crossCPredictionModeId < crossCPredictionModesToTest; crossCPredictionModeId++)
+          {
+            pcCU->setCrossComponentPredictionAlphaPartRange(0, compID, subTUAbsPartIdx, partIdxesPerSubTU);
+            DEBUG_STRING_NEW(sDebugMode)
+            pcCU->setTransformSkipPartRange( transformSkipModeId, compID, subTUAbsPartIdx, partIdxesPerSubTU );
+            currModeId++;
+
+            const Bool isOneMode  = (totalModesToTest == 1);
+            const Bool isLastMode = (currModeId == totalModesToTest); // currModeId is indexed from 1
+
+            if (isOneMode)
+            {
+              default0Save1Load2 = 0;
+            }
+            else if (!isOneMode && (transformSkipModeId == 0) && (crossCPredictionModeId == 0))
+            {
+              default0Save1Load2 = 1; //save prediction on first mode
+            }
+            else
+            {
+              default0Save1Load2 = 2; //load it on subsequent modes
+            }
+
+            singleDistCTmp = 0;
+
+            xIntraCodingTUBlock( pcOrgYuv, pcPredYuv, pcResiYuv, resiLuma, (crossCPredictionModeId != 0), singleDistCTmp, compID, TUIterator DEBUG_STRING_PASS_INTO(sDebugMode), default0Save1Load2);
+            singleCbfCTmp = pcCU->getCbf( subTUAbsPartIdx, compID, uiTrDepth);
+
+            if (  ((crossCPredictionModeId == 1) && (pcCU->getCrossComponentPredictionAlpha(subTUAbsPartIdx, compID) == 0))
+               || ((transformSkipModeId    == 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 if (!isOneMode)
+            {
+              UInt bitsTmp = xGetIntraBitsQTChroma( TUIterator, compID, false );
+              singleCostTmp  = m_pcRdCost->calcRdCost( bitsTmp, singleDistCTmp);
+            }
+
+            if(singleCostTmp < dSingleCost)
+            {
+              DEBUG_STRING_SWAP(sDebugBestMode, sDebugMode)
+              dSingleCost               = singleCostTmp;
+              singleDistC               = singleDistCTmp;
+              bestCrossCPredictionAlpha = (crossCPredictionModeId != 0) ? pcCU->getCrossComponentPredictionAlpha(subTUAbsPartIdx, compID) : 0;
+              bestTransformSkipMode     = transformSkipModeId;
+              bestModeId                = currModeId;
+              singleCbfC                = singleCbfCTmp;
+
+              if (!isOneMode && !isLastMode)
+              {
+                xStoreIntraResultQT(compID, compID, TUIterator);
+                m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[ uiFullDepth ][ CI_TEMP_BEST ] );
+              }
+            }
+
+            if (!isOneMode && !isLastMode)
+            {
+              m_pcRDGoOnSbacCoder->load ( m_pppcRDSbacCoder[ uiFullDepth ][ CI_QT_TRAFO_ROOT ] );
+            }
+          }
+        }
+
+        if(bestModeId < totalModesToTest)
+        {
+          xLoadIntraResultQT(compID, compID, TUIterator);
+          pcCU->setCbfPartRange( singleCbfC << uiTrDepth, compID, subTUAbsPartIdx, partIdxesPerSubTU );
+
+          m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[ uiFullDepth ][ CI_TEMP_BEST ] );
+        }
+
+        DEBUG_STRING_APPEND(sDebug, sDebugBestMode)
+        pcCU ->setTransformSkipPartRange                ( bestTransformSkipMode,     compID, subTUAbsPartIdx, partIdxesPerSubTU );
+        pcCU ->setCrossComponentPredictionAlphaPartRange( bestCrossCPredictionAlpha, compID, subTUAbsPartIdx, partIdxesPerSubTU );
+        ruiDist += singleDistC;
+      }
+      while (TUIterator.nextSection(rTu));
+
+      if (splitIntoSubTUs) offsetSubTUCBFs(rTu, compID);
+    }
+  }
+  else
+  {
+    UInt    uiSplitCbf[MAX_NUM_COMPONENT] = {0,0,0};
+
+    TComTURecurse tuRecurseChild(rTu, false);
+    const UInt uiTrDepthChild   = tuRecurseChild.GetTransformDepthRel();
+    do
+    {
+      DEBUG_STRING_NEW(sChild)
+
+      xRecurIntraChromaCodingQT( pcOrgYuv, pcPredYuv, pcResiYuv, resiLuma, ruiDist, tuRecurseChild DEBUG_STRING_PASS_INTO(sChild) );
+
+      DEBUG_STRING_APPEND(sDebug, sChild)
+      const UInt uiAbsPartIdxSub=tuRecurseChild.GetAbsPartIdxTU();
+
+      for(UInt ch=COMPONENT_Cb; ch<numberValidComponents; ch++)
+      {
+        uiSplitCbf[ch] |= pcCU->getCbf( uiAbsPartIdxSub, ComponentID(ch), uiTrDepthChild );
+      }
+    } while ( tuRecurseChild.nextSection(rTu) );
+
+
+    UInt uiPartsDiv = rTu.GetAbsPartIdxNumParts();
+    for(UInt ch=COMPONENT_Cb; ch<numberValidComponents; ch++)
+    {
+      if (uiSplitCbf[ch])
+      {
+        const UInt flag=1<<uiTrDepth;
+        ComponentID compID=ComponentID(ch);
+        UChar *pBase=pcCU->getCbf( compID );
+        for( UInt uiOffs = 0; uiOffs < uiPartsDiv; uiOffs++ )
+        {
+          pBase[ uiAbsPartIdx + uiOffs ] |= flag;
+        }
+      }
+    }
+  }
+}
+
+
+
+
+Void
+TEncSearch::xSetIntraResultChromaQT(TComYuv*    pcRecoYuv, TComTU &rTu)
+{
+  if (!rTu.ProcessChannelSection(CHANNEL_TYPE_CHROMA)) return;
+  TComDataCU *pcCU=rTu.getCU();
+  const UInt uiAbsPartIdx = rTu.GetAbsPartIdxTU();
+  const UInt uiTrDepth   = rTu.GetTransformDepthRel();
+  UInt uiTrMode     = pcCU->getTransformIdx( uiAbsPartIdx );
+  if(  uiTrMode == uiTrDepth )
+  {
+    UInt uiLog2TrSize = rTu.GetLog2LumaTrSize();
+    UInt uiQTLayer    = pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() - uiLog2TrSize;
+
+    //===== copy transform coefficients =====
+    const TComRectangle &tuRectCb=rTu.getRect(COMPONENT_Cb);
+    UInt uiNumCoeffC    = tuRectCb.width*tuRectCb.height;//( pcCU->getSlice()->getSPS()->getMaxCUWidth() * pcCU->getSlice()->getSPS()->getMaxCUHeight() ) >> ( uiFullDepth << 1 );
+    const UInt offset = rTu.getCoefficientOffset(COMPONENT_Cb);
+
+    const UInt numberValidComponents = getNumberValidComponents(rTu.GetChromaFormat());
+    for (UInt ch=COMPONENT_Cb; ch<numberValidComponents; ch++)
+    {
+      const ComponentID component = ComponentID(ch);
+      const TCoeff* src           = m_ppcQTTempCoeff[component][uiQTLayer] + offset;//(uiNumCoeffIncC*uiAbsPartIdx);
+      TCoeff* dest                = pcCU->getCoeff(component) + offset;//(uiNumCoeffIncC*uiAbsPartIdx);
+      ::memcpy( dest, src, sizeof(TCoeff)*uiNumCoeffC );
+#if ADAPTIVE_QP_SELECTION
+      TCoeff* pcArlCoeffSrc = m_ppcQTTempArlCoeff[component][ uiQTLayer ] + offset;//( uiNumCoeffIncC * uiAbsPartIdx );
+      TCoeff* pcArlCoeffDst = pcCU->getArlCoeff(component)                + offset;//( uiNumCoeffIncC * uiAbsPartIdx );
+      ::memcpy( pcArlCoeffDst, pcArlCoeffSrc, sizeof( TCoeff ) * uiNumCoeffC );
+#endif
+    }
+
+    //===== copy reconstruction =====
+
+    m_pcQTTempTComYuv[ uiQTLayer ].copyPartToPartComponent( COMPONENT_Cb, pcRecoYuv, uiAbsPartIdx, tuRectCb.width, tuRectCb.height );
+    m_pcQTTempTComYuv[ uiQTLayer ].copyPartToPartComponent( COMPONENT_Cr, pcRecoYuv, uiAbsPartIdx, tuRectCb.width, tuRectCb.height );
+  }
+  else
+  {
+    TComTURecurse tuRecurseChild(rTu, false);
+    do
+    {
+      xSetIntraResultChromaQT( pcRecoYuv, tuRecurseChild );
+    } while (tuRecurseChild.nextSection(rTu));
+  }
+}
+
+
+
+Void
+TEncSearch::preestChromaPredMode( TComDataCU* pcCU,
+                                 TComYuv*    pcOrgYuv,
+                                 TComYuv*    pcPredYuv )
+{
+
+  //===== loop over partitions =====
+  const UInt    uiInitTrDepth  = pcCU->getPartitionSize(0) != SIZE_2Nx2N && enable4ChromaPUsInIntraNxNCU(pcOrgYuv->getChromaFormat()) ? 1 : 0;
+  TComTURecurse tuRecurseCU(pcCU, 0);
+  TComTURecurse tuRecurseWithPU(tuRecurseCU, false, (uiInitTrDepth==0)?TComTU::DONT_SPLIT : TComTU::QUAD_SPLIT);
+  const ChromaFormat chFmt = tuRecurseWithPU.GetChromaFormat();
+  Bool bFilterEnabled=filterIntraReferenceSamples(CHANNEL_TYPE_CHROMA, chFmt, pcCU->getSlice()->getSPS()->getDisableIntraReferenceSmoothing());
+
+  do
+  {
+    if (tuRecurseWithPU.ProcessChannelSection(CHANNEL_TYPE_CHROMA))
+    {
+      const TComRectangle &rect=tuRecurseWithPU.getRect(COMPONENT_Cb);
+      const UInt  uiWidth     = rect.width;
+      const UInt  uiHeight    = rect.height;
+      const UInt  partIdx     = tuRecurseWithPU.GetAbsPartIdxCU();
+      const UInt  uiStride    = pcOrgYuv ->getStride(COMPONENT_Cb);
+      Pel*  piOrgU      = pcOrgYuv ->getAddr ( COMPONENT_Cb, partIdx ); //TODO: Change this into an array and loop over chroma components below
+      Pel*  piOrgV      = pcOrgYuv ->getAddr ( COMPONENT_Cr, partIdx );
+      Pel*  piPredU     = pcPredYuv->getAddr ( COMPONENT_Cb, partIdx );
+      Pel*  piPredV     = pcPredYuv->getAddr ( COMPONENT_Cr, partIdx );
+
+      //===== init pattern =====
+      Bool  bAboveAvail = false;
+      Bool  bLeftAvail  = false;
+      DEBUG_STRING_NEW(sTemp)
+      initAdiPatternChType( tuRecurseWithPU, bAboveAvail, bLeftAvail, COMPONENT_Cb, bFilterEnabled DEBUG_STRING_PASS_INTO(sTemp) );
+      initAdiPatternChType( tuRecurseWithPU, bAboveAvail, bLeftAvail, COMPONENT_Cr, bFilterEnabled DEBUG_STRING_PASS_INTO(sTemp) );
+
+      //===== get best prediction modes (using SAD) =====
+            UInt        uiMinMode          = 0;
+            UInt        uiMaxMode          = 4;
+            UInt        uiBestMode         = MAX_UINT;
+            Distortion  uiMinSAD           = std::numeric_limits<Distortion>::max();
+      const UInt        mappedModeTable[4] = {PLANAR_IDX,DC_IDX,HOR_IDX,VER_IDX};
+
+      DistParam distParamU, distParamV;
+      const Bool bUseHadamard=pcCU->getCUTransquantBypass(0) == 0;
+      m_pcRdCost->setDistParam(distParamU, g_bitDepth[CHANNEL_TYPE_CHROMA], piOrgU, uiStride, piPredU, uiStride, uiWidth, uiHeight, bUseHadamard);
+      m_pcRdCost->setDistParam(distParamV, g_bitDepth[CHANNEL_TYPE_CHROMA], piOrgV, uiStride, piPredV, uiStride, uiWidth, uiHeight, bUseHadamard);
+      distParamU.bApplyWeight = false;
+      distParamV.bApplyWeight = false;
+
+      for( UInt uiMode_  = uiMinMode; uiMode_ < uiMaxMode; uiMode_++ )
+      {
+        UInt uiMode=mappedModeTable[uiMode_];
+        //--- get prediction ---
+        const Bool bUseFilter=TComPrediction::filteringIntraReferenceSamples(COMPONENT_Cb, uiMode, uiWidth, uiHeight, chFmt, pcCU->getSlice()->getSPS()->getDisableIntraReferenceSmoothing());
+
+        predIntraAng( COMPONENT_Cb, uiMode, piOrgU, uiStride, piPredU, uiStride, tuRecurseCU, bAboveAvail, bLeftAvail, bUseFilter );
+        predIntraAng( COMPONENT_Cr, uiMode, piOrgV, uiStride, piPredV, uiStride, tuRecurseCU, bAboveAvail, bLeftAvail, bUseFilter );
+
+        //--- get SAD ---
+        Distortion uiSAD  = distParamU.DistFunc(&distParamU);
+        uiSAD            += distParamV.DistFunc(&distParamV);
+        //--- check ---
+        if( uiSAD < uiMinSAD )
+        {
+          uiMinSAD   = uiSAD;
+          uiBestMode = uiMode;
+        }
+      }
+
+      //===== set chroma pred mode =====
+      pcCU->setIntraDirSubParts( CHANNEL_TYPE_CHROMA, uiBestMode, partIdx, tuRecurseWithPU.getCUDepth() + uiInitTrDepth );
+    }
+  } while (tuRecurseWithPU.nextSection(tuRecurseCU));
+}
+
+
+
+
+Void
+TEncSearch::estIntraPredQT(TComDataCU* pcCU,
+                           TComYuv*    pcOrgYuv,
+                           TComYuv*    pcPredYuv,
+                           TComYuv*    pcResiYuv,
+                           TComYuv*    pcRecoYuv,
+                           Pel         resiLuma[NUMBER_OF_STORED_RESIDUAL_TYPES][MAX_CU_SIZE * MAX_CU_SIZE],
+                           Distortion& ruiDistC,
+                           Bool        bLumaOnly
+                           DEBUG_STRING_FN_DECLARE(sDebug))
+{
+  const UInt         uiDepth               = pcCU->getDepth(0);
+  const UInt         uiInitTrDepth         = pcCU->getPartitionSize(0) == SIZE_2Nx2N ? 0 : 1;
+  const UInt         uiInitTrDepthC        = pcCU->getPartitionSize(0) != SIZE_2Nx2N && enable4ChromaPUsInIntraNxNCU(pcOrgYuv->getChromaFormat()) ? 1 : 0;
+  const UInt         uiNumPU               = 1<<(2*uiInitTrDepth);
+  const UInt         uiQNumParts           = pcCU->getTotalNumPart() >> 2;
+  const UInt         uiWidthBit            = pcCU->getIntraSizeIdx(0);
+  const ChromaFormat chFmt                 = pcCU->getPic()->getChromaFormat();
+  const UInt         numberValidComponents = getNumberValidComponents(chFmt);
+        Distortion   uiOverallDistY        = 0;
+        Distortion   uiOverallDistC        = 0;
+        UInt         CandNum;
+        Double       CandCostList[ FAST_UDI_MAX_RDMODE_NUM ];
+        Pel          resiLumaPU[NUMBER_OF_STORED_RESIDUAL_TYPES][MAX_CU_SIZE * MAX_CU_SIZE];
+
+        Bool    bMaintainResidual[NUMBER_OF_STORED_RESIDUAL_TYPES];
+        for (UInt residualTypeIndex = 0; residualTypeIndex < NUMBER_OF_STORED_RESIDUAL_TYPES; residualTypeIndex++)
+        {
+          bMaintainResidual[residualTypeIndex] = true; //assume true unless specified otherwise
+        }
+
+        bMaintainResidual[RESIDUAL_ENCODER_SIDE] = !(m_pcEncCfg->getUseReconBasedCrossCPredictionEstimate());
+
+  // Lambda calculation at equivalent Qp of 4 is recommended because at that Qp, the quantisation divisor is 1.
+#if FULL_NBIT
+  const Double sqrtLambdaForFirstPass= (m_pcEncCfg->getCostMode()==COST_MIXED_LOSSLESS_LOSSY_CODING && pcCU->getCUTransquantBypass(0)) ?
+                sqrt(0.57 * pow(2.0, ((LOSSLESS_AND_MIXED_LOSSLESS_RD_COST_TEST_QP_PRIME - 12) / 3.0)))
+              : m_pcRdCost->getSqrtLambda();
+#else
+  const Double sqrtLambdaForFirstPass= (m_pcEncCfg->getCostMode()==COST_MIXED_LOSSLESS_LOSSY_CODING && pcCU->getCUTransquantBypass(0)) ?
+                sqrt(0.57 * pow(2.0, ((LOSSLESS_AND_MIXED_LOSSLESS_RD_COST_TEST_QP_PRIME - 12 - 6 * (g_bitDepth[CHANNEL_TYPE_LUMA] - 8)) / 3.0)))
+              : m_pcRdCost->getSqrtLambda();
+#endif
+
+  //===== 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 =====
+  TComTURecurse tuRecurseCU(pcCU, 0);
+  TComTURecurse tuRecurseWithPU(tuRecurseCU, false, (uiInitTrDepth==0)?TComTU::DONT_SPLIT : TComTU::QUAD_SPLIT);
+
+  do
+  {
+    const UInt uiPartOffset=tuRecurseWithPU.GetAbsPartIdxTU();
+//  for( UInt uiPU = 0, uiPartOffset=0; uiPU < uiNumPU; uiPU++, uiPartOffset += uiQNumParts )
+  //{
+    //===== init pattern for luma prediction =====
+    Bool bAboveAvail = false;
+    Bool bLeftAvail  = false;
+    DEBUG_STRING_NEW(sTemp2)
+
+    //===== determine set of modes to be tested (using prediction signal only) =====
+    Int numModesAvailable     = 35; //total number of Intra modes
+    UInt uiRdModeList[FAST_UDI_MAX_RDMODE_NUM];
+    Int numModesForFullRD = g_aucIntraModeNumFast[ uiWidthBit ];
+
+    if (tuRecurseWithPU.ProcessComponentSection(COMPONENT_Y))
+      initAdiPatternChType( tuRecurseWithPU, bAboveAvail, bLeftAvail, COMPONENT_Y, true DEBUG_STRING_PASS_INTO(sTemp2) );
+
+    Bool doFastSearch = (numModesForFullRD != numModesAvailable);
+    if (doFastSearch)
+    {
+      assert(numModesForFullRD < numModesAvailable);
+#if FAST_INTRA_SHVC
+      Int   uiPreds[3] = {-1, -1, -1};
+      Int   iMode = -1;
+      Bool  skipFastHAD = false;
+      Int numCand = pcCU->getIntraDirPredictor( uiPartOffset, uiPreds, COMPONENT_Y, &iMode );
+
+      if( m_pcEncCfg->getUseFastIntraScalable() && pcCU->getLayerId() > 0 )
+      {
+        numModesAvailable = pcCU->reduceSetOfIntraModes(uiPartOffset, uiPreds, iMode );
+        if( numModesForFullRD > numModesAvailable ) //fast HAD can be skipped
+        {
+          skipFastHAD = true;
+          numModesForFullRD = numModesAvailable;
+          for( Int i=0; i < numModesForFullRD; i++ )
+          {
+            uiRdModeList[ i ] = g_reducedSetIntraModes[ i ];
+          }
+        }
+      }
+#endif
+
+      for( Int i=0; i < numModesForFullRD; i++ ) 
+      {
+        CandCostList[ i ] = MAX_DOUBLE;
+      }
+      CandNum = 0;
+
+      const TComRectangle &puRect=tuRecurseWithPU.getRect(COMPONENT_Y);
+      const UInt uiAbsPartIdx=tuRecurseWithPU.GetAbsPartIdxTU();
+
+      Pel* piOrg         = pcOrgYuv ->getAddr( COMPONENT_Y, uiAbsPartIdx );
+      Pel* piPred        = pcPredYuv->getAddr( COMPONENT_Y, uiAbsPartIdx );
+      UInt uiStride      = pcPredYuv->getStride( COMPONENT_Y );
+      DistParam distParam;
+      const Bool bUseHadamard=pcCU->getCUTransquantBypass(0) == 0;
+      m_pcRdCost->setDistParam(distParam, g_bitDepth[CHANNEL_TYPE_LUMA], piOrg, uiStride, piPred, uiStride, puRect.width, puRect.height, bUseHadamard);
+      distParam.bApplyWeight = false;
+      for( Int modeIdx = 0; modeIdx < numModesAvailable; modeIdx++ )
+      {
+        UInt       uiMode = modeIdx;
+        Distortion uiSad  = 0;
+#if FAST_INTRA_SHVC
+        if ( m_pcEncCfg->getUseFastIntraScalable() )
+        {
+          if( skipFastHAD )//indicates that fast HAD can be skipped
+          {
+            break;
+          }
+          uiMode = ( iMode==0 ) ? g_reducedSetIntraModes[modeIdx] : uiMode; //(iMode=0) indicates reduced set of modes
+        }
+#endif
+
+        const Bool bUseFilter=TComPrediction::filteringIntraReferenceSamples(COMPONENT_Y, uiMode, puRect.width, puRect.height, chFmt, pcCU->getSlice()->getSPS()->getDisableIntraReferenceSmoothing());
+
+        predIntraAng( COMPONENT_Y, uiMode, piOrg, uiStride, piPred, uiStride, tuRecurseWithPU, bAboveAvail, bLeftAvail, bUseFilter, TComPrediction::UseDPCMForFirstPassIntraEstimation(tuRecurseWithPU, uiMode) );
+
+        // use hadamard transform here
+        uiSad+=distParam.DistFunc(&distParam);
+
+        UInt   iModeBits = 0;
+
+        // NB xModeBitsIntra will not affect the mode for chroma that may have already been pre-estimated.
+        iModeBits+=xModeBitsIntra( pcCU, uiMode, uiPartOffset, uiDepth, uiInitTrDepth, CHANNEL_TYPE_LUMA );
+
+        Double cost      = (Double)uiSad + (Double)iModeBits * sqrtLambdaForFirstPass;
+
+#ifdef DEBUG_INTRA_SEARCH_COSTS
+        std::cout << "1st pass mode " << uiMode << " SAD = " << uiSad << ", mode bits = " << iModeBits << ", cost = " << cost << "\n";
+#endif
+
+        CandNum += xUpdateCandList( uiMode, cost, numModesForFullRD, uiRdModeList, CandCostList );
+      }
+
+#if FAST_UDI_USE_MPM
+#if FAST_INTRA_SHVC == 0
+      Int uiPreds[NUM_MOST_PROBABLE_MODES] = {-1, -1, -1};
+
+      Int iMode = -1;
+      Int numCand = pcCU->getIntraDirPredictor( uiPartOffset, uiPreds, COMPONENT_Y, &iMode );
+#endif
+      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;
+      }
+    }
+
+    //===== check modes (using r-d costs) =====
+#if HHI_RQT_INTRA_SPEEDUP_MOD
+    UInt   uiSecondBestMode  = MAX_UINT;
+    Double dSecondBestPUCost = MAX_DOUBLE;
+#endif
+    DEBUG_STRING_NEW(sPU)
+    UInt       uiBestPUMode  = 0;
+    Distortion uiBestPUDistY = 0;
+    Distortion uiBestPUDistC = 0;
+    Double     dBestPUCost   = MAX_DOUBLE;
+
+#if ENVIRONMENT_VARIABLE_DEBUG_AND_TEST
+    UInt max=numModesForFullRD;
+
+    if (DebugOptionList::ForceLumaMode.isSet()) max=0;  // we are forcing a direction, so don't bother with mode check
+    for ( UInt uiMode = 0; uiMode < max; uiMode++)
+#else
+    for( UInt uiMode = 0; uiMode < numModesForFullRD; uiMode++ )
+#endif
+    {
+      // set luma prediction mode
+      UInt uiOrgMode = uiRdModeList[uiMode];
+
+      pcCU->setIntraDirSubParts ( CHANNEL_TYPE_LUMA, uiOrgMode, uiPartOffset, uiDepth + uiInitTrDepth );
+
+      DEBUG_STRING_NEW(sMode)
+      // set context models
+      m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[uiDepth][CI_CURR_BEST] );
+
+      // determine residual for partition
+      Distortion uiPUDistY = 0;
+      Distortion uiPUDistC = 0;
+      Double     dPUCost   = 0.0;
+#if HHI_RQT_INTRA_SPEEDUP
+      xRecurIntraCodingQT( bLumaOnly, pcOrgYuv, pcPredYuv, pcResiYuv, resiLumaPU, uiPUDistY, uiPUDistC, true, dPUCost, tuRecurseWithPU DEBUG_STRING_PASS_INTO(sMode) );
+#else
+      xRecurIntraCodingQT( bLumaOnly, pcOrgYuv, pcPredYuv, pcResiYuv, resiLumaPU, uiPUDistY, uiPUDistC, dPUCost, tuRecurseWithPU DEBUG_STRING_PASS_INTO(sMode) );
+#endif
+
+#ifdef DEBUG_INTRA_SEARCH_COSTS
+      std::cout << "2nd pass [luma,chroma] mode [" << Int(pcCU->getIntraDir(CHANNEL_TYPE_LUMA, uiPartOffset)) << "," << Int(pcCU->getIntraDir(CHANNEL_TYPE_CHROMA, uiPartOffset)) << "] cost = " << dPUCost << "\n";
+#endif
+
+      // check r-d cost
+      if( dPUCost < dBestPUCost )
+      {
+        DEBUG_STRING_SWAP(sPU, sMode)
+#if HHI_RQT_INTRA_SPEEDUP_MOD
+        uiSecondBestMode  = uiBestPUMode;
+        dSecondBestPUCost = dBestPUCost;
+#endif
+        uiBestPUMode  = uiOrgMode;
+        uiBestPUDistY = uiPUDistY;
+        uiBestPUDistC = uiPUDistC;
+        dBestPUCost   = dPUCost;
+
+        xSetIntraResultQT( bLumaOnly, pcRecoYuv, tuRecurseWithPU );
+
+        if (pcCU->getSlice()->getPPS()->getUseCrossComponentPrediction())
+        {
+          const Int xOffset = tuRecurseWithPU.getRect( COMPONENT_Y ).x0;
+          const Int yOffset = tuRecurseWithPU.getRect( COMPONENT_Y ).y0;
+          for (UInt storedResidualIndex = 0; storedResidualIndex < NUMBER_OF_STORED_RESIDUAL_TYPES; storedResidualIndex++)
+          {
+            if (bMaintainResidual[storedResidualIndex])
+            {
+              xStoreCrossComponentPredictionResult(resiLuma[storedResidualIndex], resiLumaPU[storedResidualIndex], tuRecurseWithPU, xOffset, yOffset, MAX_CU_SIZE, MAX_CU_SIZE );
+            }
+          }
+        }
+
+        UInt uiQPartNum = tuRecurseWithPU.GetAbsPartIdxNumParts();
+
+        ::memcpy( m_puhQTTempTrIdx,  pcCU->getTransformIdx()       + uiPartOffset, uiQPartNum * sizeof( UChar ) );
+        for (UInt component = 0; component < numberValidComponents; component++)
+        {
+          const ComponentID compID = ComponentID(component);
+          ::memcpy( m_puhQTTempCbf[compID], pcCU->getCbf( compID  ) + uiPartOffset, uiQPartNum * sizeof( UChar ) );
+          ::memcpy( m_puhQTTempTransformSkipFlag[compID],  pcCU->getTransformSkip(compID)  + uiPartOffset, uiQPartNum * sizeof( UChar ) );
+        }
+      }
+#if HHI_RQT_INTRA_SPEEDUP_MOD
+      else if( dPUCost < dSecondBestPUCost )
+      {
+        uiSecondBestMode  = uiOrgMode;
+        dSecondBestPUCost = dPUCost;
+      }
+#endif
+    } // Mode loop
+
+#if HHI_RQT_INTRA_SPEEDUP
+#if HHI_RQT_INTRA_SPEEDUP_MOD
+    for( UInt ui =0; ui < 2; ++ui )
+#endif
+    {
+#if HHI_RQT_INTRA_SPEEDUP_MOD
+      UInt uiOrgMode   = ui ? uiSecondBestMode  : uiBestPUMode;
+      if( uiOrgMode == MAX_UINT )
+      {
+        break;
+      }
+#else
+      UInt uiOrgMode = uiBestPUMode;
+#endif
+
+#if ENVIRONMENT_VARIABLE_DEBUG_AND_TEST
+      if (DebugOptionList::ForceLumaMode.isSet())
+        uiOrgMode = DebugOptionList::ForceLumaMode.getInt();
+#endif
+
+      pcCU->setIntraDirSubParts ( CHANNEL_TYPE_LUMA, uiOrgMode, uiPartOffset, uiDepth + uiInitTrDepth );
+      DEBUG_STRING_NEW(sModeTree)
+
+      // set context models
+      m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[uiDepth][CI_CURR_BEST] );
+
+      // determine residual for partition
+      Distortion uiPUDistY = 0;
+      Distortion uiPUDistC = 0;
+      Double     dPUCost   = 0.0;
+
+      xRecurIntraCodingQT( bLumaOnly, pcOrgYuv, pcPredYuv, pcResiYuv, resiLumaPU, uiPUDistY, uiPUDistC, false, dPUCost, tuRecurseWithPU DEBUG_STRING_PASS_INTO(sModeTree));
+
+      // check r-d cost
+      if( dPUCost < dBestPUCost )
+      {
+        DEBUG_STRING_SWAP(sPU, sModeTree)
+        uiBestPUMode  = uiOrgMode;
+        uiBestPUDistY = uiPUDistY;
+        uiBestPUDistC = uiPUDistC;
+        dBestPUCost   = dPUCost;
+
+        xSetIntraResultQT( bLumaOnly, pcRecoYuv, tuRecurseWithPU );
+
+        if (pcCU->getSlice()->getPPS()->getUseCrossComponentPrediction())
+        {
+          const Int xOffset = tuRecurseWithPU.getRect( COMPONENT_Y ).x0;
+          const Int yOffset = tuRecurseWithPU.getRect( COMPONENT_Y ).y0;
+          for (UInt storedResidualIndex = 0; storedResidualIndex < NUMBER_OF_STORED_RESIDUAL_TYPES; storedResidualIndex++)
+          {
+            if (bMaintainResidual[storedResidualIndex])
+            {
+              xStoreCrossComponentPredictionResult(resiLuma[storedResidualIndex], resiLumaPU[storedResidualIndex], tuRecurseWithPU, xOffset, yOffset, MAX_CU_SIZE, MAX_CU_SIZE );
+            }
+          }
+        }
+
+        const UInt uiQPartNum = tuRecurseWithPU.GetAbsPartIdxNumParts();
+        ::memcpy( m_puhQTTempTrIdx,  pcCU->getTransformIdx()       + uiPartOffset, uiQPartNum * sizeof( UChar ) );
+
+        for (UInt component = 0; component < numberValidComponents; component++)
+        {
+          const ComponentID compID = ComponentID(component);
+          ::memcpy( m_puhQTTempCbf[compID], pcCU->getCbf( compID  ) + uiPartOffset, uiQPartNum * sizeof( UChar ) );
+          ::memcpy( m_puhQTTempTransformSkipFlag[compID],  pcCU->getTransformSkip(compID)  + uiPartOffset, uiQPartNum * sizeof( UChar ) );
+        }
+      }
+    } // Mode loop
+#endif
+
+    DEBUG_STRING_APPEND(sDebug, sPU)
+
+    //--- update overall distortion ---
+    uiOverallDistY += uiBestPUDistY;
+    uiOverallDistC += uiBestPUDistC;
+
+    //--- update transform index and cbf ---
+    const UInt uiQPartNum = tuRecurseWithPU.GetAbsPartIdxNumParts();
+    ::memcpy( pcCU->getTransformIdx()       + uiPartOffset, m_puhQTTempTrIdx,  uiQPartNum * sizeof( UChar ) );
+    for (UInt component = 0; component < numberValidComponents; component++)
+    {
+      const ComponentID compID = ComponentID(component);
+      ::memcpy( pcCU->getCbf( compID  ) + uiPartOffset, m_puhQTTempCbf[compID], uiQPartNum * sizeof( UChar ) );
+      ::memcpy( pcCU->getTransformSkip( compID  ) + uiPartOffset, m_puhQTTempTransformSkipFlag[compID ], uiQPartNum * sizeof( UChar ) );
+    }
+
+    //--- set reconstruction for next intra prediction blocks ---
+    if( !tuRecurseWithPU.IsLastSection() )
+    {
+      const Bool bSkipChroma  = tuRecurseWithPU.ProcessChannelSection(CHANNEL_TYPE_CHROMA);
+
+      const UInt numChannelToProcess = (bLumaOnly || bSkipChroma) ? 1 : getNumberValidComponents(pcCU->getPic()->getChromaFormat());
+
+      for (UInt ch=0; ch<numChannelToProcess; ch++)
+      {
+        const ComponentID compID = ComponentID(ch);
+        const TComRectangle &puRect=tuRecurseWithPU.getRect(compID);
+        const UInt  uiCompWidth   = puRect.width;
+        const UInt  uiCompHeight  = puRect.height;
+
+        const UInt  uiZOrder      = pcCU->getZorderIdxInCtu() + uiPartOffset;
+              Pel*  piDes         = pcCU->getPic()->getPicYuvRec()->getAddr( compID, pcCU->getCtuRsAddr(), uiZOrder );
+        const UInt  uiDesStride   = pcCU->getPic()->getPicYuvRec()->getStride( compID);
+        const Pel*  piSrc         = pcRecoYuv->getAddr( compID, uiPartOffset );
+        const UInt  uiSrcStride   = pcRecoYuv->getStride( compID);
+
+        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->setIntraDirSubParts     ( CHANNEL_TYPE_LUMA, uiBestPUMode, uiPartOffset, uiDepth + uiInitTrDepth );
+    if (!bLumaOnly && getChromasCorrespondingPULumaIdx(uiPartOffset, chFmt)==uiPartOffset)
+    {
+      UInt chromaDir=pcCU->getIntraDir(CHANNEL_TYPE_CHROMA, getChromasCorrespondingPULumaIdx(uiPartOffset, chFmt));
+      if (chromaDir == uiBestPUMode && tuRecurseWithPU.ProcessChannelSection(CHANNEL_TYPE_CHROMA))
+      {
+        pcCU->setIntraDirSubParts     ( CHANNEL_TYPE_CHROMA, DM_CHROMA_IDX, getChromasCorrespondingPULumaIdx(uiPartOffset, chFmt), uiDepth + uiInitTrDepthC );
+      }
+    }
+    //pcCU->copyToPic                   ( uiDepth, uiPU, uiInitTrDepth ); // Unnecessary copy?
+  } while (tuRecurseWithPU.nextSection(tuRecurseCU));
+
+
+  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, COMPONENT_Y,  1 );
+      uiCombCbfU |= pcCU->getCbf( uiPartIdx, COMPONENT_Cb, 1 );
+      uiCombCbfV |= pcCU->getCbf( uiPartIdx, COMPONENT_Cr, 1 );
+    }
+    for( UInt uiOffs = 0; uiOffs < 4 * uiQNumParts; uiOffs++ )
+    {
+      pcCU->getCbf( COMPONENT_Y  )[ uiOffs ] |= uiCombCbfY;
+      pcCU->getCbf( COMPONENT_Cb )[ uiOffs ] |= uiCombCbfU;
+      pcCU->getCbf( COMPONENT_Cr )[ uiOffs ] |= uiCombCbfV;
+    }
+  }
+
+  //===== reset context models =====
+  m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[uiDepth][CI_CURR_BEST]);
+
+  //===== set distortion (rate and r-d costs are determined later) =====
+  ruiDistC                   = uiOverallDistC;
+  pcCU->getTotalDistortion() = uiOverallDistY + uiOverallDistC;
+}
+
+
+
+
+Void
+TEncSearch::estIntraPredChromaQT(TComDataCU* pcCU,
+                                 TComYuv*    pcOrgYuv,
+                                 TComYuv*    pcPredYuv,
+                                 TComYuv*    pcResiYuv,
+                                 TComYuv*    pcRecoYuv,
+                                 Pel         resiLuma[NUMBER_OF_STORED_RESIDUAL_TYPES][MAX_CU_SIZE * MAX_CU_SIZE],
+                                 Distortion  uiPreCalcDistC
+                                 DEBUG_STRING_FN_DECLARE(sDebug))
+{
+  pcCU->getTotalDistortion      () -= uiPreCalcDistC;
+
+  //const UInt    uiDepthCU     = pcCU->getDepth(0);
+  const UInt    uiInitTrDepth  = pcCU->getPartitionSize(0) != SIZE_2Nx2N && enable4ChromaPUsInIntraNxNCU(pcOrgYuv->getChromaFormat()) ? 1 : 0;
+//  const UInt    uiNumPU        = 1<<(2*uiInitTrDepth);
+
+  TComTURecurse tuRecurseCU(pcCU, 0);
+  TComTURecurse tuRecurseWithPU(tuRecurseCU, false, (uiInitTrDepth==0)?TComTU::DONT_SPLIT : TComTU::QUAD_SPLIT);
+  const UInt    uiQNumParts    = tuRecurseWithPU.GetAbsPartIdxNumParts();
+  const UInt    uiDepthCU=tuRecurseWithPU.getCUDepth();
+  const UInt    numberValidComponents = pcCU->getPic()->getNumberValidComponents();
+
+  do
+  {
+    UInt       uiBestMode  = 0;
+    Distortion uiBestDist  = 0;
+    Double     dBestCost   = MAX_DOUBLE;
+
+    //----- init mode list -----
+    if (tuRecurseWithPU.ProcessChannelSection(CHANNEL_TYPE_CHROMA))
+    {
+      UInt uiModeList[FAST_UDI_MAX_RDMODE_NUM];
+      const UInt  uiQPartNum     = uiQNumParts;
+      const UInt  uiPartOffset   = tuRecurseWithPU.GetAbsPartIdxTU();
+      {
+        UInt  uiMinMode = 0;
+        UInt  uiMaxMode = NUM_CHROMA_MODE;
+
+        //----- check chroma modes -----
+        pcCU->getAllowedChromaDir( uiPartOffset, uiModeList );
+
+#if ENVIRONMENT_VARIABLE_DEBUG_AND_TEST
+        if (DebugOptionList::ForceChromaMode.isSet())
+        {
+          uiMinMode=DebugOptionList::ForceChromaMode.getInt();
+          if (uiModeList[uiMinMode]==34) uiMinMode=4; // if the fixed mode has been renumbered because DM_CHROMA covers it, use DM_CHROMA.
+          uiMaxMode=uiMinMode+1;
+        }
+#endif
+
+        DEBUG_STRING_NEW(sPU)
+
+        for( UInt uiMode = uiMinMode; uiMode < uiMaxMode; uiMode++ )
+        {
+          //----- restore context models -----
+          m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[uiDepthCU][CI_CURR_BEST] );
+          
+          DEBUG_STRING_NEW(sMode)
+          //----- chroma coding -----
+          Distortion uiDist = 0;
+          pcCU->setIntraDirSubParts  ( CHANNEL_TYPE_CHROMA, uiModeList[uiMode], uiPartOffset, uiDepthCU+uiInitTrDepth );
+          xRecurIntraChromaCodingQT       ( pcOrgYuv, pcPredYuv, pcResiYuv, resiLuma, uiDist, tuRecurseWithPU DEBUG_STRING_PASS_INTO(sMode) );
+
+          if( pcCU->getSlice()->getPPS()->getUseTransformSkip() )
+          {
+            m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[uiDepthCU][CI_CURR_BEST] );
+          }
+
+          UInt    uiBits = xGetIntraBitsQT( tuRecurseWithPU, false, true, false );
+          Double  dCost  = m_pcRdCost->calcRdCost( uiBits, uiDist );
+
+          //----- compare -----
+          if( dCost < dBestCost )
+          {
+            DEBUG_STRING_SWAP(sPU, sMode);
+            dBestCost   = dCost;
+            uiBestDist  = uiDist;
+            uiBestMode  = uiModeList[uiMode];
+
+            xSetIntraResultChromaQT( pcRecoYuv, tuRecurseWithPU );
+            for (UInt componentIndex = COMPONENT_Cb; componentIndex < numberValidComponents; componentIndex++)
+            {
+              const ComponentID compID = ComponentID(componentIndex);
+              ::memcpy( m_puhQTTempCbf[compID], pcCU->getCbf( compID )+uiPartOffset, uiQPartNum * sizeof( UChar ) );
+              ::memcpy( m_puhQTTempTransformSkipFlag[compID], pcCU->getTransformSkip( compID )+uiPartOffset, uiQPartNum * sizeof( UChar ) );
+              ::memcpy( m_phQTTempCrossComponentPredictionAlpha[compID], pcCU->getCrossComponentPredictionAlpha(compID)+uiPartOffset, uiQPartNum * sizeof( Char ) );
+            }
+          }
+        }
+
+        DEBUG_STRING_APPEND(sDebug, sPU)
+
+        //----- set data -----
+        for (UInt componentIndex = COMPONENT_Cb; componentIndex < numberValidComponents; componentIndex++)
+        {
+          const ComponentID compID = ComponentID(componentIndex);
+          ::memcpy( pcCU->getCbf( compID )+uiPartOffset, m_puhQTTempCbf[compID], uiQPartNum * sizeof( UChar ) );
+          ::memcpy( pcCU->getTransformSkip( compID )+uiPartOffset, m_puhQTTempTransformSkipFlag[compID], uiQPartNum * sizeof( UChar ) );
+          ::memcpy( pcCU->getCrossComponentPredictionAlpha(compID)+uiPartOffset, m_phQTTempCrossComponentPredictionAlpha[compID], uiQPartNum * sizeof( Char ) );
+        }
+      }
+
+      if( ! tuRecurseWithPU.IsLastSection() )
+      {
+        for (UInt ch=COMPONENT_Cb; ch<numberValidComponents; ch++)
+        {
+          const ComponentID compID    = ComponentID(ch);
+          const TComRectangle &tuRect = tuRecurseWithPU.getRect(compID);
+          const UInt  uiCompWidth     = tuRect.width;
+          const UInt  uiCompHeight    = tuRect.height;
+          const UInt  uiZOrder        = pcCU->getZorderIdxInCtu() + tuRecurseWithPU.GetAbsPartIdxTU();
+                Pel*  piDes           = pcCU->getPic()->getPicYuvRec()->getAddr( compID, pcCU->getCtuRsAddr(), uiZOrder );
+          const UInt  uiDesStride     = pcCU->getPic()->getPicYuvRec()->getStride( compID);
+          const Pel*  piSrc           = pcRecoYuv->getAddr( compID, uiPartOffset );
+          const UInt  uiSrcStride     = pcRecoYuv->getStride( compID);
+
+          for( UInt uiY = 0; uiY < uiCompHeight; uiY++, piSrc += uiSrcStride, piDes += uiDesStride )
+          {
+            for( UInt uiX = 0; uiX < uiCompWidth; uiX++ )
+            {
+              piDes[ uiX ] = piSrc[ uiX ];
+            }
+          }
+        }
+      }
+
+      pcCU->setIntraDirSubParts( CHANNEL_TYPE_CHROMA, uiBestMode, uiPartOffset, uiDepthCU+uiInitTrDepth );
+      pcCU->getTotalDistortion      () += uiBestDist;
+    }
+
+  } while (tuRecurseWithPU.nextSection(tuRecurseCU));
+
+  //----- restore context models -----
+
+  if( uiInitTrDepth != 0 )
+  { // set Cbf for all blocks
+    UInt uiCombCbfU = 0;
+    UInt uiCombCbfV = 0;
+    UInt uiPartIdx  = 0;
+    for( UInt uiPart = 0; uiPart < 4; uiPart++, uiPartIdx += uiQNumParts )
+    {
+      uiCombCbfU |= pcCU->getCbf( uiPartIdx, COMPONENT_Cb, 1 );
+      uiCombCbfV |= pcCU->getCbf( uiPartIdx, COMPONENT_Cr, 1 );
+    }
+    for( UInt uiOffs = 0; uiOffs < 4 * uiQNumParts; uiOffs++ )
+    {
+      pcCU->getCbf( COMPONENT_Cb )[ uiOffs ] |= uiCombCbfU;
+      pcCU->getCbf( COMPONENT_Cr )[ uiOffs ] |= uiCombCbfV;
+    }
+  }
+
+  m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[uiDepthCU][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* pOrg, Pel* pPCM, Pel* pPred, Pel* pResi, Pel* pReco, UInt uiStride, UInt uiWidth, UInt uiHeight, const ComponentID compID )
+{
+  const UInt uiReconStride = pcCU->getPic()->getPicYuvRec()->getStride(compID);
+  const UInt uiPCMBitDepth = pcCU->getSlice()->getSPS()->getPCMBitDepth(toChannelType(compID));
+  Pel* pRecoPic = pcCU->getPic()->getPicYuvRec()->getAddr(compID, pcCU->getCtuRsAddr(), pcCU->getZorderIdxInCtu()+uiAbsPartIdx);
+
+  const Int pcmShiftRight=(g_bitDepth[toChannelType(compID)] - Int(uiPCMBitDepth));
+
+  assert(pcmShiftRight >= 0);
+
+  for( UInt uiY = 0; uiY < uiHeight; uiY++ )
+  {
+    for( UInt uiX = 0; uiX < uiWidth; uiX++ )
+    {
+      // Reset pred and residual
+      pPred[uiX] = 0;
+      pResi[uiX] = 0;
+      // Encode
+      pPCM[uiX] = (pOrg[uiX]>>pcmShiftRight);
+      // Reconstruction
+      pReco   [uiX] = (pPCM[uiX]<<(pcmShiftRight));
+      pRecoPic[uiX] = pReco[uiX];
+    }
+    pPred += uiStride;
+    pResi += uiStride;
+    pPCM += uiWidth;
+    pOrg += uiStride;
+    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* pcPredYuv, TComYuv* pcResiYuv, TComYuv* pcRecoYuv )
+{
+  UInt        uiDepth      = pcCU->getDepth(0);
+  const UInt  uiDistortion = 0;
+  UInt        uiBits;
+
+  Double dCost;
+
+  for (UInt ch=0; ch < pcCU->getPic()->getNumberValidComponents(); ch++)
+  {
+    const ComponentID compID  = ComponentID(ch);
+    const UInt width  = pcCU->getWidth(0)  >> pcCU->getPic()->getComponentScaleX(compID);
+    const UInt height = pcCU->getHeight(0) >> pcCU->getPic()->getComponentScaleY(compID);
+    const UInt stride = pcPredYuv->getStride(compID);
+
+    Pel * pOrig    = pcOrgYuv->getAddr  (compID, 0, width);
+    Pel * pResi    = pcResiYuv->getAddr(compID, 0, width);
+    Pel * pPred    = pcPredYuv->getAddr(compID, 0, width);
+    Pel * pReco    = pcRecoYuv->getAddr(compID, 0, width);
+    Pel * pPCM     = pcCU->getPCMSample (compID);
+
+    xEncPCM ( pcCU, 0, pOrig, pPCM, pPred, pResi, pReco, stride, width, height, compID );
+
+  }
+
+  m_pcEntropyCoder->resetBits();
+  xEncIntraHeader ( pcCU, uiDepth, 0, true, false);
+  uiBits = m_pcEntropyCoder->getNumberOfWrittenBits();
+
+  dCost = m_pcRdCost->calcRdCost( uiBits, uiDistortion );
+
+  m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[uiDepth][CI_CURR_BEST]);
+
+  pcCU->getTotalBits()       = uiBits;
+  pcCU->getTotalCost()       = dCost;
+  pcCU->getTotalDistortion() = uiDistortion;
+
+  pcCU->copyToPic(uiDepth, 0, 0);
+}
+
+
+
+
+Void TEncSearch::xGetInterPredictionError( TComDataCU* pcCU, TComYuv* pcYuvOrg, Int iPartIdx, Distortion& 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_bitDepth[CHANNEL_TYPE_LUMA],
+                            pcYuvOrg->getAddr( COMPONENT_Y, uiAbsPartIdx ), pcYuvOrg->getStride(COMPONENT_Y),
+                            m_tmpYuvPred .getAddr( COMPONENT_Y, uiAbsPartIdx ), m_tmpYuvPred.getStride(COMPONENT_Y),
+                            iWidth, iHeight, m_pcEncCfg->getUseHADME() && (pcCU->getCUTransquantBypass(iPartIdx) == 0) );
+
+  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, Distortion& ruiCost, TComMvField* cMvFieldNeighbours, UChar* uhInterDirNeighbours, 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, numValidMergeCand );
+    }
+    pcCU->setPartSizeSubParts( partSize, 0, uiDepth );
+  }
+  else
+  {
+    pcCU->getInterMergeCandidates( uiAbsPartIdx, iPUIdx, cMvFieldNeighbours, uhInterDirNeighbours, numValidMergeCand );
+  }
+
+  xRestrictBipredMergeCand( pcCU, iPUIdx, cMvFieldNeighbours, uhInterDirNeighbours, numValidMergeCand );
+
+  ruiCost = std::numeric_limits<Distortion>::max();
+  for( UInt uiMergeCand = 0; uiMergeCand < numValidMergeCand; ++uiMergeCand )
+  {
+#if REF_IDX_ME_ZEROMV
+    Bool bZeroMVILR = pcCU->xCheckZeroMVILRMerge(uhInterDirNeighbours[uiMergeCand], cMvFieldNeighbours[0 + 2*uiMergeCand], cMvFieldNeighbours[1 + 2*uiMergeCand]);
+    if(bZeroMVILR)
+    {
+#endif
+#if N0383_IL_CONSTRAINED_TILE_SETS_SEI
+    if (!(pcCU->isInterLayerReference(uhInterDirNeighbours[uiMergeCand], cMvFieldNeighbours[0 + 2*uiMergeCand], cMvFieldNeighbours[1 + 2*uiMergeCand]) && m_disableILP))
+    {
+#endif
+    Distortion uiCostCand = std::numeric_limits<Distortion>::max();
+    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 );
+
+    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;
+    }
+#if N0383_IL_CONSTRAINED_TILE_SETS_SEI
+    }
+#endif
+#if REF_IDX_ME_ZEROMV
+    }
+#endif
+  }
+}
+
+/** 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 SVC_EXTENSION
+#if AMP_MRG
+Bool TEncSearch::predInterSearch( TComDataCU* pcCU, TComYuv* pcOrgYuv, TComYuv* pcPredYuv, TComYuv* pcResiYuv, TComYuv* pcRecoYuv DEBUG_STRING_FN_DECLARE(sDebug), Bool bUseRes, Bool bUseMRG )
+#else
+Bool TEncSearch::predInterSearch( TComDataCU* pcCU, TComYuv* pcOrgYuv, TComYuv* pcPredYuv, TComYuv* pcResiYuv, TComYuv* pcRecoYuv, Bool bUseRes )
+#endif
+#else
+#if AMP_MRG
+Void TEncSearch::predInterSearch( TComDataCU* pcCU, TComYuv* pcOrgYuv, TComYuv* pcPredYuv, TComYuv* pcResiYuv, TComYuv* pcRecoYuv DEBUG_STRING_FN_DECLARE(sDebug), Bool bUseRes, Bool bUseMRG )
+#else
+Void TEncSearch::predInterSearch( TComDataCU* pcCU, TComYuv* pcOrgYuv, TComYuv* pcPredYuv, TComYuv* pcResiYuv, TComYuv* pcRecoYuv, Bool bUseRes )
+#endif
+#endif
+{
+  for(UInt i=0; i<NUM_REF_PIC_LIST_01; i++)
+  {
+    m_acYuvPred[i].clear();
+  }
+  m_cYuvPredTemp.clear();
+  pcPredYuv->clear();
+
+  if ( !bUseRes )
+  {
+    pcResiYuv->clear();
+  }
+
+  pcRecoYuv->clear();
+
+  TComMv       cMvSrchRngLT;
+  TComMv       cMvSrchRngRB;
+
+  TComMv       cMvZero;
+  TComMv       TempMv; //kolya
+
+  TComMv       cMv[2];
+  TComMv       cMvBi[2];
+  TComMv       cMvTemp[2][33];
+
+  Int          iNumPart    = pcCU->getNumPartitions();
+  Int          iNumPredDir = pcCU->getSlice()->isInterP() ? 1 : 2;
+
+  TComMv       cMvPred[2][33];
+
+  TComMv       cMvPredBi[2][33];
+  Int          aaiMvpIdxBi[2][33];
+
+  Int          aaiMvpIdx[2][33];
+  Int          aaiMvpNum[2][33];
+
+  AMVPInfo     aacAMVPInfo[2][33];
+
+  Int          iRefIdx[2]={0,0}; //If un-initialized, may cause SEGV in bi-directional prediction iterative stage.
+  Int          iRefIdxBi[2];
+
+  UInt         uiPartAddr;
+  Int          iRoiWidth, iRoiHeight;
+
+  UInt         uiMbBits[3] = {1, 1, 0};
+
+  UInt         uiLastMode = 0;
+  Int          iRefStart, iRefEnd;
+
+  PartSize     ePartSize = pcCU->getPartitionSize( 0 );
+
+  Int          bestBiPRefIdxL1 = 0;
+  Int          bestBiPMvpL1 = 0;
+  Distortion   biPDistTemp = std::numeric_limits<Distortion>::max();
+
+  TComMvField cMvFieldNeighbours[MRG_MAX_NUM_CANDS << 1]; // double length for mv of both lists
+  UChar uhInterDirNeighbours[MRG_MAX_NUM_CANDS];
+  Int numValidMergeCand = 0 ;
+
+  for ( Int iPartIdx = 0; iPartIdx < iNumPart; iPartIdx++ )
+  {
+    Distortion   uiCost[2] = { std::numeric_limits<Distortion>::max(), std::numeric_limits<Distortion>::max() };
+    Distortion   uiCostBi  =   std::numeric_limits<Distortion>::max();
+    Distortion   uiCostTemp;
+
+    UInt         uiBits[3];
+    UInt         uiBitsTemp;
+    Distortion   bestBiPDist = std::numeric_limits<Distortion>::max();
+
+    Distortion   uiCostTempL0[MAX_NUM_REF];
+    for (Int iNumRef=0; iNumRef < MAX_NUM_REF; iNumRef++)
+    {
+      uiCostTempL0[iNumRef] = std::numeric_limits<Distortion>::max();
+    }
+    UInt         uiBitsTempL0[MAX_NUM_REF];
+
+    TComMv       mvValidList1;
+    Int          refIdxValidList1 = 0;
+    UInt         bitsValidList1 = MAX_UINT;
+    Distortion   costValidList1 = std::numeric_limits<Distortion>::max();
+
+    xGetBlkBits( ePartSize, pcCU->getSlice()->isInterP(), iPartIdx, uiLastMode, uiMbBits);
+
+    pcCU->getPartIndexAndSize( iPartIdx, uiPartAddr, iRoiWidth, iRoiHeight );
+
+#if AMP_MRG
+    Bool bTestNormalMC = true;
+
+    if ( bUseMRG && pcCU->getWidth( 0 ) > 8 && iNumPart == 2 )
+    {
+      bTestNormalMC = false;
+    }
+
+    if (bTestNormalMC)
+    {
+#endif
+
+#if SVC_EXTENSION
+      Bool doneUniPred = false;
+#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++ )
+      {
+#if SVC_EXTENSION
+        TComPic* pcPic = pcCU->getSlice()->getRefPic( eRefPicList, iRefIdxTemp );
+        
+        // motion search only for the ILRP with sample prediction type
+        if( pcPic->isILR( pcCU->getLayerId() ) && !pcCU->getSlice()->getVPS()->isSamplePredictionType( pcCU->getLayerIdx(), pcPic->getLayerIdx() ) )
+        {
+          continue;
+        }
+
+#if N0383_IL_CONSTRAINED_TILE_SETS_SEI
+        if( pcPic->isILR(pcCU->getLayerId()) && m_disableILP )
+        {
+          continue;
+        }
+#endif
+#if ENCODER_FAST_MODE        
+        if( pcPic->isILR(pcCU->getLayerId()) && (ePartSize == SIZE_2Nx2N) ) 
+        {
+          continue;
+        }
+#endif
+        doneUniPred = true;
+#endif
+
+        uiBitsTemp = uiMbBits[iRefList];
+        if ( pcCU->getSlice()->getNumRefIdx(eRefPicList) > 1 )
+        {
+          uiBitsTemp += iRefIdxTemp+1;
+          if ( iRefIdxTemp == pcCU->getSlice()->getNumRefIdx(eRefPicList)-1 ) uiBitsTemp--;
+        }
+
+        xEstimateMvPredAMVP( pcCU, pcOrgYuv, iPartIdx, eRefPicList, iRefIdxTemp, cMvPred[iRefList][iRefIdxTemp], false, &biPDistTemp);
+
+        aaiMvpIdx[iRefList][iRefIdxTemp] = pcCU->getMVPIdx(eRefPicList, uiPartAddr);
+        aaiMvpNum[iRefList][iRefIdxTemp] = pcCU->getMVPNum(eRefPicList, uiPartAddr);
+
+        if(pcCU->getSlice()->getMvdL1ZeroFlag() && iRefList==1 && biPDistTemp < bestBiPDist)
+        {
+#if REF_IDX_ME_ZEROMV 
+          Bool bZeroMVILR = pcCU->xCheckZeroMVILRMvdL1Zero(iRefList, iRefIdxTemp, aaiMvpIdx[iRefList][iRefIdxTemp]);
+          if(bZeroMVILR)
+          {
+#endif
+          bestBiPDist = biPDistTemp;
+          bestBiPMvpL1 = aaiMvpIdx[iRefList][iRefIdxTemp];
+          bestBiPRefIdxL1 = iRefIdxTemp;
+#if REF_IDX_ME_ZEROMV
+          }
+#endif
+        }
+
+        uiBitsTemp += m_auiMVPIdxCost[aaiMvpIdx[iRefList][iRefIdxTemp]][AMVP_MAX_NUM_CANDS];
+        
+#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;
+        }
+      }
+    }
+
+#if SVC_EXTENSION
+    if( pcCU->getLayerId() && !doneUniPred )
+    {
+      // there is no valid reference pictures for inter prediction
+      return false;
+    }
+#endif
+
+    //  Bi-directional prediction
+#if REF_IDX_ME_ZEROMV
+    if ( (pcCU->getSlice()->isInterB()) && (pcCU->isBipredRestriction(iPartIdx) == false) && !(pcCU->getSlice()->getMvdL1ZeroFlag() && bestBiPDist == MAX_INT) )
+#else
+    if ( (pcCU->getSlice()->isInterB()) && (pcCU->isBipredRestriction(iPartIdx) == false) )
+#endif
+    {
+
+      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[REF_PIC_LIST_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;
+        
+#if ENCODER_FAST_MODE
+        Bool     testIter = true;
+        TComPic* pcPic    = pcCU->getSlice()->getRefPic( RefPicList(1 - iRefList), iRefIdxBi[1 - iRefList] );
+        if(pcPic->isILR(pcCU->getLayerId()) && (ePartSize == SIZE_2Nx2N))
+        {
+          testIter = false;  //the fixed part is ILR, skip this iteration       
+        }
+#if N0383_IL_CONSTRAINED_TILE_SETS_SEI
+        if (pcPic->isILR(pcCU->getLayerId()) && m_disableILP)
+        {
+          testIter = false;
+        }
+#endif
+        if(testIter)
+        {
+#endif
+        iRefStart = 0;
+        iRefEnd   = pcCU->getSlice()->getNumRefIdx(eRefPicList)-1;
+
+        for ( Int iRefIdxTemp = iRefStart; iRefIdxTemp <= iRefEnd; iRefIdxTemp++ )
+        {
+#if ENCODER_FAST_MODE
+          Bool testRefIdx = true;
+          pcPic = pcCU->getSlice()->getRefPic( RefPicList(iRefList) , iRefIdxTemp );
+
+          // motion search only for the ILRP with sample prediction type
+          if( pcPic->isILR( pcCU->getLayerId() ) && !pcCU->getSlice()->getVPS()->isSamplePredictionType( pcCU->getLayerIdx(), pcPic->getLayerIdx() ) )
+          {
+            continue;
+          }
+
+          if(pcPic->isILR(pcCU->getLayerId()) && (ePartSize == SIZE_2Nx2N))
+          {
+            testRefIdx = false;  //the refined part is ILR, skip this reference pic           
+          }
+#if N0383_IL_CONSTRAINED_TILE_SETS_SEI
+          if (pcPic->isILR(pcCU->getLayerId()) && m_disableILP)
+          {
+            testRefIdx = false;
+          }
+#endif
+          if(testRefIdx)
+          {
+#endif
+          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 );
+            }
+          }
+#if (ENCODER_FAST_MODE)
+          }
+#endif
+        }
+#if (ENCODER_FAST_MODE)
+        } // for loop-iRefIdxTemp
+#endif
+        
+        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 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 ( 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( true, 0, pcCU->getCUTransquantBypass(uiPartAddr) );
+
+#if AMP_MRG
+      // calculate ME cost
+      Distortion uiMEError = std::numeric_limits<Distortion>::max();
+      Distortion uiMECost  = std::numeric_limits<Distortion>::max();
+
+      if (bTestNormalMC)
+      {
+        xGetInterPredictionError( pcCU, pcOrgYuv, iPartIdx, uiMEError, m_pcEncCfg->getUseHADME() );
+        uiMECost = uiMEError + m_pcRdCost->getCost( uiMEBits );
+      }
+#else
+      // calculate ME cost
+      Distortion uiMEError = std::numeric_limits<Distortion>::max();
+      xGetInterPredictionError( pcCU, pcOrgYuv, iPartIdx, uiMEError, m_pcEncCfg->getUseHADME() );
+      Distortion 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
+      Distortion uiMRGCost = std::numeric_limits<Distortion>::max();
+
+      xMergeEstimation( pcCU, pcOrgYuv, iPartIdx, uiMRGInterDir, cMRGMvField, uiMRGIndex, uiMRGCost, cMvFieldNeighbours, uhInterDirNeighbours, numValidMergeCand);
+
+      if ( uiMRGCost < uiMECost )
+      {
+        // set Merge result
+        pcCU->setMergeFlagSubParts ( true,          uiPartAddr, iPartIdx, pcCU->getDepth( uiPartAddr ) );
+        pcCU->setMergeIndexSubParts( uiMRGIndex,    uiPartAddr, iPartIdx, pcCU->getDepth( uiPartAddr ) );
+        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 ) );
+        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, pcPredYuv, REF_PIC_LIST_X, iPartIdx );
+
+  } //  end of for ( Int iPartIdx = 0; iPartIdx < iNumPart; iPartIdx++ )
+
+  setWpScalingDistParam( pcCU, -1, REF_PIC_LIST_X );
+
+#if SVC_EXTENSION
+  return true;
+#else
+  return;
+#endif
+}
+
+
+// AMVP
+Void TEncSearch::xEstimateMvPredAMVP( TComDataCU* pcCU, TComYuv* pcOrgYuv, UInt uiPartIdx, RefPicList eRefPicList, Int iRefIdx, TComMv& rcMvPred, Bool bFilled, Distortion* puiDistBiP )
+{
+  AMVPInfo*  pcAMVPInfo = pcCU->getCUMvField(eRefPicList)->getAMVPInfo();
+
+  TComMv     cBestMv;
+  Int        iBestIdx   = 0;
+  TComMv     cZeroMv;
+  TComMv     cMvPred;
+  Distortion uiBestCost = std::numeric_limits<Distortion>::max();
+  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 (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)
+    {
+      (*puiDistBiP) = xGetTemplateCost( pcCU, uiPartIdx, uiPartAddr, pcOrgYuv, &m_cYuvPredTemp, rcMvPred, 0, AMVP_MAX_NUM_CANDS, eRefPicList, iRefIdx, iRoiWidth, iRoiHeight);
+    }
+    return;
+  }
+
+  if (bFilled)
+  {
+    assert(pcCU->getMVPIdx(eRefPicList,uiPartAddr) >= 0);
+    rcMvPred = pcAMVPInfo->m_acMvCand[pcCU->getMVPIdx(eRefPicList,uiPartAddr)];
+    return;
+  }
+
+  m_cYuvPredTemp.clear();
+  //-- Check Minimum Cost.
+  for ( i = 0 ; i < pcAMVPInfo->iN; i++)
+  {
+    Distortion uiTmpCost;
+    uiTmpCost = xGetTemplateCost( pcCU, uiPartIdx, uiPartAddr, pcOrgYuv, &m_cYuvPredTemp, pcAMVPInfo->m_acMvCand[i], i, AMVP_MAX_NUM_CANDS, eRefPicList, iRefIdx, iRoiWidth, iRoiHeight);
+    if ( uiBestCost > uiTmpCost )
+    {
+      uiBestCost = uiTmpCost;
+      cBestMv   = pcAMVPInfo->m_acMvCand[i];
+      iBestIdx  = i;
+      (*puiDistBiP) = uiTmpCost;
+    }
+  }
+
+  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, Distortion& ruiCost )
+{
+  AMVPInfo* pcAMVPInfo = pcCU->getCUMvField(eRefPicList)->getAMVPInfo();
+
+  assert(pcAMVPInfo->m_acMvCand[riMVPIdx] == rcMvPred);
+
+  if (pcAMVPInfo->iN < 2) return;
+
+  m_pcRdCost->getMotionCost( true, 0, pcCU->getCUTransquantBypass(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 );
+  }
+}
+
+
+Distortion 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
+                                         )
+{
+  Distortion uiCost = std::numeric_limits<Distortion>::max();
+
+  TComPicYuv* pcPicYuvRef = pcCU->getSlice()->getRefPic( eRefPicList, iRefIdx )->getPicYuvRec();
+
+  pcCU->clipMv( cMvCand );
+
+  // prediction pattern
+#if O0194_WEIGHTED_PREDICTION_CGS
+  // Bug Fix (It did not check WP for BSlices)
+  if ( pcCU->getSlice()->getPPS()->getUseWP())
+#else
+  if ( pcCU->getSlice()->getPPS()->getUseWP() && pcCU->getSlice()->getSliceType()==P_SLICE )
+#endif
+  {
+    xPredInterBlk( COMPONENT_Y, pcCU, pcPicYuvRef, uiPartAddr, &cMvCand, iSizeX, iSizeY, pcTemplateCand, true );
+  }
+  else
+  {
+    xPredInterBlk( COMPONENT_Y, pcCU, pcPicYuvRef, uiPartAddr, &cMvCand, iSizeX, iSizeY, pcTemplateCand, false );
+  }
+
+#if O0194_WEIGHTED_PREDICTION_CGS
+  if ( pcCU->getSlice()->getPPS()->getUseWP())
+  ///< Bug Fix (It did not check WP for BSlices)
+#else
+  if ( pcCU->getSlice()->getPPS()->getUseWP() && pcCU->getSlice()->getSliceType()==P_SLICE )
+#endif
+  {
+    xWeightedPredictionUni( pcCU, pcTemplateCand, uiPartAddr, iSizeX, iSizeY, eRefPicList, pcTemplateCand, iRefIdx );
+  }
+
+  // calc distortion
+
+  uiCost = m_pcRdCost->getDistPart( g_bitDepth[CHANNEL_TYPE_LUMA], pcTemplateCand->getAddr(COMPONENT_Y, uiPartAddr), pcTemplateCand->getStride(COMPONENT_Y), pcOrgYuv->getAddr(COMPONENT_Y, uiPartAddr), pcOrgYuv->getStride(COMPONENT_Y), iSizeX, iSizeY, COMPONENT_Y, DF_SAD );
+  uiCost = (UInt) m_pcRdCost->calcRdCost( m_auiMVPIdxCost[iMVPIdx][iMVPNum], uiCost, false, DF_SAD );
+  return uiCost;
+}
+
+
+
+
+Void TEncSearch::xMotionEstimation( TComDataCU* pcCU, TComYuv* pcYuvOrg, Int iPartIdx, RefPicList eRefPicList, TComMv* pcMvPred, Int iRefIdxPred, TComMv& rcMv, UInt& ruiBits, Distortion& ruiCost, Bool bBi  )
+{
+  UInt          uiPartAddr;
+  Int           iRoiWidth;
+  Int           iRoiHeight;
+
+  TComMv        cMvHalf, cMvQter;
+  TComMv        cMvSrchRngLT;
+  TComMv        cMvSrchRngRB;
+
+  TComYuv*      pcYuv = pcYuvOrg;
+
+  assert(eRefPicList < MAX_NUM_REF_LIST_ADAPT_SR && iRefIdxPred<Int(MAX_IDX_ADAPT_SR));
+  m_iSearchRange = m_aaiAdaptSR[eRefPicList][iRefIdxPred];
+
+  Int           iSrchRng      = ( bBi ? m_bipredSearchRange : m_iSearchRange );
+  TComPattern   tmpPattern;
+  TComPattern*  pcPatternKey  = &tmpPattern;
+
+  Double        fWeight       = 1.0;
+
+  pcCU->getPartIndexAndSize( iPartIdx, uiPartAddr, iRoiWidth, iRoiHeight );
+
+  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->getAddr  ( COMPONENT_Y, uiPartAddr ),
+                             iRoiWidth,
+                             iRoiHeight,
+                             pcYuv->getStride(COMPONENT_Y) );
+
+  Pel*        piRefY      = pcCU->getSlice()->getRefPic( eRefPicList, iRefIdxPred )->getPicYuvRec()->getAddr( COMPONENT_Y, pcCU->getCtuRsAddr(), pcCU->getZorderIdxInCtu() + uiPartAddr );
+  Int         iRefStride  = pcCU->getSlice()->getRefPic( eRefPicList, iRefIdxPred )->getPicYuvRec()->getStride(COMPONENT_Y);
+
+  TComMv      cMvPred = *pcMvPred;
+
+  if ( bBi )  xSetSearchRange   ( pcCU, rcMv   , iSrchRng, cMvSrchRngLT, cMvSrchRngRB );
+  else        xSetSearchRange   ( pcCU, cMvPred, iSrchRng, cMvSrchRngLT, cMvSrchRngRB );
+
+  m_pcRdCost->getMotionCost( true, 0, pcCU->getCUTransquantBypass(uiPartAddr) );
+
+  m_pcRdCost->setPredictor  ( *pcMvPred );
+  m_pcRdCost->setCostScale  ( 2 );
+
+  setWpScalingDistParam( pcCU, iRefIdxPred, eRefPicList );
+  //  Do integer search
+#if REF_IDX_ME_ZEROMV
+  if( pcCU->getSlice()->getRefPic( eRefPicList, iRefIdxPred )->isILR(pcCU->getLayerId()))  //ILR reference pic 
+  {
+    rcMv.setZero();  //use Mv(0, 0) for integer ME 
+  }
+  else  //non ILR reference pic
+  {
+#endif
+    
+  if ( !m_iFastSearch || bBi )
+  {
+    xPatternSearch      ( pcPatternKey, piRefY, iRefStride, &cMvSrchRngLT, &cMvSrchRngRB, rcMv, ruiCost );
+  }
+  else
+  {
+    rcMv = *pcMvPred;
+    const TComMv *pIntegerMv2Nx2NPred=0;
+    if (pcCU->getPartitionSize(0) != SIZE_2Nx2N || pcCU->getDepth(0) != 0)
+    {
+      pIntegerMv2Nx2NPred = &(m_integerMv2Nx2N[eRefPicList][iRefIdxPred]);
+    }
+    xPatternSearchFast  ( pcCU, pcPatternKey, piRefY, iRefStride, &cMvSrchRngLT, &cMvSrchRngRB, rcMv, ruiCost, pIntegerMv2Nx2NPred );
+    if (pcCU->getPartitionSize(0) == SIZE_2Nx2N)
+    {
+      m_integerMv2Nx2N[eRefPicList][iRefIdxPred] = rcMv;
+    }
+  }
+#if REF_IDX_ME_ZEROMV
+  }
+#endif
+  
+  m_pcRdCost->getMotionCost( true, 0, pcCU->getCUTransquantBypass(uiPartAddr) );
+  m_pcRdCost->setCostScale ( 1 );
+
+  const Bool bIsLosslessCoded = pcCU->getCUTransquantBypass(uiPartAddr) != 0;
+
+#if REF_IDX_ME_ZEROMV
+  if( pcCU->getSlice()->getRefPic( eRefPicList, iRefIdxPred )->isILR(pcCU->getLayerId()))  //ILR reference pic
+  {
+    xPatternSearchFracDIFMv0( pcPatternKey, piRefY, iRefStride, &rcMv, cMvHalf, cMvQter, ruiCost );
+  }
+  else    //non ILR reference pic
+#endif
+  xPatternSearchFracDIF( bIsLosslessCoded, pcPatternKey, piRefY, iRefStride, &rcMv, cMvHalf, cMvQter, ruiCost ,bBi );
+
+  m_pcRdCost->setCostScale( 0 );
+  rcMv <<= 2;
+  rcMv += (cMvHalf <<= 1);
+  rcMv +=  cMvQter;
+
+  UInt uiMvBits = m_pcRdCost->getBits( rcMv.getHor(), rcMv.getVer() );
+
+  ruiBits      += uiMvBits;
+  ruiCost       = (Distortion)( 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;
+  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, Distortion& ruiSAD )
+{
+  Int   iSrchRngHorLeft   = pcMvSrchRngLT->getHor();
+  Int   iSrchRngHorRight  = pcMvSrchRngRB->getHor();
+  Int   iSrchRngVerTop    = pcMvSrchRngLT->getVer();
+  Int   iSrchRngVerBottom = pcMvSrchRngRB->getVer();
+
+  Distortion  uiSad;
+  Distortion  uiSadBest = std::numeric_limits<Distortion>::max();
+  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(COMPONENT_Y);
+
+      m_cDistParam.bitDepth = g_bitDepth[CHANNEL_TYPE_LUMA];
+      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,
+                                     Distortion   &ruiSAD,
+                                     const TComMv* pIntegerMv2Nx2NPred )
+{
+  assert (MD_LEFT < NUM_MV_PREDICTORS);
+  pcCU->getMvPredLeft       ( m_acMvPredictors[MD_LEFT] );
+  assert (MD_ABOVE < NUM_MV_PREDICTORS);
+  pcCU->getMvPredAbove      ( m_acMvPredictors[MD_ABOVE] );
+  assert (MD_ABOVE_RIGHT < NUM_MV_PREDICTORS);
+  pcCU->getMvPredAboveRight ( m_acMvPredictors[MD_ABOVE_RIGHT] );
+
+  switch ( m_iFastSearch )
+  {
+    case 1:
+      xTZSearch( pcCU, pcPatternKey, piRefY, iRefStride, pcMvSrchRngLT, pcMvSrchRngRB, rcMv, ruiSAD, pIntegerMv2Nx2NPred );
+      break;
+
+    case 2:
+      xTZSearchSelective( pcCU, pcPatternKey, piRefY, iRefStride, pcMvSrchRngLT, pcMvSrchRngRB, rcMv, ruiSAD, pIntegerMv2Nx2NPred );
+      break;
+    default:
+      break;
+  }
+}
+
+
+
+
+Void TEncSearch::xTZSearch( TComDataCU*  pcCU,
+                            TComPattern* pcPatternKey,
+                            Pel*         piRefY,
+                            Int          iRefStride,
+                            TComMv*      pcMvSrchRngLT,
+                            TComMv*      pcMvSrchRngRB,
+                            TComMv      &rcMv,
+                            Distortion  &ruiSAD,
+                            const TComMv* pIntegerMv2Nx2NPred )
+{
+  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 );
+  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 < NUM_MV_PREDICTORS; index++ )
+    {
+      TComMv cMv = m_acMvPredictors[index];
+      pcCU->clipMv( cMv );
+      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 );
+  }
+
+  if (pIntegerMv2Nx2NPred != 0)
+  {
+    TComMv integerMv2Nx2NPred = *pIntegerMv2Nx2NPred;
+    integerMv2Nx2NPred <<= 2;
+    pcCU->clipMv( integerMv2Nx2NPred );
+    integerMv2Nx2NPred >>= 2;
+    xTZSearchHelp(pcPatternKey, cStruct, integerMv2Nx2NPred.getHor(), integerMv2Nx2NPred.getVer(), 0, 0);
+
+    // reset search range
+    TComMv cMvSrchRngLT;
+    TComMv cMvSrchRngRB;
+    Int iSrchRng = m_iSearchRange;
+    TComMv currBestMv(cStruct.iBestX, cStruct.iBestY );
+    currBestMv <<= 2;
+    xSetSearchRange( pcCU, currBestMv, iSrchRng, cMvSrchRngLT, cMvSrchRngRB );
+    iSrchRngHorLeft   = cMvSrchRngLT.getHor();
+    iSrchRngHorRight  = cMvSrchRngRB.getHor();
+    iSrchRngVerTop    = cMvSrchRngLT.getVer();
+    iSrchRngVerBottom = cMvSrchRngRB.getVer();
+  }
+
+  // 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::xTZSearchSelective( TComDataCU*   pcCU,
+                                     TComPattern*  pcPatternKey,
+                                     Pel*          piRefY,
+                                     Int           iRefStride,
+                                     TComMv*       pcMvSrchRngLT,
+                                     TComMv*       pcMvSrchRngRB,
+                                     TComMv       &rcMv,
+                                     Distortion   &ruiSAD,
+                                     const TComMv* pIntegerMv2Nx2NPred )
+{
+  SEL_SEARCH_CONFIGURATION
+
+  Int   iSrchRngHorLeft         = pcMvSrchRngLT->getHor();
+  Int   iSrchRngHorRight        = pcMvSrchRngRB->getHor();
+  Int   iSrchRngVerTop          = pcMvSrchRngLT->getVer();
+  Int   iSrchRngVerBottom       = pcMvSrchRngRB->getVer();
+  Int   iFirstSrchRngHorLeft    = 0;
+  Int   iFirstSrchRngHorRight   = 0;
+  Int   iFirstSrchRngVerTop     = 0;
+  Int   iFirstSrchRngVerBottom  = 0;
+  Int   iStartX                 = 0;
+  Int   iStartY                 = 0;
+  Int   iBestX                  = 0;
+  Int   iBestY                  = 0;
+  Int   iDist                   = 0;
+
+  pcCU->clipMv( rcMv );
+  rcMv >>= 2;
+  // init TZSearchStruct
+  IntTZSearchStruct cStruct;
+  cStruct.iYStride    = iRefStride;
+  cStruct.piRefY      = piRefY;
+  cStruct.uiBestSad   = MAX_UINT;
+  cStruct.iBestX = 0;
+  cStruct.iBestY = 0;
+
+
+  // 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 < NUM_MV_PREDICTORS; index++ )
+    {
+      TComMv cMv = m_acMvPredictors[index];
+      pcCU->clipMv( cMv );
+      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 );
+  }
+
+  if ( pIntegerMv2Nx2NPred != 0 )
+  {
+    TComMv integerMv2Nx2NPred = *pIntegerMv2Nx2NPred;
+    integerMv2Nx2NPred <<= 2;
+    pcCU->clipMv( integerMv2Nx2NPred );
+    integerMv2Nx2NPred >>= 2;
+    xTZSearchHelp(pcPatternKey, cStruct, integerMv2Nx2NPred.getHor(), integerMv2Nx2NPred.getVer(), 0, 0);
+
+    // reset search range
+    TComMv cMvSrchRngLT;
+    TComMv cMvSrchRngRB;
+    Int iSrchRng = m_iSearchRange;
+    TComMv currBestMv(cStruct.iBestX, cStruct.iBestY );
+    currBestMv <<= 2;
+    xSetSearchRange( pcCU, currBestMv, iSrchRng, cMvSrchRngLT, cMvSrchRngRB );
+    iSrchRngHorLeft   = cMvSrchRngLT.getHor();
+    iSrchRngHorRight  = cMvSrchRngRB.getHor();
+    iSrchRngVerTop    = cMvSrchRngLT.getVer();
+    iSrchRngVerBottom = cMvSrchRngRB.getVer();
+  }
+
+  // Initial search
+  iBestX = cStruct.iBestX;
+  iBestY = cStruct.iBestY; 
+  iFirstSrchRngHorLeft    = ((iBestX - uiSearchRangeInitial) > iSrchRngHorLeft)   ? (iBestX - uiSearchRangeInitial) : iSrchRngHorLeft;
+  iFirstSrchRngVerTop     = ((iBestY - uiSearchRangeInitial) > iSrchRngVerTop)    ? (iBestY - uiSearchRangeInitial) : iSrchRngVerTop;
+  iFirstSrchRngHorRight   = ((iBestX + uiSearchRangeInitial) < iSrchRngHorRight)  ? (iBestX + uiSearchRangeInitial) : iSrchRngHorRight;  
+  iFirstSrchRngVerBottom  = ((iBestY + uiSearchRangeInitial) < iSrchRngVerBottom) ? (iBestY + uiSearchRangeInitial) : iSrchRngVerBottom;    
+
+  for ( iStartY = iFirstSrchRngVerTop; iStartY <= iFirstSrchRngVerBottom; iStartY += uiSearchStep )
+  {
+    for ( iStartX = iFirstSrchRngHorLeft; iStartX <= iFirstSrchRngHorRight; iStartX += uiSearchStep )
+    {
+      xTZSearchHelp( pcPatternKey, cStruct, iStartX, iStartY, 0, 0 );
+      xTZ8PointDiamondSearch ( pcPatternKey, cStruct, pcMvSrchRngLT, pcMvSrchRngRB, iStartX, iStartY, 1 );
+      xTZ8PointDiamondSearch ( pcPatternKey, cStruct, pcMvSrchRngLT, pcMvSrchRngRB, iStartX, iStartY, 2 );
+    }
+  }
+
+  Int iMaxMVDistToPred = (abs(cStruct.iBestX - iBestX) > iMVDistThresh || abs(cStruct.iBestY - iBestY) > iMVDistThresh);
+
+  //full search with early exit if MV is distant from predictors
+  if ( bEnableRasterSearch && (iMaxMVDistToPred || bAlwaysRasterSearch) )
+  {
+    for ( iStartY = iSrchRngVerTop; iStartY <= iSrchRngVerBottom; iStartY += 1 )
+    {
+      for ( iStartX = iSrchRngHorLeft; iStartX <= iSrchRngHorRight; iStartX += 1 )
+      {
+        xTZSearchHelp( pcPatternKey, cStruct, iStartX, iStartY, 0, 1 );
+      }
+    }
+  }
+  //Smaller MV, refine around predictor
+  else if ( bStarRefinementEnable && cStruct.uiBestDistance > 0 )
+  {
+    // start refinement
+    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(
+                                       Bool         bIsLosslessCoded,
+                                       TComPattern* pcPatternKey,
+                                       Pel*         piRefY,
+                                       Int          iRefStride,
+                                       TComMv*      pcMvInt,
+                                       TComMv&      rcMvHalf,
+                                       TComMv&      rcMvQter,
+                                       Distortion&  ruiCost,
+                                       Bool         biPred
+                                      )
+{
+  //  Reference pattern initialization (integer scale)
+  TComPattern cPatternRoi;
+  Int         iOffset    = pcMvInt->getHor() + pcMvInt->getVer() * iRefStride;
+  cPatternRoi.initPattern(piRefY + iOffset,
+                          pcPatternKey->getROIYWidth(),
+                          pcPatternKey->getROIYHeight(),
+                          iRefStride );
+
+  //  Half-pel refinement
+  xExtDIFUpSamplingH ( &cPatternRoi, biPred );
+
+  rcMvHalf = *pcMvInt;   rcMvHalf <<= 1;    // for mv-cost
+  TComMv baseRefMv(0, 0);
+  ruiCost = xPatternRefinement( pcPatternKey, baseRefMv, 2, rcMvHalf, !bIsLosslessCoded );
+
+  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, !bIsLosslessCoded );
+}
+
+
+/** 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* pcYuvResi, TComYuv* pcYuvResiBest, TComYuv* pcYuvRec,
+                                            Bool bSkipRes DEBUG_STRING_FN_DECLARE(sDebug) )
+{
+  if ( pcCU->isIntra(0) )
+  {
+    return;
+  }
+
+  Bool       bHighPass    = pcCU->getSlice()->getDepth() ? true : false;
+  UInt       uiBits       = 0, uiBitsBest       = 0;
+  Distortion uiDistortion = 0, uiDistortionBest = 0;
+
+  UInt        uiWidth      = pcCU->getWidth ( 0 );
+  UInt        uiHeight     = pcCU->getHeight( 0 );
+
+  //  No residual coding : SKIP mode
+  if ( bSkipRes )
+  {
+    pcCU->setSkipFlagSubParts( true, 0, pcCU->getDepth(0) );
+
+    pcYuvResi->clear();
+
+    pcYuvPred->copyToPartYuv( pcYuvRec, 0 );
+
+    for (UInt ch=0; ch < pcCU->getPic()->getNumberValidComponents(); ch++)
+    {
+      const ComponentID compID=ComponentID(ch);
+      const UInt csx=pcYuvOrg->getComponentScaleX(compID);
+      const UInt csy=pcYuvOrg->getComponentScaleY(compID);
+      uiDistortion += m_pcRdCost->getDistPart( g_bitDepth[toChannelType(compID)], pcYuvRec->getAddr(compID), pcYuvRec->getStride(compID), pcYuvOrg->getAddr(compID),
+                                               pcYuvOrg->getStride(compID), uiWidth >> csx, uiHeight >> csy, compID);
+    }
+
+    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 );
+
+    uiBits = m_pcEntropyCoder->getNumberOfWrittenBits();
+    pcCU->getTotalBits()       = uiBits;
+    pcCU->getTotalDistortion() = uiDistortion;
+    pcCU->getTotalCost()       = m_pcRdCost->calcRdCost( uiBits, uiDistortion );
+
+    m_pcRDGoOnSbacCoder->store(m_pppcRDSbacCoder[pcCU->getDepth(0)][CI_TEMP_BEST]);
+
+    static const UInt cbfZero[MAX_NUM_COMPONENT]={0,0,0};
+    pcCU->setCbfSubParts( cbfZero, 0, pcCU->getDepth( 0 ) );
+    pcCU->setTrIdxSubParts( 0, 0, pcCU->getDepth(0) );
+
+#ifdef DEBUG_STRING
+    pcYuvResiBest->clear(); // Clear the residual image, if we didn't code it.
+    for(UInt i=0; i<MAX_NUM_COMPONENT+1; i++)
+    {
+      sDebug+=debug_reorder_data_inter_token[i];
+    }
+#endif
+
+    return;
+  }
+
+  //  Residual coding.
+  Int qp;
+  Int qpBest = 0;
+  Int qpMin;
+  Int 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++;
+  }
+
+#if REPN_FORMAT_IN_VPS
+  qpMin =  bHighPass ? Clip3( -pcCU->getSlice()->getQpBDOffsetY(), MAX_QP, pcCU->getQP(0) - m_iMaxDeltaQP ) : pcCU->getQP( 0 );
+  qpMax =  bHighPass ? Clip3( -pcCU->getSlice()->getQpBDOffsetY(), MAX_QP, pcCU->getQP(0) + m_iMaxDeltaQP ) : pcCU->getQP( 0 );
+#else
+  qpMin =  bHighPass ? Clip3( -pcCU->getSlice()->getSPS()->getQpBDOffset(CHANNEL_TYPE_LUMA), MAX_QP, pcCU->getQP(0) - m_iMaxDeltaQP ) : pcCU->getQP( 0 );
+  qpMax =  bHighPass ? Clip3( -pcCU->getSlice()->getSPS()->getQpBDOffset(CHANNEL_TYPE_LUMA), MAX_QP, pcCU->getQP(0) + m_iMaxDeltaQP ) : pcCU->getQP( 0 );
+#endif
+
+  pcYuvResi->subtract( pcYuvOrg, pcYuvPred, 0, uiWidth );
+
+  TComTURecurse tuLevel0(pcCU, 0);
+
+  for ( qp = qpMin; qp <= qpMax; qp++ )
+  {
+    dCost = 0.;
+    uiBits = 0;
+    uiDistortion = 0;
+
+    m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[ pcCU->getDepth( 0 ) ][ CI_CURR_BEST ] );
+
+    Distortion uiZeroDistortion = 0;
+
+    xEstimateResidualQT( pcYuvResi,  dCost, uiBits, uiDistortion, &uiZeroDistortion, tuLevel0 DEBUG_STRING_PASS_INTO(sDebug) );
+
+    // -------------------------------------------------------
+    // set the coefficients in the pcCU, and also calculates the residual data.
+    // If a block full of 0's is efficient, then just use 0's.
+    // The costs at this point do not include header bits.
+
+    m_pcEntropyCoder->resetBits();
+    m_pcEntropyCoder->encodeQtRootCbfZero( pcCU );
+    UInt zeroResiBits = m_pcEntropyCoder->getNumberOfWrittenBits();
+    Double dZeroCost = m_pcRdCost->calcRdCost( zeroResiBits, uiZeroDistortion );
+
+    if(pcCU->isLosslessCoded( 0 ))
+    {
+      dZeroCost = dCost + 1;
+    }
+
+    if ( dZeroCost < dCost )
+    {
+      if ( dZeroCost < dCost )
+      {
+        dCost        = dZeroCost;
+      }
+      uiDistortion = uiZeroDistortion;
+
+      const UInt uiQPartNum = tuLevel0.GetAbsPartIdxNumParts();
+      ::memset( pcCU->getTransformIdx()     , 0, uiQPartNum * sizeof(UChar) );
+      for (UInt ch=0; ch < pcCU->getPic()->getNumberValidComponents(); ch++)
+      {
+        const ComponentID component = ComponentID(ch);
+        const UInt componentShift   = pcCU->getPic()->getComponentScaleX(component) + pcCU->getPic()->getComponentScaleY(component);
+        ::memset( pcCU->getCbf( component ) , 0, uiQPartNum * sizeof(UChar) );
+        ::memset( pcCU->getCoeff(component), 0, (uiWidth*uiHeight*sizeof(TCoeff))>>componentShift );
+        ::memset( pcCU->getCrossComponentPredictionAlpha(component), 0, ( uiQPartNum * sizeof(Char) ) );
+      }
+      static const UInt useTS[MAX_NUM_COMPONENT]={0,0,0};
+      pcCU->setTransformSkipSubParts ( useTS, 0, pcCU->getDepth(0) );
+#ifdef DEBUG_STRING
+      sDebug.clear();
+      for(UInt i=0; i<MAX_NUM_COMPONENT+1; i++)
+      {
+        sDebug+=debug_reorder_data_inter_token[i];
+      }
+#endif
+    }
+    else
+    {
+      xSetResidualQTData( NULL, false, tuLevel0); // Call first time to set coefficients.
+    }
+
+    m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[pcCU->getDepth(0)][CI_CURR_BEST] );
+
+    uiBits = 0;
+    xAddSymbolBitsInter( pcCU, 0, 0, uiBits );
+    // we've now encoded the pcCU, and so have a valid bit cost
+
+
+    Double dExactCost = m_pcRdCost->calcRdCost( uiBits, uiDistortion );
+    dCost = dExactCost;
+
+    // Is our new cost better?
+    if ( dCost < dCostBest )
+    {
+      if ( !pcCU->getQtRootCbf( 0 ) )
+      {
+        pcYuvResiBest->clear(); // Clear the residual image, if we didn't code it.
+      }
+      else
+      {
+        xSetResidualQTData( pcYuvResiBest, true, tuLevel0 ); // else set the residual image data pcYUVResiBest from the various temp images.
+      }
+
+      if( qpMin != qpMax && qp != qpMax )
+      {
+        const UInt uiQPartNum = tuLevel0.GetAbsPartIdxNumParts();
+        ::memcpy( m_puhQTTempTrIdx, pcCU->getTransformIdx(),        uiQPartNum * sizeof(UChar) );
+        for(UInt i=0; i<pcCU->getPic()->getNumberValidComponents(); i++)
+        {
+          const ComponentID compID=ComponentID(i);
+          const UInt csr = pcCU->getPic()->getComponentScaleX(compID) + pcCU->getPic()->getComponentScaleY(compID);
+          ::memcpy( m_puhQTTempCbf[compID],      pcCU->getCbf( compID ),     uiQPartNum * sizeof(UChar) );
+          ::memcpy( m_pcQTTempCoeff[compID],     pcCU->getCoeff(compID),     uiWidth * uiHeight * sizeof( TCoeff ) >> csr     );
+#if ADAPTIVE_QP_SELECTION
+          ::memcpy( m_pcQTTempArlCoeff[compID],  pcCU->getArlCoeff(compID),  uiWidth * uiHeight * sizeof( TCoeff )>> csr     );
+#endif
+          ::memcpy( m_puhQTTempTransformSkipFlag[compID], pcCU->getTransformSkip(compID),     uiQPartNum * sizeof( UChar ) );
+          ::memcpy( m_phQTTempCrossComponentPredictionAlpha[compID], pcCU->getCrossComponentPredictionAlpha(compID), uiQPartNum * sizeof(Char) );
+        }
+      }
+      uiBitsBest       = uiBits;
+      uiDistortionBest = uiDistortion;
+      dCostBest        = dCost;
+      qpBest           = qp;
+
+      m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[ pcCU->getDepth( 0 ) ][ CI_TEMP_BEST ] );
+    }
+  }
+
+  assert ( dCostBest != MAX_DOUBLE );
+
+  if( qpMin != qpMax && qpBest != qpMax )
+  {
+    assert( 0 ); // check
+    m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[ pcCU->getDepth( 0 ) ][ CI_TEMP_BEST ] );
+
+      // copy best cbf and trIdx to pcCU
+    const UInt uiQPartNum = tuLevel0.GetAbsPartIdxNumParts();
+    ::memcpy( pcCU->getTransformIdx(),       m_puhQTTempTrIdx,  uiQPartNum * sizeof(UChar) );
+    for(UInt i=0; i<pcCU->getPic()->getNumberValidComponents(); i++)
+    {
+      const ComponentID compID=ComponentID(i);
+      const UInt csr = pcCU->getPic()->getComponentScaleX(compID) + pcCU->getPic()->getComponentScaleY(compID);
+      ::memcpy( pcCU->getCbf( compID ),     m_puhQTTempCbf[compID],     uiQPartNum * sizeof(UChar) );
+      ::memcpy( pcCU->getCoeff(compID),     m_pcQTTempCoeff[compID],    uiWidth * uiHeight * sizeof( TCoeff ) >> csr     );
+#if ADAPTIVE_QP_SELECTION
+      ::memcpy( pcCU->getArlCoeff(compID),  m_pcQTTempArlCoeff[compID], uiWidth * uiHeight * sizeof( TCoeff    ) >> csr );
+#endif
+      ::memcpy( pcCU->getTransformSkip(compID),     m_puhQTTempTransformSkipFlag[compID], uiQPartNum * sizeof( UChar ) );
+      ::memcpy( pcCU->getCrossComponentPredictionAlpha(compID),  m_phQTTempCrossComponentPredictionAlpha[compID], uiQPartNum * sizeof( Char ) );
+    }
+  }
+  pcYuvRec->addClip ( pcYuvPred, pcYuvResiBest, 0, uiWidth );
+
+  // update with clipped distortion and cost (qp estimation loop uses unclipped values)
+
+  uiDistortionBest = 0;
+  for(UInt ch=0; ch<pcYuvRec->getNumberValidComponents(); ch++)
+  {
+    const ComponentID compID=ComponentID(ch);
+    uiDistortionBest += m_pcRdCost->getDistPart( g_bitDepth[toChannelType(compID)], pcYuvRec->getAddr(compID ), pcYuvRec->getStride(compID ), pcYuvOrg->getAddr(compID ), pcYuvOrg->getStride(compID), uiWidth >> pcYuvOrg->getComponentScaleX(compID), uiHeight >> pcYuvOrg->getComponentScaleY(compID), compID);
+  }
+  dCostBest = m_pcRdCost->calcRdCost( uiBitsBest, uiDistortionBest );
+
+  pcCU->getTotalBits()       = uiBitsBest;
+  pcCU->getTotalDistortion() = uiDistortionBest;
+  pcCU->getTotalCost()       = dCostBest;
+
+  if ( pcCU->isSkipped(0) )
+  {
+    static const UInt cbfZero[MAX_NUM_COMPONENT]={0,0,0};
+    pcCU->setCbfSubParts( cbfZero, 0, pcCU->getDepth( 0 ) );
+  }
+
+  pcCU->setQPSubParts( qpBest, 0, pcCU->getDepth(0) );
+}
+
+
+
+Void TEncSearch::xEstimateResidualQT( TComYuv    *pcResi,
+                                      Double     &rdCost,
+                                      UInt       &ruiBits,
+                                      Distortion &ruiDist,
+                                      Distortion *puiZeroDist,
+                                      TComTU     &rTu
+                                      DEBUG_STRING_FN_DECLARE(sDebug) )
+{
+  TComDataCU *pcCU        = rTu.getCU();
+  const UInt uiAbsPartIdx = rTu.GetAbsPartIdxTU();
+  const UInt uiDepth      = rTu.GetTransformDepthTotal();
+  const UInt uiTrMode     = rTu.GetTransformDepthRel();
+  const UInt subTUDepth   = uiTrMode + 1;
+  const UInt numValidComp = pcCU->getPic()->getNumberValidComponents();
+  DEBUG_STRING_NEW(sSingleStringComp[MAX_NUM_COMPONENT])
+
+  assert( pcCU->getDepth( 0 ) == pcCU->getDepth( uiAbsPartIdx ) );
+  const UInt uiLog2TrSize = rTu.GetLog2LumaTrSize();
+
+  UInt SplitFlag = ((pcCU->getSlice()->getSPS()->getQuadtreeTUMaxDepthInter() == 1) && pcCU->isInter(uiAbsPartIdx) && ( pcCU->getPartitionSize(uiAbsPartIdx) != SIZE_2Nx2N ));
+#ifdef DEBUG_STRING
+  const Int debugPredModeMask = DebugStringGetPredModeMask(pcCU->getPredictionMode(uiAbsPartIdx));
+#endif
+
+  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 );
+
+  // code full block
+  Double     dSingleCost = MAX_DOUBLE;
+  UInt       uiSingleBits                                                                                                        = 0;
+  Distortion uiSingleDistComp            [MAX_NUM_COMPONENT][2/*0 = top (or whole TU for non-4:2:2) sub-TU, 1 = bottom sub-TU*/] = {{0,0},{0,0},{0,0}};
+  Distortion uiSingleDist                                                                                                        = 0;
+  TCoeff     uiAbsSum                    [MAX_NUM_COMPONENT][2/*0 = top (or whole TU for non-4:2:2) sub-TU, 1 = bottom sub-TU*/] = {{0,0},{0,0},{0,0}};
+  UInt       uiBestTransformMode         [MAX_NUM_COMPONENT][2/*0 = top (or whole TU for non-4:2:2) sub-TU, 1 = bottom sub-TU*/] = {{0,0},{0,0},{0,0}};
+  //  Stores the best explicit RDPCM mode for a TU encoded without split
+  UInt       bestExplicitRdpcmModeUnSplit[MAX_NUM_COMPONENT][2/*0 = top (or whole TU for non-4:2:2) sub-TU, 1 = bottom sub-TU*/] = {{3,3}, {3,3}, {3,3}};
+  Char       bestCrossCPredictionAlpha   [MAX_NUM_COMPONENT][2/*0 = top (or whole TU for non-4:2:2) sub-TU, 1 = bottom sub-TU*/] = {{0,0},{0,0},{0,0}};
+
+  m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[ uiDepth ][ CI_QT_TRAFO_ROOT ] );
+
+  if( bCheckFull )
+  {
+    Double minCost[MAX_NUM_COMPONENT][2/*0 = top (or whole TU for non-4:2:2) sub-TU, 1 = bottom sub-TU*/];
+    Bool checkTransformSkip[MAX_NUM_COMPONENT];
+    pcCU->setTrIdxSubParts( uiTrMode, uiAbsPartIdx, uiDepth );
+
+    m_pcEntropyCoder->resetBits();
+
+    memset( m_pTempPel, 0, sizeof( Pel ) * rTu.getRect(COMPONENT_Y).width * rTu.getRect(COMPONENT_Y).height ); // not necessary needed for inside of recursion (only at the beginning)
+
+    const UInt uiQTTempAccessLayer = pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() - uiLog2TrSize;
+    TCoeff *pcCoeffCurr[MAX_NUM_COMPONENT];
+#if ADAPTIVE_QP_SELECTION
+    TCoeff *pcArlCoeffCurr[MAX_NUM_COMPONENT];
+#endif
+
+    for(UInt i=0; i<numValidComp; i++)
+    {
+      minCost[i][0] = MAX_DOUBLE;
+      minCost[i][1] = MAX_DOUBLE;
+    }
+
+    Pel crossCPredictedResidualBuffer[ MAX_TU_SIZE * MAX_TU_SIZE ];
+
+    for(UInt i=0; i<numValidComp; i++)
+    {
+      checkTransformSkip[i]=false;
+      const ComponentID compID=ComponentID(i);
+      pcCoeffCurr[compID]    = m_ppcQTTempCoeff[compID][uiQTTempAccessLayer] + rTu.getCoefficientOffset(compID);
+#if ADAPTIVE_QP_SELECTION
+      pcArlCoeffCurr[compID] = m_ppcQTTempArlCoeff[compID ][uiQTTempAccessLayer] +  rTu.getCoefficientOffset(compID);
+#endif
+
+      if(rTu.ProcessComponentSection(compID))
+      {
+        const QpParam cQP(*pcCU, compID);
+
+        checkTransformSkip[compID] = pcCU->getSlice()->getPPS()->getUseTransformSkip() &&
+                                     TUCompRectHasAssociatedTransformSkipFlag(rTu.getRect(compID), pcCU->getSlice()->getPPS()->getTransformSkipLog2MaxSize()) &&
+                                     (!pcCU->isLosslessCoded(0));
+
+        const Bool splitIntoSubTUs = rTu.getRect(compID).width != rTu.getRect(compID).height;
+
+        TComTURecurse TUIterator(rTu, false, (splitIntoSubTUs ? TComTU::VERTICAL_SPLIT : TComTU::DONT_SPLIT), true, compID);
+
+        const UInt partIdxesPerSubTU = TUIterator.GetAbsPartIdxNumParts(compID);
+
+        do
+        {
+          const UInt           subTUIndex             = TUIterator.GetSectionNumber();
+          const UInt           subTUAbsPartIdx        = TUIterator.GetAbsPartIdxTU(compID);
+          const TComRectangle &tuCompRect             = TUIterator.getRect(compID);
+          const UInt           subTUBufferOffset      = tuCompRect.width * tuCompRect.height * subTUIndex;
+
+                TCoeff        *currentCoefficients    = pcCoeffCurr[compID] + subTUBufferOffset;
+#if ADAPTIVE_QP_SELECTION
+                TCoeff        *currentARLCoefficients = pcArlCoeffCurr[compID] + subTUBufferOffset;
+#endif
+          const Bool isCrossCPredictionAvailable      =    isChroma(compID)
+                                                         && pcCU->getSlice()->getPPS()->getUseCrossComponentPrediction()
+                                                         && (pcCU->getCbf(subTUAbsPartIdx, COMPONENT_Y, uiTrMode) != 0);
+
+          Char preCalcAlpha = 0;
+          const Pel *pLumaResi = m_pcQTTempTComYuv[uiQTTempAccessLayer].getAddrPix( COMPONENT_Y, rTu.getRect( COMPONENT_Y ).x0, rTu.getRect( COMPONENT_Y ).y0 );
+
+          if (isCrossCPredictionAvailable)
+          {
+            const Bool bUseReconstructedResidualForEstimate = m_pcEncCfg->getUseReconBasedCrossCPredictionEstimate();
+            const Pel  *const lumaResidualForEstimate       = bUseReconstructedResidualForEstimate ? pLumaResi                                                     : pcResi->getAddrPix(COMPONENT_Y, tuCompRect.x0, tuCompRect.y0);
+            const UInt        lumaResidualStrideForEstimate = bUseReconstructedResidualForEstimate ? m_pcQTTempTComYuv[uiQTTempAccessLayer].getStride(COMPONENT_Y) : pcResi->getStride(COMPONENT_Y);
+
+            preCalcAlpha = xCalcCrossComponentPredictionAlpha(TUIterator,
+                                                              compID,
+                                                              lumaResidualForEstimate,
+                                                              pcResi->getAddrPix(compID, tuCompRect.x0, tuCompRect.y0),
+                                                              tuCompRect.width,
+                                                              tuCompRect.height,
+                                                              lumaResidualStrideForEstimate,
+                                                              pcResi->getStride(compID));
+          }
+
+          const Int transformSkipModesToTest    = checkTransformSkip[compID] ? 2 : 1;
+          const Int crossCPredictionModesToTest = (preCalcAlpha != 0)        ? 2 : 1; // preCalcAlpha cannot be anything other than 0 if isCrossCPredictionAvailable is false
+
+          const Bool isOneMode                  = (crossCPredictionModesToTest == 1) && (transformSkipModesToTest == 1);
+
+          for (Int transformSkipModeId = 0; transformSkipModeId < transformSkipModesToTest; transformSkipModeId++)
+          {
+            pcCU->setTransformSkipPartRange(transformSkipModeId, compID, subTUAbsPartIdx, partIdxesPerSubTU);
+
+            for (Int crossCPredictionModeId = 0; crossCPredictionModeId < crossCPredictionModesToTest; crossCPredictionModeId++)
+            {
+              const Bool isFirstMode          = (transformSkipModeId == 0) && (crossCPredictionModeId == 0);
+              const Bool bUseCrossCPrediction = crossCPredictionModeId != 0;
+
+              m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[ uiDepth ][ CI_QT_TRAFO_ROOT ] );
+              m_pcEntropyCoder->resetBits();
+
+              pcCU->setTransformSkipPartRange(transformSkipModeId, compID, subTUAbsPartIdx, partIdxesPerSubTU);
+              pcCU->setCrossComponentPredictionAlphaPartRange((bUseCrossCPrediction ? preCalcAlpha : 0), compID, subTUAbsPartIdx, partIdxesPerSubTU );
+
+              if ((compID != COMPONENT_Cr) && ((transformSkipModeId == 1) ? m_pcEncCfg->getUseRDOQTS() : m_pcEncCfg->getUseRDOQ()))
+              {
+                m_pcEntropyCoder->estimateBit(m_pcTrQuant->m_pcEstBitsSbac, tuCompRect.width, tuCompRect.height, toChannelType(compID));
+              }
+
+#if RDOQ_CHROMA_LAMBDA
+              m_pcTrQuant->selectLambda(compID);
+#endif
+
+              Pel *pcResiCurrComp = m_pcQTTempTComYuv[uiQTTempAccessLayer].getAddrPix(compID, tuCompRect.x0, tuCompRect.y0);
+              UInt resiStride     = m_pcQTTempTComYuv[uiQTTempAccessLayer].getStride(compID);
+
+              TCoeff bestCoeffComp   [MAX_TU_SIZE*MAX_TU_SIZE];
+              Pel    bestResiComp    [MAX_TU_SIZE*MAX_TU_SIZE];
+
+#if ADAPTIVE_QP_SELECTION
+              TCoeff bestArlCoeffComp[MAX_TU_SIZE*MAX_TU_SIZE];
+#endif
+              TCoeff     currAbsSum   = 0;
+              UInt       currCompBits = 0;
+              Distortion currCompDist = 0;
+              Double     currCompCost = 0;
+              UInt       nonCoeffBits = 0;
+              Distortion nonCoeffDist = 0;
+              Double     nonCoeffCost = 0;
+
+              if(!isOneMode && !isFirstMode)
+              {
+                memcpy(bestCoeffComp,    currentCoefficients,    (sizeof(TCoeff) * tuCompRect.width * tuCompRect.height));
+#if ADAPTIVE_QP_SELECTION
+                memcpy(bestArlCoeffComp, currentARLCoefficients, (sizeof(TCoeff) * tuCompRect.width * tuCompRect.height));
+#endif
+                for(Int y = 0; y < tuCompRect.height; y++)
+                {
+                  memcpy(&bestResiComp[y * tuCompRect.width], (pcResiCurrComp + (y * resiStride)), (sizeof(Pel) * tuCompRect.width));
+                }
+              }
+
+              if (bUseCrossCPrediction)
+              {
+                TComTrQuant::crossComponentPrediction(TUIterator,
+                                                      compID,
+                                                      pLumaResi,
+                                                      pcResi->getAddrPix(compID, tuCompRect.x0, tuCompRect.y0),
+                                                      crossCPredictedResidualBuffer,
+                                                      tuCompRect.width,
+                                                      tuCompRect.height,
+                                                      m_pcQTTempTComYuv[uiQTTempAccessLayer].getStride(COMPONENT_Y),
+                                                      pcResi->getStride(compID),
+                                                      tuCompRect.width,
+                                                      false);
+
+                m_pcTrQuant->transformNxN(TUIterator, compID, crossCPredictedResidualBuffer, tuCompRect.width, currentCoefficients,
+#if ADAPTIVE_QP_SELECTION
+                                          currentARLCoefficients,
+#endif
+                                          currAbsSum, cQP);
+              }
+              else
+              {
+                m_pcTrQuant->transformNxN(TUIterator, compID, pcResi->getAddrPix( compID, tuCompRect.x0, tuCompRect.y0 ), pcResi->getStride(compID), currentCoefficients,
+#if ADAPTIVE_QP_SELECTION
+                                          currentARLCoefficients,
+#endif
+                                          currAbsSum, cQP);
+              }
+
+              if(isFirstMode || (currAbsSum == 0))
+              {
+                if (bUseCrossCPrediction)
+                {
+                  TComTrQuant::crossComponentPrediction(TUIterator,
+                                                        compID,
+                                                        pLumaResi,
+                                                        m_pTempPel,
+                                                        m_pcQTTempTComYuv[uiQTTempAccessLayer].getAddrPix(compID, tuCompRect.x0, tuCompRect.y0),
+                                                        tuCompRect.width,
+                                                        tuCompRect.height,
+                                                        m_pcQTTempTComYuv[uiQTTempAccessLayer].getStride(COMPONENT_Y),
+                                                        tuCompRect.width,
+                                                        m_pcQTTempTComYuv[uiQTTempAccessLayer].getStride(compID),
+                                                        true);
+
+                  nonCoeffDist = m_pcRdCost->getDistPart( g_bitDepth[toChannelType(compID)], m_pcQTTempTComYuv[uiQTTempAccessLayer].getAddrPix( compID, tuCompRect.x0, tuCompRect.y0 ),
+                                                                                              m_pcQTTempTComYuv[uiQTTempAccessLayer].getStride( compID ), pcResi->getAddrPix( compID, tuCompRect.x0, tuCompRect.y0 ),
+                                                                                              pcResi->getStride(compID), tuCompRect.width, tuCompRect.height, compID); // initialized with zero residual destortion
+                }
+                else
+                {
+                  nonCoeffDist = m_pcRdCost->getDistPart( g_bitDepth[toChannelType(compID)], m_pTempPel, tuCompRect.width, pcResi->getAddrPix( compID, tuCompRect.x0, tuCompRect.y0 ),
+                                                                                              pcResi->getStride(compID), tuCompRect.width, tuCompRect.height, compID); // initialized with zero residual destortion
+                }
+
+                m_pcEntropyCoder->encodeQtCbfZero( TUIterator, toChannelType(compID) );
+
+                if ( isCrossCPredictionAvailable )
+                {
+                  m_pcEntropyCoder->encodeCrossComponentPrediction( TUIterator, compID );
+                }
+
+                nonCoeffBits = m_pcEntropyCoder->getNumberOfWrittenBits();
+                nonCoeffCost = m_pcRdCost->calcRdCost( nonCoeffBits, nonCoeffDist );
+              }
+
+              if((puiZeroDist != NULL) && isFirstMode)
+              {
+                *puiZeroDist += nonCoeffDist; // initialized with zero residual destortion
+              }
+
+              DEBUG_STRING_NEW(sSingleStringTest)
+
+              if( currAbsSum > 0 ) //if non-zero coefficients are present, a residual needs to be derived for further prediction
+              {
+                if (isFirstMode)
+                {
+                  m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[ uiDepth ][ CI_QT_TRAFO_ROOT ] );
+                  m_pcEntropyCoder->resetBits();
+                }
+
+                m_pcEntropyCoder->encodeQtCbf( TUIterator, compID, true );
+
+                if (isCrossCPredictionAvailable)
+                {
+                  m_pcEntropyCoder->encodeCrossComponentPrediction( TUIterator, compID );
+                }
+
+                m_pcEntropyCoder->encodeCoeffNxN( TUIterator, currentCoefficients, compID );
+                currCompBits = m_pcEntropyCoder->getNumberOfWrittenBits();
+
+                pcResiCurrComp = m_pcQTTempTComYuv[uiQTTempAccessLayer].getAddrPix( compID, tuCompRect.x0, tuCompRect.y0 );
+
+                m_pcTrQuant->invTransformNxN( TUIterator, compID, pcResiCurrComp, m_pcQTTempTComYuv[uiQTTempAccessLayer].getStride(compID), currentCoefficients, cQP DEBUG_STRING_PASS_INTO_OPTIONAL(&sSingleStringTest, (DebugOptionList::DebugString_InvTran.getInt()&debugPredModeMask)) );
+
+                if (bUseCrossCPrediction)
+                {
+                  TComTrQuant::crossComponentPrediction(TUIterator,
+                                                        compID,
+                                                        pLumaResi,
+                                                        m_pcQTTempTComYuv[uiQTTempAccessLayer].getAddrPix(compID, tuCompRect.x0, tuCompRect.y0),
+                                                        m_pcQTTempTComYuv[uiQTTempAccessLayer].getAddrPix(compID, tuCompRect.x0, tuCompRect.y0),
+                                                        tuCompRect.width,
+                                                        tuCompRect.height,
+                                                        m_pcQTTempTComYuv[uiQTTempAccessLayer].getStride(COMPONENT_Y),
+                                                        m_pcQTTempTComYuv[uiQTTempAccessLayer].getStride(compID     ),
+                                                        m_pcQTTempTComYuv[uiQTTempAccessLayer].getStride(compID     ),
+                                                        true);
+                }
+
+                currCompDist = m_pcRdCost->getDistPart( g_bitDepth[toChannelType(compID)], m_pcQTTempTComYuv[uiQTTempAccessLayer].getAddrPix( compID, tuCompRect.x0, tuCompRect.y0 ),
+                                                        m_pcQTTempTComYuv[uiQTTempAccessLayer].getStride(compID),
+                                                        pcResi->getAddrPix( compID, tuCompRect.x0, tuCompRect.y0 ),
+                                                        pcResi->getStride(compID),
+                                                        tuCompRect.width, tuCompRect.height, compID);
+
+                currCompCost = m_pcRdCost->calcRdCost(currCompBits, currCompDist);
+                  
+                if (pcCU->isLosslessCoded(0)) nonCoeffCost = MAX_DOUBLE;
+              }
+              else if ((transformSkipModeId == 1) && !bUseCrossCPrediction)
+              {
+                currCompCost = MAX_DOUBLE;
+              }
+              else
+              {
+                currCompBits = nonCoeffBits;
+                currCompDist = nonCoeffDist;
+                currCompCost = nonCoeffCost;
+              }
+
+              // evaluate
+              if ((currCompCost < minCost[compID][subTUIndex]) || ((transformSkipModeId == 1) && (currCompCost == minCost[compID][subTUIndex])))
+              {
+                bestExplicitRdpcmModeUnSplit[compID][subTUIndex] = pcCU->getExplicitRdpcmMode(compID, subTUAbsPartIdx);
+
+                if(isFirstMode) //check for forced null
+                {
+                  if((nonCoeffCost < currCompCost) || (currAbsSum == 0))
+                  {
+                    memset(currentCoefficients, 0, (sizeof(TCoeff) * tuCompRect.width * tuCompRect.height));
+
+                    currAbsSum   = 0;
+                    currCompBits = nonCoeffBits;
+                    currCompDist = nonCoeffDist;
+                    currCompCost = nonCoeffCost;
+                  }
+                }
+
+#ifdef DEBUG_STRING
+                if (currAbsSum > 0)
+                {
+                  DEBUG_STRING_SWAP(sSingleStringComp[compID], sSingleStringTest)
+                }
+                else
+                {
+                  sSingleStringComp[compID].clear();
+                }
+#endif
+
+                uiAbsSum                 [compID][subTUIndex] = currAbsSum;
+                uiSingleDistComp         [compID][subTUIndex] = currCompDist;
+                minCost                  [compID][subTUIndex] = currCompCost;
+                uiBestTransformMode      [compID][subTUIndex] = transformSkipModeId;
+                bestCrossCPredictionAlpha[compID][subTUIndex] = (crossCPredictionModeId == 1) ? pcCU->getCrossComponentPredictionAlpha(subTUAbsPartIdx, compID) : 0;
+
+                if (uiAbsSum[compID][subTUIndex] == 0)
+                {
+                  if (bUseCrossCPrediction)
+                  {
+                    TComTrQuant::crossComponentPrediction(TUIterator,
+                                                          compID,
+                                                          pLumaResi,
+                                                          m_pTempPel,
+                                                          m_pcQTTempTComYuv[uiQTTempAccessLayer].getAddrPix(compID, tuCompRect.x0, tuCompRect.y0),
+                                                          tuCompRect.width,
+                                                          tuCompRect.height,
+                                                          m_pcQTTempTComYuv[uiQTTempAccessLayer].getStride(COMPONENT_Y),
+                                                          tuCompRect.width,
+                                                          m_pcQTTempTComYuv[uiQTTempAccessLayer].getStride(compID),
+                                                          true);
+                  }
+                  else
+                  {
+                    pcResiCurrComp = m_pcQTTempTComYuv[uiQTTempAccessLayer].getAddrPix(compID, tuCompRect.x0, tuCompRect.y0);
+                    const UInt uiStride = m_pcQTTempTComYuv[uiQTTempAccessLayer].getStride(compID);
+                    for(UInt uiY = 0; uiY < tuCompRect.height; uiY++)
+                    {
+                      memset(pcResiCurrComp, 0, (sizeof(Pel) * tuCompRect.width));
+                      pcResiCurrComp += uiStride;
+                    }
+                  }
+                }
+              }
+              else
+              {
+                // reset
+                memcpy(currentCoefficients,    bestCoeffComp,    (sizeof(TCoeff) * tuCompRect.width * tuCompRect.height));
+#if ADAPTIVE_QP_SELECTION
+                memcpy(currentARLCoefficients, bestArlCoeffComp, (sizeof(TCoeff) * tuCompRect.width * tuCompRect.height));
+#endif
+                for (Int y = 0; y < tuCompRect.height; y++)
+                {
+                  memcpy((pcResiCurrComp + (y * resiStride)), &bestResiComp[y * tuCompRect.width], (sizeof(Pel) * tuCompRect.width));
+                }
+              }
+            }
+          }
+
+          pcCU->setExplicitRdpcmModePartRange            (   bestExplicitRdpcmModeUnSplit[compID][subTUIndex],                            compID, subTUAbsPartIdx, partIdxesPerSubTU);
+          pcCU->setTransformSkipPartRange                (   uiBestTransformMode         [compID][subTUIndex],                            compID, subTUAbsPartIdx, partIdxesPerSubTU );
+          pcCU->setCbfPartRange                          ((((uiAbsSum                    [compID][subTUIndex] > 0) ? 1 : 0) << uiTrMode), compID, subTUAbsPartIdx, partIdxesPerSubTU );
+          pcCU->setCrossComponentPredictionAlphaPartRange(   bestCrossCPredictionAlpha   [compID][subTUIndex],                            compID, subTUAbsPartIdx, partIdxesPerSubTU );
+        } //end of sub-TU loop
+        while (TUIterator.nextSection(rTu));
+      } // processing section
+    } // component loop
+
+    for(UInt ch = 0; ch < numValidComp; ch++)
+    {
+      const ComponentID compID = ComponentID(ch);
+      if (rTu.ProcessComponentSection(compID) && (rTu.getRect(compID).width != rTu.getRect(compID).height))
+      {
+        offsetSubTUCBFs(rTu, compID); //the CBFs up to now have been defined for two sub-TUs - shift them down a level and replace with the parent level CBF
+      }
+    }
+
+    m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[ uiDepth ][ CI_QT_TRAFO_ROOT ] );
+    m_pcEntropyCoder->resetBits();
+
+    if( uiLog2TrSize > pcCU->getQuadtreeTULog2MinSizeInCU(uiAbsPartIdx) )
+    {
+      m_pcEntropyCoder->encodeTransformSubdivFlag( 0, 5 - uiLog2TrSize );
+    }
+
+    for(UInt ch = 0; ch < numValidComp; ch++)
+    {
+      const UInt chOrderChange = ((ch + 1) == numValidComp) ? 0 : (ch + 1);
+      const ComponentID compID=ComponentID(chOrderChange);
+      if( rTu.ProcessComponentSection(compID) )
+      {
+        m_pcEntropyCoder->encodeQtCbf( rTu, compID, true );
+      }
+    }
+
+    for(UInt ch = 0; ch < numValidComp; ch++)
+    {
+      const ComponentID compID=ComponentID(ch);
+      if (rTu.ProcessComponentSection(compID))
+      {
+        if(isChroma(compID) && (uiAbsSum[COMPONENT_Y][0] != 0))
+        {
+          m_pcEntropyCoder->encodeCrossComponentPrediction( rTu, compID );
+        }
+
+        m_pcEntropyCoder->encodeCoeffNxN( rTu, pcCoeffCurr[compID], compID );
+        for (UInt subTUIndex = 0; subTUIndex < 2; subTUIndex++) uiSingleDist += uiSingleDistComp[compID][subTUIndex];
+      }
+    }
+
+    uiSingleBits = m_pcEntropyCoder->getNumberOfWrittenBits();
+
+    dSingleCost = m_pcRdCost->calcRdCost( uiSingleBits, uiSingleDist );
+  } // check full
+
+  // code sub-blocks
+  if( bCheckSplit )
+  {
+    if( bCheckFull )
+    {
+      m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[ uiDepth ][ CI_QT_TRAFO_TEST ] );
+      m_pcRDGoOnSbacCoder->load ( m_pppcRDSbacCoder[ uiDepth ][ CI_QT_TRAFO_ROOT ] );
+    }
+    Distortion uiSubdivDist = 0;
+    UInt       uiSubdivBits = 0;
+    Double     dSubdivCost = 0.0;
+
+    //save the non-split CBFs in case we need to restore them later
+
+    UInt bestCBF     [MAX_NUM_COMPONENT];
+    UInt bestsubTUCBF[MAX_NUM_COMPONENT][2];
+    for(UInt ch = 0; ch < numValidComp; ch++)
+    {
+      const ComponentID compID=ComponentID(ch);
+
+      if (rTu.ProcessComponentSection(compID))
+      {
+        bestCBF[compID] = pcCU->getCbf(uiAbsPartIdx, compID, uiTrMode);
+
+        const TComRectangle &tuCompRect = rTu.getRect(compID);
+        if (tuCompRect.width != tuCompRect.height)
+        {
+          const UInt partIdxesPerSubTU = rTu.GetAbsPartIdxNumParts(compID) >> 1;
+
+          for (UInt subTU = 0; subTU < 2; subTU++)
+            bestsubTUCBF[compID][subTU] = pcCU->getCbf ((uiAbsPartIdx + (subTU * partIdxesPerSubTU)), compID, subTUDepth);
+        }
+      }
+    }
+
+
+    TComTURecurse tuRecurseChild(rTu, false);
+    const UInt uiQPartNumSubdiv = tuRecurseChild.GetAbsPartIdxNumParts();
+
+    DEBUG_STRING_NEW(sSplitString[MAX_NUM_COMPONENT])
+
+    do
+    {
+      DEBUG_STRING_NEW(childString)
+      xEstimateResidualQT( pcResi, dSubdivCost, uiSubdivBits, uiSubdivDist, bCheckFull ? NULL : puiZeroDist,  tuRecurseChild DEBUG_STRING_PASS_INTO(childString));
+#ifdef DEBUG_STRING
+      // split the string by component and append to the relevant output (because decoder decodes in channel order, whereas this search searches by TU-order)
+      std::size_t lastPos=0;
+      const std::size_t endStrng=childString.find(debug_reorder_data_inter_token[MAX_NUM_COMPONENT], lastPos);
+      for(UInt ch = 0; ch < numValidComp; ch++)
+      {
+        if (lastPos!=std::string::npos && childString.find(debug_reorder_data_inter_token[ch], lastPos)==lastPos) lastPos+=strlen(debug_reorder_data_inter_token[ch]); // skip leading string
+        std::size_t pos=childString.find(debug_reorder_data_inter_token[ch+1], lastPos);
+        if (pos!=std::string::npos && pos>endStrng) lastPos=endStrng;
+        sSplitString[ch]+=childString.substr(lastPos, (pos==std::string::npos)? std::string::npos : (pos-lastPos) );
+        lastPos=pos;
+      }
+#endif
+    }
+    while ( tuRecurseChild.nextSection(rTu) ) ;
+
+    UInt uiCbfAny=0;
+    for(UInt ch = 0; ch < numValidComp; ch++)
+    {
+      UInt uiYUVCbf = 0;
+      for( UInt ui = 0; ui < 4; ++ui )
+      {
+        uiYUVCbf |= pcCU->getCbf( uiAbsPartIdx + ui * uiQPartNumSubdiv, ComponentID(ch),  uiTrMode + 1 );
+      }
+      UChar *pBase=pcCU->getCbf( ComponentID(ch) );
+      const UInt flags=uiYUVCbf << uiTrMode;
+      for( UInt ui = 0; ui < 4 * uiQPartNumSubdiv; ++ui )
+      {
+        pBase[uiAbsPartIdx + ui] |= flags;
+      }
+      uiCbfAny|=uiYUVCbf;
+    }
+
+    m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[ uiDepth ][ CI_QT_TRAFO_ROOT ] );
+    m_pcEntropyCoder->resetBits();
+
+    // when compID isn't a channel, code Cbfs:
+    xEncodeResidualQT( MAX_NUM_COMPONENT, rTu );
+    for(UInt ch = 0; ch < numValidComp; ch++)
+    {
+      xEncodeResidualQT( ComponentID(ch), rTu );
+    }
+
+    uiSubdivBits = m_pcEntropyCoder->getNumberOfWrittenBits();
+    dSubdivCost  = m_pcRdCost->calcRdCost( uiSubdivBits, uiSubdivDist );
+
+    if (!bCheckFull || (uiCbfAny && (dSubdivCost < dSingleCost)))
+    {
+      rdCost += dSubdivCost;
+      ruiBits += uiSubdivBits;
+      ruiDist += uiSubdivDist;
+#ifdef DEBUG_STRING
+      for(UInt ch = 0; ch < numValidComp; ch++)
+      {
+        DEBUG_STRING_APPEND(sDebug, debug_reorder_data_inter_token[ch])
+        DEBUG_STRING_APPEND(sDebug, sSplitString[ch])
+      }
+#endif
+    }
+    else
+    {
+      rdCost  += dSingleCost;
+      ruiBits += uiSingleBits;
+      ruiDist += uiSingleDist;
+
+      //restore state to unsplit
+
+      pcCU->setTrIdxSubParts( uiTrMode, uiAbsPartIdx, uiDepth );
+
+      for(UInt ch = 0; ch < numValidComp; ch++)
+      {
+        const ComponentID compID=ComponentID(ch);
+
+        DEBUG_STRING_APPEND(sDebug, debug_reorder_data_inter_token[ch])
+        if (rTu.ProcessComponentSection(compID))
+        {
+          DEBUG_STRING_APPEND(sDebug, sSingleStringComp[compID])
+
+          const Bool splitIntoSubTUs   = rTu.getRect(compID).width != rTu.getRect(compID).height;
+          const UInt numberOfSections  = splitIntoSubTUs ? 2 : 1;
+          const UInt partIdxesPerSubTU = rTu.GetAbsPartIdxNumParts(compID) >> (splitIntoSubTUs ? 1 : 0);
+
+          for (UInt subTUIndex = 0; subTUIndex < numberOfSections; subTUIndex++)
+          {
+            const UInt  uisubTUPartIdx = uiAbsPartIdx + (subTUIndex * partIdxesPerSubTU);
+
+            if (splitIntoSubTUs)
+            {
+              const UChar combinedCBF = (bestsubTUCBF[compID][subTUIndex] << subTUDepth) | (bestCBF[compID] << uiTrMode);
+              pcCU->setCbfPartRange(combinedCBF, compID, uisubTUPartIdx, partIdxesPerSubTU);
+            }
+            else
+            {
+              pcCU->setCbfPartRange((bestCBF[compID] << uiTrMode), compID, uisubTUPartIdx, partIdxesPerSubTU);
+            }
+
+            pcCU->setCrossComponentPredictionAlphaPartRange(bestCrossCPredictionAlpha[compID][subTUIndex], compID, uisubTUPartIdx, partIdxesPerSubTU);
+            pcCU->setTransformSkipPartRange(uiBestTransformMode[compID][subTUIndex], compID, uisubTUPartIdx, partIdxesPerSubTU);
+            pcCU->setExplicitRdpcmModePartRange(bestExplicitRdpcmModeUnSplit[compID][subTUIndex], compID, uisubTUPartIdx, partIdxesPerSubTU);
+          }
+        }
+      }
+
+      m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[ uiDepth ][ CI_QT_TRAFO_TEST ] );
+    }
+  }
+  else
+  {
+    rdCost  += dSingleCost;
+    ruiBits += uiSingleBits;
+    ruiDist += uiSingleDist;
+#ifdef DEBUG_STRING
+    for(UInt ch = 0; ch < numValidComp; ch++)
+    {
+      const ComponentID compID=ComponentID(ch);
+      DEBUG_STRING_APPEND(sDebug, debug_reorder_data_inter_token[compID])
+
+      if (rTu.ProcessComponentSection(compID))
+      {
+        DEBUG_STRING_APPEND(sDebug, sSingleStringComp[compID])
+      }
+    }
+#endif
+  }
+  DEBUG_STRING_APPEND(sDebug, debug_reorder_data_inter_token[MAX_NUM_COMPONENT])
+}
+
+
+
+Void TEncSearch::xEncodeResidualQT( const ComponentID compID, TComTU &rTu )
+{
+  TComDataCU* pcCU=rTu.getCU();
+  const UInt uiAbsPartIdx=rTu.GetAbsPartIdxTU();
+  const UInt uiCurrTrMode = rTu.GetTransformDepthRel();
+  assert( pcCU->getDepth( 0 ) == pcCU->getDepth( uiAbsPartIdx ) );
+  const UInt uiTrMode = pcCU->getTransformIdx( uiAbsPartIdx );
+
+  const Bool bSubdiv = uiCurrTrMode != uiTrMode;
+
+  const UInt uiLog2TrSize = rTu.GetLog2LumaTrSize();
+
+  if (compID==MAX_NUM_COMPONENT)  // we are not processing a channel, instead we always recurse and code the CBFs
+  {
+    if( uiLog2TrSize <= pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() && uiLog2TrSize > pcCU->getQuadtreeTULog2MinSizeInCU(uiAbsPartIdx) )
+    {
+      m_pcEntropyCoder->encodeTransformSubdivFlag( bSubdiv, 5 - uiLog2TrSize );
+    }
+
+    assert( !pcCU->isIntra(uiAbsPartIdx) );
+
+    const Bool bFirstCbfOfCU = uiCurrTrMode == 0;
+
+    for (UInt ch=COMPONENT_Cb; ch<pcCU->getPic()->getNumberValidComponents(); ch++)
+    {
+      const ComponentID compIdInner=ComponentID(ch);
+      if( bFirstCbfOfCU || rTu.ProcessingAllQuadrants(compIdInner) )
+      {
+        if( bFirstCbfOfCU || pcCU->getCbf( uiAbsPartIdx, compIdInner, uiCurrTrMode - 1 ) )
+        {
+          m_pcEntropyCoder->encodeQtCbf( rTu, compIdInner, !bSubdiv );
+        }
+      }
+      else
+      {
+        assert( pcCU->getCbf( uiAbsPartIdx, compIdInner, uiCurrTrMode ) == pcCU->getCbf( uiAbsPartIdx, compIdInner, uiCurrTrMode - 1 ) );
+      }
+    }
+
+    if (!bSubdiv)
+    {
+      m_pcEntropyCoder->encodeQtCbf( rTu, COMPONENT_Y, true );
+    }
+  }
+
+  if( !bSubdiv )
+  {
+    if (compID != MAX_NUM_COMPONENT) // we have already coded the CBFs, so now we code coefficients
+    {
+      if (rTu.ProcessComponentSection(compID))
+      {
+        if (isChroma(compID) && (pcCU->getCbf(uiAbsPartIdx, COMPONENT_Y, uiTrMode) != 0))
+        {
+          m_pcEntropyCoder->encodeCrossComponentPrediction(rTu, compID);
+        }
+
+        if (pcCU->getCbf(uiAbsPartIdx, compID, uiTrMode) != 0)
+        {
+          const UInt uiQTTempAccessLayer = pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() - uiLog2TrSize;
+          TCoeff *pcCoeffCurr = m_ppcQTTempCoeff[compID][uiQTTempAccessLayer] + rTu.getCoefficientOffset(compID);
+          m_pcEntropyCoder->encodeCoeffNxN( rTu, pcCoeffCurr, compID );
+        }
+      }
+    }
+  }
+  else
+  {
+    if( compID==MAX_NUM_COMPONENT || pcCU->getCbf( uiAbsPartIdx, compID, uiCurrTrMode ) )
+    {
+      TComTURecurse tuRecurseChild(rTu, false);
+      do
+      {
+        xEncodeResidualQT( compID, tuRecurseChild );
+      } while (tuRecurseChild.nextSection(rTu));
+    }
+  }
+}
+
+
+
+
+Void TEncSearch::xSetResidualQTData( TComYuv* pcResi, Bool bSpatial, TComTU &rTu )
+{
+  TComDataCU* pcCU=rTu.getCU();
+  const UInt uiCurrTrMode=rTu.GetTransformDepthRel();
+  const UInt uiAbsPartIdx=rTu.GetAbsPartIdxTU();
+  assert( pcCU->getDepth( 0 ) == pcCU->getDepth( uiAbsPartIdx ) );
+  const UInt uiTrMode = pcCU->getTransformIdx( uiAbsPartIdx );
+  TComSPS *sps=pcCU->getSlice()->getSPS();
+
+  if( uiCurrTrMode == uiTrMode )
+  {
+    const UInt uiLog2TrSize = rTu.GetLog2LumaTrSize();
+    const UInt uiQTTempAccessLayer = sps->getQuadtreeTULog2MaxSize() - uiLog2TrSize;
+
+    if( bSpatial )
+    {
+      // Data to be copied is in the spatial domain, i.e., inverse-transformed.
+
+      for(UInt i=0; i<pcResi->getNumberValidComponents(); i++)
+      {
+        const ComponentID compID=ComponentID(i);
+        if (rTu.ProcessComponentSection(compID))
+        {
+          const TComRectangle &rectCompTU(rTu.getRect(compID));
+          m_pcQTTempTComYuv[uiQTTempAccessLayer].copyPartToPartComponentMxN    ( compID, pcResi, rectCompTU );
+        }
+      }
+    }
+    else
+    {
+      for (UInt ch=0; ch < getNumberValidComponents(sps->getChromaFormatIdc()); ch++)
+      {
+        const ComponentID compID   = ComponentID(ch);
+        if (rTu.ProcessComponentSection(compID))
+        {
+          const TComRectangle &rectCompTU(rTu.getRect(compID));
+          const UInt numCoeffInBlock    = rectCompTU.width * rectCompTU.height;
+          const UInt offset             = rTu.getCoefficientOffset(compID);
+          TCoeff* dest                  = pcCU->getCoeff(compID)                        + offset;
+          const TCoeff* src             = m_ppcQTTempCoeff[compID][uiQTTempAccessLayer] + offset;
+          ::memcpy( dest, src, sizeof(TCoeff)*numCoeffInBlock );
+
+#if ADAPTIVE_QP_SELECTION
+          TCoeff* pcArlCoeffSrc            = m_ppcQTTempArlCoeff[compID][uiQTTempAccessLayer] + offset;
+          TCoeff* pcArlCoeffDst            = pcCU->getArlCoeff(compID)                        + offset;
+          ::memcpy( pcArlCoeffDst, pcArlCoeffSrc, sizeof( TCoeff ) * numCoeffInBlock );
+#endif
+        }
+      }
+    }
+  }
+  else
+  {
+
+    TComTURecurse tuRecurseChild(rTu, false);
+    do
+    {
+      xSetResidualQTData( pcResi, bSpatial, tuRecurseChild );
+    } while (tuRecurseChild.nextSection(rTu));
+  }
+}
+
+
+
+
+UInt TEncSearch::xModeBitsIntra( TComDataCU* pcCU, UInt uiMode, UInt uiPartOffset, UInt uiDepth, UInt uiInitTrDepth, const ChannelType chType )
+{
+  // Reload only contexts required for coding intra mode information
+  m_pcRDGoOnSbacCoder->loadIntraDirMode( m_pppcRDSbacCoder[uiDepth][CI_CURR_BEST], chType );
+
+  // Temporarily set the intra dir being tested, and only
+  // for absPartIdx, since encodeIntraDirModeLuma/Chroma only use
+  // the entry at absPartIdx.
+
+  UChar &rIntraDirVal=pcCU->getIntraDir( chType )[uiPartOffset];
+  UChar origVal=rIntraDirVal;
+  rIntraDirVal = uiMode;
+  //pcCU->setIntraDirSubParts ( chType, uiMode, uiPartOffset, uiDepth + uiInitTrDepth );
+
+  m_pcEntropyCoder->resetBits();
+  if (isLuma(chType))
+    m_pcEntropyCoder->encodeIntraDirModeLuma ( pcCU, uiPartOffset);
+  else
+    m_pcEntropyCoder->encodeIntraDirModeChroma ( pcCU, uiPartOffset);
+
+  rIntraDirVal = origVal; // restore
+
+  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
+ * \returns Void
+ */
+Void  TEncSearch::xAddSymbolBitsInter( TComDataCU* pcCU, UInt uiQp, UInt uiTrMode, UInt& ruiBits )
+{
+  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);
+
+    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 );
+
+    Bool codeDeltaQp = false;
+    Bool codeChromaQpAdj = false;
+    m_pcEntropyCoder->encodeCoeff   ( pcCU, 0, pcCU->getDepth(0), codeDeltaQp, codeChromaQpAdj );
+
+    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(COMPONENT_Y);
+  Int dstStride = m_filteredBlock[0][0].getStride(COMPONENT_Y);
+  Pel *intPtr;
+  Pel *dstPtr;
+  Int filterSize = NTAPS_LUMA;
+  Int halfFilterSize = (filterSize>>1);
+  Pel *srcPtr = pattern->getROIY() - halfFilterSize*srcStride - 1;
+
+  const ChromaFormat chFmt = m_filteredBlock[0][0].getChromaFormat();
+
+  m_if.filterHor(COMPONENT_Y, srcPtr, srcStride, m_filteredBlockTmp[0].getAddr(COMPONENT_Y), intStride, width+1, height+filterSize, 0, false, chFmt);
+  m_if.filterHor(COMPONENT_Y, srcPtr, srcStride, m_filteredBlockTmp[2].getAddr(COMPONENT_Y), intStride, width+1, height+filterSize, 2, false, chFmt);
+
+  intPtr = m_filteredBlockTmp[0].getAddr(COMPONENT_Y) + halfFilterSize * intStride + 1;
+  dstPtr = m_filteredBlock[0][0].getAddr(COMPONENT_Y);
+  m_if.filterVer(COMPONENT_Y, intPtr, intStride, dstPtr, dstStride, width+0, height+0, 0, false, true, chFmt);
+
+  intPtr = m_filteredBlockTmp[0].getAddr(COMPONENT_Y) + (halfFilterSize-1) * intStride + 1;
+  dstPtr = m_filteredBlock[2][0].getAddr(COMPONENT_Y);
+  m_if.filterVer(COMPONENT_Y, intPtr, intStride, dstPtr, dstStride, width+0, height+1, 2, false, true, chFmt);
+
+  intPtr = m_filteredBlockTmp[2].getAddr(COMPONENT_Y) + halfFilterSize * intStride;
+  dstPtr = m_filteredBlock[0][2].getAddr(COMPONENT_Y);
+  m_if.filterVer(COMPONENT_Y, intPtr, intStride, dstPtr, dstStride, width+1, height+0, 0, false, true, chFmt);
+
+  intPtr = m_filteredBlockTmp[2].getAddr(COMPONENT_Y) + (halfFilterSize-1) * intStride;
+  dstPtr = m_filteredBlock[2][2].getAddr(COMPONENT_Y);
+  m_if.filterVer(COMPONENT_Y, intPtr, intStride, dstPtr, dstStride, width+1, height+1, 2, false, true, chFmt);
+}
+
+
+
+
+
+/**
+ * \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(COMPONENT_Y);
+  Int dstStride = m_filteredBlock[0][0].getStride(COMPONENT_Y);
+  Pel *intPtr;
+  Pel *dstPtr;
+  Int filterSize = NTAPS_LUMA;
+
+  Int halfFilterSize = (filterSize>>1);
+
+  Int extHeight = (halfPelRef.getVer() == 0) ? height + filterSize : height + filterSize-1;
+
+  const ChromaFormat chFmt = m_filteredBlock[0][0].getChromaFormat();
+
+  // Horizontal filter 1/4
+  srcPtr = pattern->getROIY() - halfFilterSize * srcStride - 1;
+  intPtr = m_filteredBlockTmp[1].getAddr(COMPONENT_Y);
+  if (halfPelRef.getVer() > 0)
+  {
+    srcPtr += srcStride;
+  }
+  if (halfPelRef.getHor() >= 0)
+  {
+    srcPtr += 1;
+  }
+  m_if.filterHor(COMPONENT_Y, srcPtr, srcStride, intPtr, intStride, width, extHeight, 1, false, chFmt);
+
+  // Horizontal filter 3/4
+  srcPtr = pattern->getROIY() - halfFilterSize*srcStride - 1;
+  intPtr = m_filteredBlockTmp[3].getAddr(COMPONENT_Y);
+  if (halfPelRef.getVer() > 0)
+  {
+    srcPtr += srcStride;
+  }
+  if (halfPelRef.getHor() > 0)
+  {
+    srcPtr += 1;
+  }
+  m_if.filterHor(COMPONENT_Y, srcPtr, srcStride, intPtr, intStride, width, extHeight, 3, false, chFmt);
+
+  // Generate @ 1,1
+  intPtr = m_filteredBlockTmp[1].getAddr(COMPONENT_Y) + (halfFilterSize-1) * intStride;
+  dstPtr = m_filteredBlock[1][1].getAddr(COMPONENT_Y);
+  if (halfPelRef.getVer() == 0)
+  {
+    intPtr += intStride;
+  }
+  m_if.filterVer(COMPONENT_Y, intPtr, intStride, dstPtr, dstStride, width, height, 1, false, true, chFmt);
+
+  // Generate @ 3,1
+  intPtr = m_filteredBlockTmp[1].getAddr(COMPONENT_Y) + (halfFilterSize-1) * intStride;
+  dstPtr = m_filteredBlock[3][1].getAddr(COMPONENT_Y);
+  m_if.filterVer(COMPONENT_Y, intPtr, intStride, dstPtr, dstStride, width, height, 3, false, true, chFmt);
+
+  if (halfPelRef.getVer() != 0)
+  {
+    // Generate @ 2,1
+    intPtr = m_filteredBlockTmp[1].getAddr(COMPONENT_Y) + (halfFilterSize-1) * intStride;
+    dstPtr = m_filteredBlock[2][1].getAddr(COMPONENT_Y);
+    if (halfPelRef.getVer() == 0)
+    {
+      intPtr += intStride;
+    }
+    m_if.filterVer(COMPONENT_Y, intPtr, intStride, dstPtr, dstStride, width, height, 2, false, true, chFmt);
+
+    // Generate @ 2,3
+    intPtr = m_filteredBlockTmp[3].getAddr(COMPONENT_Y) + (halfFilterSize-1) * intStride;
+    dstPtr = m_filteredBlock[2][3].getAddr(COMPONENT_Y);
+    if (halfPelRef.getVer() == 0)
+    {
+      intPtr += intStride;
+    }
+    m_if.filterVer(COMPONENT_Y, intPtr, intStride, dstPtr, dstStride, width, height, 2, false, true, chFmt);
+  }
+  else
+  {
+    // Generate @ 0,1
+    intPtr = m_filteredBlockTmp[1].getAddr(COMPONENT_Y) + halfFilterSize * intStride;
+    dstPtr = m_filteredBlock[0][1].getAddr(COMPONENT_Y);
+    m_if.filterVer(COMPONENT_Y, intPtr, intStride, dstPtr, dstStride, width, height, 0, false, true, chFmt);
+
+    // Generate @ 0,3
+    intPtr = m_filteredBlockTmp[3].getAddr(COMPONENT_Y) + halfFilterSize * intStride;
+    dstPtr = m_filteredBlock[0][3].getAddr(COMPONENT_Y);
+    m_if.filterVer(COMPONENT_Y, intPtr, intStride, dstPtr, dstStride, width, height, 0, false, true, chFmt);
+  }
+
+  if (halfPelRef.getHor() != 0)
+  {
+    // Generate @ 1,2
+    intPtr = m_filteredBlockTmp[2].getAddr(COMPONENT_Y) + (halfFilterSize-1) * intStride;
+    dstPtr = m_filteredBlock[1][2].getAddr(COMPONENT_Y);
+    if (halfPelRef.getHor() > 0)
+    {
+      intPtr += 1;
+    }
+    if (halfPelRef.getVer() >= 0)
+    {
+      intPtr += intStride;
+    }
+    m_if.filterVer(COMPONENT_Y, intPtr, intStride, dstPtr, dstStride, width, height, 1, false, true, chFmt);
+
+    // Generate @ 3,2
+    intPtr = m_filteredBlockTmp[2].getAddr(COMPONENT_Y) + (halfFilterSize-1) * intStride;
+    dstPtr = m_filteredBlock[3][2].getAddr(COMPONENT_Y);
+    if (halfPelRef.getHor() > 0)
+    {
+      intPtr += 1;
+    }
+    if (halfPelRef.getVer() > 0)
+    {
+      intPtr += intStride;
+    }
+    m_if.filterVer(COMPONENT_Y, intPtr, intStride, dstPtr, dstStride, width, height, 3, false, true, chFmt);
+  }
+  else
+  {
+    // Generate @ 1,0
+    intPtr = m_filteredBlockTmp[0].getAddr(COMPONENT_Y) + (halfFilterSize-1) * intStride + 1;
+    dstPtr = m_filteredBlock[1][0].getAddr(COMPONENT_Y);
+    if (halfPelRef.getVer() >= 0)
+    {
+      intPtr += intStride;
+    }
+    m_if.filterVer(COMPONENT_Y, intPtr, intStride, dstPtr, dstStride, width, height, 1, false, true, chFmt);
+
+    // Generate @ 3,0
+    intPtr = m_filteredBlockTmp[0].getAddr(COMPONENT_Y) + (halfFilterSize-1) * intStride + 1;
+    dstPtr = m_filteredBlock[3][0].getAddr(COMPONENT_Y);
+    if (halfPelRef.getVer() > 0)
+    {
+      intPtr += intStride;
+    }
+    m_if.filterVer(COMPONENT_Y, intPtr, intStride, dstPtr, dstStride, width, height, 3, false, true, chFmt);
+  }
+
+  // Generate @ 1,3
+  intPtr = m_filteredBlockTmp[3].getAddr(COMPONENT_Y) + (halfFilterSize-1) * intStride;
+  dstPtr = m_filteredBlock[1][3].getAddr(COMPONENT_Y);
+  if (halfPelRef.getVer() == 0)
+  {
+    intPtr += intStride;
+  }
+  m_if.filterVer(COMPONENT_Y, intPtr, intStride, dstPtr, dstStride, width, height, 1, false, true, chFmt);
+
+  // Generate @ 3,3
+  intPtr = m_filteredBlockTmp[3].getAddr(COMPONENT_Y) + (halfFilterSize-1) * intStride;
+  dstPtr = m_filteredBlock[3][3].getAddr(COMPONENT_Y);
+  m_if.filterVer(COMPONENT_Y, intPtr, intStride, dstPtr, dstStride, width, height, 3, false, true, chFmt);
+}
+
+
+
+
+
+/** set wp tables
+ * \param TComDataCU* pcCU
+ * \param iRefIdx
+ * \param eRefPicListCur
+ * \returns Void
+ */
+Void  TEncSearch::setWpScalingDistParam( TComDataCU* pcCU, Int iRefIdx, RefPicList eRefPicListCur )
+{
+  if ( iRefIdx<0 )
+  {
+    m_cDistParam.bApplyWeight = false;
+    return;
+  }
+
+  TComSlice       *pcSlice  = pcCU->getSlice();
+  TComPPS         *pps      = pcCU->getSlice()->getPPS();
+  WPScalingParam  *wp0 , *wp1;
+
+  m_cDistParam.bApplyWeight = ( pcSlice->getSliceType()==P_SLICE && pps->getUseWP() ) || ( pcSlice->getSliceType()==B_SLICE && pps->getWPBiPred() ) ;
+
+  if ( !m_cDistParam.bApplyWeight ) return;
+
+  Int iRefIdx0 = ( eRefPicListCur == REF_PIC_LIST_0 ) ? iRefIdx : (-1);
+  Int iRefIdx1 = ( eRefPicListCur == REF_PIC_LIST_1 ) ? iRefIdx : (-1);
+
+  getWpScaling( pcCU, iRefIdx0, iRefIdx1, wp0 , wp1 );
+
+  if ( iRefIdx0 < 0 ) wp0 = NULL;
+  if ( iRefIdx1 < 0 ) wp1 = NULL;
+
+  m_cDistParam.wpCur  = NULL;
+
+  if ( eRefPicListCur == REF_PIC_LIST_0 )
+  {
+    m_cDistParam.wpCur = wp0;
+  }
+  else
+  {
+    m_cDistParam.wpCur = wp1;
+  }
+}
+
+#if SVC_EXTENSION
+#if REF_IDX_ME_ZEROMV
+Void TEncSearch::xPatternSearchFracDIFMv0( TComPattern* pcPatternKey,
+                                           Pel* piRefY,
+                                           Int iRefStride,
+                                           TComMv* pcMvInt,
+                                           TComMv& rcMvHalf,
+                                           TComMv& rcMvQter,
+                                           UInt& ruiCost     )                                           
+{
+  assert(pcMvInt->getHor() == 0 && pcMvInt->getVer() == 0);
+  Int         iOffset    = pcMvInt->getHor() + pcMvInt->getVer() * iRefStride;
+  m_pcRdCost->setDistParam( pcPatternKey, piRefY + iOffset, iRefStride, 1, m_cDistParam, m_pcEncCfg->getUseHADME() );
+  m_pcRdCost->setCostScale ( 2 );
+  setDistParamComp(COMPONENT_Y);
+  ruiCost = m_cDistParam.DistFunc( &m_cDistParam );  //SATD
+  ruiCost += m_pcRdCost->getCost( pcMvInt->getHor(), pcMvInt->getVer() );  //SATD rdCost
+  rcMvHalf.setZero();
+  rcMvQter.setZero();
+}
+#endif
+
+#if ENCODER_FAST_MODE
+Bool TEncSearch::predInterSearchILRUni( TComDataCU* pcCU, TComYuv* pcOrgYuv, TComYuv*& rpcPredYuv, TComYuv*& rpcResiYuv, TComYuv*& rpcRecoYuv, UInt refLayerId )
+{
+  rpcPredYuv->clear();
+  rpcRecoYuv->clear();
+
+  Int           iNumPredDir = pcCU->getSlice()->isInterP() ? 1 : 2;
+
+  TComMv        cMv[2];
+  TComMv        cMvPred[2][33];
+  TComMv        cMvTemp[2][33];
+  TComMv        TempMv;
+
+  Int           iRefIdx[2]={0,0};
+
+  Int           aaiMvpIdx[2][33];
+  Int           aaiMvpNum[2][33];
+
+  UInt          uiMbBits[3] = {1, 1, 0};
+  UInt          uiLastMode = 0;
+
+  UInt          uiCost[2]   = { MAX_UINT, MAX_UINT };     //uni, rdCost
+  UInt          uiCostTemp;
+  UInt          biPDistTemp = MAX_INT;
+  UInt          uiBitsTemp;
+
+  PartSize      ePartSize = pcCU->getPartitionSize( 0 );  //2Nx2N
+  Int           iPartIdx  = 0;                            //one PU in CU
+  UInt          uiPartAddr;
+  Int           iRoiWidth, iRoiHeight;
+  Bool          bILRSearched = false;
+
+  xGetBlkBits( ePartSize, pcCU->getSlice()->isInterP(), iPartIdx, uiLastMode, uiMbBits);
+  pcCU->getPartIndexAndSize( iPartIdx, uiPartAddr, iRoiWidth, iRoiHeight );
+
+  for( Int iRefList = 0; iRefList < iNumPredDir; iRefList++)  //list
+  {
+    if(bILRSearched)
+    {
+      continue;
+    }
+
+    RefPicList  eRefPicList = ( iRefList ? REF_PIC_LIST_1 : REF_PIC_LIST_0 );
+
+    Int  iRefIdxTemp = -1;
+    Bool foundILR    = false;
+
+    for( Int refIdx = 0; refIdx < pcCU->getSlice()->getNumRefIdx(eRefPicList); refIdx++ )
+    {
+      TComPic* refPic = pcCU->getSlice()->getRefPic(eRefPicList, refIdx);
+
+      // ILRP has to be for the sample prediction type
+      if( refPic->isILR(pcCU->getLayerId()) && refPic->getLayerId() == refLayerId && pcCU->getSlice()->getVPS()->isSamplePredictionType( pcCU->getLayerIdx(), pcCU->getSlice()->getVPS()->getLayerIdxInVps(refLayerId) ) )
+      {
+        iRefIdxTemp = refIdx;
+        foundILR    = true;
+        bILRSearched = true;
+        break;
+      }
+    }
+
+    if(!foundILR)  //no ILR in eRefPiclist
+    {
+      continue;  
+    }    
+
+    uiBitsTemp = uiMbBits[iRefList];
+    if ( pcCU->getSlice()->getNumRefIdx(eRefPicList) > 1 ) 
+    { 
+      uiBitsTemp += iRefIdxTemp+1; 
+      if ( iRefIdxTemp == pcCU->getSlice()->getNumRefIdx(eRefPicList)-1 ) uiBitsTemp--; 
+    }
+
+    xEstimateMvPredAMVP( pcCU, pcOrgYuv, iPartIdx, eRefPicList, iRefIdxTemp, cMvPred[iRefList][iRefIdxTemp], false, &biPDistTemp);
+    aaiMvpIdx[iRefList][iRefIdxTemp] = pcCU->getMVPIdx(eRefPicList, uiPartAddr);
+    aaiMvpNum[iRefList][iRefIdxTemp] = pcCU->getMVPNum(eRefPicList, uiPartAddr);
+
+    uiBitsTemp += m_auiMVPIdxCost[aaiMvpIdx[iRefList][iRefIdxTemp]][AMVP_MAX_NUM_CANDS];
+
+    xMotionEstimation ( pcCU, pcOrgYuv, iPartIdx, eRefPicList, &cMvPred[iRefList][iRefIdxTemp], iRefIdxTemp, cMvTemp[iRefList][iRefIdxTemp], uiBitsTemp, uiCostTemp );
+    xCheckBestMVP(pcCU, eRefPicList, cMvTemp[iRefList][iRefIdxTemp], cMvPred[iRefList][iRefIdxTemp], aaiMvpIdx[iRefList][iRefIdxTemp], uiBitsTemp, uiCostTemp);
+
+    if( uiCostTemp < uiCost[iRefList] )
+    {
+      uiCost[iRefList] = uiCostTemp;
+
+      cMv[iRefList]     = cMvTemp[iRefList][iRefIdxTemp];
+      iRefIdx[iRefList] = iRefIdxTemp;
+
+      pcCU->getCUMvField(eRefPicList)->setAllMv( cMv[iRefList], ePartSize, uiPartAddr, 0, iPartIdx );
+      pcCU->getCUMvField(eRefPicList)->setAllRefIdx( iRefIdx[iRefList], ePartSize, uiPartAddr, 0, iPartIdx );
+    }
+  }
+
+  if( uiCost[0] == MAX_UINT && uiCost[1] == MAX_UINT )  //no ILR in both list0 and list1
+  {
+    return false;
+  }
+
+  //  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    ( TComMv(),      ePartSize, uiPartAddr, 0, iPartIdx ); 
+  pcCU->getCUMvField(REF_PIC_LIST_1)->setAllMvd    ( TComMv(),      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));
+
+  if( uiCost[0] <= uiCost[1] )  //list0 ILR
+  {
+    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));
+  }
+  else if( uiCost[1] < uiCost[0] )  //list1 ILR
+  {
+    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));
+  }
+  else
+  {
+    assert(0);
+  }
+
+  pcCU->setMergeFlagSubParts( false, uiPartAddr, iPartIdx, pcCU->getDepth( uiPartAddr ) );
+
+  motionCompensation ( pcCU, rpcPredYuv, REF_PIC_LIST_X, iPartIdx );
+  setWpScalingDistParam( pcCU, -1, REF_PIC_LIST_X );
+
+  return true;
+}
+#endif
+#endif //SVC_EXTENSION
+
+//! \}
Index: /tags/SHM-9.0/source/Lib/TLibEncoder/TEncSearch.h
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibEncoder/TEncSearch.h	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibEncoder/TEncSearch.h	(revision 1088)
@@ -0,0 +1,504 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \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 "TLibCommon/TComRectangle.h"
+#include "TEncEntropy.h"
+#include "TEncSbac.h"
+#include "TEncCfg.h"
+
+
+//! \ingroup TLibEncoder
+//! \{
+
+class TEncCu;
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+static const UInt MAX_NUM_REF_LIST_ADAPT_SR=2;
+static const UInt MAX_IDX_ADAPT_SR=33;
+static const UInt NUM_MV_PREDICTORS=3;
+
+/// encoder search class
+class TEncSearch : public TComPrediction
+{
+private:
+  TCoeff**        m_ppcQTTempCoeff[MAX_NUM_COMPONENT /* 0->Y, 1->Cb, 2->Cr*/];
+  TCoeff*         m_pcQTTempCoeff[MAX_NUM_COMPONENT];
+#if ADAPTIVE_QP_SELECTION
+  TCoeff**        m_ppcQTTempArlCoeff[MAX_NUM_COMPONENT];
+  TCoeff*         m_pcQTTempArlCoeff[MAX_NUM_COMPONENT];
+#endif
+  UChar*          m_puhQTTempTrIdx;
+  UChar*          m_puhQTTempCbf[MAX_NUM_COMPONENT];
+
+  TComYuv*        m_pcQTTempTComYuv;
+  TComYuv         m_tmpYuvPred; // To be used in xGetInterPredictionError() to avoid constant memory allocation/deallocation
+
+  Char*           m_phQTTempCrossComponentPredictionAlpha[MAX_NUM_COMPONENT];
+  Pel*            m_pSharedPredTransformSkip[MAX_NUM_COMPONENT];
+  TCoeff*         m_pcQTTempTUCoeff[MAX_NUM_COMPONENT];
+  UChar*          m_puhQTTempTransformSkipFlag[MAX_NUM_COMPONENT];
+  TComYuv         m_pcQTTempTransformSkipTComYuv;
+#if ADAPTIVE_QP_SELECTION
+  TCoeff*         m_ppcQTTempTUArlCoeff[MAX_NUM_COMPONENT];
+#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[MAX_NUM_REF_LIST_ADAPT_SR][MAX_IDX_ADAPT_SR];
+  TComMv          m_cSrchRngLT;
+  TComMv          m_cSrchRngRB;
+  TComMv          m_acMvPredictors[NUM_MV_PREDICTORS]; // Left, Above, AboveRight. enum MVP_DIR first NUM_MV_PREDICTORS entries are suitable for accessing.
+
+  // RD computation
+  TEncSbac***     m_pppcRDSbacCoder;
+  TEncSbac*       m_pcRDGoOnSbacCoder;
+  DistParam       m_cDistParam;
+
+  // Misc.
+  Pel*            m_pTempPel;
+  const UInt*     m_puiDFilter;
+  Int             m_iMaxDeltaQP;
+
+  // 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
+
+  TComMv          m_integerMv2Nx2N[NUM_REF_PIC_LIST_01][MAX_NUM_REF];
+
+#if SVC_EXTENSION
+#if N0383_IL_CONSTRAINED_TILE_SETS_SEI
+  Bool            m_disableILP;
+#endif
+#endif //SVC_EXTENSION
+
+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
+  Distortion  xPatternRefinement( TComPattern* pcPatternKey,
+                                  TComMv baseRefMv,
+                                  Int iFrac, TComMv& rcMvFrac, Bool bAllowUseOfHadamard
+                                 );
+
+  typedef struct
+  {
+    Pel*        piRefY;
+    Int         iYStride;
+    Int         iBestX;
+    Int         iBestY;
+    UInt        uiBestRound;
+    UInt        uiBestDistance;
+    Distortion  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, Distortion& ruiSAD, Bool Hadamard );
+
+public:
+  Void  preestChromaPredMode    ( TComDataCU* pcCU,
+                                  TComYuv*    pcOrgYuv,
+                                  TComYuv*    pcPredYuv );
+
+  Void  estIntraPredQT          ( TComDataCU* pcCU,
+                                  TComYuv*    pcOrgYuv,
+                                  TComYuv*    pcPredYuv,
+                                  TComYuv*    pcResiYuv,
+                                  TComYuv*    pcRecoYuv,
+                                  Pel         resiLuma[NUMBER_OF_STORED_RESIDUAL_TYPES][MAX_CU_SIZE * MAX_CU_SIZE],
+                                  Distortion& ruiDistC,
+                                  Bool        bLumaOnly
+                                  DEBUG_STRING_FN_DECLARE(sDebug));
+
+  Void  estIntraPredChromaQT    ( TComDataCU* pcCU,
+                                  TComYuv*    pcOrgYuv,
+                                  TComYuv*    pcPredYuv,
+                                  TComYuv*    pcResiYuv,
+                                  TComYuv*    pcRecoYuv,
+                                  Pel         resiLuma[NUMBER_OF_STORED_RESIDUAL_TYPES][MAX_CU_SIZE * MAX_CU_SIZE],
+                                  Distortion  uiPreCalcDistC
+                                  DEBUG_STRING_FN_DECLARE(sDebug));
+
+  /// encoder estimation - inter prediction (non-skip)
+#if SVC_EXTENSION
+  Bool predInterSearch          ( TComDataCU* pcCU,
+#else
+  Void predInterSearch          ( TComDataCU* pcCU,
+#endif
+                                  TComYuv*    pcOrgYuv,
+                                  TComYuv*    pcPredYuv,
+                                  TComYuv*    pcResiYuv,
+                                  TComYuv*    pcRecoYuv
+                                  DEBUG_STRING_FN_DECLARE(sDebug),
+                                  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*    pcYuvResi,
+                                  TComYuv*    pcYuvResiBest,
+                                  TComYuv*    pcYuvRec,
+                                  Bool        bSkipRes
+                                  DEBUG_STRING_FN_DECLARE(sDebug) );
+
+  /// set ME search range
+  Void setAdaptiveSearchRange   ( Int iDir, Int iRefIdx, Int iSearchRange) { assert(iDir < MAX_NUM_REF_LIST_ADAPT_SR && iRefIdx<Int(MAX_IDX_ADAPT_SR)); 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, const ComponentID compID );
+  Void IPCMSearch (TComDataCU* pcCU, TComYuv* pcOrgYuv, TComYuv* rpcPredYuv, TComYuv* rpcResiYuv, TComYuv* rpcRecoYuv );
+
+#if SVC_EXTENSION
+#if ENCODER_FAST_MODE
+  Bool predInterSearchILRUni    ( TComDataCU* pcCU, TComYuv*    pcOrgYuv, TComYuv*&   rpcPredYuv, TComYuv*&   rpcResiYuv, TComYuv*&   rpcRecoYuv, UInt        refLayerId );
+#endif  
+#if N0383_IL_CONSTRAINED_TILE_SETS_SEI
+  Void setDisableILP(Bool a) {m_disableILP = a;}
+#endif
+#endif //SVC_EXTENSION
+
+protected:
+
+  // -------------------------------------------------------------------------------------------------------------------
+  // Intra search
+  // -------------------------------------------------------------------------------------------------------------------
+
+  Void  xEncSubdivCbfQT           ( TComTU      &rTu,
+                                    Bool         bLuma,
+                                    Bool         bChroma );
+
+  Void  xEncCoeffQT               ( TComTU &rTu,
+                                    ComponentID  component,
+                                    Bool         bRealCoeff );
+  Void  xEncIntraHeader           ( TComDataCU*  pcCU,
+                                    UInt         uiTrDepth,
+                                    UInt         uiAbsPartIdx,
+                                    Bool         bLuma,
+                                    Bool         bChroma );
+  UInt  xGetIntraBitsQT           ( TComTU &rTu,
+                                    Bool         bLuma,
+                                    Bool         bChroma,
+                                    Bool         bRealCoeff );
+
+  UInt  xGetIntraBitsQTChroma    ( TComTU &rTu,
+                                   ComponentID compID,
+                                   Bool          bRealCoeff );
+
+  Void  xIntraCodingTUBlock       (       TComYuv*      pcOrgYuv,
+                                          TComYuv*      pcPredYuv,
+                                          TComYuv*      pcResiYuv,
+                                          Pel           resiLuma[NUMBER_OF_STORED_RESIDUAL_TYPES][MAX_CU_SIZE * MAX_CU_SIZE],
+                                    const Bool          checkCrossCPrediction,
+                                          Distortion&   ruiDist,
+                                    const ComponentID   compID,
+                                          TComTU        &rTu
+                                    DEBUG_STRING_FN_DECLARE(sTest)
+                                         ,Int           default0Save1Load2 = 0
+                                   );
+
+  Void  xRecurIntraCodingQT       ( Bool        bLumaOnly,
+                                    TComYuv*    pcOrgYuv,
+                                    TComYuv*    pcPredYuv,
+                                    TComYuv*    pcResiYuv,
+                                    Pel         resiLuma[NUMBER_OF_STORED_RESIDUAL_TYPES][MAX_CU_SIZE * MAX_CU_SIZE],
+                                    Distortion& ruiDistY,
+                                    Distortion& ruiDistC,
+#if HHI_RQT_INTRA_SPEEDUP
+                                   Bool         bCheckFirst,
+#endif
+                                   Double&      dRDCost,
+                                   TComTU      &rTu
+                                   DEBUG_STRING_FN_DECLARE(sDebug));
+
+  Void  xSetIntraResultQT         ( Bool         bLumaOnly,
+                                    TComYuv*     pcRecoYuv,
+                                    TComTU &rTu);
+
+  Void xStoreCrossComponentPredictionResult  (       Pel    *pResiLuma,
+                                               const Pel    *pBestLuma,
+                                                     TComTU &rTu,
+                                               const Int     xOffset,
+                                               const Int     yOffset,
+                                               const Int     strideResi,
+                                               const Int     strideBest );
+
+  Char xCalcCrossComponentPredictionAlpha    (       TComTU &rTu,
+                                               const ComponentID compID,
+                                               const Pel*        piResiL,
+                                               const Pel*        piResiC,
+                                               const Int         width,
+                                               const Int         height,
+                                               const Int         strideL,
+                                               const Int         strideC );
+
+  Void  xRecurIntraChromaCodingQT ( TComYuv*    pcOrgYuv,
+                                    TComYuv*    pcPredYuv,
+                                    TComYuv*    pcResiYuv,
+                                    Pel         resiLuma[NUMBER_OF_STORED_RESIDUAL_TYPES][MAX_CU_SIZE * MAX_CU_SIZE],
+                                    Distortion& ruiDist,
+                                    TComTU      &rTu
+                                    DEBUG_STRING_FN_DECLARE(sDebug));
+
+  Void  xSetIntraResultChromaQT   ( TComYuv*    pcRecoYuv, TComTU &rTu);
+
+  Void  xStoreIntraResultQT       ( const ComponentID first, const ComponentID lastIncl, TComTU &rTu);
+  Void  xLoadIntraResultQT        ( const ComponentID first, const ComponentID lastIncl, TComTU &rTu);
+
+
+  // -------------------------------------------------------------------------------------------------------------------
+  // Inter search (AMP)
+  // -------------------------------------------------------------------------------------------------------------------
+
+  Void xEstimateMvPredAMVP        ( TComDataCU* pcCU,
+                                    TComYuv*    pcOrgYuv,
+                                    UInt        uiPartIdx,
+                                    RefPicList  eRefPicList,
+                                    Int         iRefIdx,
+                                    TComMv&     rcMvPred,
+                                    Bool        bFilled = false
+                                  , Distortion* puiDistBiP = NULL
+                                     );
+
+  Void xCheckBestMVP              ( TComDataCU* pcCU,
+                                    RefPicList  eRefPicList,
+                                    TComMv      cMv,
+                                    TComMv&     rcMvPred,
+                                    Int&        riMVPIdx,
+                                    UInt&       ruiBits,
+                                    Distortion& ruiCost );
+
+  Distortion 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
+                                   );
+
+
+  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,
+                                    Distortion&  ruiCost,
+                                    TComMvField* cMvFieldNeighbours,
+                                    UChar*       uhInterDirNeighbours,
+                                    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,
+                                    Distortion&  ruiCost,
+                                    Bool         bBi = false  );
+
+  Void xTZSearch                  ( TComDataCU*  pcCU,
+                                    TComPattern* pcPatternKey,
+                                    Pel*         piRefY,
+                                    Int          iRefStride,
+                                    TComMv*      pcMvSrchRngLT,
+                                    TComMv*      pcMvSrchRngRB,
+                                    TComMv&      rcMv,
+                                    Distortion&  ruiSAD,
+                                    const TComMv *pIntegerMv2Nx2NPred
+                                    );
+
+  Void xTZSearchSelective         ( TComDataCU*  pcCU,
+                                    TComPattern* pcPatternKey,
+                                    Pel*         piRefY,
+                                    Int          iRefStride,
+                                    TComMv*      pcMvSrchRngLT,
+                                    TComMv*      pcMvSrchRngRB,
+                                    TComMv&      rcMv,
+                                    Distortion&  ruiSAD,
+                                    const TComMv *pIntegerMv2Nx2NPred
+                                    );
+
+  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,
+                                    Distortion&  ruiSAD,
+                                    const TComMv* pIntegerMv2Nx2NPred
+                                  );
+
+  Void xPatternSearch             ( TComPattern* pcPatternKey,
+                                    Pel*         piRefY,
+                                    Int          iRefStride,
+                                    TComMv*      pcMvSrchRngLT,
+                                    TComMv*      pcMvSrchRngRB,
+                                    TComMv&      rcMv,
+                                    Distortion&  ruiSAD );
+
+  Void xPatternSearchFracDIF      (
+                                    Bool         bIsLosslessCoded,
+                                    TComPattern* pcPatternKey,
+                                    Pel*         piRefY,
+                                    Int          iRefStride,
+                                    TComMv*      pcMvInt,
+                                    TComMv&      rcMvHalf,
+                                    TComMv&      rcMvQter,
+                                    Distortion&  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( const ComponentID compID, TComTU &rTu );
+  Void xEstimateResidualQT( TComYuv* pcResi, Double &rdCost, UInt &ruiBits, Distortion &ruiDist, Distortion *puiZeroDist, TComTU &rTu DEBUG_STRING_FN_DECLARE(sDebug) );
+  Void xSetResidualQTData( TComYuv* pcResi, Bool bSpatial, TComTU &rTu  );
+
+  UInt  xModeBitsIntra ( TComDataCU* pcCU, UInt uiMode, UInt uiPartOffset, UInt uiDepth, UInt uiInitTrDepth, const ChannelType compID );
+  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);
+
+  Void  setWpScalingDistParam( TComDataCU* pcCU, Int iRefIdx, RefPicList eRefPicListCur );
+  inline  Void  setDistParamComp( ComponentID compIdx )  { m_cDistParam.compIdx = compIdx; }
+
+#if SVC_EXTENSION && REF_IDX_ME_ZEROMV
+  Void xPatternSearchFracDIFMv0  ( TComPattern*  pcPatternKey,
+                                   Pel*          piRefY,
+                                   Int           iRefStride,
+                                   TComMv*       pcMvInt,
+                                   TComMv&       rcMvHalf,
+                                   TComMv&       rcMvQter,
+                                   UInt&         ruiCost     );
+#endif //SVC_EXTENSION  
+
+};// END CLASS DEFINITION TEncSearch
+
+//! \}
+
+#endif // __TENCSEARCH__
Index: /tags/SHM-9.0/source/Lib/TLibEncoder/TEncSlice.cpp
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibEncoder/TEncSlice.cpp	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibEncoder/TEncSlice.cpp	(revision 1088)
@@ -0,0 +1,1359 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TEncSlice.cpp
+    \brief    slice encoder class
+*/
+
+#include "TEncTop.h"
+#include "TEncSlice.h"
+#include <math.h>
+
+//! \ingroup TLibEncoder
+//! \{
+
+// ====================================================================================================================
+// Constructor / destructor / create / destroy
+// ====================================================================================================================
+
+TEncSlice::TEncSlice()
+{
+  m_apcPicYuvPred = NULL;
+  m_apcPicYuvResi = NULL;
+
+  m_pdRdPicLambda = NULL;
+  m_pdRdPicQp     = NULL;
+  m_piRdPicQp     = NULL;
+}
+
+TEncSlice::~TEncSlice()
+{
+}
+
+Void TEncSlice::create( Int iWidth, Int iHeight, ChromaFormat chromaFormat, UInt iMaxCUWidth, UInt iMaxCUHeight, UChar uhTotalDepth )
+{
+  // create prediction picture
+  if ( m_apcPicYuvPred == NULL )
+  {
+    m_apcPicYuvPred  = new TComPicYuv;
+    m_apcPicYuvPred->create( iWidth, iHeight, chromaFormat, iMaxCUWidth, iMaxCUHeight, uhTotalDepth );
+  }
+
+  // create residual picture
+  if( m_apcPicYuvResi == NULL )
+  {
+    m_apcPicYuvResi  = new TComPicYuv;
+    m_apcPicYuvResi->create( iWidth, iHeight, chromaFormat, 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; }
+}
+
+Void TEncSlice::init( TEncTop* pcEncTop )
+{
+  m_pcCfg             = pcEncTop;
+  m_pcListPic         = pcEncTop->getListPic();
+#if SVC_EXTENSION
+  m_ppcTEncTop        = pcEncTop->getLayerEnc();
+#endif
+  m_pcGOPEncoder      = pcEncTop->getGOPEncoder();
+  m_pcCuEncoder       = pcEncTop->getCuEncoder();
+  m_pcPredSearch      = pcEncTop->getPredSearch();
+
+  m_pcEntropyCoder    = pcEncTop->getEntropyCoder();
+  m_pcSbacCoder       = pcEncTop->getSbacCoder();
+  m_pcBinCABAC        = pcEncTop->getBinCABAC();
+  m_pcTrQuant         = pcEncTop->getTrQuant();
+
+  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();
+}
+
+
+
+Void
+#if JCTVC_M0259_LAMBDAREFINEMENT
+TEncSlice::setUpLambda(TComSlice* slice, Double dLambda, Int iQP, Int depth)
+#else
+TEncSlice::setUpLambda(TComSlice* slice, const Double dLambda, Int iQP)
+#endif
+{
+#if JCTVC_M0259_LAMBDAREFINEMENT
+  Int layerIdx = slice->getLayerIdx();
+
+  if( slice->getLayerId() > 0 && m_ppcTEncTop[layerIdx]->getNumActiveRefLayers() && depth >= 3 && m_pcCfg->getGOPSize() == ( 1 << depth ) )
+  {
+    UInt prevLayerIdx = 0; 
+    if( m_ppcTEncTop[layerIdx]->getNumActiveRefLayers() > 0 )
+    {
+      prevLayerIdx = m_ppcTEncTop[layerIdx]->getPredLayerIdx( m_ppcTEncTop[layerIdx]->getNumActiveRefLayers() - 1);
+    }
+
+    Double gamma = xCalEnhLambdaFactor( m_ppcTEncTop[prevLayerIdx]->getQP() - m_ppcTEncTop[layerIdx]->getQP() ,
+                                        1.0 * m_ppcTEncTop[layerIdx]->getSourceWidth() * m_ppcTEncTop[layerIdx]->getSourceHeight()
+                                        / m_ppcTEncTop[prevLayerIdx]->getSourceWidth() / m_ppcTEncTop[prevLayerIdx]->getSourceHeight() );
+
+    dLambda *= gamma;
+  }
+#endif
+
+  // store lambda
+  m_pcRdCost ->setLambda( dLambda );
+
+  // 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 dLambdas[MAX_NUM_COMPONENT] = { dLambda };
+  for(UInt compIdx=1; compIdx<MAX_NUM_COMPONENT; compIdx++)
+  {
+    const ComponentID compID=ComponentID(compIdx);
+    Int chromaQPOffset = slice->getPPS()->getQpOffset(compID) + slice->getSliceChromaQpDelta(compID);
+    Int qpc=(iQP + chromaQPOffset < 0) ? iQP : getScaledChromaQP(iQP + chromaQPOffset, m_pcCfg->getChromaFormatIdc());
+    Double tmpWeight = pow( 2.0, (iQP-qpc)/3.0 );  // takes into account of the chroma qp mapping and chroma qp Offset
+
+#if JCTVC_M0259_LAMBDAREFINEMENT
+    if( slice->getLayerId() > 0 && m_ppcTEncTop[slice->getLayerIdx()]->getNumActiveRefLayers() && m_pcCfg->getGOPSize() >= 8 && slice->isIntra() == false && depth == 0 )
+    {
+      dLambdas[0] = dLambda * 1.1;
+      m_pcRdCost->setLambda( dLambdas[0] );
+
+      m_pcRdCost->setDistortionWeight(compID, tmpWeight * 1.15);
+      dLambdas[compIdx] = dLambdas[0] / tmpWeight / 1.15;
+    }
+    else
+    {
+#endif
+    m_pcRdCost->setDistortionWeight(compID, tmpWeight);
+    dLambdas[compIdx]=dLambda/tmpWeight;
+#if JCTVC_M0259_LAMBDAREFINEMENT
+    }
+#endif
+  }
+
+#if RDOQ_CHROMA_LAMBDA
+// for RDOQ
+  m_pcTrQuant->setLambdas( dLambdas );
+#else
+  m_pcTrQuant->setLambda( dLambda );
+#endif
+
+// For SAO
+  slice   ->setLambdas( dLambdas );
+}
+
+
+
+/**
+ - 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 SVC_EXTENSION
+//\param vps          VPS associated with the slice
+Void TEncSlice::initEncSlice( TComPic* pcPic, Int pocLast, Int pocCurr, Int iNumPicRcvd, Int iGOPid, TComSlice*& rpcSlice, TComSPS* pSPS, TComPPS *pPPS, TComVPS *vps, Bool isField )
+#else
+Void TEncSlice::initEncSlice( TComPic* pcPic, Int pocLast, Int pocCurr, Int iNumPicRcvd, Int iGOPid, TComSlice*& rpcSlice, TComSPS* pSPS, TComPPS *pPPS, Bool isField )
+#endif
+{
+  Double dQP;
+  Double dLambda;
+
+  rpcSlice = pcPic->getSlice(0);
+  rpcSlice->setSPS( pSPS );
+  rpcSlice->setPPS( pPPS );
+  rpcSlice->setSliceBits(0);
+  rpcSlice->setPic( pcPic );
+#if SVC_EXTENSION
+  UInt layerId = pcPic->getLayerId();
+  rpcSlice->setVPS( vps );
+  rpcSlice->initSlice( layerId );
+#else
+  rpcSlice->initSlice();
+#endif
+  rpcSlice->setPicOutputFlag( true );
+  rpcSlice->setPOC( pocCurr );
+
+  // depth computation based on GOP size
+  Int depth;
+  {
+    Int poc = rpcSlice->getPOC();
+    if(isField)
+    {
+      poc = (poc/2) % (m_pcCfg->getGOPSize()/2);
+    }
+    else
+    {
+      poc = poc % 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++;
+      }
+    }
+
+#if HARMONIZE_GOP_FIRST_FIELD_COUPLE
+    if(poc != 0)
+    {
+#endif
+      if (isField && ((rpcSlice->getPOC() % 2) == 1))
+      {
+        depth ++;
+      }
+#if HARMONIZE_GOP_FIRST_FIELD_COUPLE
+    }
+#endif
+  }
+
+  // slice type
+  SliceType eSliceType;
+
+  eSliceType=B_SLICE;
+#if EFFICIENT_FIELD_IRAP
+  if(!(isField && pocLast == 1))
+  {
+#endif // EFFICIENT_FIELD_IRAP
+#if ALLOW_RECOVERY_POINT_AS_RAP
+    if(m_pcCfg->getDecodingRefreshType() == 3)
+    {
+      eSliceType = (pocLast == 0 || pocCurr % m_pcCfg->getIntraPeriod() == 0             || m_pcGOPEncoder->getGOPSize() == 0) ? I_SLICE : eSliceType;
+    }
+    else
+    {
+#endif
+      eSliceType = (pocLast == 0 || (pocCurr - (isField ? 1 : 0)) % m_pcCfg->getIntraPeriod() == 0 || m_pcGOPEncoder->getGOPSize() == 0) ? I_SLICE : eSliceType;
+#if ALLOW_RECOVERY_POINT_AS_RAP
+    }
+#endif
+#if EFFICIENT_FIELD_IRAP
+  }
+#endif
+
+  rpcSlice->setSliceType    ( eSliceType );
+
+  // ------------------------------------------------------------------------------------------------------------------
+  // Non-referenced frame marking
+  // ------------------------------------------------------------------------------------------------------------------
+
+  if(pocLast == 0)
+  {
+    rpcSlice->setTemporalLayerNonReferenceFlag(false);
+  }
+  else
+  {
+    rpcSlice->setTemporalLayerNonReferenceFlag(!m_pcCfg->getGOPEntry(iGOPid).m_refPic);
+  }
+  rpcSlice->setReferenced(true);
+
+  // ------------------------------------------------------------------------------------------------------------------
+  // QP setting
+  // ------------------------------------------------------------------------------------------------------------------
+
+  dQP = m_pcCfg->getQP();
+  if(eSliceType!=I_SLICE)
+  {
+#if REPN_FORMAT_IN_VPS
+    if (!(( m_pcCfg->getMaxDeltaQP() == 0 ) && (dQP == -rpcSlice->getQpBDOffsetY() ) && (rpcSlice->getPPS()->getTransquantBypassEnableFlag())))
+#else
+    if (!(( m_pcCfg->getMaxDeltaQP() == 0 ) && (dQP == -rpcSlice->getSPS()->getQpBDOffset(CHANNEL_TYPE_LUMA) ) && (rpcSlice->getPPS()->getTransquantBypassEnableFlag())))
+#endif
+    {
+      dQP += m_pcCfg->getGOPEntry(iGOPid).m_QPOffset;
+    }
+  }
+
+  // modify QP
+  Int* pdQPs = m_pcCfg->getdQPs();
+  if ( pdQPs )
+  {
+    dQP += pdQPs[ rpcSlice->getPOC() ];
+  }
+
+  if (m_pcCfg->getCostMode()==COST_LOSSLESS_CODING)
+  {
+    dQP=LOSSLESS_AND_MIXED_LOSSLESS_RD_COST_TEST_QP;
+    m_pcCfg->setDeltaQpRD(0);
+  }
+
+  // ------------------------------------------------------------------------------------------------------------------
+  // Lambda computation
+  // ------------------------------------------------------------------------------------------------------------------
+
+  Int iQP;
+  Double dOrigQP = dQP;
+
+  // pre-compute lambda and QP values for all possible QP candidates
+  for ( Int iDQpIdx = 0; iDQpIdx < 2 * m_pcCfg->getDeltaQpRD() + 1; iDQpIdx++ )
+  {
+    // compute QP value
+    dQP = dOrigQP + ((iDQpIdx+1)>>1)*(iDQpIdx%2 ? -1 : 1);
+
+    // compute lambda value
+    Int    NumberBFrames = ( m_pcCfg->getGOPSize() - 1 );
+    Int    SHIFT_QP = 12;
+
+    Double dLambda_scale = 1.0 - Clip3( 0.0, 0.5, 0.05*(Double)(isField ? NumberBFrames/2 : NumberBFrames) );
+
+#if FULL_NBIT
+    Int    bitdepth_luma_qp_scale = 6 * (g_bitDepth[CHANNEL_TYPE_LUMA] - 8);
+#else
+    Int    bitdepth_luma_qp_scale = 0;
+#endif
+    Double qp_temp = (Double) dQP + bitdepth_luma_qp_scale - SHIFT_QP;
+#if FULL_NBIT
+    Double qp_temp_orig = (Double) dQP - SHIFT_QP;
+#endif
+    // Case #1: I or P-slices (key-frame)
+    Double dQPFactor = m_pcCfg->getGOPEntry(iGOPid).m_QPFactor;
+    if ( eSliceType==I_SLICE )
+    {
+      dQPFactor=0.57*dLambda_scale;
+    }
+    dLambda = dQPFactor*pow( 2.0, qp_temp/3.0 );
+
+    if ( depth>0 )
+    {
+#if FULL_NBIT
+        dLambda *= Clip3( 2.00, 4.00, (qp_temp_orig / 6.0) ); // (j == B_SLICE && p_cur_frm->layer != 0 )
+#else
+        dLambda *= Clip3( 2.00, 4.00, (qp_temp / 6.0) ); // (j == B_SLICE && p_cur_frm->layer != 0 )
+#endif
+    }
+
+    // if hadamard is used in ME process
+    if ( !m_pcCfg->getUseHADME() && rpcSlice->getSliceType( ) != I_SLICE )
+    {
+      dLambda *= 0.95;
+    }
+
+#if REPN_FORMAT_IN_VPS
+    iQP = max( -rpcSlice->getQpBDOffsetY(), min( MAX_QP, (Int) floor( dQP + 0.5 ) ) );
+#else
+    iQP = max( -pSPS->getQpBDOffset(CHANNEL_TYPE_LUMA), min( MAX_QP, (Int) floor( dQP + 0.5 ) ) );
+#endif
+
+    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 )
+  {
+    dLambda *= m_pcCfg->getLambdaModifier( m_pcCfg->getGOPEntry(iGOPid).m_temporalId );
+  }
+
+#if JCTVC_M0259_LAMBDAREFINEMENT
+  setUpLambda(rpcSlice, dLambda, iQP, depth);
+#else
+  setUpLambda(rpcSlice, dLambda, iQP);
+#endif
+#if HB_LAMBDA_FOR_LDC
+  // restore original slice type
+
+#if EFFICIENT_FIELD_IRAP
+  if(!(isField && pocLast == 1))
+  {
+#endif // EFFICIENT_FIELD_IRAP
+#if ALLOW_RECOVERY_POINT_AS_RAP
+    if(m_pcCfg->getDecodingRefreshType() == 3)
+    {
+      eSliceType = (pocLast == 0 || (pocCurr)                     % m_pcCfg->getIntraPeriod() == 0 || m_pcGOPEncoder->getGOPSize() == 0) ? I_SLICE : eSliceType;
+    }
+    else
+    {
+#endif
+      eSliceType = (pocLast == 0 || (pocCurr - (isField ? 1 : 0)) % m_pcCfg->getIntraPeriod() == 0 || m_pcGOPEncoder->getGOPSize() == 0) ? I_SLICE : eSliceType;
+#if ALLOW_RECOVERY_POINT_AS_RAP
+    }
+#endif
+#if EFFICIENT_FIELD_IRAP
+  }
+#endif // EFFICIENT_FIELD_IRAP
+
+#if SVC_EXTENSION
+  if( m_pcCfg->getLayerId() > 0 && m_pcCfg->getNumActiveRefLayers() > 0 )
+  {
+    eSliceType=B_SLICE;
+  }
+#endif
+  rpcSlice->setSliceType        ( eSliceType );
+#endif
+
+  if (m_pcCfg->getUseRecalculateQPAccordingToLambda())
+  {
+    dQP = xGetQPValueAccordingToLambda( dLambda );
+#if REPN_FORMAT_IN_VPS
+    iQP = max( -rpcSlice->getQpBDOffsetY(), min( MAX_QP, (Int) floor( dQP + 0.5 ) ) );
+#else
+    iQP = max( -pSPS->getQpBDOffset(CHANNEL_TYPE_LUMA), min( MAX_QP, (Int) floor( dQP + 0.5 ) ) );
+#endif
+  }
+
+  rpcSlice->setSliceQp           ( iQP );
+#if ADAPTIVE_QP_SELECTION
+  rpcSlice->setSliceQpBase       ( iQP );
+#endif
+  rpcSlice->setSliceQpDelta      ( 0 );
+  rpcSlice->setSliceChromaQpDelta( COMPONENT_Cb, 0 );
+  rpcSlice->setSliceChromaQpDelta( COMPONENT_Cr, 0 );
+  rpcSlice->setUseChromaQpAdj( pPPS->getChromaQpAdjTableSize() > 0 );
+  rpcSlice->setNumRefIdx(REF_PIC_LIST_0,m_pcCfg->getGOPEntry(iGOPid).m_numRefPicsActive);
+  rpcSlice->setNumRefIdx(REF_PIC_LIST_1,m_pcCfg->getGOPEntry(iGOPid).m_numRefPicsActive);
+
+  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)
+      {
+        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() );
+      }
+      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 );
+
+  pcPic->setTLayer( m_pcCfg->getGOPEntry(iGOPid).m_temporalId );
+  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() );
+  rpcSlice->setMaxNumMergeCand        ( m_pcCfg->getMaxNumMergeCand()        );
+#if HIGHER_LAYER_IRAP_SKIP_FLAG
+  if (m_pcCfg->getSkipPictureAtArcSwitch() && m_pcCfg->getAdaptiveResolutionChange() > 0 && rpcSlice->getLayerId() == 1 && rpcSlice->getPOC() == m_pcCfg->getAdaptiveResolutionChange())
+  {
+    rpcSlice->setMaxNumMergeCand        ( 1 );
+  }
+#endif
+  xStoreWPparam( pPPS->getUseWP(), pPPS->getWPBiPred() );
+
+#if SVC_EXTENSION
+  if( layerId > 0 )
+  {
+    if( rpcSlice->getNumILRRefIdx() > 0 )
+    {
+      rpcSlice->setActiveNumILRRefIdx( m_ppcTEncTop[rpcSlice->getVPS()->getLayerIdxInVps(layerId)]->getNumActiveRefLayers() );
+      for( Int i = 0; i < rpcSlice->getActiveNumILRRefIdx(); i++ )
+      {
+        rpcSlice->setInterLayerPredLayerIdc( m_ppcTEncTop[rpcSlice->getVPS()->getLayerIdxInVps(layerId)]->getPredLayerIdx(i), i );
+      }
+      rpcSlice->setInterLayerPredEnabledFlag(1);
+    }
+    rpcSlice->setMFMEnabledFlag(m_ppcTEncTop[rpcSlice->getVPS()->getLayerIdxInVps(layerId)]->getMFMEnabledFlag());
+  }
+
+#endif
+}
+
+Void TEncSlice::resetQP( TComPic* pic, Int sliceQP, Double lambda )
+{
+  TComSlice* slice = pic->getSlice(0);
+
+  // store lambda
+  slice->setSliceQp( sliceQP );
+#if ADAPTIVE_QP_SELECTION
+  slice->setSliceQpBase ( sliceQP );
+#endif
+  setUpLambda(slice, lambda, sliceQP);
+}
+
+// ====================================================================================================================
+// 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* pcPic )
+{
+  // if deltaQP RD is not used, simply return
+  if ( m_pcCfg->getDeltaQpRD() == 0 )
+  {
+    return;
+  }
+
+  if ( m_pcCfg->getUseRateCtrl() )
+  {
+    printf( "\nMultiple QP optimization is not allowed when rate control is enabled." );
+    assert(0);
+  }
+
+  TComSlice* pcSlice        = pcPic->getSlice(getSliceIdx());
+  Double     dPicRdCostBest = MAX_DOUBLE;
+  UInt       uiQpIdxBest = 0;
+
+  Double dFrameLambda;
+#if FULL_NBIT
+  Int    SHIFT_QP = 12 + 6 * (g_bitDepth[CHANNEL_TYPE_LUMA] - 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);
+
+  const UInt initialSliceQp=pcSlice->getSliceQp();
+  // 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
+    setUpLambda(pcSlice, m_pdRdPicLambda[uiQpIdx], m_piRdPicQp    [uiQpIdx]);
+
+    // try compress
+    compressSlice   ( pcPic );
+
+    Double dPicRdCost;
+    UInt64 uiPicDist        = m_uiPicDist;
+    // TODO: will this work if multiple slices are being used? There may not be any reconstruction data yet.
+    //       Will this also be ideal if a byte-restriction is placed on the slice?
+    //         - what if the last CTU was sometimes included, sometimes not, and that had all the distortion?
+    m_pcGOPEncoder->preLoopFilterPicAll( pcPic, uiPicDist );
+
+    // compute RD cost and choose the best
+    dPicRdCost = m_pcRdCost->calcRdCost64( m_uiPicTotalBits, uiPicDist, true, DF_SSE_FRAME);
+
+    if ( dPicRdCost < dPicRdCostBest )
+    {
+      uiQpIdxBest    = uiQpIdx;
+      dPicRdCostBest = dPicRdCost;
+    }
+  }
+
+  if (pcSlice->getDependentSliceSegmentFlag() && initialSliceQp!=m_piRdPicQp[uiQpIdxBest] )
+  {
+    // TODO: this won't work with dependent slices: they do not have their own QP.
+    fprintf(stderr,"ERROR - attempt to change QP for a dependent slice-segment, having already coded the slice\n");
+    assert(pcSlice->getDependentSliceSegmentFlag()==false || initialSliceQp==m_piRdPicQp[uiQpIdxBest]);
+  }
+  // set best values
+  pcSlice       ->setSliceQp             ( m_piRdPicQp    [uiQpIdxBest] );
+#if ADAPTIVE_QP_SELECTION
+  pcSlice       ->setSliceQpBase         ( m_piRdPicQp    [uiQpIdxBest] );
+#endif
+  setUpLambda(pcSlice, m_pdRdPicLambda[uiQpIdxBest], m_piRdPicQp    [uiQpIdxBest]);
+}
+
+Void TEncSlice::calCostSliceI(TComPic* pcPic)
+{
+  UInt    ctuRsAddr;
+  UInt    startCtuTsAddr;
+  UInt    boundingCtuTsAddr;
+  Int     iSumHad, shift = g_bitDepth[CHANNEL_TYPE_LUMA]-8, offset = (shift>0)?(1<<(shift-1)):0;;
+  Double  iSumHadSlice = 0;
+
+  pcPic->getSlice(getSliceIdx())->setSliceSegmentBits(0);
+  TComSlice* pcSlice            = pcPic->getSlice(getSliceIdx());
+  xDetermineStartAndBoundingCtuTsAddr ( startCtuTsAddr, boundingCtuTsAddr, pcPic, false );
+
+  UInt ctuTsAddr;
+  ctuRsAddr = pcPic->getPicSym()->getCtuTsToRsAddrMap( startCtuTsAddr);
+  for( ctuTsAddr = startCtuTsAddr; ctuTsAddr < boundingCtuTsAddr; ctuRsAddr = pcPic->getPicSym()->getCtuTsToRsAddrMap(++ctuTsAddr) )
+  {
+    // initialize CU encoder
+    TComDataCU* pCtu = pcPic->getCtu( ctuRsAddr );
+    pCtu->initCtu( pcPic, ctuRsAddr );
+
+#if REPN_FORMAT_IN_VPS
+    Int height  = min( pcSlice->getSPS()->getMaxCUHeight(),pcSlice->getPicHeightInLumaSamples() - ctuRsAddr / pcPic->getFrameWidthInCtus() * pcSlice->getSPS()->getMaxCUHeight() );
+    Int width   = min( pcSlice->getSPS()->getMaxCUWidth(),pcSlice->getPicWidthInLumaSamples() - ctuRsAddr % pcPic->getFrameWidthInCtus() * pcSlice->getSPS()->getMaxCUWidth() );
+#else
+    Int height  = min( pcSlice->getSPS()->getMaxCUHeight(),pcSlice->getSPS()->getPicHeightInLumaSamples() - ctuRsAddr / pcPic->getFrameWidthInCtus() * pcSlice->getSPS()->getMaxCUHeight() );
+    Int width   = min( pcSlice->getSPS()->getMaxCUWidth(),pcSlice->getSPS()->getPicWidthInLumaSamples() - ctuRsAddr % pcPic->getFrameWidthInCtus() * pcSlice->getSPS()->getMaxCUWidth() );
+#endif
+
+    iSumHad = m_pcCuEncoder->updateCtuDataISlice(pCtu, width, height);
+
+    (m_pcRateCtrl->getRCPic()->getLCU(ctuRsAddr)).m_costIntra=(iSumHad+offset)>>shift;
+    iSumHadSlice += (m_pcRateCtrl->getRCPic()->getLCU(ctuRsAddr)).m_costIntra;
+
+  }
+  m_pcRateCtrl->getRCPic()->setTotalIntraCost(iSumHadSlice);
+}
+
+/** \param rpcPic   picture class
+ */
+Void TEncSlice::compressSlice( TComPic* pcPic )
+{
+  UInt   startCtuTsAddr;
+  UInt   boundingCtuTsAddr;
+  TComSlice* pcSlice            = pcPic->getSlice(getSliceIdx());
+  pcSlice->setSliceSegmentBits(0);
+  xDetermineStartAndBoundingCtuTsAddr ( startCtuTsAddr, boundingCtuTsAddr, pcPic, false );
+
+  // initialize cost values - these are used by precompressSlice (they should be parameters).
+  m_uiPicTotalBits  = 0;
+  m_dPicRdCost      = 0; // NOTE: This is a write-only variable!
+  m_uiPicDist       = 0;
+
+  m_pcEntropyCoder->setEntropyCoder   ( m_pppcRDSbacCoder[0][CI_CURR_BEST], pcSlice );
+  m_pcEntropyCoder->resetEntropy      ();
+
+  TEncBinCABAC* pRDSbacCoder = (TEncBinCABAC *) m_pppcRDSbacCoder[0][CI_CURR_BEST]->getEncBinIf();
+  pRDSbacCoder->setBinCountingEnableFlag( false );
+  pRDSbacCoder->setBinsCoded( 0 );
+
+  TComBitCounter  tempBitCounter;
+  const UInt      frameWidthInCtus = pcPic->getPicSym()->getFrameWidthInCtus();
+
+  //------------------------------------------------------------------------------
+  //  Weighted Prediction parameters estimation.
+  //------------------------------------------------------------------------------
+  // calculate AC/DC values for current picture
+  if( pcSlice->getPPS()->getUseWP() || pcSlice->getPPS()->getWPBiPred() )
+  {
+    xCalcACDCParamSlice(pcSlice);
+  }
+#if O0194_WEIGHTED_PREDICTION_CGS
+  else if( m_ppcTEncTop[pcSlice->getLayerIdx()]->getInterLayerWeightedPredFlag() )
+  {
+    // Calculate for the base layer to be used in EL as Inter layer reference
+    estimateILWpParam( pcSlice );    
+  }
+#endif
+
+  const 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()==FIXED_NUMBER_OF_BYTES || pcSlice->getSliceSegmentMode()==FIXED_NUMBER_OF_BYTES )
+    {
+      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() && !(pcSlice->getDependentSliceSegmentFlag()))
+  {
+    // TODO: this won't work with dependent slices: they do not have their own QP. Check fix to mask clause execution with && !(pcSlice->getDependentSliceSegmentFlag())
+    m_pcTrQuant->clearSliceARLCnt();
+    if(pcSlice->getSliceType()!=I_SLICE)
+    {
+      Int qpBase = pcSlice->getSliceQpBase();
+      pcSlice->setSliceQp(qpBase + m_pcTrQuant->getQpDelta(qpBase));
+    }
+  }
+#endif
+
+
+
+  // Adjust initial state if this is the start of a dependent slice.
+  {
+    const UInt      ctuRsAddr               = pcPic->getPicSym()->getCtuTsToRsAddrMap( startCtuTsAddr);
+    const UInt      currentTileIdx          = pcPic->getPicSym()->getTileIdxMap(ctuRsAddr);
+    const TComTile *pCurrentTile            = pcPic->getPicSym()->getTComTile(currentTileIdx);
+    const UInt      firstCtuRsAddrOfTile    = pCurrentTile->getFirstCtuRsAddr();
+    if( pcSlice->getDependentSliceSegmentFlag() && ctuRsAddr != firstCtuRsAddrOfTile )
+    {
+      // This will only occur if dependent slice-segments (m_entropyCodingSyncContextState=true) are being used.
+      if( pCurrentTile->getTileWidthInCtus() >= 2 || !m_pcCfg->getWaveFrontsynchro() )
+      {
+        m_pppcRDSbacCoder[0][CI_CURR_BEST]->loadContexts( &m_lastSliceSegmentEndContextState );
+      }
+    }
+  }
+
+  // for every CTU in the slice segment (may terminate sooner if there is a byte limit on the slice-segment)
+
+  for( UInt ctuTsAddr = startCtuTsAddr; ctuTsAddr < boundingCtuTsAddr; ++ctuTsAddr )
+  {
+    const UInt ctuRsAddr = pcPic->getPicSym()->getCtuTsToRsAddrMap(ctuTsAddr);
+    // initialize CTU encoder
+    TComDataCU* pCtu = pcPic->getCtu( ctuRsAddr );
+    pCtu->initCtu( pcPic, ctuRsAddr );
+
+    // update CABAC state
+    const UInt firstCtuRsAddrOfTile = pcPic->getPicSym()->getTComTile(pcPic->getPicSym()->getTileIdxMap(ctuRsAddr))->getFirstCtuRsAddr();
+    const UInt tileXPosInCtus = firstCtuRsAddrOfTile % frameWidthInCtus;
+    const UInt ctuXPosInCtus  = ctuRsAddr % frameWidthInCtus;
+    
+    if (ctuRsAddr == firstCtuRsAddrOfTile)
+    {
+      m_pppcRDSbacCoder[0][CI_CURR_BEST]->resetEntropy();
+    }
+    else if ( ctuXPosInCtus == tileXPosInCtus && m_pcCfg->getWaveFrontsynchro())
+    {
+      // reset and then update contexts to the state at the end of the top-right CTU (if within current slice and tile).
+      m_pppcRDSbacCoder[0][CI_CURR_BEST]->resetEntropy();
+      // Sync if the Top-Right is available.
+      TComDataCU *pCtuUp = pCtu->getCtuAbove();
+      if ( pCtuUp && ((ctuRsAddr%frameWidthInCtus+1) < frameWidthInCtus)  )
+      {
+        TComDataCU *pCtuTR = pcPic->getCtu( ctuRsAddr - frameWidthInCtus + 1 );
+        if ( pCtu->CUIsFromSameSliceAndTile(pCtuTR) )
+        {
+          // Top-Right is available, we use it.
+          m_pppcRDSbacCoder[0][CI_CURR_BEST]->loadContexts( &m_entropyCodingSyncContextState );
+        }
+      }
+    }
+
+    // set go-on entropy coder (used for all trial encodings - the cu encoder and encoder search also have a copy of the same pointer)
+    m_pcEntropyCoder->setEntropyCoder ( m_pcRDGoOnSbacCoder, pcSlice );
+    m_pcEntropyCoder->setBitstream( &tempBitCounter );
+    tempBitCounter.resetBits();
+    m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[0][CI_CURR_BEST] ); // this copy is not strictly necessary here, but indicates that the GoOnSbacCoder
+                                                                     // is reset to a known state before every decision process.
+
+    ((TEncBinCABAC*)m_pcRDGoOnSbacCoder->getEncBinIf())->setBinCountingEnableFlag(true);
+
+    Double oldLambda = m_pcRdCost->getLambda();
+    if ( m_pcCfg->getUseRateCtrl() )
+    {
+      Int estQP        = pcSlice->getSliceQp();
+      Double estLambda = -1.0;
+      Double bpp       = -1.0;
+
+      if ( ( pcPic->getSlice( 0 )->getSliceType() == I_SLICE && m_pcCfg->getForceIntraQP() ) || !m_pcCfg->getLCULevelRC() )
+      {
+        estQP = pcSlice->getSliceQp();
+      }
+      else
+      {
+        bpp = m_pcRateCtrl->getRCPic()->getLCUTargetBpp(pcSlice->getSliceType());
+        if ( pcPic->getSlice( 0 )->getSliceType() == I_SLICE)
+        {
+          estLambda = m_pcRateCtrl->getRCPic()->getLCUEstLambdaAndQP(bpp, pcSlice->getSliceQp(), &estQP);
+        }
+        else
+        {
+          estLambda = m_pcRateCtrl->getRCPic()->getLCUEstLambda( bpp );
+          estQP     = m_pcRateCtrl->getRCPic()->getLCUEstQP    ( estLambda, pcSlice->getSliceQp() );
+        }
+
+#if REPN_FORMAT_IN_VPS
+        estQP     = Clip3( -pcSlice->getQpBDOffsetY(), MAX_QP, estQP );
+#else
+        estQP     = Clip3( -pcSlice->getSPS()->getQpBDOffset(CHANNEL_TYPE_LUMA), MAX_QP, estQP );
+#endif
+
+        m_pcRdCost->setLambda(estLambda);
+
+#if RDOQ_CHROMA_LAMBDA
+        // set lambda for RDOQ
+        const Double chromaLambda = estLambda / m_pcRdCost->getChromaWeight();
+        const Double lambdaArray[MAX_NUM_COMPONENT] = { estLambda, chromaLambda, chromaLambda };
+        m_pcTrQuant->setLambdas( lambdaArray );
+#else
+        m_pcTrQuant->setLambda( estLambda );
+#endif
+      }
+
+      m_pcRateCtrl->setRCQP( estQP );
+#if ADAPTIVE_QP_SELECTION
+      pCtu->getSlice()->setSliceQpBase( estQP );
+#endif
+    }
+
+    // run CTU trial encoder
+    m_pcCuEncoder->compressCtu( pCtu );
+
+
+    // All CTU decisions have now been made. Restore entropy coder to an initial stage, ready to make a true encode,
+    // which will result in the state of the contexts being correct. It will also count up the number of bits coded,
+    // which is used if there is a limit of the number of bytes per slice-segment.
+
+    m_pcEntropyCoder->setEntropyCoder ( m_pppcRDSbacCoder[0][CI_CURR_BEST], pcSlice );
+    m_pcEntropyCoder->setBitstream( &tempBitCounter );
+    pRDSbacCoder->setBinCountingEnableFlag( true );
+    m_pppcRDSbacCoder[0][CI_CURR_BEST]->resetBits();
+    pRDSbacCoder->setBinsCoded( 0 );
+
+    // encode CTU and calculate the true bit counters.
+    m_pcCuEncoder->encodeCtu( pCtu );
+
+
+    pRDSbacCoder->setBinCountingEnableFlag( false );
+
+    const Int numberOfWrittenBits = m_pcEntropyCoder->getNumberOfWrittenBits();
+
+    // Calculate if this CTU puts us over slice bit size.
+    // cannot terminate if current slice/slice-segment would be 0 Ctu in size,
+    const UInt validEndOfSliceCtuTsAddr = ctuTsAddr + (ctuTsAddr == startCtuTsAddr ? 1 : 0);
+    // Set slice end parameter
+    if(pcSlice->getSliceMode()==FIXED_NUMBER_OF_BYTES && pcSlice->getSliceBits()+numberOfWrittenBits > (pcSlice->getSliceArgument()<<3))
+    {
+      pcSlice->setSliceSegmentCurEndCtuTsAddr(validEndOfSliceCtuTsAddr);
+      pcSlice->setSliceCurEndCtuTsAddr(validEndOfSliceCtuTsAddr);
+      boundingCtuTsAddr=validEndOfSliceCtuTsAddr;
+    }
+    else if(pcSlice->getSliceSegmentMode()==FIXED_NUMBER_OF_BYTES && pcSlice->getSliceSegmentBits()+numberOfWrittenBits > (pcSlice->getSliceSegmentArgument()<<3))
+    {
+      pcSlice->setSliceSegmentCurEndCtuTsAddr(validEndOfSliceCtuTsAddr);
+      boundingCtuTsAddr=validEndOfSliceCtuTsAddr;
+    }
+
+    if (boundingCtuTsAddr <= ctuTsAddr)
+      break;
+
+    pcSlice->setSliceBits( (UInt)(pcSlice->getSliceBits() + numberOfWrittenBits) );
+    pcSlice->setSliceSegmentBits(pcSlice->getSliceSegmentBits()+numberOfWrittenBits);
+
+    // Store probabilities of second CTU in line into buffer - used only if wavefront-parallel-processing is enabled.
+    if ( ctuXPosInCtus == tileXPosInCtus+1 && m_pcCfg->getWaveFrontsynchro())
+    {
+      m_entropyCodingSyncContextState.loadContexts(m_pppcRDSbacCoder[0][CI_CURR_BEST]);
+    }
+
+
+    if ( m_pcCfg->getUseRateCtrl() )
+    {
+      Int actualQP        = g_RCInvalidQPValue;
+      Double actualLambda = m_pcRdCost->getLambda();
+      Int actualBits      = pCtu->getTotalBits();
+      Int numberOfEffectivePixels    = 0;
+      for ( Int idx = 0; idx < pcPic->getNumPartitionsInCtu(); idx++ )
+      {
+        if ( pCtu->getPredictionMode( idx ) != NUMBER_OF_PREDICTION_MODES && ( !pCtu->isSkipped( idx ) ) )
+        {
+          numberOfEffectivePixels = numberOfEffectivePixels + 16;
+          break;
+        }
+      }
+
+      if ( numberOfEffectivePixels == 0 )
+      {
+        actualQP = g_RCInvalidQPValue;
+      }
+      else
+      {
+        actualQP = pCtu->getQP( 0 );
+      }
+      m_pcRdCost->setLambda(oldLambda);
+      m_pcRateCtrl->getRCPic()->updateAfterCTU( m_pcRateCtrl->getRCPic()->getLCUCoded(), actualBits, actualQP, actualLambda,
+                                                pCtu->getSlice()->getSliceType() == I_SLICE ? 0 : m_pcCfg->getLCULevelRC() );
+    }
+
+    m_uiPicTotalBits += pCtu->getTotalBits();
+    m_dPicRdCost     += pCtu->getTotalCost();
+    m_uiPicDist      += pCtu->getTotalDistortion();
+  }
+
+  // store context state at the end of this slice-segment, in case the next slice is a dependent slice and continues using the CABAC contexts.
+  if( pcSlice->getPPS()->getDependentSliceSegmentsEnabledFlag() )
+  {
+    m_lastSliceSegmentEndContextState.loadContexts( m_pppcRDSbacCoder[0][CI_CURR_BEST] );//ctx end of dep.slice
+  }
+  xRestoreWPparam( pcSlice );
+
+  // stop use of temporary bit counter object.
+  m_pppcRDSbacCoder[0][CI_CURR_BEST]->setBitstream(NULL);
+  m_pcRDGoOnSbacCoder->setBitstream(NULL); // stop use of tempBitCounter.
+}
+
+/**
+ \param  rpcPic        picture class
+ \retval rpcBitstream  bitstream class
+ */
+Void TEncSlice::encodeSlice   ( TComPic* pcPic, TComOutputBitstream* pcSubstreams, UInt &numBinsCoded )
+{
+  TComSlice* pcSlice                 = pcPic->getSlice(getSliceIdx());
+
+  const UInt startCtuTsAddr          = pcSlice->getSliceSegmentCurStartCtuTsAddr();
+  const UInt boundingCtuTsAddr       = pcSlice->getSliceSegmentCurEndCtuTsAddr();
+
+  const UInt frameWidthInCtus        = pcPic->getPicSym()->getFrameWidthInCtus();
+  const Bool depSliceSegmentsEnabled = pcSlice->getPPS()->getDependentSliceSegmentsEnabledFlag();
+  const Bool wavefrontsEnabled       = pcSlice->getPPS()->getEntropyCodingSyncEnabledFlag();
+
+  // initialise entropy coder for the slice
+  m_pcSbacCoder->init( (TEncBinIf*)m_pcBinCABAC );
+  m_pcEntropyCoder->setEntropyCoder ( m_pcSbacCoder, pcSlice );
+  m_pcEntropyCoder->resetEntropy      ();
+
+  numBinsCoded = 0;
+  m_pcBinCABAC->setBinCountingEnableFlag( true );
+  m_pcBinCABAC->setBinsCoded(0);
+
+#if ENC_DEC_TRACE
+  g_bJustDoIt = g_bEncDecTraceEnable;
+#endif
+  DTRACE_CABAC_VL( g_nSymbolCounter++ );
+  DTRACE_CABAC_T( "\tPOC: " );
+  DTRACE_CABAC_V( pcPic->getPOC() );
+  DTRACE_CABAC_T( "\n" );
+#if ENC_DEC_TRACE
+  g_bJustDoIt = g_bEncDecTraceDisable;
+#endif
+
+
+  if (depSliceSegmentsEnabled)
+  {
+    // modify initial contexts with previous slice segment if this is a dependent slice.
+    const UInt ctuRsAddr        = pcPic->getPicSym()->getCtuTsToRsAddrMap( startCtuTsAddr );
+    const UInt currentTileIdx=pcPic->getPicSym()->getTileIdxMap(ctuRsAddr);
+    const TComTile *pCurrentTile=pcPic->getPicSym()->getTComTile(currentTileIdx);
+    const UInt firstCtuRsAddrOfTile = pCurrentTile->getFirstCtuRsAddr();
+
+    if( pcSlice->getDependentSliceSegmentFlag() && ctuRsAddr != firstCtuRsAddrOfTile )
+    {
+      if( pCurrentTile->getTileWidthInCtus() >= 2 || !wavefrontsEnabled )
+      {
+        m_pcSbacCoder->loadContexts(&m_lastSliceSegmentEndContextState);
+      }
+    }
+  }
+
+  // for every CTU in the slice segment...
+
+  for( UInt ctuTsAddr = startCtuTsAddr; ctuTsAddr < boundingCtuTsAddr; ++ctuTsAddr )
+  {
+    const UInt ctuRsAddr = pcPic->getPicSym()->getCtuTsToRsAddrMap(ctuTsAddr);
+    const TComTile &currentTile = *(pcPic->getPicSym()->getTComTile(pcPic->getPicSym()->getTileIdxMap(ctuRsAddr)));
+    const UInt firstCtuRsAddrOfTile = currentTile.getFirstCtuRsAddr();
+    const UInt tileXPosInCtus       = firstCtuRsAddrOfTile % frameWidthInCtus;
+    const UInt tileYPosInCtus       = firstCtuRsAddrOfTile / frameWidthInCtus;
+    const UInt ctuXPosInCtus        = ctuRsAddr % frameWidthInCtus;
+    const UInt ctuYPosInCtus        = ctuRsAddr / frameWidthInCtus;
+    const UInt uiSubStrm=pcPic->getSubstreamForCtuAddr(ctuRsAddr, true, pcSlice);
+    TComDataCU* pCtu = pcPic->getCtu( ctuRsAddr );
+
+    m_pcEntropyCoder->setBitstream( &pcSubstreams[uiSubStrm] );
+
+    // set up CABAC contexts' state for this CTU
+    if (ctuRsAddr == firstCtuRsAddrOfTile)
+    {
+      if (ctuTsAddr != startCtuTsAddr) // if it is the first CTU, then the entropy coder has already been reset
+      {
+        m_pcEntropyCoder->resetEntropy();
+      }
+    }
+    else if (ctuXPosInCtus == tileXPosInCtus && wavefrontsEnabled)
+    {
+      // Synchronize cabac probabilities with upper-right CTU if it's available and at the start of a line.
+      if (ctuTsAddr != startCtuTsAddr) // if it is the first CTU, then the entropy coder has already been reset
+      {
+        m_pcEntropyCoder->resetEntropy();
+      }
+      TComDataCU *pCtuUp = pCtu->getCtuAbove();
+      if ( pCtuUp && ((ctuRsAddr%frameWidthInCtus+1) < frameWidthInCtus)  )
+      {
+        TComDataCU *pCtuTR = pcPic->getCtu( ctuRsAddr - frameWidthInCtus + 1 );
+        if ( pCtu->CUIsFromSameSliceAndTile(pCtuTR) )
+        {
+          // Top-right is available, so use it.
+          m_pcSbacCoder->loadContexts( &m_entropyCodingSyncContextState );
+        }
+      }
+    }
+
+
+    if ( pcSlice->getSPS()->getUseSAO() )
+    {
+      Bool bIsSAOSliceEnabled = false;
+      Bool sliceEnabled[MAX_NUM_COMPONENT];
+      for(Int comp=0; comp < MAX_NUM_COMPONENT; comp++)
+      {
+        ComponentID compId=ComponentID(comp);
+        sliceEnabled[compId] = pcSlice->getSaoEnabledFlag(toChannelType(compId)) && (comp < pcPic->getNumberValidComponents());
+        if (sliceEnabled[compId]) bIsSAOSliceEnabled=true;
+      }
+      if (bIsSAOSliceEnabled)
+      {
+        SAOBlkParam& saoblkParam = (pcPic->getPicSym()->getSAOBlkParam())[ctuRsAddr];
+
+        Bool leftMergeAvail = false;
+        Bool aboveMergeAvail= false;
+        //merge left condition
+        Int rx = (ctuRsAddr % frameWidthInCtus);
+        if(rx > 0)
+        {
+          leftMergeAvail = pcPic->getSAOMergeAvailability(ctuRsAddr, ctuRsAddr-1);
+        }
+
+        //merge up condition
+        Int ry = (ctuRsAddr / frameWidthInCtus);
+        if(ry > 0)
+        {
+          aboveMergeAvail = pcPic->getSAOMergeAvailability(ctuRsAddr, ctuRsAddr-frameWidthInCtus);
+        }
+
+#if SVC_EXTENSION
+        m_pcEntropyCoder->encodeSAOBlkParam(saoblkParam, m_ppcTEncTop[pcSlice->getLayerIdx()]->getSAO()->getSaoMaxOffsetQVal(), sliceEnabled, leftMergeAvail, aboveMergeAvail);
+#else
+        m_pcEntropyCoder->encodeSAOBlkParam(saoblkParam, sliceEnabled, leftMergeAvail, aboveMergeAvail);
+#endif
+      }
+    }
+
+#if ENC_DEC_TRACE
+    g_bJustDoIt = g_bEncDecTraceEnable;
+#endif
+      m_pcCuEncoder->encodeCtu( pCtu );
+#if ENC_DEC_TRACE
+    g_bJustDoIt = g_bEncDecTraceDisable;
+#endif
+
+    //Store probabilities of second CTU in line into buffer
+    if ( ctuXPosInCtus == tileXPosInCtus+1 && wavefrontsEnabled)
+    {
+      m_entropyCodingSyncContextState.loadContexts( m_pcSbacCoder );
+    }
+
+    // terminate the sub-stream, if required (end of slice-segment, end of tile, end of wavefront-CTU-row):
+    if (ctuTsAddr+1 == boundingCtuTsAddr ||
+         (  ctuXPosInCtus + 1 == tileXPosInCtus + currentTile.getTileWidthInCtus() &&
+          ( ctuYPosInCtus + 1 == tileYPosInCtus + currentTile.getTileHeightInCtus() || wavefrontsEnabled)
+         )
+       )
+    {
+      m_pcEntropyCoder->encodeTerminatingBit(1);
+      m_pcEntropyCoder->encodeSliceFinish();
+      // Byte-alignment in slice_data() when new tile
+      pcSubstreams[uiSubStrm].writeByteAlignment();
+
+      // write sub-stream size
+      if (ctuTsAddr+1 != boundingCtuTsAddr)
+      {
+        pcSlice->addSubstreamSize( (pcSubstreams[uiSubStrm].getNumberOfWrittenBits() >> 3) + pcSubstreams[uiSubStrm].countStartCodeEmulations() );
+      }
+    }
+  } // CTU-loop
+
+  if( depSliceSegmentsEnabled )
+  {
+    m_lastSliceSegmentEndContextState.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();
+    }
+  }
+  numBinsCoded = m_pcBinCABAC->getBinsCoded();
+}
+
+Void TEncSlice::calculateBoundingCtuTsAddrForSlice(UInt &startCtuTSAddrSlice, UInt &boundingCtuTSAddrSlice, Bool &haveReachedTileBoundary,
+                                                   TComPic* pcPic, const Bool encodingSlice, const Int sliceMode, const Int sliceArgument, const UInt sliceCurEndCtuTSAddr)
+{
+  TComSlice* pcSlice = pcPic->getSlice(getSliceIdx());
+  const UInt numberOfCtusInFrame = pcPic->getNumberOfCtusInFrame();
+  boundingCtuTSAddrSlice=0;
+  haveReachedTileBoundary=false;
+
+  switch (sliceMode)
+  {
+    case FIXED_NUMBER_OF_CTU:
+      {
+        UInt ctuAddrIncrement    = sliceArgument;
+        boundingCtuTSAddrSlice  = ((startCtuTSAddrSlice + ctuAddrIncrement) < numberOfCtusInFrame) ? (startCtuTSAddrSlice + ctuAddrIncrement) : numberOfCtusInFrame;
+      }
+      break;
+    case FIXED_NUMBER_OF_BYTES:
+      if (encodingSlice)
+        boundingCtuTSAddrSlice  = sliceCurEndCtuTSAddr;
+      else
+        boundingCtuTSAddrSlice  = numberOfCtusInFrame;
+      break;
+    case FIXED_NUMBER_OF_TILES:
+      {
+        const UInt tileIdx        = pcPic->getPicSym()->getTileIdxMap( pcPic->getPicSym()->getCtuTsToRsAddrMap(startCtuTSAddrSlice) );
+        const UInt tileTotalCount = (pcPic->getPicSym()->getNumTileColumnsMinus1()+1) * (pcPic->getPicSym()->getNumTileRowsMinus1()+1);
+        UInt ctuAddrIncrement   = 0;
+
+        for(UInt tileIdxIncrement = 0; tileIdxIncrement < sliceArgument; tileIdxIncrement++)
+        {
+          if((tileIdx + tileIdxIncrement) < tileTotalCount)
+          {
+            UInt tileWidthInCtus   = pcPic->getPicSym()->getTComTile(tileIdx + tileIdxIncrement)->getTileWidthInCtus();
+            UInt tileHeightInCtus  = pcPic->getPicSym()->getTComTile(tileIdx + tileIdxIncrement)->getTileHeightInCtus();
+            ctuAddrIncrement    += (tileWidthInCtus * tileHeightInCtus);
+          }
+        }
+
+        boundingCtuTSAddrSlice  = ((startCtuTSAddrSlice + ctuAddrIncrement) < numberOfCtusInFrame) ? (startCtuTSAddrSlice + ctuAddrIncrement) : numberOfCtusInFrame;
+      }
+      break;
+    default:
+      boundingCtuTSAddrSlice    = numberOfCtusInFrame;
+      break;
+  }
+
+  // Adjust for tiles and wavefronts.
+  if ((sliceMode == FIXED_NUMBER_OF_CTU || sliceMode == FIXED_NUMBER_OF_BYTES) &&
+      (m_pcCfg->getNumRowsMinus1() > 0 || m_pcCfg->getNumColumnsMinus1() > 0))
+  {
+    const UInt ctuRSAddr                  = pcPic->getPicSym()->getCtuTsToRsAddrMap(startCtuTSAddrSlice);
+    const UInt startTileIdx               = pcPic->getPicSym()->getTileIdxMap(ctuRSAddr);
+    const Bool wavefrontsAreEnabled       = m_pcCfg->getWaveFrontsynchro();
+
+    const TComTile *pStartingTile         = pcPic->getPicSym()->getTComTile(startTileIdx);
+    const UInt tileStartTsAddr            = pcPic->getPicSym()->getCtuRsToTsAddrMap(pStartingTile->getFirstCtuRsAddr());
+    const UInt tileStartWidth             = pStartingTile->getTileWidthInCtus();
+    const UInt tileStartHeight            = pStartingTile->getTileHeightInCtus();
+    const UInt tileLastTsAddr_excl        = tileStartTsAddr + tileStartWidth*tileStartHeight;
+    const UInt tileBoundingCtuTsAddrSlice = tileLastTsAddr_excl;
+
+    const UInt ctuColumnOfStartingTile    = ((startCtuTSAddrSlice-tileStartTsAddr)%tileStartWidth);
+    if (wavefrontsAreEnabled && ctuColumnOfStartingTile!=0)
+    {
+      // WPP: if a slice does not start at the beginning of a CTB row, it must end within the same CTB row
+      const UInt numberOfCTUsToEndOfRow            = tileStartWidth - ctuColumnOfStartingTile;
+      const UInt wavefrontTileBoundingCtuAddrSlice = startCtuTSAddrSlice + numberOfCTUsToEndOfRow;
+      if (wavefrontTileBoundingCtuAddrSlice < boundingCtuTSAddrSlice)
+      {
+        boundingCtuTSAddrSlice = wavefrontTileBoundingCtuAddrSlice;
+      }
+    }
+
+    if (tileBoundingCtuTsAddrSlice < boundingCtuTSAddrSlice)
+    {
+      boundingCtuTSAddrSlice = tileBoundingCtuTsAddrSlice;
+      haveReachedTileBoundary = true;
+    }
+  }
+  else if ((sliceMode == FIXED_NUMBER_OF_CTU || sliceMode == FIXED_NUMBER_OF_BYTES) && pcSlice->getPPS()->getEntropyCodingSyncEnabledFlag() && ((startCtuTSAddrSlice % pcPic->getFrameWidthInCtus()) != 0))
+  {
+    // Adjust for wavefronts (no tiles).
+    // WPP: if a slice does not start at the beginning of a CTB row, it must end within the same CTB row
+    boundingCtuTSAddrSlice = min(boundingCtuTSAddrSlice, startCtuTSAddrSlice - (startCtuTSAddrSlice % pcPic->getFrameWidthInCtus()) + (pcPic->getFrameWidthInCtus()));
+  }
+}
+
+/** Determines the starting and bounding CTU address of current slice / dependent slice
+ * \param bEncodeSlice Identifies if the calling function is compressSlice() [false] or encodeSlice() [true]
+ * \returns Updates startCtuTsAddr, boundingCtuTsAddr with appropriate CTU address
+ */
+Void TEncSlice::xDetermineStartAndBoundingCtuTsAddr  ( UInt& startCtuTsAddr, UInt& boundingCtuTsAddr, TComPic* pcPic, const Bool encodingSlice )
+{
+  TComSlice* pcSlice                 = pcPic->getSlice(getSliceIdx());
+
+  // Non-dependent slice
+  UInt startCtuTsAddrSlice           = pcSlice->getSliceCurStartCtuTsAddr();
+  Bool haveReachedTileBoundarySlice  = false;
+  UInt boundingCtuTsAddrSlice;
+  calculateBoundingCtuTsAddrForSlice(startCtuTsAddrSlice, boundingCtuTsAddrSlice, haveReachedTileBoundarySlice, pcPic,
+                                     encodingSlice, m_pcCfg->getSliceMode(), m_pcCfg->getSliceArgument(), pcSlice->getSliceCurEndCtuTsAddr());
+  pcSlice->setSliceCurEndCtuTsAddr(   boundingCtuTsAddrSlice );
+  pcSlice->setSliceCurStartCtuTsAddr( startCtuTsAddrSlice    );
+
+  // Dependent slice
+  UInt startCtuTsAddrSliceSegment          = pcSlice->getSliceSegmentCurStartCtuTsAddr();
+  Bool haveReachedTileBoundarySliceSegment = false;
+  UInt boundingCtuTsAddrSliceSegment;
+  calculateBoundingCtuTsAddrForSlice(startCtuTsAddrSliceSegment, boundingCtuTsAddrSliceSegment, haveReachedTileBoundarySliceSegment, pcPic,
+                                     encodingSlice, m_pcCfg->getSliceSegmentMode(), m_pcCfg->getSliceSegmentArgument(), pcSlice->getSliceSegmentCurEndCtuTsAddr());
+  if (boundingCtuTsAddrSliceSegment>boundingCtuTsAddrSlice)
+  {
+    boundingCtuTsAddrSliceSegment = boundingCtuTsAddrSlice;
+  }
+  pcSlice->setSliceSegmentCurEndCtuTsAddr( boundingCtuTsAddrSliceSegment );
+  pcSlice->setSliceSegmentCurStartCtuTsAddr(startCtuTsAddrSliceSegment);
+
+  // Make a joint decision based on reconstruction and dependent slice bounds
+  startCtuTsAddr    = max(startCtuTsAddrSlice   , startCtuTsAddrSliceSegment   );
+  boundingCtuTsAddr = boundingCtuTsAddrSliceSegment;
+}
+
+Double TEncSlice::xGetQPValueAccordingToLambda ( Double lambda )
+{
+  return 4.2005*log(lambda) + 13.7122;
+}
+
+#if SVC_EXTENSION
+#if JCTVC_M0259_LAMBDAREFINEMENT
+Double TEncSlice::xCalEnhLambdaFactor( Double deltaQP , Double beta )
+{
+  double tmp = beta * pow( 2.0 , deltaQP / 6 );
+  double gamma = tmp / ( tmp + 1 );
+  return( gamma );
+}
+#endif
+#if O0194_WEIGHTED_PREDICTION_CGS
+Void TEncSlice::estimateILWpParam( TComSlice* pcSlice )
+{
+  xCalcACDCParamSlice(pcSlice);
+  WPACDCParam * temp_weightACDCParam;
+
+  pcSlice->getWpAcDcParam(temp_weightACDCParam);
+  g_refWeightACDCParam = (void *) temp_weightACDCParam;
+}
+#endif
+#endif //SVC_EXTENSION
+//! \}
Index: /tags/SHM-9.0/source/Lib/TLibEncoder/TEncSlice.h
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibEncoder/TEncSlice.h	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibEncoder/TEncSlice.h	(revision 1088)
@@ -0,0 +1,159 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TEncSlice.h
+    \brief    slice encoder class (header)
+*/
+
+#ifndef __TENCSLICE__
+#define __TENCSLICE__
+
+// Include files
+#include "TLibCommon/CommonDef.h"
+#include "TLibCommon/TComList.h"
+#include "TLibCommon/TComPic.h"
+#include "TLibCommon/TComPicYuv.h"
+#include "TEncCu.h"
+#include "WeightPredAnalysis.h"
+#include "TEncRateCtrl.h"
+
+//! \ingroup TLibEncoder
+//! \{
+
+class TEncTop;
+class TEncGOP;
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// slice encoder class
+class TEncSlice
+  : public WeightPredAnalysis
+{
+private:
+  // encoder configuration
+  TEncCfg*                m_pcCfg;                              ///< encoder configuration class
+
+  // pictures
+  TComList<TComPic*>*     m_pcListPic;                          ///< list of pictures
+  TComPicYuv*             m_apcPicYuvPred;                      ///< prediction picture buffer
+  TComPicYuv*             m_apcPicYuvResi;                      ///< residual picture buffer
+
+  // processing units
+  TEncGOP*                m_pcGOPEncoder;                       ///< GOP encoder
+  TEncCu*                 m_pcCuEncoder;                        ///< CU encoder
+
+  // encoder search
+  TEncSearch*             m_pcPredSearch;                       ///< encoder search class
+
+  // coding tools
+  TEncEntropy*            m_pcEntropyCoder;                     ///< entropy encoder
+  TEncSbac*               m_pcSbacCoder;                        ///< SBAC encoder
+  TEncBinCABAC*           m_pcBinCABAC;                         ///< Bin encoder CABAC
+  TComTrQuant*            m_pcTrQuant;                          ///< transform & quantization
+
+  // RD optimization
+  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
+  UInt64                  m_uiPicDist;                          ///< total distortion for the picture
+  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)
+  TEncRateCtrl*           m_pcRateCtrl;                         ///< Rate control manager
+  UInt                    m_uiSliceIdx;
+  TEncSbac                m_lastSliceSegmentEndContextState;    ///< context storage for state at the end of the previous slice-segment (used for dependent slices only).
+  TEncSbac                m_entropyCodingSyncContextState;      ///< context storate for state of contexts at the wavefront/WPP/entropy-coding-sync second CTU of tile-row
+
+#if SVC_EXTENSION && JCTVC_M0259_LAMBDAREFINEMENT
+  Void     setUpLambda(TComSlice* slice, Double dLambda, Int iQP, Int dpeth = -1);
+#else
+  Void     setUpLambda(TComSlice* slice, const Double dLambda, Int iQP);
+#endif
+  Void     calculateBoundingCtuTsAddrForSlice(UInt &startCtuTSAddrSlice, UInt &boundingCtuTSAddrSlice, Bool &haveReachedTileBoundary, TComPic* pcPic, const Bool encodingSlice, const Int sliceMode, const Int sliceArgument, const UInt uiSliceCurEndCtuTSAddr);
+
+#if SVC_EXTENSION
+  TEncTop**               m_ppcTEncTop;
+#endif 
+
+public:
+  TEncSlice();
+  virtual ~TEncSlice();
+
+  Void    create              ( Int iWidth, Int iHeight, ChromaFormat chromaFormat, UInt iMaxCUWidth, UInt iMaxCUHeight, UChar uhTotalDepth );
+  Void    destroy             ();
+  Void    init                ( TEncTop* pcEncTop );
+
+  /// preparation of slice encoding (reference marking, QP and lambda)
+#if SVC_EXTENSION
+  Void    initEncSlice        ( TComPic*  pcPic, Int pocLast, Int pocCurr, Int iNumPicRcvd,
+                                Int iGOPid,   TComSlice*& rpcSlice, TComSPS* pSPS, TComPPS *pPPS, TComVPS *vps, Bool isField );
+#if O0194_WEIGHTED_PREDICTION_CGS
+  Void    estimateILWpParam   ( TComSlice* pcSlice );
+#endif
+#else
+  Void    initEncSlice        ( TComPic*  pcPic, Int pocLast, Int pocCurr, Int iNumPicRcvd,
+                                Int iGOPid,   TComSlice*& rpcSlice, TComSPS* pSPS, TComPPS *pPPS, Bool isField );
+#endif
+
+  Void    resetQP             ( TComPic* pic, Int sliceQP, Double lambda );
+  // compress and encode slice
+  Void    precompressSlice    ( TComPic* pcPic                                     );      ///< precompress slice for multi-loop opt.
+  Void    compressSlice       ( TComPic* pcPic                                     );      ///< analysis stage of slice
+  Void    calCostSliceI       ( TComPic* pcPic );
+  Void    encodeSlice         ( TComPic* pcPic, TComOutputBitstream* pcSubstreams, UInt &numBinsCoded );
+
+  // misc. functions
+  Void    setSearchRange      ( TComSlice* pcSlice  );                                  ///< set ME range adaptively
+
+  TEncCu*        getCUEncoder() { return m_pcCuEncoder; }                        ///< CU encoder
+  Void    xDetermineStartAndBoundingCtuTsAddr  ( UInt& startCtuTsAddr, UInt& boundingCtuTsAddr, TComPic* pcPic, const Bool encodingSlice );
+  UInt    getSliceIdx()         { return m_uiSliceIdx;                    }
+  Void    setSliceIdx(UInt i)   { m_uiSliceIdx = i;                       }
+
+private:
+  Double  xGetQPValueAccordingToLambda ( Double lambda );
+
+#if SVC_EXTENSION
+#if JCTVC_M0259_LAMBDAREFINEMENT
+  Double  xCalEnhLambdaFactor( Double deltaQP , Double beta );
+#endif
+#endif //SVC_EXTENSION
+};
+
+//! \}
+
+#endif // __TENCSLICE__
Index: /tags/SHM-9.0/source/Lib/TLibEncoder/TEncTop.cpp
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibEncoder/TEncTop.cpp	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibEncoder/TEncTop.cpp	(revision 1088)
@@ -0,0 +1,1709 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TEncTop.cpp
+    \brief    encoder class
+*/
+
+#include "TLibCommon/CommonDef.h"
+#include "TEncTop.h"
+#include "TEncPic.h"
+#include "TLibCommon/TComChromaFormat.h"
+#if FAST_BIT_EST
+#include "TLibCommon/ContextModel.h"
+#endif
+
+//! \ingroup TLibEncoder
+//! \{
+#if SVC_EXTENSION  
+Int TEncTop::m_iSPSIdCnt = 0;
+Int TEncTop::m_iPPSIdCnt = 0;
+TComVPS TEncCfg::m_cVPS;
+#endif
+
+// ====================================================================================================================
+// 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
+  if (g_hTrace == NULL)
+  {
+    g_hTrace = fopen( "TraceEnc.txt", "wb" );
+  }
+  g_bJustDoIt = g_bEncDecTraceDisable;
+  g_nSymbolCounter = 0;
+#endif
+
+  m_iMaxRefPicNum     = 0;
+
+#if FAST_BIT_EST
+  ContextModel::buildNextStateTable();
+#endif
+
+#if SVC_EXTENSION
+  memset(m_cIlpPic, 0, sizeof(m_cIlpPic));
+#if REF_IDX_MFM
+  m_bMFMEnabledFlag = false;
+#endif
+  m_numRefLayerLocationOffsets = 0;
+#if POC_RESET_FLAG || POC_RESET_IDC_ENCODER
+  m_pocAdjustmentValue     = 0;
+#endif
+#if NO_CLRAS_OUTPUT_FLAG
+  m_noClrasOutputFlag          = false;
+  m_layerInitializedFlag       = false;
+  m_firstPicInLayerDecodedFlag = false;
+  m_noOutputOfPriorPicsFlags   = false;
+#endif
+#if P0297_VPS_POC_LSB_ALIGNED_FLAG
+  m_pocDecrementedInDPBFlag    = false;
+#endif
+#endif //SVC_EXTENSION
+}
+
+TEncTop::~TEncTop()
+{
+#if ENC_DEC_TRACE
+  if (g_hTrace != stdout)
+  {
+    fclose( g_hTrace );
+  }
+#endif
+}
+
+Void TEncTop::create ()
+{
+#if !SVC_EXTENSION
+  // initialize global variables
+  initROM();
+#endif
+
+  // create processing unit classes
+#if SVC_EXTENSION
+  m_cGOPEncoder.        create( m_layerId );
+#else
+  m_cGOPEncoder.        create( );
+#endif
+  m_cSliceEncoder.      create( getSourceWidth(), getSourceHeight(), m_chromaFormatIDC, g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth );
+  m_cCuEncoder.         create( g_uiMaxCUDepth, g_uiMaxCUWidth, g_uiMaxCUHeight, m_chromaFormatIDC );
+  if (m_bUseSAO)
+  {
+    m_cEncSAO.create( getSourceWidth(), getSourceHeight(), m_chromaFormatIDC, g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth, m_saoOffsetBitShift[CHANNEL_TYPE_LUMA], m_saoOffsetBitShift[CHANNEL_TYPE_CHROMA] );
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+    m_cEncSAO.createEncData(getSaoCtuBoundary());
+#else
+    m_cEncSAO.createEncData();
+#endif
+  }
+#if ADAPTIVE_QP_SELECTION
+  if (m_bUseAdaptQpSelect)
+  {
+    m_cTrQuant.initSliceQpDelta();
+  }
+#endif
+
+  m_cLoopFilter.create( g_uiMaxCUDepth );
+
+  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 );
+  }
+
+  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] );
+    }
+  }
+
+#if LAYER_CTB
+  memcpy(g_auiLayerZscanToRaster[m_layerId], g_auiZscanToRaster, sizeof( g_auiZscanToRaster ) );
+  memcpy(g_auiLayerRasterToZscan[m_layerId], g_auiRasterToZscan, sizeof( g_auiRasterToZscan ) );
+  memcpy(g_auiLayerRasterToPelX[m_layerId],  g_auiRasterToPelX,  sizeof( g_auiRasterToPelX ) );
+  memcpy(g_auiLayerRasterToPelY[m_layerId],  g_auiRasterToPelY,  sizeof( g_auiRasterToPelY ) );
+#endif
+}
+
+Void TEncTop::destroy ()
+{
+  // destroy processing unit classes
+  m_cGOPEncoder.        destroy();
+  m_cSliceEncoder.      destroy();
+  m_cCuEncoder.         destroy();
+  if (m_cSPS.getUseSAO())
+  {
+    m_cEncSAO.destroyEncData();
+    m_cEncSAO.destroy();
+  }
+  m_cLoopFilter.        destroy();
+  m_cRateCtrl.          destroy();
+  Int iDepth;
+  for ( iDepth = 0; iDepth < g_uiMaxCUDepth+1; iDepth++ )
+  {
+    for (Int iCIIdx = 0; iCIIdx < CI_NUM; iCIIdx ++ )
+    {
+      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;
+  
+#if SVC_EXTENSION
+  for(Int i=0; i<MAX_NUM_REF; i++)
+  {
+    if(m_cIlpPic[i])
+    {
+      m_cIlpPic[i]->destroy();
+      delete m_cIlpPic[i];
+      m_cIlpPic[i] = NULL;
+    }
+  }
+#else
+  // destroy ROM
+  destroyROM();
+#endif
+  return;
+}
+
+Void TEncTop::init(Bool isFieldCoding)
+{
+  // initialize SPS
+  xInitSPS();
+
+  // set the VPS profile information
+#if !MULTIPLE_PTL_SUPPORT
+  *m_cVPS.getPTL() = *m_cSPS.getPTL();
+#endif
+#if VPS_VUI_BSP_HRD_PARAMS
+  m_cVPS.getTimingInfo()->setTimingInfoPresentFlag       ( true );
+#else
+  m_cVPS.getTimingInfo()->setTimingInfoPresentFlag       ( false );
+#endif
+  m_cRdCost.setCostMode(m_costMode);
+
+  // initialize PPS
+  m_cPPS.setSPS(&m_cSPS);
+  xInitPPS();
+  xInitRPS(isFieldCoding);
+
+  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;
+#if SVC_EXTENSION
+  m_iSPSIdCnt ++;
+  m_iPPSIdCnt ++;
+  xInitILRP();
+#endif
+}
+
+// ====================================================================================================================
+// Public member functions
+// ====================================================================================================================
+
+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 SVC_EXTENSION
+Void TEncTop::encode( TComPicYuv* pcPicYuvOrg, const InputColourSpaceConversion snrCSC, TComList<TComPicYuv*>& rcListPicYuvRecOut, std::list<AccessUnit>& accessUnitsOut, Int iPicIdInGOP )
+{
+  // compress GOP
+#if !RC_SHVC_HARMONIZATION
+  if ( m_RCEnableRateControl )
+  {
+    m_cRateCtrl.initRCGOP( m_iNumPicRcvd );
+  }
+#endif
+
+  // compress GOP
+  m_cGOPEncoder.compressGOP(iPicIdInGOP, m_iPOCLast, m_iNumPicRcvd, m_cListPic, rcListPicYuvRecOut, accessUnitsOut, false, false, snrCSC, m_printFrameMSE);
+
+#if !RC_SHVC_HARMONIZATION
+  if ( m_RCEnableRateControl )
+  {
+    m_cRateCtrl.destroyRCGOP();
+  }
+#endif
+  
+  m_uiNumAllPicCoded ++;
+}
+
+Void TEncTop::encodePrep( TComPicYuv* pcPicYuvOrg, TComPicYuv* pcPicYuvTrueOrg )
+{
+  if (pcPicYuvOrg != NULL)
+  {
+    // get original YUV
+    TComPic* pcPicCurr = NULL;
+    xGetNewPicBuffer( pcPicCurr );
+    pcPicYuvOrg->copyToPic( pcPicCurr->getPicYuvOrg() );
+    pcPicYuvTrueOrg->copyToPic( pcPicCurr->getPicYuvTrueOrg() );
+
+    // compute image characteristics
+    if ( getUseAdaptiveQP() )
+    {
+      m_cPreanalyzer.xPreanalyze( dynamic_cast<TEncPic*>( pcPicCurr ) );
+    }
+  }
+}
+#else
+Void TEncTop::encode( Bool flush, TComPicYuv* pcPicYuvOrg, TComPicYuv* pcPicYuvTrueOrg, const InputColourSpaceConversion snrCSC, TComList<TComPicYuv*>& rcListPicYuvRecOut, std::list<AccessUnit>& accessUnitsOut, Int& iNumEncoded )
+{
+  if (pcPicYuvOrg != NULL)
+  {
+    // get original YUV
+    TComPic* pcPicCurr = NULL;
+
+    xGetNewPicBuffer( pcPicCurr );
+    pcPicYuvOrg->copyToPic( pcPicCurr->getPicYuvOrg() );
+    pcPicYuvTrueOrg->copyToPic( pcPicCurr->getPicYuvTrueOrg() );
+
+    // compute image characteristics
+    if ( getUseAdaptiveQP() )
+    {
+      m_cPreanalyzer.xPreanalyze( dynamic_cast<TEncPic*>( pcPicCurr ) );
+    }
+  }
+
+  if ((m_iNumPicRcvd == 0) || (!flush && (m_iPOCLast != 0) && (m_iNumPicRcvd != m_iGOPSize) && (m_iGOPSize != 0)))
+  {
+    iNumEncoded = 0;
+    return;
+  }
+
+  if ( m_RCEnableRateControl )
+  {
+    m_cRateCtrl.initRCGOP( m_iNumPicRcvd );
+  }
+
+  // compress GOP
+  m_cGOPEncoder.compressGOP(m_iPOCLast, m_iNumPicRcvd, m_cListPic, rcListPicYuvRecOut, accessUnitsOut, false, false, snrCSC, m_printFrameMSE);
+
+  if ( m_RCEnableRateControl )
+  {
+    m_cRateCtrl.destroyRCGOP();
+  }
+
+  iNumEncoded         = m_iNumPicRcvd;
+  m_iNumPicRcvd       = 0;
+  m_uiNumAllPicCoded += iNumEncoded;
+}
+#endif
+
+/**------------------------------------------------
+ Separate interlaced frame into two fields
+ -------------------------------------------------**/
+Void separateFields(Pel* org, Pel* dstField, UInt stride, UInt width, UInt height, Bool isTop)
+{
+  if (!isTop)
+  {
+    org += stride;
+  }
+  for (Int y = 0; y < height>>1; y++)
+  {
+    for (Int x = 0; x < width; x++)
+    {
+      dstField[x] = org[x];
+    }
+
+    dstField += stride;
+    org += stride*2;
+  }
+
+}
+
+#if SVC_EXTENSION
+Void TEncTop::encodePrep( TComPicYuv* pcPicYuvOrg, TComPicYuv* pcPicYuvTrueOrg, Bool isTff )
+{
+  for (Int fieldNum=0; fieldNum<2; fieldNum++)
+  {
+    if (pcPicYuvOrg)
+    {
+      /* -- field initialization -- */
+      const Bool isTopField=isTff==(fieldNum==0);
+
+      TComPic *pcField;
+      xGetNewPicBuffer( pcField );
+      pcField->setReconMark (false);                     // where is this normally?
+            
+      pcField->getSlice(0)->setPOC( m_iPOCLast );        // superfluous?
+      pcField->getPicYuvRec()->setBorderExtension(false);// where is this normally?
+
+      pcField->setTopField(isTopField);                  // interlaced requirement
+
+      for (UInt componentIndex = 0; componentIndex < pcPicYuvOrg->getNumberValidComponents(); componentIndex++)
+      {
+        const ComponentID component = ComponentID(componentIndex);
+        const UInt stride = pcPicYuvOrg->getStride(component);
+
+        separateFields((pcPicYuvOrg->getBuf(component) + pcPicYuvOrg->getMarginX(component) + (pcPicYuvOrg->getMarginY(component) * stride)),
+                       pcField->getPicYuvOrg()->getAddr(component),
+                       pcPicYuvOrg->getStride(component),
+                       pcPicYuvOrg->getWidth(component),
+                       pcPicYuvOrg->getHeight(component),
+                       isTopField);
+
+        separateFields((pcPicYuvTrueOrg->getBuf(component) + pcPicYuvTrueOrg->getMarginX(component) + (pcPicYuvTrueOrg->getMarginY(component) * stride)),
+                       pcField->getPicYuvTrueOrg()->getAddr(component),
+                       pcPicYuvTrueOrg->getStride(component),
+                       pcPicYuvTrueOrg->getWidth(component),
+                       pcPicYuvTrueOrg->getHeight(component),
+                       isTopField);
+      }
+
+      // compute image characteristics
+      if ( getUseAdaptiveQP() )
+      {
+        m_cPreanalyzer.xPreanalyze( dynamic_cast<TEncPic*>( pcField ) );
+      }
+    }
+  }
+}
+
+Void TEncTop::encode( TComPicYuv* pcPicYuvOrg, const InputColourSpaceConversion snrCSC, TComList<TComPicYuv*>& rcListPicYuvRecOut, std::list<AccessUnit>& accessUnitsOut, Int iPicIdInGOP, Bool isTff )
+{
+  for (Int fieldNum=0; fieldNum<2; fieldNum++)
+  {
+    if (pcPicYuvOrg)
+    {
+      if (fieldNum==1)                                   // where is this normally?
+      {
+        TComPicYuv* rpcPicYuvRec;
+
+        // org. buffer
+        if ( rcListPicYuvRecOut.size() >= (UInt)m_iGOPSize+1 ) // need to maintain field 0 in list of RecOuts while processing field 1. Hence +1 on m_iGOPSize.
+        {
+          rpcPicYuvRec = rcListPicYuvRecOut.popFront();
+        }
+        else
+        {
+          rpcPicYuvRec = new TComPicYuv;
+          rpcPicYuvRec->create( m_iSourceWidth, m_iSourceHeight, m_chromaFormatIDC, g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth);
+        }
+        rcListPicYuvRecOut.pushBack( rpcPicYuvRec );
+      }
+    }
+
+    // compress GOP
+    m_cGOPEncoder.compressGOP(iPicIdInGOP, m_iPOCLast, m_iNumPicRcvd, m_cListPic, rcListPicYuvRecOut, accessUnitsOut, true, isTff, snrCSC, m_printFrameMSE);
+  }
+
+  m_uiNumAllPicCoded ++;
+}
+#else
+Void TEncTop::encode(Bool flush, TComPicYuv* pcPicYuvOrg, TComPicYuv* pcPicYuvTrueOrg, const InputColourSpaceConversion snrCSC, TComList<TComPicYuv*>& rcListPicYuvRecOut, std::list<AccessUnit>& accessUnitsOut, Int& iNumEncoded, Bool isTff)
+{
+  iNumEncoded = 0;
+
+  for (Int fieldNum=0; fieldNum<2; fieldNum++)
+  {
+    if (pcPicYuvOrg)
+    {
+
+      /* -- field initialization -- */
+      const Bool isTopField=isTff==(fieldNum==0);
+
+      TComPic *pcField;
+      xGetNewPicBuffer( pcField );
+      pcField->setReconMark (false);                     // where is this normally?
+
+      if (fieldNum==1)                                   // where is this normally?
+      {
+        TComPicYuv* rpcPicYuvRec;
+
+        // org. buffer
+        if ( rcListPicYuvRecOut.size() >= (UInt)m_iGOPSize+1 ) // need to maintain field 0 in list of RecOuts while processing field 1. Hence +1 on m_iGOPSize.
+        {
+          rpcPicYuvRec = rcListPicYuvRecOut.popFront();
+        }
+        else
+        {
+          rpcPicYuvRec = new TComPicYuv;
+          rpcPicYuvRec->create( m_iSourceWidth, m_iSourceHeight, m_chromaFormatIDC, g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth);
+        }
+        rcListPicYuvRecOut.pushBack( rpcPicYuvRec );
+      }
+
+      pcField->getSlice(0)->setPOC( m_iPOCLast );        // superfluous?
+      pcField->getPicYuvRec()->setBorderExtension(false);// where is this normally?
+
+      pcField->setTopField(isTopField);                  // interlaced requirement
+
+      for (UInt componentIndex = 0; componentIndex < pcPicYuvOrg->getNumberValidComponents(); componentIndex++)
+      {
+        const ComponentID component = ComponentID(componentIndex);
+        const UInt stride = pcPicYuvOrg->getStride(component);
+
+        separateFields((pcPicYuvOrg->getBuf(component) + pcPicYuvOrg->getMarginX(component) + (pcPicYuvOrg->getMarginY(component) * stride)),
+                       pcField->getPicYuvOrg()->getAddr(component),
+                       pcPicYuvOrg->getStride(component),
+                       pcPicYuvOrg->getWidth(component),
+                       pcPicYuvOrg->getHeight(component),
+                       isTopField);
+
+        separateFields((pcPicYuvTrueOrg->getBuf(component) + pcPicYuvTrueOrg->getMarginX(component) + (pcPicYuvTrueOrg->getMarginY(component) * stride)),
+                       pcField->getPicYuvTrueOrg()->getAddr(component),
+                       pcPicYuvTrueOrg->getStride(component),
+                       pcPicYuvTrueOrg->getWidth(component),
+                       pcPicYuvTrueOrg->getHeight(component),
+                       isTopField);
+      }
+
+      // compute image characteristics
+      if ( getUseAdaptiveQP() )
+      {
+        m_cPreanalyzer.xPreanalyze( dynamic_cast<TEncPic*>( pcField ) );
+      }
+    }
+
+    if ( m_iNumPicRcvd && ((flush&&fieldNum==1) || (m_iPOCLast/2)==0 || m_iNumPicRcvd==m_iGOPSize ) )
+    {
+      // compress GOP
+      m_cGOPEncoder.compressGOP(m_iPOCLast, m_iNumPicRcvd, m_cListPic, rcListPicYuvRecOut, accessUnitsOut, true, isTff, snrCSC, m_printFrameMSE);
+
+      iNumEncoded += m_iNumPicRcvd;
+      m_uiNumAllPicCoded += m_iNumPicRcvd;
+      m_iNumPicRcvd = 0;
+    }
+  }
+}
+#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;
+
+#if SVC_EXTENSION //Temporal solution, should be modified
+      if(m_layerId > 0)
+      {
+        for(UInt i = 0; i < m_cVPS.getNumDirectRefLayers( m_layerId ); i++ )
+        {
+#if MOVE_SCALED_OFFSET_TO_PPS
+#if O0098_SCALED_REF_LAYER_ID
+          const Window scalEL = getPPS()->getScaledRefLayerWindowForLayer(m_cVPS.getRefLayerId(m_layerId, i));
+#else
+          const Window scalEL = getPPS()->getScaledRefLayerWindow(i);
+#endif
+#else
+#if O0098_SCALED_REF_LAYER_ID
+          const Window scalEL = getSPS()->getScaledRefLayerWindowForLayer(m_cVPS.getRefLayerId(m_layerId, i));
+#else
+          const Window scalEL = getSPS()->getScaledRefLayerWindow(i);
+#endif
+#endif
+#if REF_REGION_OFFSET
+          const Window altRL  = getPPS()->getRefLayerWindowForLayer(m_cVPS.getRefLayerId(m_layerId, i));
+#if RESAMPLING_FIX
+          Bool equalOffsets = scalEL.hasEqualOffset(altRL);
+#if R0209_GENERIC_PHASE
+          Bool zeroPhase = getPPS()->hasZeroResamplingPhase(m_cVPS.getRefLayerId(m_layerId, i));
+#endif
+#else
+          Bool zeroOffsets = ( scalEL.getWindowLeftOffset() == 0 && scalEL.getWindowRightOffset() == 0 && scalEL.getWindowTopOffset() == 0 && scalEL.getWindowBottomOffset() == 0
+                               && altRL.getWindowLeftOffset() == 0 && altRL.getWindowRightOffset() == 0 && altRL.getWindowTopOffset() == 0 && altRL.getWindowBottomOffset() == 0);
+#endif
+#else
+          Bool zeroOffsets = ( scalEL.getWindowLeftOffset() == 0 && scalEL.getWindowRightOffset() == 0 && scalEL.getWindowTopOffset() == 0 && scalEL.getWindowBottomOffset() == 0 );
+#endif
+
+#if VPS_EXTN_DIRECT_REF_LAYERS
+          TEncTop *pcEncTopBase = (TEncTop *)getRefLayerEnc( i );
+#else
+          TEncTop *pcEncTopBase = (TEncTop *)getLayerEnc( m_layerId-1 );
+#endif
+#if O0194_DIFFERENT_BITDEPTH_EL_BL
+          UInt refLayerId = m_cVPS.getRefLayerId(m_layerId, i);
+          Bool sameBitDepths = ( g_bitDepthLayer[CHANNEL_TYPE_LUMA][m_layerId] == g_bitDepthLayer[CHANNEL_TYPE_LUMA][refLayerId] ) && ( g_bitDepthLayer[CHANNEL_TYPE_CHROMA][m_layerId] == g_bitDepthLayer[CHANNEL_TYPE_CHROMA][refLayerId] );
+
+#if REF_IDX_MFM
+          if( m_iSourceWidth == pcEncTopBase->getSourceWidth() && m_iSourceHeight == pcEncTopBase->getSourceHeight() && equalOffsets && zeroPhase )
+          {
+            pcEPic->setEqualPictureSizeAndOffsetFlag( i, true );
+          }
+
+          if( !pcEPic->equalPictureSizeAndOffsetFlag(i) || !sameBitDepths 
+#else
+          if( m_iSourceWidth != pcEncTopBase->getSourceWidth() || m_iSourceHeight != pcEncTopBase->getSourceHeight() || !sameBitDepths 
+#if REF_REGION_OFFSET && RESAMPLING_FIX
+            || !equalOffsets
+#if R0209_GENERIC_PHASE
+            || !zeroPhase
+#endif
+#else
+            || !zeroOffsets
+#endif
+#endif
+#if Q0048_CGS_3D_ASYMLUT
+            || m_cPPS.getCGSFlag() > 0
+#endif
+#if LAYER_CTB
+            || pcEncTopBase->getSPS()->getMaxCUWidth() != m_cSPS.getMaxCUWidth() || pcEncTopBase->getSPS()->getMaxCUHeight() != m_cSPS.getMaxCUHeight() || pcEncTopBase->getSPS()->getMaxCUDepth() != m_cSPS.getMaxCUDepth()
+#endif
+            )
+#else
+          if(m_iSourceWidth != pcEncTopBase->getSourceWidth() || m_iSourceHeight != pcEncTopBase->getSourceHeight()
+#if REF_REGION_OFFSET && RESAMPLING_FIX
+            || !equalOffsets
+#if R0209_GENERIC_PHASE
+            || !zeroPhase
+#endif
+#else
+            || !zeroOffsets
+#endif
+          )
+#endif
+          {
+            pcEPic->setSpatialEnhLayerFlag( i, true );
+
+            //only for scalable extension
+            assert( m_cVPS.getScalabilityMask( SCALABILITY_ID ) == true );
+          }
+        }
+      }
+#endif
+
+#if SVC_EXTENSION
+      pcEPic->create( m_iSourceWidth, m_iSourceHeight, m_chromaFormatIDC, g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth, m_cPPS.getMaxCuDQPDepth()+1 ,
+                      m_conformanceWindow, m_defaultDisplayWindow, m_numReorderPics, &m_cSPS);
+#else  //SVC_EXTENSION
+      pcEPic->create( m_iSourceWidth, m_iSourceHeight, m_chromaFormatIDC, g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth, m_cPPS.getMaxCuDQPDepth()+1, m_conformanceWindow, m_defaultDisplayWindow, m_numReorderPics);
+#endif //SVC_EXTENSION
+      rpcPic = pcEPic;
+    }
+    else
+    {
+      rpcPic = new TComPic;
+
+#if SVC_EXTENSION //Temporal solution, should be modified
+      if(m_layerId > 0)
+      {
+        for(UInt i = 0; i < m_cVPS.getNumDirectRefLayers( m_layerId ); i++ )
+        {
+#if MOVE_SCALED_OFFSET_TO_PPS
+#if O0098_SCALED_REF_LAYER_ID
+          const Window scalEL = getPPS()->getScaledRefLayerWindowForLayer(m_cVPS.getRefLayerId(m_layerId, i));
+#else
+          const Window scalEL = getPPS()->getScaledRefLayerWindow(i);
+#endif
+#else
+#if O0098_SCALED_REF_LAYER_ID
+          const Window scalEL = getSPS()->getScaledRefLayerWindowForLayer(m_cVPS.getRefLayerId(m_layerId, i));
+#else
+          const Window scalEL = getSPS()->getScaledRefLayerWindow(i);
+#endif
+#endif
+#if REF_REGION_OFFSET
+          const Window altRL  = getPPS()->getRefLayerWindowForLayer(m_cVPS.getRefLayerId(m_layerId, i));
+#if RESAMPLING_FIX
+          Bool equalOffsets = scalEL.hasEqualOffset(altRL);
+#if R0209_GENERIC_PHASE
+          Bool zeroPhase = getPPS()->hasZeroResamplingPhase(m_cVPS.getRefLayerId(m_layerId, i));
+#endif
+#else
+          Bool zeroOffsets = ( scalEL.getWindowLeftOffset() == 0 && scalEL.getWindowRightOffset() == 0 && scalEL.getWindowTopOffset() == 0 && scalEL.getWindowBottomOffset() == 0
+                               && altRL.getWindowLeftOffset() == 0 && altRL.getWindowRightOffset() == 0 && altRL.getWindowTopOffset() == 0 && altRL.getWindowBottomOffset() == 0);
+#endif
+#else
+          Bool zeroOffsets = ( scalEL.getWindowLeftOffset() == 0 && scalEL.getWindowRightOffset() == 0 && scalEL.getWindowTopOffset() == 0 && scalEL.getWindowBottomOffset() == 0 );
+#endif
+
+#if VPS_EXTN_DIRECT_REF_LAYERS
+          TEncTop *pcEncTopBase = (TEncTop *)getRefLayerEnc( i );
+#else
+          TEncTop *pcEncTopBase = (TEncTop *)getLayerEnc( m_layerId-1 );
+#endif
+#if O0194_DIFFERENT_BITDEPTH_EL_BL
+          UInt refLayerId = m_cVPS.getRefLayerId(m_layerId, i);
+          Bool sameBitDepths = ( g_bitDepthLayer[CHANNEL_TYPE_LUMA][m_layerId] == g_bitDepthLayer[CHANNEL_TYPE_LUMA][refLayerId] ) && ( g_bitDepthLayer[CHANNEL_TYPE_CHROMA][m_layerId] == g_bitDepthLayer[CHANNEL_TYPE_CHROMA][refLayerId] );
+
+          if( m_iSourceWidth != pcEncTopBase->getSourceWidth() || m_iSourceHeight != pcEncTopBase->getSourceHeight() || !sameBitDepths 
+#if REF_REGION_OFFSET && RESAMPLING_FIX
+            || !equalOffsets 
+#if R0209_GENERIC_PHASE
+            || !zeroPhase
+#endif
+#else
+            || !zeroOffsets 
+#endif
+#if Q0048_CGS_3D_ASYMLUT
+            || m_cPPS.getCGSFlag() > 0
+#endif
+#if LAYER_CTB
+            || pcEncTopBase->getSPS()->getMaxCUWidth() != m_cSPS.getMaxCUWidth() || pcEncTopBase->getSPS()->getMaxCUHeight() != m_cSPS.getMaxCUHeight() || pcEncTopBase->getSPS()->getMaxCUDepth() != m_cSPS.getMaxCUDepth()
+#endif
+)
+#else
+          if(m_iSourceWidth != pcEncTopBase->getSourceWidth() || m_iSourceHeight != pcEncTopBase->getSourceHeight()
+#if REF_REGION_OFFSET && RESAMPLING_FIX
+            || !equalOffsets 
+#if R0209_GENERIC_PHASE
+            || !zeroPhase
+#endif
+#else
+            || !zeroOffsets 
+#endif
+          )
+#endif
+          {
+            rpcPic->setSpatialEnhLayerFlag( i, true );
+
+            //only for scalable extension
+            assert( m_cVPS.getScalabilityMask( SCALABILITY_ID ) == true );
+          }
+        }
+      }
+#endif
+
+#if SVC_EXTENSION
+      rpcPic->create( m_iSourceWidth, m_iSourceHeight, m_chromaFormatIDC, g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth, m_conformanceWindow, m_defaultDisplayWindow, m_numReorderPics, &m_cSPS);
+#else  //SVC_EXTENSION
+      rpcPic->create( m_iSourceWidth, m_iSourceHeight, m_chromaFormatIDC, g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth, m_conformanceWindow, m_defaultDisplayWindow, m_numReorderPics, false );
+#endif //SVC_EXTENSION
+    }
+
+    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);
+}
+
+Void TEncTop::xInitSPS()
+{
+#if SVC_EXTENSION
+  m_cSPS.setExtensionFlag( m_layerId > 0 ? true : false );
+#if R0042_PROFILE_INDICATION
+  m_cSPS.setNumDirectRefLayers(m_numDirectRefLayers);
+#endif
+#if Q0078_ADD_LAYER_SETS
+  if( !m_numDirectRefLayers && m_numAddLayerSets )
+  {
+    m_cSPS.setLayerId(0); // layer ID 0 for independent layers
+  }
+  else
+  {
+    m_cSPS.setLayerId(m_layerId);
+  }
+#else
+  m_cSPS.setLayerId(m_layerId);
+#endif
+#if !MOVE_SCALED_OFFSET_TO_PPS
+  m_cSPS.setNumScaledRefLayerOffsets(m_numScaledRefLayerOffsets);
+  for(Int i = 0; i < m_cSPS.getNumScaledRefLayerOffsets(); i++)
+  {
+#if O0098_SCALED_REF_LAYER_ID
+    m_cSPS.setScaledRefLayerId(i, m_scaledRefLayerId[i]);
+#endif
+    m_cSPS.getScaledRefLayerWindow(i) = m_scaledRefLayerWindow[i];
+#if P0312_VERT_PHASE_ADJ
+    m_cSPS.setVertPhasePositionEnableFlag( m_scaledRefLayerId[i], m_scaledRefLayerWindow[i].getVertPhasePositionEnableFlag() );
+#endif
+  }
+#endif
+#endif //SVC_EXTENSION
+  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);
+  profileTierLevel.setBitDepthConstraint(m_bitDepthConstraintValue);
+  profileTierLevel.setChromaFormatConstraint(m_chromaFormatConstraintValue);
+  profileTierLevel.setIntraConstraintFlag(m_intraConstraintFlag);
+  profileTierLevel.setLowerBitRateConstraintFlag(m_lowerBitRateConstraintFlag);
+
+  if ((m_profile == Profile::MAIN10) && (g_bitDepth[CHANNEL_TYPE_LUMA] == 8) && (g_bitDepth[CHANNEL_TYPE_CHROMA] == 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      );
+  m_cSPS.setChromaFormatIdc( m_chromaFormatIDC);
+
+  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-getMaxCUDepthOffset(m_cSPS.getChromaFormatIdc(), m_cSPS.getQuadtreeTULog2MinSize()));
+#if SVC_EXTENSION
+  m_cSPS.setSPSId         ( m_iSPSIdCnt       );
+#endif
+  
+  m_cSPS.setPCMLog2MinSize (m_uiPCMLog2MinSize);
+  m_cSPS.setUsePCM        ( m_usePCM           );
+  m_cSPS.setPCMLog2MaxSize( m_pcmLog2MaxSize  );
+
+  m_cSPS.setQuadtreeTULog2MaxSize( m_uiQuadtreeTULog2MaxSize );
+  m_cSPS.setQuadtreeTULog2MinSize( m_uiQuadtreeTULog2MinSize );
+  m_cSPS.setQuadtreeTUMaxDepthInter( m_uiQuadtreeTUMaxDepthInter    );
+  m_cSPS.setQuadtreeTUMaxDepthIntra( m_uiQuadtreeTUMaxDepthIntra    );
+
+  m_cSPS.setTMVPFlagsPresent(false);
+
+  m_cSPS.setMaxTrSize   ( 1 << m_uiQuadtreeTULog2MaxSize );
+
+  Int i;
+
+  for (i = 0; i < g_uiMaxCUDepth-g_uiAddCUDepth; i++ )
+  {
+    m_cSPS.setAMPAcc( i, m_useAMP );
+    //m_cSPS.setAMPAcc( i, 1 );
+  }
+
+  m_cSPS.setUseAMP ( m_useAMP );
+
+  for (i = g_uiMaxCUDepth-g_uiAddCUDepth; i < g_uiMaxCUDepth; i++ )
+  {
+    m_cSPS.setAMPAcc(i, 0);
+  }
+
+
+  for (UInt channelType = 0; channelType < MAX_NUM_CHANNEL_TYPE; channelType++)
+  {
+#if REPN_FORMAT_IN_VPS
+    m_cSPS.setBitDepth    (ChannelType(channelType), m_cVPS.getVpsRepFormat( m_cVPS.getVpsRepFormatIdx( m_cVPS.getLayerIdxInVps( m_layerId ) ) )->getBitDepthVps(ChannelType(channelType))            );
+    m_cSPS.setQpBDOffset  (ChannelType(channelType), (6 * (m_cVPS.getVpsRepFormat( m_cVPS.getVpsRepFormatIdx( m_cVPS.getLayerIdxInVps( m_layerId ) ) )->getBitDepthVps(ChannelType(channelType)) - 8)));
+#else
+    m_cSPS.setBitDepth    (ChannelType(channelType), g_bitDepth[channelType]            );
+    m_cSPS.setQpBDOffset  (ChannelType(channelType), (6 * (g_bitDepth[channelType] - 8)));
+#endif
+    m_cSPS.setPCMBitDepth (ChannelType(channelType), g_PCMBitDepth[channelType]         );
+  }
+
+  m_cSPS.setUseExtendedPrecision(m_useExtendedPrecision);
+  m_cSPS.setUseHighPrecisionPredictionWeighting(m_useHighPrecisionPredictionWeighting);
+
+  m_cSPS.setUseSAO( m_bUseSAO );
+  m_cSPS.setUseResidualRotation(m_useResidualRotation);
+  m_cSPS.setUseSingleSignificanceMapContext(m_useSingleSignificanceMapContext);
+  m_cSPS.setUseGolombRiceParameterAdaptation(m_useGolombRiceParameterAdaptation);
+  m_cSPS.setAlignCABACBeforeBypass(m_alignCABACBeforeBypass);
+
+  for (UInt signallingModeIndex = 0; signallingModeIndex < NUMBER_OF_RDPCM_SIGNALLING_MODES; signallingModeIndex++)
+  {
+    m_cSPS.setUseResidualDPCM(RDPCMSignallingMode(signallingModeIndex), m_useResidualDPCM[signallingModeIndex]);
+  }
+
+  m_cSPS.setMaxTLayers( m_maxTempLayer );
+  m_cSPS.setTemporalIdNestingFlag( ( m_maxTempLayer == 1 ) ? true : false );
+
+  for ( i = 0; i < min(m_cSPS.getMaxTLayers(),(UInt) MAX_TLAYER); i++ )
+  {
+#if SVC_EXTENSION
+    assert(i < MAX_TLAYER);
+#endif
+    m_cSPS.setMaxDecPicBuffering(m_maxDecPicBuffering[i], i);
+    m_cSPS.setNumReorderPics(m_numReorderPics[i], i);
+  }
+
+  m_cSPS.setPCMFilterDisableFlag  ( m_bPCMFilterDisableFlag );
+  m_cSPS.setDisableIntraReferenceSmoothing( m_disableIntraReferenceSmoothing );
+  m_cSPS.setScalingListFlag ( (m_useScalingListId == 0) ? 0 : 1 );
+  m_cSPS.setUseStrongIntraSmoothing( m_useStrongIntraSmoothing );
+  m_cSPS.setVuiParametersPresentFlag(getVuiParametersPresentFlag());
+
+  if (m_cSPS.getVuiParametersPresentFlag())
+  {
+    TComVUI* pcVUI = m_cSPS.getVuiParameters();
+    pcVUI->setAspectRatioInfoPresentFlag(getAspectRatioInfoPresentFlag());
+    pcVUI->setAspectRatioIdc(getAspectRatioIdc());
+    pcVUI->setSarWidth(getSarWidth());
+    pcVUI->setSarHeight(getSarHeight());
+    pcVUI->setOverscanInfoPresentFlag(getOverscanInfoPresentFlag());
+    pcVUI->setOverscanAppropriateFlag(getOverscanAppropriateFlag());
+    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());
+  }
+}
+
+Void TEncTop::xInitPPS()
+{
+  m_cPPS.setConstrainedIntraPred( m_bUseConstrainedIntraPred );
+  Bool bUseDQP = (getMaxCuDQPDepth() > 0)? true : false;
+
+  if((getMaxDeltaQP() != 0 )|| getUseAdaptiveQP())
+  {
+    bUseDQP = true;
+  }
+
+  if (m_costMode==COST_SEQUENCE_LEVEL_LOSSLESS || m_costMode==COST_LOSSLESS_CODING) bUseDQP=false;
+
+  if(bUseDQP)
+  {
+    m_cPPS.setUseDQP(true);
+    m_cPPS.setMaxCuDQPDepth( m_iMaxCuDQPDepth );
+    m_cPPS.setMinCuDQPSize( m_cPPS.getSPS()->getMaxCUWidth() >> ( m_cPPS.getMaxCuDQPDepth()) );
+  }
+  else
+  {
+    m_cPPS.setUseDQP(false);
+    m_cPPS.setMaxCuDQPDepth( 0 );
+    m_cPPS.setMinCuDQPSize( m_cPPS.getSPS()->getMaxCUWidth() >> ( m_cPPS.getMaxCuDQPDepth()) );
+  }
+
+  if ( m_maxCUChromaQpAdjustmentDepth >= 0 )
+  {
+    m_cPPS.setMaxCuChromaQpAdjDepth(m_maxCUChromaQpAdjustmentDepth);
+    m_cPPS.setChromaQpAdjTableAt(1, 6, 6);
+    /* todo, insert table entries from command line (NB, 0 should not be touched) */
+  }
+  else
+  {
+    m_cPPS.setMaxCuChromaQpAdjDepth(0);
+    m_cPPS.clearChromaQpAdjTable();
+  }
+
+  if ( m_RCEnableRateControl )
+  {
+    m_cPPS.setUseDQP(true);
+    m_cPPS.setMaxCuDQPDepth( 0 );
+    m_cPPS.setMinCuDQPSize( m_cPPS.getSPS()->getMaxCUWidth() >> ( m_cPPS.getMaxCuDQPDepth()) );
+  }
+
+  m_cPPS.setMinCuChromaQpAdjSize( m_cPPS.getSPS()->getMaxCUWidth() >> ( m_cPPS.getMaxCuChromaQpAdjDepth()) );
+
+  m_cPPS.setQpOffset(COMPONENT_Cb, m_chromaCbQpOffset );
+  m_cPPS.setQpOffset(COMPONENT_Cr, 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.setUseCrossComponentPrediction(m_useCrossComponentPrediction);
+  m_cPPS.setSaoOffsetBitShift(CHANNEL_TYPE_LUMA,   m_saoOffsetBitShift[CHANNEL_TYPE_LUMA  ]);
+  m_cPPS.setSaoOffsetBitShift(CHANNEL_TYPE_CHROMA, m_saoOffsetBitShift[CHANNEL_TYPE_CHROMA]);
+  m_cPPS.setOutputFlagPresentFlag( false );
+  m_cPPS.setSignHideFlag(getSignHideFlag());
+  if ( getDeblockingFilterMetric() )
+  {
+    m_cPPS.setDeblockingFilterControlPresentFlag (true);
+    m_cPPS.setDeblockingFilterOverrideEnabledFlag(true);
+    m_cPPS.setPicDisableDeblockingFilterFlag(false);
+    m_cPPS.setDeblockingFilterBetaOffsetDiv2(0);
+    m_cPPS.setDeblockingFilterTcOffsetDiv2(0);
+  }
+  else
+  {
+    m_cPPS.setDeblockingFilterControlPresentFlag (m_DeblockingFilterControlPresent );
+  }
+  m_cPPS.setLog2ParallelMergeLevelMinus2   (m_log2ParallelMergeLevelMinus2 );
+  m_cPPS.setCabacInitPresentFlag(CABAC_INIT_PRESENT_FLAG);
+  m_cPPS.setLoopFilterAcrossSlicesEnabledFlag( m_bLFCrossSliceBoundaryFlag );
+
+  Int histogram[MAX_NUM_REF + 1];
+  for( Int i = 0; i <= MAX_NUM_REF; i++ )
+  {
+    histogram[i]=0;
+  }
+  for( Int i = 0; i < getGOPSize(); i++)
+  {
+    assert(getGOPEntry(i).m_numRefPicsActive >= 0 && getGOPEntry(i).m_numRefPicsActive <= MAX_NUM_REF);
+    histogram[getGOPEntry(i).m_numRefPicsActive]++;
+  }
+
+  Int maxHist=-1;
+  Int bestPos=0;
+  for( Int i = 0; i <= MAX_NUM_REF; i++ )
+  {
+    if(histogram[i]>maxHist)
+    {
+      maxHist=histogram[i];
+      bestPos=i;
+    }
+  }
+  assert(bestPos <= 15);
+  m_cPPS.setNumRefIdxL0DefaultActive(bestPos);
+  m_cPPS.setNumRefIdxL1DefaultActive(bestPos);
+  m_cPPS.setTransquantBypassEnableFlag(getTransquantBypassEnableFlag());
+  m_cPPS.setUseTransformSkip( m_useTransformSkip );
+  m_cPPS.setTransformSkipLog2MaxSize( m_transformSkipLog2MaxSize  );
+
+  if (m_sliceSegmentMode != NO_SLICES)
+  {
+    m_cPPS.setDependentSliceSegmentsEnabledFlag( true );
+  }
+  
+#if SVC_EXTENSION
+#if SCALINGLIST_INFERRING
+  m_cPPS.setLayerId( m_layerId );
+#endif
+
+#if Q0078_ADD_LAYER_SETS
+  if( !m_numDirectRefLayers && m_numAddLayerSets )
+  {
+    m_cPPS.setLayerId(0); // layer ID 0 for independent layers
+  }
+#endif
+
+  if( m_layerId > 0 )
+  {
+    m_cPPS.setListsModificationPresentFlag(true);
+    m_cPPS.setExtensionFlag(true);
+  }
+  else
+  {
+    m_cPPS.setListsModificationPresentFlag(false);
+    m_cPPS.setExtensionFlag(false);
+  }
+
+  m_cPPS.setPPSId( m_iPPSIdCnt );
+  m_cPPS.setSPSId( m_iSPSIdCnt );
+#if POC_RESET_FLAG
+  m_cPPS.setNumExtraSliceHeaderBits( 2 );
+#endif
+#if O0149_CROSS_LAYER_BLA_FLAG
+  if (m_crossLayerBLAFlag)
+  {
+    m_cPPS.setNumExtraSliceHeaderBits( 3 );
+  }
+#endif
+#if MOVE_SCALED_OFFSET_TO_PPS
+  m_cPPS.setNumRefLayerLocationOffsets(m_numRefLayerLocationOffsets);
+  for(Int i = 0; i < m_cPPS.getNumRefLayerLocationOffsets(); i++)
+  {
+#if O0098_SCALED_REF_LAYER_ID
+    m_cPPS.setRefLocationOffsetLayerId(i, m_refLocationOffsetLayerId[i]);
+#endif
+    m_cPPS.getScaledRefLayerWindow(i) = m_scaledRefLayerWindow[i];
+#if REF_REGION_OFFSET
+    m_cPPS.getRefLayerWindow(i) = m_refLayerWindow[i];
+    m_cPPS.setScaledRefLayerOffsetPresentFlag( i, m_scaledRefLayerOffsetPresentFlag[i] );
+    m_cPPS.setRefRegionOffsetPresentFlag( i, m_refRegionOffsetPresentFlag[i] );
+#endif
+#if R0209_GENERIC_PHASE
+    m_cPPS.setResamplePhaseSetPresentFlag( i, m_resamplePhaseSetPresentFlag[i] );
+    m_cPPS.setPhaseHorLuma( m_refLocationOffsetLayerId[i], m_phaseHorLuma[i] );
+    m_cPPS.setPhaseVerLuma( m_refLocationOffsetLayerId[i], m_phaseVerLuma[i] );
+    m_cPPS.setPhaseHorChroma( m_refLocationOffsetLayerId[i], m_phaseHorChroma[i] );
+    m_cPPS.setPhaseVerChroma( m_refLocationOffsetLayerId[i], m_phaseVerChroma[i] );
+#endif
+#if P0312_VERT_PHASE_ADJ
+    m_cPPS.setVertPhasePositionEnableFlag( m_scaledRefLayerId[i], m_scaledRefLayerWindow[i].getVertPhasePositionEnableFlag() );
+#endif
+  }
+#endif
+#if Q0048_CGS_3D_ASYMLUT
+  m_cPPS.setCGSFlag( m_nCGSFlag );
+#endif
+#if POC_RESET_IDC_ENCODER
+  m_cPPS.setPocResetInfoPresentFlag( true );
+  m_cPPS.setExtensionFlag( true );
+  m_cPPS.setSliceHeaderExtensionPresentFlag( true );
+#endif
+#endif //SVC_EXTENSION
+}
+
+//Function for initializing m_RPSList, a list of TComReferencePictureSet, based on the GOPEntry objects read from the config file.
+Void TEncTop::xInitRPS(Bool isFieldCoding)
+{
+  TComReferencePictureSet*      rps;
+
+  m_cSPS.createRPSList(getGOPSize() + m_extraRPSs + 1);
+  TComRPSList* rpsList = m_cSPS.getRPSList();
+
+  for( Int i = 0; i < getGOPSize()+m_extraRPSs; i++)
+  {
+    GOPEntry ge = getGOPEntry(i);
+    rps = rpsList->getReferencePictureSet(i);
+    rps->setNumberOfPictures(ge.m_numRefPics);
+    rps->setNumRefIdc(ge.m_numRefIdc);
+    Int numNeg = 0;
+    Int numPos = 0;
+    for( Int j = 0; j < ge.m_numRefPics; j++)
+    {
+      rps->setDeltaPOC(j,ge.m_referencePics[j]);
+      rps->setUsed(j,ge.m_usedByCurrPic[j]);
+      if(ge.m_referencePics[j]>0)
+      {
+        numPos++;
+      }
+      else
+      {
+        numNeg++;
+      }
+    }
+    rps->setNumberOfNegativePictures(numNeg);
+    rps->setNumberOfPositivePictures(numPos);
+
+    // handle inter RPS intialization from the config file.
+#if AUTO_INTER_RPS
+    rps->setInterRPSPrediction(ge.m_interRPSPrediction > 0);  // not very clean, converting anything > 0 to true.
+    rps->setDeltaRIdxMinus1(0);                               // index to the Reference RPS is always the previous one.
+    TComReferencePictureSet*     RPSRef = rpsList->getReferencePictureSet(i-1);  // get the reference RPS
+
+    if (ge.m_interRPSPrediction == 2)  // Automatic generation of the inter RPS idc based on the RIdx provided.
+    {
+      Int deltaRPS = getGOPEntry(i-1).m_POC - ge.m_POC;  // the ref POC - current POC
+      Int numRefDeltaPOC = RPSRef->getNumberOfPictures();
+
+      rps->setDeltaRPS(deltaRPS);           // set delta RPS
+      rps->setNumRefIdc(numRefDeltaPOC+1);  // set the numRefIdc to the number of pictures in the reference RPS + 1.
+      Int count=0;
+      for (Int j = 0; j <= numRefDeltaPOC; j++ ) // cycle through pics in reference RPS.
+      {
+        Int RefDeltaPOC = (j<numRefDeltaPOC)? RPSRef->getDeltaPOC(j): 0;  // if it is the last decoded picture, set RefDeltaPOC = 0
+        rps->setRefIdc(j, 0);
+        for (Int k = 0; k < rps->getNumberOfPictures(); k++ )  // cycle through pics in current RPS.
+        {
+          if (rps->getDeltaPOC(k) == ( RefDeltaPOC + deltaRPS))  // if the current RPS has a same picture as the reference RPS.
+          {
+              rps->setRefIdc(j, (rps->getUsed(k)?1:2));
+              count++;
+              break;
+          }
+        }
+      }
+      if (count != rps->getNumberOfPictures())
+      {
+        printf("Warning: Unable fully predict all delta POCs using the reference RPS index given in the config file.  Setting Inter RPS to false for this RPS.\n");
+        rps->setInterRPSPrediction(0);
+      }
+    }
+    else if (ge.m_interRPSPrediction == 1)  // inter RPS idc based on the RefIdc values provided in config file.
+    {
+      rps->setDeltaRPS(ge.m_deltaRPS);
+      rps->setNumRefIdc(ge.m_numRefIdc);
+      for (Int j = 0; j < ge.m_numRefIdc; j++ )
+      {
+        rps->setRefIdc(j, ge.m_refIdc[j]);
+      }
+#if WRITE_BACK
+      // the folowing code overwrite the deltaPOC and Used by current values read from the config file with the ones
+      // computed from the RefIdc.  A warning is printed if they are not identical.
+      numNeg = 0;
+      numPos = 0;
+      TComReferencePictureSet      RPSTemp;  // temporary variable
+
+      for (Int j = 0; j < ge.m_numRefIdc; j++ )
+      {
+        if (ge.m_refIdc[j])
+        {
+          Int deltaPOC = ge.m_deltaRPS + ((j < RPSRef->getNumberOfPictures())? RPSRef->getDeltaPOC(j) : 0);
+          RPSTemp.setDeltaPOC((numNeg+numPos),deltaPOC);
+          RPSTemp.setUsed((numNeg+numPos),ge.m_refIdc[j]==1?1:0);
+          if (deltaPOC<0)
+          {
+            numNeg++;
+          }
+          else
+          {
+            numPos++;
+          }
+        }
+      }
+      if (numNeg != rps->getNumberOfNegativePictures())
+      {
+        printf("Warning: number of negative pictures in RPS is different between intra and inter RPS specified in the config file.\n");
+        rps->setNumberOfNegativePictures(numNeg);
+        rps->setNumberOfPictures(numNeg+numPos);
+      }
+      if (numPos != rps->getNumberOfPositivePictures())
+      {
+        printf("Warning: number of positive pictures in RPS is different between intra and inter RPS specified in the config file.\n");
+        rps->setNumberOfPositivePictures(numPos);
+        rps->setNumberOfPictures(numNeg+numPos);
+      }
+      RPSTemp.setNumberOfPictures(numNeg+numPos);
+      RPSTemp.setNumberOfNegativePictures(numNeg);
+      RPSTemp.sortDeltaPOC();     // sort the created delta POC before comparing
+      // check if Delta POC and Used are the same
+      // print warning if they are not.
+      for (Int j = 0; j < ge.m_numRefIdc; j++ )
+      {
+        if (RPSTemp.getDeltaPOC(j) != rps->getDeltaPOC(j))
+        {
+          printf("Warning: delta POC is different between intra RPS and inter RPS specified in the config file.\n");
+          rps->setDeltaPOC(j,RPSTemp.getDeltaPOC(j));
+        }
+        if (RPSTemp.getUsed(j) != rps->getUsed(j))
+        {
+          printf("Warning: Used by Current in RPS is different between intra and inter RPS specified in the config file.\n");
+          rps->setUsed(j,RPSTemp.getUsed(j));
+        }
+      }
+#endif
+    }
+#else
+    rps->setInterRPSPrediction(ge.m_interRPSPrediction);
+    if (ge.m_interRPSPrediction)
+    {
+      rps->setDeltaRIdxMinus1(0);
+      rps->setDeltaRPS(ge.m_deltaRPS);
+      rps->setNumRefIdc(ge.m_numRefIdc);
+      for (Int j = 0; j < ge.m_numRefIdc; j++ )
+      {
+        rps->setRefIdc(j, ge.m_refIdc[j]);
+      }
+#if WRITE_BACK
+      // the folowing code overwrite the deltaPOC and Used by current values read from the config file with the ones
+      // computed from the RefIdc.  This is not necessary if both are identical. Currently there is no check to see if they are identical.
+      numNeg = 0;
+      numPos = 0;
+      TComReferencePictureSet*     RPSRef = m_RPSList.getReferencePictureSet(i-1);
+
+      for (Int j = 0; j < ge.m_numRefIdc; j++ )
+      {
+        if (ge.m_refIdc[j])
+        {
+          Int deltaPOC = ge.m_deltaRPS + ((j < RPSRef->getNumberOfPictures())? RPSRef->getDeltaPOC(j) : 0);
+          rps->setDeltaPOC((numNeg+numPos),deltaPOC);
+          rps->setUsed((numNeg+numPos),ge.m_refIdc[j]==1?1:0);
+          if (deltaPOC<0)
+          {
+            numNeg++;
+          }
+          else
+          {
+            numPos++;
+          }
+        }
+      }
+      rps->setNumberOfNegativePictures(numNeg);
+      rps->setNumberOfPositivePictures(numPos);
+      rps->sortDeltaPOC();
+#endif
+    }
+#endif //INTER_RPS_AUTO
+  }
+  //In case of field coding, we need to set special parameters for the first bottom field of the sequence, since it is not specified in the cfg file.
+  //The position = GOPSize + extraRPSs which is (a priori) unused is reserved for this field in the RPS.
+  if (isFieldCoding)
+  {
+    rps = rpsList->getReferencePictureSet(getGOPSize()+m_extraRPSs);
+    rps->setNumberOfPictures(1);
+    rps->setNumberOfNegativePictures(1);
+    rps->setNumberOfPositivePictures(0);
+    rps->setNumberOfLongtermPictures(0);
+    rps->setDeltaPOC(0,-1);
+    rps->setPOC(0,0);
+    rps->setUsed(0,true);
+    rps->setInterRPSPrediction(false);
+    rps->setDeltaRIdxMinus1(0);
+    rps->setDeltaRPS(0);
+    rps->setNumRefIdc(0);
+  }
+}
+
+   // This is a function that
+   // determines what Reference Picture Set to use
+   // for a specific slice (with POC = POCCurr)
+Void TEncTop::selectReferencePictureSet(TComSlice* slice, Int POCCurr, Int GOPid )
+{
+  slice->setRPSidx(GOPid);
+
+  for(Int extraNum=m_iGOPSize; extraNum<m_extraRPSs+m_iGOPSize; extraNum++)
+  {
+    if(m_uiIntraPeriod > 0 && getDecodingRefreshType() > 0)
+    {
+      Int POCIndex = POCCurr%m_uiIntraPeriod;
+      if(POCIndex == 0)
+      {
+        POCIndex = m_uiIntraPeriod;
+      }
+      if(POCIndex == m_GOPList[extraNum].m_POC)
+      {
+        slice->setRPSidx(extraNum);
+      }
+    }
+    else
+    {
+      if(POCCurr==m_GOPList[extraNum].m_POC)
+      {
+        slice->setRPSidx(extraNum);
+      }
+    }
+  }
+
+  if(POCCurr == 1 && slice->getPic()->isField())
+  {
+    slice->setRPSidx(m_iGOPSize+m_extraRPSs);
+  }
+
+  slice->setRPS(getSPS()->getRPSList()->getReferencePictureSet(slice->getRPSidx()));
+  slice->getRPS()->setNumberOfPictures(slice->getRPS()->getNumberOfNegativePictures()+slice->getRPS()->getNumberOfPositivePictures());
+}
+
+Int TEncTop::getReferencePictureSetIdxForSOP(TComSlice* slice, Int POCCurr, Int GOPid )
+{
+  Int rpsIdx = GOPid;
+
+  for(Int extraNum=m_iGOPSize; extraNum<m_extraRPSs+m_iGOPSize; extraNum++)
+  {
+    if(m_uiIntraPeriod > 0 && getDecodingRefreshType() > 0)
+    {
+      Int POCIndex = POCCurr%m_uiIntraPeriod;
+      if(POCIndex == 0)
+      {
+        POCIndex = m_uiIntraPeriod;
+      }
+      if(POCIndex == m_GOPList[extraNum].m_POC)
+      {
+        rpsIdx = extraNum;
+      }
+    }
+    else
+    {
+      if(POCCurr==m_GOPList[extraNum].m_POC)
+      {
+        rpsIdx = extraNum;
+      }
+    }
+  }
+
+  return rpsIdx;
+}
+
+Void  TEncTop::xInitPPSforTiles()
+{
+  m_cPPS.setTileUniformSpacingFlag( m_tileUniformSpacingFlag );
+  m_cPPS.setNumTileColumnsMinus1( m_iNumColumnsMinus1 );
+  m_cPPS.setNumTileRowsMinus1( m_iNumRowsMinus1 );
+  if( !m_tileUniformSpacingFlag )
+  {
+    m_cPPS.setTileColumnWidth( m_tileColumnWidth );
+    m_cPPS.setTileRowHeight( m_tileRowHeight );
+  }
+  m_cPPS.setLoopFilterAcrossTilesEnabledFlag( m_loopFilterAcrossTilesEnabledFlag );
+
+  // # substreams is "per tile" when tiles are independent.
+  if (m_iWaveFrontSynchro )
+  {
+    m_cPPS.setNumSubstreams(m_iWaveFrontSubstreams * (m_iNumColumnsMinus1+1));
+  }
+  else
+  {
+    m_cPPS.setNumSubstreams((m_iNumRowsMinus1+1) * (m_iNumColumnsMinus1+1));
+  }
+}
+
+Void  TEncCfg::xCheckGSParameters()
+{
+  Int   iWidthInCU = ( m_iSourceWidth%g_uiMaxCUWidth ) ? m_iSourceWidth/g_uiMaxCUWidth + 1 : m_iSourceWidth/g_uiMaxCUWidth;
+  Int   iHeightInCU = ( m_iSourceHeight%g_uiMaxCUHeight ) ? m_iSourceHeight/g_uiMaxCUHeight + 1 : m_iSourceHeight/g_uiMaxCUHeight;
+  UInt  uiCummulativeColumnWidth = 0;
+  UInt  uiCummulativeRowHeight = 0;
+
+  //check the column relative parameters
+  if( m_iNumColumnsMinus1 >= (1<<(LOG2_MAX_NUM_COLUMNS_MINUS1+1)) )
+  {
+    printf( "The number of columns is larger than the maximum allowed number of columns.\n" );
+    exit( EXIT_FAILURE );
+  }
+
+  if( m_iNumColumnsMinus1 >= iWidthInCU )
+  {
+    printf( "The current picture can not have so many columns.\n" );
+    exit( EXIT_FAILURE );
+  }
+
+  if( m_iNumColumnsMinus1 && !m_tileUniformSpacingFlag )
+  {
+    for(Int i=0; i<m_iNumColumnsMinus1; i++)
+    {
+      uiCummulativeColumnWidth += m_tileColumnWidth[i];
+    }
+
+    if( uiCummulativeColumnWidth >= iWidthInCU )
+    {
+      printf( "The width of the column is too large.\n" );
+      exit( EXIT_FAILURE );
+    }
+  }
+
+  //check the row relative parameters
+  if( m_iNumRowsMinus1 >= (1<<(LOG2_MAX_NUM_ROWS_MINUS1+1)) )
+  {
+    printf( "The number of rows is larger than the maximum allowed number of rows.\n" );
+    exit( EXIT_FAILURE );
+  }
+
+  if( m_iNumRowsMinus1 >= iHeightInCU )
+  {
+    printf( "The current picture can not have so many rows.\n" );
+    exit( EXIT_FAILURE );
+  }
+
+  if( m_iNumRowsMinus1 && !m_tileUniformSpacingFlag )
+  {
+    for(Int i=0; i<m_iNumRowsMinus1; i++)
+      uiCummulativeRowHeight += m_tileRowHeight[i];
+
+    if( uiCummulativeRowHeight >= iHeightInCU )
+    {
+      printf( "The height of the row is too large.\n" );
+      exit( EXIT_FAILURE );
+    }
+  }
+}
+
+#if SVC_EXTENSION
+#if VPS_EXTN_DIRECT_REF_LAYERS
+TEncTop* TEncTop::getRefLayerEnc( UInt refLayerIdx )
+{
+  if( m_ppcTEncTop[m_cVPS.getLayerIdxInVps(m_layerId)]->getNumDirectRefLayers() <= 0 )
+  {
+    return (TEncTop *)getLayerEnc( 0 );
+  }
+
+  return (TEncTop *)getLayerEnc( m_cVPS.getLayerIdxInVps(m_cVPS.getRefLayerId( m_layerId, refLayerIdx )) );
+}
+#endif
+
+#if !REPN_FORMAT_IN_VPS
+Void TEncTop::xInitILRP()
+{
+  if(m_layerId>0)
+  {
+    g_bitDepthY     = m_cSPS.getBitDepthY();
+    g_bitDepthC     = m_cSPS.getBitDepthC();
+    g_uiMaxCUWidth  = m_cSPS.getMaxCUWidth();
+    g_uiMaxCUHeight = m_cSPS.getMaxCUHeight();
+    g_uiMaxCUDepth  = m_cSPS.getMaxCUDepth();
+    g_uiAddCUDepth  = max (0, m_cSPS.getLog2MinCodingBlockSize() - (Int)m_cSPS.getQuadtreeTULog2MinSize() );
+
+    Int  numReorderPics[MAX_TLAYER];
+    Window &conformanceWindow = m_cSPS.getConformanceWindow();
+    Window defaultDisplayWindow = m_cSPS.getVuiParametersPresentFlag() ? m_cSPS.getVuiParameters()->getDefaultDisplayWindow() : Window();
+
+    if (m_cIlpPic[0] == NULL)
+    {
+      for (Int j=0; j < m_numLayer; j++) // consider to set to NumDirectRefLayers[LayerIdInVps[nuh_layer_id]]
+      {
+        m_cIlpPic[j] = new  TComPic;
+#if AUXILIARY_PICTURES
+        m_cIlpPic[j]->create(m_iSourceWidth, m_iSourceHeight, m_chromaFormatIDC, g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth, conformanceWindow, defaultDisplayWindow, numReorderPics, &m_cSPS, true);
+#else
+        m_cIlpPic[j]->create(m_iSourceWidth, m_iSourceHeight, g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth, conformanceWindow, defaultDisplayWindow, numReorderPics, &m_cSPS, true);
+#endif
+        for (Int i=0; i<m_cIlpPic[j]->getPicSym()->getNumberOfCUsInFrame(); i++)
+        {
+          m_cIlpPic[j]->getPicSym()->getCU(i)->initCU(m_cIlpPic[j], i);
+        }
+      }
+    }
+  }
+}
+#else
+Void TEncTop::xInitILRP()
+{
+#if O0096_REP_FORMAT_INDEX
+  RepFormat *repFormat = m_cVPS.getVpsRepFormat( m_cSPS.getUpdateRepFormatFlag() ? m_cSPS.getUpdateRepFormatIndex() : m_cVPS.getVpsRepFormatIdx( m_cVPS.getLayerIdxInVps(m_layerId) ) );
+#else
+  RepFormat *repFormat = m_cVPS.getVpsRepFormat( m_cVPS.getVpsRepFormatIdx( m_cVPS.getLayerIdxInVps(m_layerId) ) );
+#endif
+  Int bitDepthY,bitDepthC,picWidth,picHeight;
+
+#if O0096_REP_FORMAT_INDEX
+  bitDepthY   = repFormat->getBitDepthVpsLuma();
+  bitDepthC   = repFormat->getBitDepthVpsChroma();
+  picWidth    = repFormat->getPicWidthVpsInLumaSamples();
+  picHeight   = repFormat->getPicHeightVpsInLumaSamples();
+#else
+  if( m_cSPS.getUpdateRepFormatFlag() )
+  {
+    bitDepthY   = m_cSPS.getBitDepthY();
+    bitDepthC   = m_cSPS.getBitDepthC();
+    picWidth    = m_cSPS.getPicWidthInLumaSamples();
+    picHeight   = m_cSPS.getPicHeightInLumaSamples();
+  }
+  else
+  {
+    bitDepthY   = repFormat->getBitDepthVpsLuma();
+    bitDepthC   = repFormat->getBitDepthVpsChroma();
+    picWidth    = repFormat->getPicWidthVpsInLumaSamples();
+    picHeight   = repFormat->getPicHeightVpsInLumaSamples();
+  }
+#endif
+  
+  if(m_layerId > 0)
+  {
+    g_bitDepth[CHANNEL_TYPE_LUMA]   = bitDepthY;
+    g_bitDepth[CHANNEL_TYPE_CHROMA] = bitDepthC;
+    g_uiMaxCUWidth  = m_cSPS.getMaxCUWidth();
+    g_uiMaxCUHeight = m_cSPS.getMaxCUHeight();
+    g_uiMaxCUDepth  = m_cSPS.getMaxCUDepth();
+    g_uiAddCUDepth  = max (0, m_cSPS.getLog2MinCodingBlockSize() - (Int)m_cSPS.getQuadtreeTULog2MinSize() );
+
+    Int  numReorderPics[MAX_TLAYER];
+#if R0156_CONF_WINDOW_IN_REP_FORMAT
+    Window &conformanceWindow = repFormat->getConformanceWindowVps();
+#else
+    Window &conformanceWindow = m_cSPS.getConformanceWindow();
+#endif
+    Window defaultDisplayWindow = m_cSPS.getVuiParametersPresentFlag() ? m_cSPS.getVuiParameters()->getDefaultDisplayWindow() : Window();
+
+    if (m_cIlpPic[0] == NULL)
+    {
+      for (Int j=0; j < m_numDirectRefLayers; j++)
+      {
+        m_cIlpPic[j] = new TComPic;
+#if AUXILIARY_PICTURES
+        m_cIlpPic[j]->create(picWidth, picHeight, m_chromaFormatIDC, g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth, conformanceWindow, defaultDisplayWindow, numReorderPics, &m_cSPS, true);
+#else
+        m_cIlpPic[j]->create(picWidth, picHeight, g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth, conformanceWindow, defaultDisplayWindow, numReorderPics, &m_cSPS, true);
+#endif
+        for (Int i=0; i<m_cIlpPic[j]->getPicSym()->getNumberOfCtusInFrame(); i++)
+        {
+          m_cIlpPic[j]->getPicSym()->getCtu(i)->initCtu(m_cIlpPic[j], i);
+        }
+      }
+    }
+
+#if P0182_VPS_VUI_PS_FLAG
+    if( m_cVPS.getNumRefLayers( m_layerId ) == 0 )
+    {
+      UInt layerIdx = m_cVPS.getLayerIdxInVps( m_layerId );
+      RepFormat* repFmt = m_cVPS.getVpsRepFormat(m_cVPS.getVpsRepFormatIdx(layerIdx));
+      
+      if( m_cPPS.getLayerId() == 0 && 
+          m_cSPS.getLayerId() == 0 &&
+          repFmt->getChromaFormatVpsIdc() == m_cSPS.getChromaFormatIdc() &&
+          repFmt->getSeparateColourPlaneVpsFlag() == 0 &&
+          repFmt->getPicHeightVpsInLumaSamples() == m_cSPS.getPicHeightInLumaSamples() &&
+          repFmt->getPicWidthVpsInLumaSamples()  == m_cSPS.getPicWidthInLumaSamples() &&
+          repFmt->getBitDepthVpsLuma()   == m_cSPS.getBitDepth(CHANNEL_TYPE_LUMA) &&
+          repFmt->getBitDepthVpsChroma() == m_cSPS.getBitDepth(CHANNEL_TYPE_CHROMA) &&
+          repFmt->getConformanceWindowVps().getWindowLeftOffset()   == m_cSPS.getConformanceWindow().getWindowLeftOffset() &&
+          repFmt->getConformanceWindowVps().getWindowRightOffset()  == m_cSPS.getConformanceWindow().getWindowRightOffset() &&
+          repFmt->getConformanceWindowVps().getWindowTopOffset()    == m_cSPS.getConformanceWindow().getWindowTopOffset() &&
+          repFmt->getConformanceWindowVps().getWindowBottomOffset() == m_cSPS.getConformanceWindow().getWindowBottomOffset() )
+      {
+        m_cVPS.setBaseLayerPSCompatibilityFlag(layerIdx, 1);
+      }
+      else
+      {
+        m_cVPS.setBaseLayerPSCompatibilityFlag(layerIdx, 0);
+      }
+    }
+#endif
+  }
+}
+#endif
+
+#if O0098_SCALED_REF_LAYER_ID
+Window& TEncTop::getScaledRefLayerWindowForLayer(Int layerId)
+{
+  static Window win;
+
+  for (Int i = 0; i < m_numRefLayerLocationOffsets; i++)
+  {
+    if (layerId == m_refLocationOffsetLayerId[i])
+    {
+      return m_scaledRefLayerWindow[i];
+    }
+  }
+
+  win.resetWindow();  // scaled reference layer offsets are inferred to be zero when not present
+  return win;
+}
+#if REF_REGION_OFFSET
+Window& TEncTop::getRefLayerWindowForLayer(Int layerId)
+{
+  static Window win;
+
+  for (Int i = 0; i < m_numRefLayerLocationOffsets; i++)
+  {
+    if (layerId == m_refLayerId[i])
+    {
+      return m_refLayerWindow[i];
+    }
+  }
+
+  win.resetWindow();  // reference offsets are inferred to be zero when not present
+  return win;
+}
+#endif
+#endif
+#endif //SVC_EXTENSION
+//! \}
Index: /tags/SHM-9.0/source/Lib/TLibEncoder/TEncTop.h
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibEncoder/TEncTop.h	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibEncoder/TEncTop.h	(revision 1088)
@@ -0,0 +1,323 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TEncTop.h
+    \brief    encoder class (header)
+*/
+
+#ifndef __TENCTOP__
+#define __TENCTOP__
+
+// Include files
+#include "TLibCommon/TComList.h"
+#include "TLibCommon/TComPrediction.h"
+#include "TLibCommon/TComTrQuant.h"
+#include "TLibCommon/TComLoopFilter.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
+
+  // 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
+
+  // 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
+  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
+
+  // 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 SVC_EXTENSION
+  static Int              m_iSPSIdCnt;                    ///< next Id number for SPS    
+  static Int              m_iPPSIdCnt;                    ///< next Id number for PPS    
+  TEncTop**               m_ppcTEncTop;
+  TEncTop*                getLayerEnc(UInt layerIdx)       { return m_ppcTEncTop[layerIdx]; }
+  TComPic*                m_cIlpPic[MAX_NUM_REF];                    ///<  Inter layer Prediction picture =  upsampled picture 
+#if REF_IDX_MFM
+  Bool                    m_bMFMEnabledFlag;
+#endif
+  UInt                    m_numRefLayerLocationOffsets;
+#if O0098_SCALED_REF_LAYER_ID
+  UInt                    m_refLocationOffsetLayerId[MAX_LAYERS];
+#endif
+  Window                  m_scaledRefLayerWindow[MAX_LAYERS];
+#if REF_REGION_OFFSET
+  UInt                    m_numRefLayerOffsets;
+  UInt                    m_refLayerId[MAX_LAYERS];
+  Window                  m_refLayerWindow[MAX_LAYERS];
+  Bool                    m_scaledRefLayerOffsetPresentFlag[MAX_LAYERS];
+  Bool                    m_refRegionOffsetPresentFlag[MAX_LAYERS];
+#endif
+#if R0209_GENERIC_PHASE
+  Int                     m_phaseHorLuma  [MAX_LAYERS];
+  Int                     m_phaseVerLuma  [MAX_LAYERS];
+  Int                     m_phaseHorChroma[MAX_LAYERS];
+  Int                     m_phaseVerChroma[MAX_LAYERS];
+  Int                     m_resamplePhaseSetPresentFlag[MAX_LAYERS];
+#endif
+#if P0312_VERT_PHASE_ADJ
+  Bool                    m_vertPhasePositionEnableFlag[MAX_LAYERS];
+#endif
+#if POC_RESET_FLAG || POC_RESET_IDC_ENCODER
+  Int                     m_pocAdjustmentValue;
+#endif
+#if NO_CLRAS_OUTPUT_FLAG
+  Bool                    m_noClrasOutputFlag;
+  Bool                    m_layerInitializedFlag;
+  Bool                    m_firstPicInLayerDecodedFlag;
+  Bool                    m_noOutputOfPriorPicsFlags;
+#endif
+#if O0194_WEIGHTED_PREDICTION_CGS
+  Bool                    m_interLayerWeightedPredFlag;
+#endif
+#if Q0078_ADD_LAYER_SETS
+  int                     m_numAddLayerSets;
+#endif
+#if P0297_VPS_POC_LSB_ALIGNED_FLAG
+  Bool                    m_pocDecrementedInDPBFlag;
+  Int                     m_currPocMsb;
+#endif
+#if R0071_IRAP_EOS_CROSS_LAYER_IMPACTS
+  Bool                    m_prevPicHasEos;
+#endif
+#endif //SVC_EXTENSION
+protected:
+  Void  xGetNewPicBuffer  ( TComPic*& rpcPic );           ///< get picture buffer which will be processed
+  Void  xInitSPS          ();                             ///< initialize SPS from encoder options
+  Void  xInitPPS          ();                             ///< initialize PPS from encoder options
+
+  Void  xInitPPSforTiles  ();
+  Void  xInitRPS          (Bool isFieldCoding);           ///< initialize PPS from encoder options
+#if SVC_EXTENSION
+  Void  xInitILRP();
+#endif
+public:
+  TEncTop();
+  virtual ~TEncTop();
+
+  Void      create          ();
+  Void      destroy         ();
+  Void      init            (Bool isFieldCoding);
+  Void      deletePicBuffer ();
+
+  // -------------------------------------------------------------------------------------------------------------------
+  // 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;       }
+
+  TComRdCost*             getRdCost             () { return  &m_cRdCost;              }
+  TEncSbac***             getRDSbacCoder        () { return  m_pppcRDSbacCoder;       }
+  TEncSbac*               getRDGoOnSbacCoder    () { return  &m_cRDGoOnSbacCoder;     }
+  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;         }
+  // -------------------------------------------------------------------------------------------------------------------
+  // encoder function
+  // -------------------------------------------------------------------------------------------------------------------
+
+  /// encode several number of pictures until end-of-sequence
+#if SVC_EXTENSION
+  Void      setLayerEnc(TEncTop** p)            { m_ppcTEncTop = p;                  }
+  TEncTop** getLayerEnc()                       { return m_ppcTEncTop;               }
+  Int       getPOCLast            ()            { return m_iPOCLast;                 }
+  Int       getNumPicRcvd         ()            { return m_iNumPicRcvd;              }
+  Void      setNumPicRcvd         ( Int num )   { m_iNumPicRcvd = num;               }
+  Void      setNumRefLayerLocationOffsets(Int x)  { m_numRefLayerLocationOffsets = x;    }
+  UInt      getNumRefLayerLocationOffsets()       { return m_numRefLayerLocationOffsets; }
+#if O0098_SCALED_REF_LAYER_ID
+  Void      setRefLocationOffsetLayerId(Int x, UInt id) { m_refLocationOffsetLayerId[x] = id;   }
+  UInt      getRefLocationOffsetLayerId(Int x)          { return m_refLocationOffsetLayerId[x]; }
+  Window&   getScaledRefLayerWindowForLayer(Int layerId);
+#endif
+  Window&   getScaledRefLayerWindow(Int x)                 { return m_scaledRefLayerWindow[x];        }
+#if REF_REGION_OFFSET
+  Void      setNumRefLayerOffsets(Int x) { m_numRefLayerOffsets = x; }
+  UInt      getNumRefLayerOffsets() { return m_numRefLayerOffsets; }
+  Void      setRefLayerId(Int layerIdx, UInt layerId)     { m_refLayerId[layerIdx] = layerId;  }
+  UInt      getRefLayerId(Int layerIdx)                   { return m_refLayerId[layerIdx];     }
+  Window&   getRefLayerWindowForLayer(Int layerId);
+  Window&   getRefLayerWindow(Int x)            { return m_refLayerWindow[x]; }
+  Bool      getScaledRefLayerOffsetPresentFlag(Int x) { return m_scaledRefLayerOffsetPresentFlag[x]; }
+  Void      setScaledRefLayerOffsetPresentFlag(Int x, Bool b) { m_scaledRefLayerOffsetPresentFlag[x] = b; }
+  Bool      getRefRegionOffsetPresentFlag(Int x) { return m_refRegionOffsetPresentFlag[x]; }
+  Void      setRefRegionOffsetPresentFlag(Int x, Bool b) { m_refRegionOffsetPresentFlag[x] = b; }
+#endif
+#if P0312_VERT_PHASE_ADJ
+  Void      setVertPhasePositionEnableFlag(Int x, Bool b)  { m_vertPhasePositionEnableFlag[x] = b;    }
+  UInt      getVertPhasePositionEnableFlag(Int x)          { return m_vertPhasePositionEnableFlag[x]; }
+#endif
+#if R0209_GENERIC_PHASE
+  Int       getPhaseHorLuma(Int x) { return m_phaseHorLuma[x]; }
+  Int       getPhaseVerLuma(Int x) { return m_phaseVerLuma[x]; }
+  Int       getPhaseHorChroma(Int x) { return m_phaseHorChroma[x]; }
+  Int       getPhaseVerChroma(Int x) { return m_phaseVerChroma[x]; }
+  Void      setPhaseHorLuma(Int x, Int val) { m_phaseHorLuma[x] = val; }
+  Void      setPhaseVerLuma(Int x, Int val) { m_phaseVerLuma[x] = val; }
+  Void      setPhaseHorChroma(Int x, Int val) { m_phaseHorChroma[x] = val; }
+  Void      setPhaseVerChroma(Int x, Int val) { m_phaseVerChroma[x] = val; }
+  Bool      getResamplePhaseSetPresentFlag(Int x) { return m_resamplePhaseSetPresentFlag[x]; }
+  Void      setResamplePhaseSetPresentFlag(Int x, Bool b) { m_resamplePhaseSetPresentFlag[x] = b; }
+#endif
+
+  TComPic** getIlpList() { return m_cIlpPic; }
+#if REF_IDX_MFM
+  Void      setMFMEnabledFlag       (Bool flag)   { m_bMFMEnabledFlag = flag; }
+  Bool      getMFMEnabledFlag()                   { return m_bMFMEnabledFlag; }    
+#endif
+#if O0194_WEIGHTED_PREDICTION_CGS
+  Void      setInterLayerWeightedPredFlag(Bool flag)   { m_interLayerWeightedPredFlag = flag; }
+  Bool      getInterLayerWeightedPredFlag()            { return m_interLayerWeightedPredFlag; }
+#endif
+  Void      encode    ( TComPicYuv* pcPicYuvOrg, const InputColourSpaceConversion snrCSC, TComList<TComPicYuv*>& rcListPicYuvRecOut, std::list<AccessUnit>& accessUnitsOut, Int iPicIdInGOP );
+  Void      encodePrep( TComPicYuv* pcPicYuvOrg, TComPicYuv* pcPicYuvTrueOrg );
+  Void      encode    ( TComPicYuv* pcPicYuvOrg, const InputColourSpaceConversion snrCSC, TComList<TComPicYuv*>& rcListPicYuvRecOut, std::list<AccessUnit>& accessUnitsOut, Int iPicIdInGOP, Bool isTff );
+  Void      encodePrep( TComPicYuv* pcPicYuvOrg, TComPicYuv* pcPicYuvTrueOrg, Bool isTff );
+#if VPS_EXTN_DIRECT_REF_LAYERS
+  TEncTop*  getRefLayerEnc(UInt refLayerIdx);
+#endif
+#if POC_RESET_FLAG || POC_RESET_IDC_ENCODER
+  Int       getPocAdjustmentValue()      { return m_pocAdjustmentValue;}
+  Void      setPocAdjustmentValue(Int x) { m_pocAdjustmentValue = x;   }
+#endif
+#if NO_CLRAS_OUTPUT_FLAG
+  Int       getNoClrasOutputFlag()                { return m_noClrasOutputFlag;}
+  Void      setNoClrasOutputFlag(Bool x)          { m_noClrasOutputFlag = x;   }
+  Int       getLayerInitializedFlag()             { return m_layerInitializedFlag;}
+  Void      setLayerInitializedFlag(Bool x)       { m_layerInitializedFlag = x;   }
+  Int       getFirstPicInLayerDecodedFlag()       { return m_firstPicInLayerDecodedFlag;}
+  Void      setFirstPicInLayerDecodedFlag(Bool x) { m_firstPicInLayerDecodedFlag = x;   }
+  Int       getNoOutputOfPriorPicsFlags()         { return m_noOutputOfPriorPicsFlags;}
+  Void      setNoOutputOfPriorPicsFlags(Bool x)   { m_noOutputOfPriorPicsFlags = x;   }
+#endif
+#if Q0078_ADD_LAYER_SETS
+  Void      setNumAddLayerSets(Int x)             { m_numAddLayerSets = x; }
+  Int       getNumAddLayerSets()                  { return m_numAddLayerSets; }
+#endif
+#if P0297_VPS_POC_LSB_ALIGNED_FLAG
+  Void      setPocDecrementedInDPBFlag(Bool x)    { m_pocDecrementedInDPBFlag = x; }
+  Bool      getPocDecrementedInDPBFlag()          { return m_pocDecrementedInDPBFlag; }
+  Void      setCurrPocMsb(Int poc)                { m_currPocMsb = poc; }
+  Int       getCurrPocMsb()                       { return m_currPocMsb; }
+#endif
+#else //SVC_EXTENSION
+  Void encode( Bool bEos,
+               TComPicYuv* pcPicYuvOrg,
+               TComPicYuv* pcPicYuvTrueOrg, const InputColourSpaceConversion snrCSC, // used for SNR calculations. Picture in original colour space.
+               TComList<TComPicYuv*>& rcListPicYuvRecOut,
+               std::list<AccessUnit>& accessUnitsOut, Int& iNumEncoded );
+
+  /// encode several number of pictures until end-of-sequence
+  Void encode( Bool bEos, TComPicYuv* pcPicYuvOrg,
+               TComPicYuv* pcPicYuvTrueOrg, const InputColourSpaceConversion snrCSC, // used for SNR calculations. Picture in original colour space.
+               TComList<TComPicYuv*>& rcListPicYuvRecOut,
+               std::list<AccessUnit>& accessUnitsOut, Int& iNumEncoded, Bool isTff);
+
+  Void printSummary(Bool isField) { m_cGOPEncoder.printOutSummary (m_uiNumAllPicCoded, isField, m_printMSEBasedSequencePSNR, m_printSequenceMSE); }
+#endif //#if SVC_EXTENSION
+};
+
+//! \}
+
+#endif // __TENCTOP__
+
Index: /tags/SHM-9.0/source/Lib/TLibEncoder/WeightPredAnalysis.cpp
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibEncoder/WeightPredAnalysis.cpp	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibEncoder/WeightPredAnalysis.cpp	(revision 1088)
@@ -0,0 +1,436 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     WeightPredAnalysis.cpp
+    \brief    weighted prediction encoder class
+*/
+
+#include "../TLibCommon/TypeDef.h"
+#include "../TLibCommon/TComSlice.h"
+#include "../TLibCommon/TComPic.h"
+#include "../TLibCommon/TComPicYuv.h"
+#include "WeightPredAnalysis.h"
+
+#define ABS(a)    ((a) < 0 ? - (a) : (a))
+#define DTHRESH (0.99)
+
+WeightPredAnalysis::WeightPredAnalysis()
+{
+  m_weighted_pred_flag = false;
+  m_weighted_bipred_flag = false;
+
+  for ( UInt lst =0 ; lst<NUM_REF_PIC_LIST_01 ; lst++ )
+  {
+    for ( Int iRefIdx=0 ; iRefIdx<MAX_NUM_REF ; iRefIdx++ )
+    {
+      for ( Int comp=0 ; comp<MAX_NUM_COMPONENT ;comp++ )
+      {
+        WPScalingParam  *pwp   = &(m_wp[lst][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
+ */
+Void WeightPredAnalysis::xCalcACDCParamSlice(TComSlice *const slice)
+{
+  //===== calculate AC/DC value =====
+  TComPicYuv*   pPic = slice->getPic()->getPicYuvOrg();
+
+  WPACDCParam weightACDCParam[MAX_NUM_COMPONENT];
+
+  for(Int componentIndex = 0; componentIndex < pPic->getNumberValidComponents(); componentIndex++)
+  {
+    const ComponentID compID = ComponentID(componentIndex);
+
+    // calculate DC/AC value for channel
+
+    const Int iStride = pPic->getStride(compID);
+    const Int iWidth  = pPic->getWidth(compID);
+    const Int iHeight = pPic->getHeight(compID);
+
+    const Int iSample = iWidth*iHeight;
+
+    Int64 iOrgDC = 0;
+    {
+      const Pel *pPel = pPic->getAddr(compID);
+
+      for(Int y = 0; y < iHeight; y++, pPel+=iStride )
+        for(Int x = 0; x < iWidth; x++ )
+          iOrgDC += (Int)( pPel[x] );
+    }
+
+    const Int64 iOrgNormDC = ((iOrgDC+(iSample>>1)) / iSample);
+
+    Int64 iOrgAC = 0;
+    {
+      const Pel *pPel = pPic->getAddr(compID);
+
+      for(Int y = 0; y < iHeight; y++, pPel += iStride )
+        for(Int x = 0; x < iWidth; x++ )
+          iOrgAC += abs( (Int)pPel[x] - (Int)iOrgNormDC );
+    }
+
+    const Int fixedBitShift = (slice->getSPS()->getUseHighPrecisionPredictionWeighting())?RExt__PREDICTION_WEIGHTING_ANALYSIS_DC_PRECISION:0;
+#if O0194_WEIGHTED_PREDICTION_CGS
+    weightACDCParam[compID].iSamples = iSample;
+#endif
+    weightACDCParam[compID].iDC = (((iOrgDC<<fixedBitShift)+(iSample>>1)) / iSample);
+    weightACDCParam[compID].iAC = iOrgAC;
+  }
+
+  slice->setWpAcDcParam(weightACDCParam);
+}
+
+
+/** store weighted_pred_flag and weighted_bipred_idc values
+ * \param weighted_pred_flag
+ * \param weighted_bipred_idc
+ * \returns Void
+ */
+Void  WeightPredAnalysis::xStoreWPparam(const Bool weighted_pred_flag, const 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 *const 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 *const slice)
+{
+  const TComPicYuv *pPic = slice->getPic()->getPicYuvOrg();
+
+  Int iPresentCnt = 0;
+  for ( UInt lst=0 ; lst<NUM_REF_PIC_LIST_01 ; lst++ )
+  {
+    for ( Int iRefIdx=0 ; iRefIdx<MAX_NUM_REF ; iRefIdx++ )
+    {
+      for(Int componentIndex = 0; componentIndex < pPic->getNumberValidComponents(); componentIndex++)
+      {
+        WPScalingParam  *pwp = &(m_wp[lst][iRefIdx][componentIndex]);
+        iPresentCnt += (Int)pwp->bPresentFlag;
+      }
+    }
+  }
+
+  if(iPresentCnt==0)
+  {
+    slice->getPPS()->setUseWP(false);
+    slice->getPPS()->setWPBiPred(false);
+
+    for ( UInt lst=0 ; lst<NUM_REF_PIC_LIST_01 ; lst++ )
+    {
+      for ( Int iRefIdx=0 ; iRefIdx<MAX_NUM_REF ; iRefIdx++ )
+      {
+        for(Int componentIndex = 0; componentIndex < pPic->getNumberValidComponents(); componentIndex++)
+        {
+          WPScalingParam  *pwp = &(m_wp[lst][iRefIdx][componentIndex]);
+
+          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
+ */
+Void WeightPredAnalysis::xEstimateWPParamSlice(TComSlice *const slice)
+{
+  Int  iDenom         = 6;
+  Bool validRangeFlag = false;
+
+  if(slice->getNumRefIdx(REF_PIC_LIST_0)>3)
+  {
+    iDenom = 7;
+  }
+
+  do
+  {
+    validRangeFlag = xUpdatingWPParameters(slice, iDenom);
+    if (!validRangeFlag)
+    {
+      iDenom--; // decrement to satisfy the range limitation
+    }
+  } while (validRangeFlag == false);
+
+  // selecting whether WP is used, or not
+  xSelectWP(slice, iDenom);
+
+  slice->setWpScaling( m_wp );
+}
+
+
+/** update wp tables for explicit wp w.r.t ramge limitation
+ * \param TComSlice *slice
+ * \returns Bool
+ */
+Bool WeightPredAnalysis::xUpdatingWPParameters(TComSlice *const slice, const Int log2Denom)
+{
+  const Int  numComp                    = slice->getPic()->getPicYuvOrg()->getNumberValidComponents();
+  const Bool bUseHighPrecisionWeighting = slice->getSPS()->getUseHighPrecisionPredictionWeighting();
+  const Int numPredDir                  = slice->isInterP() ? 1 : 2;
+
+  assert (numPredDir <= Int(NUM_REF_PIC_LIST_01));
+
+  for ( Int refList = 0; refList < numPredDir; refList++ )
+  {
+    const 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);
+
+#if O0194_WEIGHTED_PREDICTION_CGS
+      UInt currLayerId = slice->getLayerId();
+      UInt refLayerId  = slice->getRefPic(eRefPicList, refIdxTemp)->getLayerId();
+      Bool validILRPic = slice->getRefPic(eRefPicList, refIdxTemp)->isILR( currLayerId ) && refLayerId == 0;
+
+      if( validILRPic )
+      {
+        refWeightACDCParam = (WPACDCParam *)g_refWeightACDCParam;
+      }
+#endif
+
+      for ( Int comp = 0; comp < numComp; comp++ )
+      {
+        const ComponentID compID        = ComponentID(comp);
+        const Int         range         = bUseHighPrecisionWeighting ? (1<<g_bitDepth[toChannelType(compID)])/2 : 128;
+        const Int         realLog2Denom = log2Denom + (bUseHighPrecisionWeighting ? RExt__PREDICTION_WEIGHTING_ANALYSIS_DC_PRECISION : (g_bitDepth[toChannelType(compID)] - 8));
+        const Int         realOffset    = ((Int)1<<(realLog2Denom-1));
+
+        // current frame
+        const Int64 currDC = currWeightACDCParam[comp].iDC;
+        const Int64 currAC = currWeightACDCParam[comp].iAC;
+        // reference frame
+#if O0194_WEIGHTED_PREDICTION_CGS
+        Int64 refDC  = refWeightACDCParam[comp].iDC;
+        Int64 refAC  = refWeightACDCParam[comp].iAC;
+
+        if( validILRPic )
+        {
+          refAC = ( refAC * currWeightACDCParam[comp].iSamples ) /refWeightACDCParam[comp].iSamples;
+#if O0194_JOINT_US_BITSHIFT
+          refAC <<= (g_bitDepthLayer[CHANNEL_TYPE_LUMA][currLayerId] - g_bitDepthLayer[CHANNEL_TYPE_LUMA][refLayerId]);
+          refDC <<= (g_bitDepthLayer[CHANNEL_TYPE_LUMA][currLayerId] - g_bitDepthLayer[CHANNEL_TYPE_LUMA][refLayerId]);
+#endif
+        }
+#else
+        const Int64 refDC  = refWeightACDCParam[comp].iDC;
+        const Int64 refAC  = refWeightACDCParam[comp].iAC;
+#endif
+
+        // calculating iWeight and iOffset params
+#if O0194_WEIGHTED_PREDICTION_CGS
+        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 );
+
+        if( !validILRPic )
+        {
+          dWeight = 1;
+          offset  = 0;
+        }
+        weight = (Int)( 0.5 + dWeight * (Double)(1<<log2Denom) );
+#else
+        const Double dWeight = (refAC==0) ? (Double)1.0 : Clip3( -16.0, 15.0, ((Double)currAC / (Double)refAC) );
+        const Int weight     = (Int)( 0.5 + dWeight * (Double)(1<<log2Denom) );
+        const Int offset     = (Int)( ((currDC<<log2Denom) - ((Int64)weight * refDC) + (Int64)realOffset) >> realLog2Denom );
+#endif
+
+        Int clippedOffset;
+        if(isChroma(compID)) // Chroma offset range limination
+        {
+          const Int pred        = ( range - ( ( range*weight)>>(log2Denom) ) );
+          const Int deltaOffset = Clip3( -4*range, 4*range-1, (offset - pred) ); // signed 10bit
+
+          clippedOffset = Clip3( -range, range-1, (deltaOffset + pred) );  // signed 8bit
+        }
+        else // Luma offset range limitation
+        {
+          clippedOffset = Clip3( -range, range-1, offset);
+        }
+
+        // Weighting factor limitation
+        const Int defaultWeight = (1<<log2Denom);
+        const Int deltaWeight   = (defaultWeight - weight);
+
+        if(deltaWeight >= range || deltaWeight < -range)
+          return false;
+
+#if O0194_WEIGHTED_PREDICTION_CGS
+        // make sure the reference frames other than ILR are not using weighted prediction
+        else
+        if( !validILRPic )
+        {
+          continue;
+        }
+#endif
+
+        m_wp[refList][refIdxTemp][comp].bPresentFlag      = true;
+        m_wp[refList][refIdxTemp][comp].iWeight           = weight;
+        m_wp[refList][refIdxTemp][comp].iOffset           = clippedOffset;
+        m_wp[refList][refIdxTemp][comp].uiLog2WeightDenom = log2Denom;
+      }
+    }
+  }
+  return true;
+}
+
+
+/** select whether weighted pred enables or not.
+ * \param TComSlice *slice
+ * \param log2Denom
+ * \returns Bool
+ */
+Bool WeightPredAnalysis::xSelectWP(TComSlice *const slice, const Int log2Denom)
+{
+        TComPicYuv *const pPic                                = slice->getPic()->getPicYuvOrg();
+  const Int               iDefaultWeight                      = ((Int)1<<log2Denom);
+  const Int               iNumPredDir                         = slice->isInterP() ? 1 : 2;
+  const Bool              useHighPrecisionPredictionWeighting = slice->getSPS()->getUseHighPrecisionPredictionWeighting();
+
+  assert (iNumPredDir <= Int(NUM_REF_PIC_LIST_01));
+
+  for ( Int iRefList = 0; iRefList < iNumPredDir; iRefList++ )
+  {
+    const RefPicList eRefPicList = ( iRefList ? REF_PIC_LIST_1 : REF_PIC_LIST_0 );
+
+    for ( Int iRefIdxTemp = 0; iRefIdxTemp < slice->getNumRefIdx(eRefPicList); iRefIdxTemp++ )
+    {
+      Int64 iSADWP = 0, iSADnoWP = 0;
+
+      for(Int comp=0; comp<pPic->getNumberValidComponents(); comp++)
+      {
+        const ComponentID  compID     = ComponentID(comp);
+              Pel         *pOrg       = pPic->getAddr(compID);
+              Pel         *pRef       = slice->getRefPic(eRefPicList, iRefIdxTemp)->getPicYuvRec()->getAddr(compID);
+        const Int          iOrgStride = pPic->getStride(compID);
+        const Int          iRefStride = slice->getRefPic(eRefPicList, iRefIdxTemp)->getPicYuvRec()->getStride(compID);
+        const Int          iWidth     = pPic->getWidth(compID);
+        const Int          iHeight    = pPic->getHeight(compID);
+        const Int          bitDepth   = g_bitDepth[toChannelType(compID)];
+
+        // calculate SAD costs with/without wp for luma
+        iSADWP   += xCalcSADvalueWP(bitDepth, pOrg, pRef, iWidth, iHeight, iOrgStride, iRefStride, log2Denom, m_wp[iRefList][iRefIdxTemp][compID].iWeight, m_wp[iRefList][iRefIdxTemp][compID].iOffset, useHighPrecisionPredictionWeighting);
+        iSADnoWP += xCalcSADvalueWP(bitDepth, pOrg, pRef, iWidth, iHeight, iOrgStride, iRefStride, log2Denom, iDefaultWeight, 0, useHighPrecisionPredictionWeighting);
+      }
+
+      const Double dRatio = ((Double)iSADWP / (Double)iSADnoWP);
+      if(dRatio >= (Double)DTHRESH)
+      {
+        for(Int comp=0; comp<pPic->getNumberValidComponents(); comp++)
+        {
+          m_wp[iRefList][iRefIdxTemp][comp].bPresentFlag      = false;
+          m_wp[iRefList][iRefIdxTemp][comp].iOffset           = 0;
+          m_wp[iRefList][iRefIdxTemp][comp].iWeight           = iDefaultWeight;
+          m_wp[iRefList][iRefIdxTemp][comp].uiLog2WeightDenom = log2Denom;
+        }
+      }
+    }
+  }
+
+  return true;
+}
+
+
+/** 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 iLog2Denom
+ * \param Int iWeight
+ * \param Int iOffset
+ * \returns Int64
+ */
+Int64 WeightPredAnalysis::xCalcSADvalueWP(const Int   bitDepth,
+                                          const Pel  *pOrgPel,
+                                          const Pel  *pRefPel,
+                                          const Int   iWidth,
+                                          const Int   iHeight,
+                                          const Int   iOrgStride,
+                                          const Int   iRefStride,
+                                          const Int   iLog2Denom,
+                                          const Int   iWeight,
+                                          const Int   iOffset,
+                                          const Bool  useHighPrecisionPredictionWeighting)
+{
+  const Int64 iSize          = iWidth*iHeight;
+  const Int64 iRealLog2Denom = useHighPrecisionPredictionWeighting ? iLog2Denom : (iLog2Denom + (bitDepth - 8));
+
+  Int64 iSAD = 0;
+  for( Int y = 0; y < iHeight; y++ )
+  {
+    for( Int x = 0; x < iWidth; x++ )
+    {
+      iSAD += ABS(( ((Int64)pOrgPel[x]<<(Int64)iLog2Denom) - ( (Int64)pRefPel[x] * (Int64)iWeight + ((Int64)iOffset<<iRealLog2Denom) ) ) );
+    }
+    pOrgPel += iOrgStride;
+    pRefPel += iRefStride;
+  }
+
+  return (iSAD/iSize);
+}
Index: /tags/SHM-9.0/source/Lib/TLibEncoder/WeightPredAnalysis.h
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibEncoder/WeightPredAnalysis.h	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibEncoder/WeightPredAnalysis.h	(revision 1088)
@@ -0,0 +1,82 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     WeightPredAnalysis.h
+    \brief    weighted prediction encoder class
+*/
+#ifndef __WEIGHTPREDANALYSIS__
+#define __WEIGHTPREDANALYSIS__
+
+#include "../TLibCommon/TypeDef.h"
+#include "../TLibCommon/TComSlice.h"
+#include "TEncCavlc.h"
+
+class  WeightPredAnalysis
+{
+private:
+
+  // member variables
+  Bool            m_weighted_pred_flag;
+  Bool            m_weighted_bipred_flag;
+  WPScalingParam  m_wp[NUM_REF_PIC_LIST_01][MAX_NUM_REF][MAX_NUM_COMPONENT];
+
+  // member functions
+
+  Bool  xSelectWP            (TComSlice *const slice, const Int log2Denom);
+  Bool  xUpdatingWPParameters(TComSlice *const slice, const Int log2Denom);
+
+  Int64 xCalcSADvalueWP      (const Int   bitDepth,
+                              const Pel  *pOrgPel,
+                              const Pel  *pRefPel,
+                              const Int   iWidth,
+                              const Int   iHeight,
+                              const Int   iOrgStride,
+                              const Int   iRefStride,
+                              const Int   iLog2Denom,
+                              const Int   iWeight,
+                              const Int   iOffset,
+                              const Bool  useHighPrecisionPredictionWeighting);
+
+public:
+
+  WeightPredAnalysis();
+
+  // WP analysis :
+  Void  xCalcACDCParamSlice  (TComSlice *const slice);
+  Void  xEstimateWPParamSlice(TComSlice *const slice);
+  Void  xStoreWPparam        (const Bool weighted_pred_flag, const Bool weighted_bipred_flag);
+  Void  xRestoreWPparam      (TComSlice *const slice);
+  Void  xCheckWPEnable       (TComSlice *const slice);
+};
+
+#endif // __WEIGHTPREDANALYSIS__
Index: /tags/SHM-9.0/source/Lib/TLibVideoIO/TVideoIOYuv.cpp
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibVideoIO/TVideoIOYuv.cpp	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibVideoIO/TVideoIOYuv.cpp	(revision 1088)
@@ -0,0 +1,988 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TVideoIOYuv.cpp
+    \brief    YUV file I/O class
+*/
+
+#include <cstdlib>
+#include <fcntl.h>
+#include <assert.h>
+#include <sys/stat.h>
+#include <fstream>
+#include <iostream>
+#include <memory.h>
+
+#include "TLibCommon/TComRom.h"
+#include "TVideoIOYuv.h"
+
+using namespace std;
+
+// ====================================================================================================================
+// Local Functions
+// ====================================================================================================================
+
+/**
+ * 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, const UInt stride, const UInt width, const UInt height, Int shiftbits, Pel minval, Pel maxval)
+{
+  if (shiftbits > 0)
+  {
+    for (UInt y = 0; y < height; y++, img+=stride)
+      for (UInt x = 0; x < width; x++)
+        img[x] <<= shiftbits;
+  }
+  else if (shiftbits < 0)
+  {
+    shiftbits=-shiftbits;
+
+    Pel rounding = 1 << (shiftbits-1);
+    for (UInt y = 0; y < height; y++, img+=stride)
+      for (UInt x = 0; x < width; x++)
+        img[x] = Clip3(minval, maxval, Pel((img[x] + rounding) >> shiftbits));
+  }
+}
+
+
+// ====================================================================================================================
+// 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 fileBitDepth     bit-depth array of input/output file data.
+ * \param internalBitDepth bit-depth array to scale image data to/from when reading/writing.
+ */
+Void TVideoIOYuv::open( Char* pchFile, Bool bWriteMode, const Int fileBitDepth[MAX_NUM_CHANNEL_TYPE], const Int MSBExtendedBitDepth[MAX_NUM_CHANNEL_TYPE], const Int internalBitDepth[MAX_NUM_CHANNEL_TYPE] )
+{
+  //NOTE: files cannot have bit depth greater than 16
+  for(UInt ch=0; ch<MAX_NUM_CHANNEL_TYPE; ch++)
+  {
+    m_fileBitdepth       [ch] = std::min<UInt>(fileBitDepth[ch], 16);
+    m_MSBExtendedBitDepth[ch] = MSBExtendedBitDepth[ch];
+    m_bitdepthShift      [ch] = internalBitDepth[ch] - m_MSBExtendedBitDepth[ch];
+
+    if (m_fileBitdepth[ch] > 16)
+    {
+      if (bWriteMode)
+      {
+        std::cerr << "\nWARNING: Cannot write a yuv file of bit depth greater than 16 - output will be right-shifted down to 16-bit precision\n" << std::endl;
+      }
+      else
+      {
+        std::cerr << "\nERROR: Cannot read a yuv file of bit depth greater than 16\n" << std::endl;
+        exit(0);
+      }
+    }
+  }
+
+  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, ChromaFormat format)
+{
+  if (!numFrames)
+    return;
+
+  //------------------
+  //set the frame size according to the chroma format
+  streamoff frameSize = 0;
+  UInt wordsize=1; // default to 8-bit, unless a channel with more than 8-bits is detected.
+  for (UInt component = 0; component < getNumberValidComponents(format); component++)
+  {
+    ComponentID compID=ComponentID(component);
+    frameSize += (width >> getComponentScaleX(compID, format)) * (height >> getComponentScaleY(compID, format));
+    if (m_fileBitdepth[toChannelType(compID)] > 8) wordsize=2;
+  }
+  frameSize *= wordsize;
+  //------------------
+
+  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 streamoff 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 stride444,
+                      UInt width444,
+                      UInt height444,
+                      UInt pad_x444,
+                      UInt pad_y444,
+                      const ComponentID compID,
+                      const ChromaFormat destFormat,
+                      const ChromaFormat fileFormat,
+                      const UInt fileBitDepth)
+{
+  const UInt csx_file =getComponentScaleX(compID, fileFormat);
+  const UInt csy_file =getComponentScaleY(compID, fileFormat);
+  const UInt csx_dest =getComponentScaleX(compID, destFormat);
+  const UInt csy_dest =getComponentScaleY(compID, destFormat);
+
+  const UInt width_dest       = width444 >>csx_dest;
+  const UInt height_dest      = height444>>csy_dest;
+  const UInt pad_x_dest       = pad_x444>>csx_dest;
+  const UInt pad_y_dest       = pad_y444>>csy_dest;
+  const UInt stride_dest      = stride444>>csx_dest;
+
+  const UInt full_width_dest  = width_dest+pad_x_dest;
+  const UInt full_height_dest = height_dest+pad_y_dest;
+
+  const UInt stride_file      = (width444 * (is16bit ? 2 : 1)) >> csx_file;
+
+  UChar  *buf   = new UChar[stride_file];
+
+  if (compID!=COMPONENT_Y && (fileFormat==CHROMA_400 || destFormat==CHROMA_400))
+  {
+    if (destFormat!=CHROMA_400)
+    {
+      // set chrominance data to mid-range: (1<<(fileBitDepth-1))
+      const Pel value=Pel(1<<(fileBitDepth-1));
+      for (UInt y = 0; y < full_height_dest; y++, dst+=stride_dest)
+        for (UInt x = 0; x < full_width_dest; x++)
+          dst[x] = value;
+    }
+
+    if (fileFormat!=CHROMA_400)
+    {
+      const UInt height_file      = height444>>csy_file;
+      fd.seekg(height_file*stride_file, ios::cur);
+      if (fd.eof() || fd.fail() )
+      {
+        delete[] buf;
+        return false;
+      }
+    }
+  }
+  else
+  {
+    const UInt mask_y_file=(1<<csy_file)-1;
+    const UInt mask_y_dest=(1<<csy_dest)-1;
+    for(UInt y444=0; y444<height444; y444++)
+    {
+      if ((y444&mask_y_file)==0)
+      {
+        // read a new line
+        fd.read(reinterpret_cast<Char*>(buf), stride_file);
+        if (fd.eof() || fd.fail() )
+        {
+          delete[] buf;
+          return false;
+        }
+      }
+
+      if ((y444&mask_y_dest)==0)
+      {
+        // process current destination line
+        if (csx_file < csx_dest)
+        {
+          // eg file is 444, dest is 422.
+          const UInt sx=csx_dest-csx_file;
+          if (!is16bit)
+          {
+            for (UInt x = 0; x < width_dest; x++)
+              dst[x] = buf[x<<sx];
+          }
+          else
+          {
+            for (UInt x = 0; x < width_dest; x++)
+            {
+              dst[x] = Pel(buf[(x<<sx)*2+0]) | (Pel(buf[(x<<sx)*2+1])<<8);
+            }
+          }
+        }
+        else
+        {
+          // eg file is 422, dest is 444.
+          const UInt sx=csx_file-csx_dest;
+          if (!is16bit)
+          {
+            for (UInt x = 0; x < width_dest; x++)
+              dst[x] = buf[x>>sx];
+          }
+          else
+          {
+            for (UInt x = 0; x < width_dest; x++)
+              dst[x] = Pel(buf[(x>>sx)*2+0]) | (Pel(buf[(x>>sx)*2+1])<<8);
+          }
+        }
+
+        // process right hand side padding
+        const Pel val=dst[width_dest-1];
+        for (UInt x = width_dest; x < full_width_dest; x++)
+          dst[x] = val;
+
+        dst += stride_dest;
+      }
+    }
+
+    // process lower padding
+    for (UInt y = height_dest; y < full_height_dest; y++, dst+=stride_dest)
+      for (UInt x = 0; x < full_width_dest; x++)
+        dst[x] = (dst - stride_dest)[x];
+  }
+  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 stride444,
+                       UInt width444, UInt height444,
+                       const ComponentID compID,
+                       const ChromaFormat srcFormat,
+                       const ChromaFormat fileFormat,
+                       const UInt fileBitDepth)
+{
+  const UInt csx_file =getComponentScaleX(compID, fileFormat);
+  const UInt csy_file =getComponentScaleY(compID, fileFormat);
+  const UInt csx_src  =getComponentScaleX(compID, srcFormat);
+  const UInt csy_src  =getComponentScaleY(compID, srcFormat);
+
+  const UInt stride_src      = stride444>>csx_src;
+
+  const UInt stride_file      = (width444 * (is16bit ? 2 : 1)) >> csx_file;
+  const UInt width_file       = width444 >>csx_file;
+  const UInt height_file      = height444>>csy_file;
+
+  UChar  *buf   = new UChar[stride_file];
+
+  if (compID!=COMPONENT_Y && (fileFormat==CHROMA_400 || srcFormat==CHROMA_400))
+  {
+    if (fileFormat!=CHROMA_400)
+    {
+      const UInt value=1<<(fileBitDepth-1);
+
+      for(UInt y=0; y< height_file; y++)
+      {
+        if (!is16bit)
+        {
+          UChar val(value);
+          for (UInt x = 0; x < width_file; x++)
+            buf[x]=val;
+        }
+        else
+        {
+          UShort val(value);
+          for (UInt x = 0; x < width_file; x++)
+          {
+            buf[2*x+0]= (val>>0) & 0xff;
+            buf[2*x+1]= (val>>8) & 0xff;
+          }
+        }
+
+        fd.write(reinterpret_cast<Char*>(buf), stride_file);
+        if (fd.eof() || fd.fail() )
+        {
+          delete[] buf;
+          return false;
+        }
+      }
+    }
+  }
+  else
+  {
+    const UInt mask_y_file=(1<<csy_file)-1;
+    const UInt mask_y_src =(1<<csy_src )-1;
+    for(UInt y444=0; y444<height444; y444++)
+    {
+      if ((y444&mask_y_file)==0)
+      {
+        // write a new line
+        if (csx_file < csx_src)
+        {
+          // eg file is 444, source is 422.
+          const UInt sx=csx_src-csx_file;
+          if (!is16bit)
+          {
+            for (UInt x = 0; x < width_file; x++)
+            {
+              buf[x] = (UChar)(src[x>>sx]);
+            }
+          }
+          else
+          {
+            for (UInt x = 0; x < width_file; x++)
+            {
+              buf[2*x  ] = (src[x>>sx]>>0) & 0xff;
+              buf[2*x+1] = (src[x>>sx]>>8) & 0xff;
+            }
+          }
+        }
+        else
+        {
+          // eg file is 422, src is 444.
+          const UInt sx=csx_file-csx_src;
+          if (!is16bit)
+          {
+            for (UInt x = 0; x < width_file; x++)
+            {
+              buf[x] = (UChar)(src[x<<sx]);
+            }
+          }
+          else
+          {
+            for (UInt x = 0; x < width_file; x++)
+            {
+              buf[2*x  ] = (src[x<<sx]>>0) & 0xff;
+              buf[2*x+1] = (src[x<<sx]>>8) & 0xff;
+            }
+          }
+        }
+
+        fd.write(reinterpret_cast<Char*>(buf), stride_file);
+        if (fd.eof() || fd.fail() )
+        {
+          delete[] buf;
+          return false;
+        }
+      }
+
+      if ((y444&mask_y_src)==0)
+      {
+        src += stride_src;
+      }
+
+    }
+  }
+  delete[] buf;
+  return true;
+}
+
+static Bool writeField(ostream& fd, Pel* top, Pel* bottom, Bool is16bit,
+                       UInt stride444,
+                       UInt width444, UInt height444,
+                       const ComponentID compID,
+                       const ChromaFormat srcFormat,
+                       const ChromaFormat fileFormat,
+                       const UInt fileBitDepth, const Bool isTff)
+{
+  const UInt csx_file =getComponentScaleX(compID, fileFormat);
+  const UInt csy_file =getComponentScaleY(compID, fileFormat);
+  const UInt csx_src  =getComponentScaleX(compID, srcFormat);
+  const UInt csy_src  =getComponentScaleY(compID, srcFormat);
+
+  const UInt stride_src      = stride444>>csx_src;
+
+  const UInt stride_file      = (width444 * (is16bit ? 2 : 1)) >> csx_file;
+  const UInt width_file       = width444 >>csx_file;
+  const UInt height_file      = height444>>csy_file;
+
+  UChar  *buf   = new UChar[stride_file * 2];
+
+  if (compID!=COMPONENT_Y && (fileFormat==CHROMA_400 || srcFormat==CHROMA_400))
+  {
+    if (fileFormat!=CHROMA_400)
+    {
+      const UInt value=1<<(fileBitDepth-1);
+
+      for(UInt y=0; y< height_file; y++)
+      {
+        for (UInt field = 0; field < 2; field++)
+        {
+          UChar *fieldBuffer = buf + (field * stride_file);
+
+          if (!is16bit)
+          {
+            UChar val(value);
+            for (UInt x = 0; x < width_file; x++)
+              fieldBuffer[x]=val;
+          }
+          else
+          {
+            UShort val(value);
+            for (UInt x = 0; x < width_file; x++)
+            {
+              fieldBuffer[2*x+0]= (val>>0) & 0xff;
+              fieldBuffer[2*x+1]= (val>>8) & 0xff;
+            }
+          }
+        }
+
+        fd.write(reinterpret_cast<Char*>(buf), (stride_file * 2));
+        if (fd.eof() || fd.fail() )
+        {
+          delete[] buf;
+          return false;
+        }
+      }
+    }
+  }
+  else
+  {
+    const UInt mask_y_file=(1<<csy_file)-1;
+    const UInt mask_y_src =(1<<csy_src )-1;
+    for(UInt y444=0; y444<height444; y444++)
+    {
+      if ((y444&mask_y_file)==0)
+      {
+        for (UInt field = 0; field < 2; field++)
+        {
+          UChar *fieldBuffer = buf + (field * stride_file);
+          Pel   *src         = (((field == 0) && isTff) || ((field == 1) && (!isTff))) ? top : bottom;
+
+          // write a new line
+          if (csx_file < csx_src)
+          {
+            // eg file is 444, source is 422.
+            const UInt sx=csx_src-csx_file;
+            if (!is16bit)
+            {
+              for (UInt x = 0; x < width_file; x++)
+              {
+                fieldBuffer[x] = (UChar)(src[x>>sx]);
+              }
+            }
+            else
+            {
+              for (UInt x = 0; x < width_file; x++)
+              {
+                fieldBuffer[2*x  ] = (src[x>>sx]>>0) & 0xff;
+                fieldBuffer[2*x+1] = (src[x>>sx]>>8) & 0xff;
+              }
+            }
+          }
+          else
+          {
+            // eg file is 422, src is 444.
+            const UInt sx=csx_file-csx_src;
+            if (!is16bit)
+            {
+              for (UInt x = 0; x < width_file; x++)
+              {
+                fieldBuffer[x] = (UChar)(src[x<<sx]);
+              }
+            }
+            else
+            {
+              for (UInt x = 0; x < width_file; x++)
+              {
+                fieldBuffer[2*x  ] = (src[x<<sx]>>0) & 0xff;
+                fieldBuffer[2*x+1] = (src[x<<sx]>>8) & 0xff;
+              }
+            }
+          }
+        }
+
+        fd.write(reinterpret_cast<Char*>(buf), (stride_file * 2));
+        if (fd.eof() || fd.fail() )
+        {
+          delete[] buf;
+          return false;
+        }
+      }
+
+      if ((y444&mask_y_src)==0)
+      {
+        top    += stride_src;
+        bottom += stride_src;
+      }
+
+    }
+  }
+  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*  pPicYuvUser, TComPicYuv* pPicYuvTrueOrg, const InputColourSpaceConversion ipcsc, Int aiPad[2], ChromaFormat format )
+{
+  // check end-of-file
+  if ( isEof() ) return false;
+  TComPicYuv *pPicYuv=pPicYuvTrueOrg;
+  if (format>=NUM_CHROMA_FORMAT) format=pPicYuv->getChromaFormat();
+
+  Bool is16bit = false;
+
+  for(UInt ch=0; ch<MAX_NUM_CHANNEL_TYPE; ch++)
+  {
+    if (m_fileBitdepth[ch] > 8) is16bit=true;
+  }
+
+  const UInt stride444      = pPicYuv->getStride(COMPONENT_Y);
+
+  // compute actual YUV width & height excluding padding size
+  const UInt pad_h444       = aiPad[0];
+  const UInt pad_v444       = aiPad[1];
+
+  const UInt width_full444  = pPicYuv->getWidth(COMPONENT_Y);
+  const UInt height_full444 = pPicYuv->getHeight(COMPONENT_Y);
+
+  const UInt width444       = width_full444 - pad_h444;
+  const UInt height444      = height_full444 - pad_v444;
+
+  for(UInt comp=0; comp<MAX_NUM_COMPONENT; comp++)
+  {
+    const ComponentID compID = ComponentID(comp);
+    const ChannelType chType=toChannelType(compID);
+
+    const Int desired_bitdepth = m_MSBExtendedBitDepth[chType] + m_bitdepthShift[chType];
+
+#if !CLIP_TO_709_RANGE
+    const Pel minval = 0;
+    const Pel maxval = (1 << desired_bitdepth) - 1;
+#else
+    const Bool b709Compliance=(m_bitdepthShift[chType] < 0 && desired_bitdepth >= 8);     /* ITU-R BT.709 compliant clipping for converting say 10b to 8b */
+    const Pel minval = b709Compliance? ((   1 << (desired_bitdepth - 8))   ) : 0;
+    const Pel maxval = b709Compliance? ((0xff << (desired_bitdepth - 8)) -1) : (1 << desired_bitdepth) - 1;
+#endif
+
+    if (! readPlane(pPicYuv->getAddr(compID), m_cHandle, is16bit, stride444, width444, height444, pad_h444, pad_v444, compID, pPicYuv->getChromaFormat(), format, m_fileBitdepth[chType]))
+    {
+      return false;
+    }
+
+    if (compID < pPicYuv->getNumberValidComponents() )
+    {
+      const UInt csx=getComponentScaleX(compID, pPicYuv->getChromaFormat());
+      const UInt csy=getComponentScaleY(compID, pPicYuv->getChromaFormat());
+      scalePlane(pPicYuv->getAddr(compID), stride444>>csx, width_full444>>csx, height_full444>>csy, m_bitdepthShift[chType], minval, maxval);
+    }
+  }
+
+  Int internalBitDepth[MAX_NUM_CHANNEL_TYPE];
+  for(UInt chType=0; chType<MAX_NUM_CHANNEL_TYPE; chType++)
+  {
+    internalBitDepth[chType] = m_bitdepthShift[chType] + m_MSBExtendedBitDepth[chType];
+  }
+  ColourSpaceConvert(*pPicYuvTrueOrg, *pPicYuvUser, ipcsc, internalBitDepth, true);
+
+  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* pPicYuvUser, const InputColourSpaceConversion ipCSC, Int confLeft, Int confRight, Int confTop, Int confBottom, ChromaFormat format )
+{
+  TComPicYuv cPicYuvCSCd;
+  if (ipCSC!=IPCOLOURSPACE_UNCHANGED)
+  {
+    cPicYuvCSCd.create(pPicYuvUser->getWidth(COMPONENT_Y), pPicYuvUser->getHeight(COMPONENT_Y), pPicYuvUser->getChromaFormat(), g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth);
+    Int internalBitDepth[MAX_NUM_CHANNEL_TYPE];
+    for(UInt chType=0; chType<MAX_NUM_CHANNEL_TYPE; chType++)
+    {
+      internalBitDepth[chType] = m_bitdepthShift[chType] + m_MSBExtendedBitDepth[chType];
+    }
+    ColourSpaceConvert(*pPicYuvUser, cPicYuvCSCd, ipCSC, internalBitDepth, false);
+  }
+  TComPicYuv *pPicYuv=(ipCSC==IPCOLOURSPACE_UNCHANGED) ? pPicYuvUser : &cPicYuvCSCd;
+
+  // compute actual YUV frame size excluding padding size
+  const Int   iStride444 = pPicYuv->getStride(COMPONENT_Y);
+  const UInt width444  = pPicYuv->getWidth(COMPONENT_Y) - confLeft - confRight;
+  const UInt height444 = pPicYuv->getHeight(COMPONENT_Y) -  confTop  - confBottom;
+  Bool is16bit = false;
+  Bool nonZeroBitDepthShift=false;
+
+  if ((width444 == 0) || (height444 == 0))
+  {
+    printf ("\nWarning: writing %d x %d luma sample output picture!", width444, height444);
+  }
+
+  for(UInt ch=0; ch<MAX_NUM_CHANNEL_TYPE; ch++)
+  {
+    if (m_fileBitdepth[ch] > 8) is16bit=true;
+    if (m_bitdepthShift[ch] != 0) nonZeroBitDepthShift=true;
+  }
+
+  TComPicYuv *dstPicYuv = NULL;
+  Bool retval = true;
+  if (format>=NUM_CHROMA_FORMAT) format=pPicYuv->getChromaFormat();
+
+  if (nonZeroBitDepthShift)
+  {
+    dstPicYuv = new TComPicYuv;
+    dstPicYuv->create( pPicYuv->getWidth(COMPONENT_Y), pPicYuv->getHeight(COMPONENT_Y), pPicYuv->getChromaFormat(), 1, 1, 0 );
+    pPicYuv->copyToPic(dstPicYuv);
+
+    for(UInt comp=0; comp<dstPicYuv->getNumberValidComponents(); comp++)
+    {
+      const ComponentID compID=ComponentID(comp);
+      const ChannelType ch=toChannelType(compID);
+#if !CLIP_TO_709_RANGE
+      const Pel minval = 0;
+      const Pel maxval = (1 << m_MSBExtendedBitDepth[ch]) - 1;
+#else
+      const Bool b709Compliance=(-m_bitdepthShift[ch] < 0 && m_MSBExtendedBitDepth[ch] >= 8);     /* ITU-R BT.709 compliant clipping for converting say 10b to 8b */
+      const Pel minval = b709Compliance? ((   1 << (m_MSBExtendedBitDepth[ch] - 8))   ) : 0;
+      const Pel maxval = b709Compliance? ((0xff << (m_MSBExtendedBitDepth[ch] - 8)) -1) : (1 << m_MSBExtendedBitDepth[ch]) - 1;
+#endif
+
+      scalePlane(dstPicYuv->getAddr(compID), dstPicYuv->getStride(compID), dstPicYuv->getWidth(compID), dstPicYuv->getHeight(compID), -m_bitdepthShift[ch], minval, maxval);
+    }
+  }
+  else
+  {
+    dstPicYuv = pPicYuv;
+  }
+
+  for(UInt comp=0; retval && comp<dstPicYuv->getNumberValidComponents(); comp++)
+  {
+    const ComponentID compID = ComponentID(comp);
+    const ChannelType ch=toChannelType(compID);
+    const UInt csx = pPicYuv->getComponentScaleX(compID);
+    const UInt csy = pPicYuv->getComponentScaleY(compID);
+    const Int planeOffset =  (confLeft>>csx) + (confTop>>csy) * pPicYuv->getStride(compID);
+    if (! writePlane(m_cHandle, dstPicYuv->getAddr(compID) + planeOffset, is16bit, iStride444, width444, height444, compID, dstPicYuv->getChromaFormat(), format, m_fileBitdepth[ch]))
+    {
+      retval=false;
+    }
+  }
+
+  if (nonZeroBitDepthShift)
+  {
+    dstPicYuv->destroy();
+    delete dstPicYuv;
+  }
+
+  cPicYuvCSCd.destroy();
+
+  return retval;
+}
+
+Bool TVideoIOYuv::write( TComPicYuv* pPicYuvUserTop, TComPicYuv* pPicYuvUserBottom, const InputColourSpaceConversion ipCSC, Int confLeft, Int confRight, Int confTop, Int confBottom, ChromaFormat format, const Bool isTff )
+{
+
+  TComPicYuv cPicYuvTopCSCd;
+  TComPicYuv cPicYuvBottomCSCd;
+  if (ipCSC!=IPCOLOURSPACE_UNCHANGED)
+  {
+    cPicYuvTopCSCd   .create(pPicYuvUserTop   ->getWidth(COMPONENT_Y), pPicYuvUserTop   ->getHeight(COMPONENT_Y), pPicYuvUserTop   ->getChromaFormat(), g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth);
+    cPicYuvBottomCSCd.create(pPicYuvUserBottom->getWidth(COMPONENT_Y), pPicYuvUserBottom->getHeight(COMPONENT_Y), pPicYuvUserBottom->getChromaFormat(), g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth);
+    Int internalBitDepth[MAX_NUM_CHANNEL_TYPE];
+    for(UInt chType=0; chType<MAX_NUM_CHANNEL_TYPE; chType++)
+    {
+      internalBitDepth[chType] = m_bitdepthShift[chType] + m_MSBExtendedBitDepth[chType];
+    }
+    ColourSpaceConvert(*pPicYuvUserTop,    cPicYuvTopCSCd,    ipCSC, internalBitDepth, false);
+    ColourSpaceConvert(*pPicYuvUserBottom, cPicYuvBottomCSCd, ipCSC, internalBitDepth, false);
+  }
+  TComPicYuv *pPicYuvTop    = (ipCSC==IPCOLOURSPACE_UNCHANGED) ? pPicYuvUserTop    : &cPicYuvTopCSCd;
+  TComPicYuv *pPicYuvBottom = (ipCSC==IPCOLOURSPACE_UNCHANGED) ? pPicYuvUserBottom : &cPicYuvBottomCSCd;
+
+  Bool is16bit = false;
+  Bool nonZeroBitDepthShift=false;
+
+  for(UInt ch=0; ch<MAX_NUM_CHANNEL_TYPE; ch++)
+  {
+    if (m_fileBitdepth[ch] > 8) is16bit=true;
+    if (m_bitdepthShift[ch] != 0) nonZeroBitDepthShift=true;
+  }
+
+  TComPicYuv *dstPicYuvTop    = NULL;
+  TComPicYuv *dstPicYuvBottom = NULL;
+
+  for (UInt field = 0; field < 2; field++)
+  {
+    TComPicYuv *pPicYuv = (field == 0) ? pPicYuvTop : pPicYuvBottom;
+
+    if (format>=NUM_CHROMA_FORMAT) format=pPicYuv->getChromaFormat();
+
+    TComPicYuv* &dstPicYuv = (field == 0) ? dstPicYuvTop : dstPicYuvBottom;
+
+    if (nonZeroBitDepthShift)
+    {
+      dstPicYuv = new TComPicYuv;
+      dstPicYuv->create( pPicYuv->getWidth(COMPONENT_Y), pPicYuv->getHeight(COMPONENT_Y), pPicYuv->getChromaFormat(), 1, 1, 0 );
+      pPicYuv->copyToPic(dstPicYuv);
+
+      for(UInt comp=0; comp<dstPicYuv->getNumberValidComponents(); comp++)
+      {
+        const ComponentID compID=ComponentID(comp);
+        const ChannelType ch=toChannelType(compID);
+#if !CLIP_TO_709_RANGE
+        const Pel minval = 0;
+        const Pel maxval = (1 << m_MSBExtendedBitDepth[ch]) - 1;
+#else
+        const Bool b709Compliance=(-m_bitdepthShift[ch] < 0 && m_MSBExtendedBitDepth[ch] >= 8);     /* ITU-R BT.709 compliant clipping for converting say 10b to 8b */
+        const Pel minval = b709Compliance? ((   1 << (m_MSBExtendedBitDepth[ch] - 8))   ) : 0;
+        const Pel maxval = b709Compliance? ((0xff << (m_MSBExtendedBitDepth[ch] - 8)) -1) : (1 << m_MSBExtendedBitDepth[ch]) - 1;
+#endif
+
+        scalePlane(dstPicYuv->getAddr(compID), dstPicYuv->getStride(compID), dstPicYuv->getWidth(compID), dstPicYuv->getHeight(compID), -m_bitdepthShift[ch], minval, maxval);
+      }
+    }
+    else
+    {
+      dstPicYuv = pPicYuv;
+    }
+  }
+
+  Bool retval = true;
+
+  assert(dstPicYuvTop->getNumberValidComponents() == dstPicYuvBottom->getNumberValidComponents());
+  assert(dstPicYuvTop->getChromaFormat()          == dstPicYuvBottom->getChromaFormat()         );
+  assert(dstPicYuvTop->getWidth(COMPONENT_Y)      == dstPicYuvBottom->getWidth(COMPONENT_Y)    );
+  assert(dstPicYuvTop->getHeight(COMPONENT_Y)     == dstPicYuvBottom->getHeight(COMPONENT_Y)    );
+  assert(dstPicYuvTop->getStride(COMPONENT_Y)     == dstPicYuvBottom->getStride(COMPONENT_Y)    );
+
+  for(UInt comp=0; retval && comp<dstPicYuvTop->getNumberValidComponents(); comp++)
+  {
+    const ComponentID compID = ComponentID(comp);
+    const ChannelType ch=toChannelType(compID);
+
+    assert(dstPicYuvTop->getComponentScaleX(compID) == dstPicYuvBottom->getComponentScaleX(compID));
+    assert(dstPicYuvTop->getComponentScaleY(compID) == dstPicYuvBottom->getComponentScaleY(compID));
+    assert(dstPicYuvTop->getStride         (compID) == dstPicYuvBottom->getStride         (compID));
+
+    const UInt width444   = dstPicYuvTop->getWidth(COMPONENT_Y)  - (confLeft + confRight);
+    const UInt height444  = dstPicYuvTop->getHeight(COMPONENT_Y) - (confTop + confBottom);
+
+    if ((width444 == 0) || (height444 == 0))
+    {
+      printf ("\nWarning: writing %d x %d luma sample output picture!", width444, height444);
+    }
+
+    const UInt csx = dstPicYuvTop->getComponentScaleX(compID);
+    const UInt csy = dstPicYuvTop->getComponentScaleY(compID);
+    const Int planeOffset  = (confLeft>>csx) + ( confTop>>csy) * dstPicYuvTop->getStride(compID); //offset is for entire frame - round up for top field and down for bottom field
+
+    if (! writeField(m_cHandle,
+                     (dstPicYuvTop   ->getAddr(compID) + planeOffset),
+                     (dstPicYuvBottom->getAddr(compID) + planeOffset),
+                     is16bit,
+                     dstPicYuvTop->getStride(COMPONENT_Y),
+                     width444, height444, compID, dstPicYuvTop->getChromaFormat(), format, m_fileBitdepth[ch], isTff))
+    {
+      retval=false;
+    }
+  }
+
+  if (nonZeroBitDepthShift)
+  {
+    dstPicYuvTop->destroy();
+    dstPicYuvBottom->destroy();
+    delete dstPicYuvTop;
+    delete dstPicYuvBottom;
+  }
+
+  cPicYuvTopCSCd.destroy();
+  cPicYuvBottomCSCd.destroy();
+
+  return retval;
+}
+
+static Void
+copyPlane(const TComPicYuv &src, const ComponentID srcPlane, TComPicYuv &dest, const ComponentID destPlane)
+{
+  const UInt width=src.getWidth(srcPlane);
+  const UInt height=src.getHeight(srcPlane);
+  assert(dest.getWidth(destPlane) == width);
+  assert(dest.getHeight(destPlane) == height);
+  const Pel *pSrc=src.getAddr(srcPlane);
+  Pel *pDest=dest.getAddr(destPlane);
+  const UInt strideSrc=src.getStride(srcPlane);
+  const UInt strideDest=dest.getStride(destPlane);
+  for(UInt y=0; y<height; y++, pSrc+=strideSrc, pDest+=strideDest)
+  {
+    memcpy(pDest, pSrc, width*sizeof(Pel));
+  }
+}
+
+// static member
+Void TVideoIOYuv::ColourSpaceConvert(const TComPicYuv &src, TComPicYuv &dest, const InputColourSpaceConversion conversion, const Int bitDepths[MAX_NUM_CHANNEL_TYPE], Bool bIsForwards)
+{
+  const ChromaFormat  format=src.getChromaFormat();
+  const UInt          numValidComp=src.getNumberValidComponents();
+
+  switch (conversion)
+  {
+    case IPCOLOURSPACE_YCbCrtoYYY:
+      if (format!=CHROMA_444)
+      {
+        // only 444 is handled.
+        assert(format==CHROMA_444);
+        exit(1);
+      }
+
+      {
+        for(UInt comp=0; comp<numValidComp; comp++)
+          copyPlane(src, ComponentID(bIsForwards?0:comp), dest, ComponentID(comp));
+      }
+      break;
+    case IPCOLOURSPACE_YCbCrtoYCrCb:
+      {
+        for(UInt comp=0; comp<numValidComp; comp++)
+          copyPlane(src, ComponentID(comp), dest, ComponentID((numValidComp-comp)%numValidComp));
+      }
+      break;
+
+    case IPCOLOURSPACE_RGBtoGBR:
+      {
+        if (format!=CHROMA_444)
+        {
+          // only 444 is handled.
+          assert(format==CHROMA_444);
+          exit(1);
+        }
+
+        // channel re-mapping
+        for(UInt comp=0; comp<numValidComp; comp++)
+        {
+          const ComponentID compIDsrc=ComponentID((comp+1)%numValidComp);
+          const ComponentID compIDdst=ComponentID(comp);
+          copyPlane(src, bIsForwards?compIDsrc:compIDdst, dest, bIsForwards?compIDdst:compIDsrc);
+        }
+      }
+      break;
+
+    case IPCOLOURSPACE_UNCHANGED:
+    default:
+      {
+        for(UInt comp=0; comp<numValidComp; comp++)
+          copyPlane(src, ComponentID(comp), dest, ComponentID(comp));
+      }
+      break;
+  }
+}
Index: /tags/SHM-9.0/source/Lib/TLibVideoIO/TVideoIOYuv.h
===================================================================
--- /tags/SHM-9.0/source/Lib/TLibVideoIO/TVideoIOYuv.h	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/TLibVideoIO/TVideoIOYuv.h	(revision 1088)
@@ -0,0 +1,86 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     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_fileBitdepth[MAX_NUM_CHANNEL_TYPE]; ///< bitdepth of input/output video file
+  Int       m_MSBExtendedBitDepth[MAX_NUM_CHANNEL_TYPE];  ///< bitdepth after addition of MSBs (with value 0)
+  Int       m_bitdepthShift[MAX_NUM_CHANNEL_TYPE];  ///< number of bits to increase or decrease image by before/after write/read
+
+public:
+  TVideoIOYuv()           {}
+  virtual ~TVideoIOYuv()  {}
+
+  Void  open  ( Char* pchFile, Bool bWriteMode, const Int fileBitDepth[MAX_NUM_CHANNEL_TYPE], const Int MSBExtendedBitDepth[MAX_NUM_CHANNEL_TYPE], const Int internalBitDepth[MAX_NUM_CHANNEL_TYPE] ); ///< open or create file
+  Void  close ();                                           ///< close file
+
+  Void skipFrames(UInt numFrames, UInt width, UInt height, ChromaFormat format);
+
+  // if fileFormat<NUM_CHROMA_FORMAT, the format of the file is that format specified, else it is the format of the TComPicYuv.
+
+
+  Bool  read  ( TComPicYuv* pPicYuv, TComPicYuv* pPicYuvTrueOrg, const InputColourSpaceConversion ipcsc, Int aiPad[2], ChromaFormat fileFormat=NUM_CHROMA_FORMAT );     ///< read one frame with padding parameter
+  Bool  write ( TComPicYuv* pPicYuv, const InputColourSpaceConversion ipCSC, Int confLeft=0, Int confRight=0, Int confTop=0, Int confBottom=0, ChromaFormat fileFormat=NUM_CHROMA_FORMAT );     ///< write one YUV frame with padding parameter
+  Bool  write ( TComPicYuv* pPicYuvTop, TComPicYuv* pPicYuvBottom, const InputColourSpaceConversion ipCSC, Int confLeft=0, Int confRight=0, Int confTop=0, Int confBottom=0, ChromaFormat fileFormat=NUM_CHROMA_FORMAT, Bool isTff=false);
+  static Void ColourSpaceConvert(const TComPicYuv &src, TComPicYuv &dest, const InputColourSpaceConversion conversion, const Int bitDepths[MAX_NUM_CHANNEL_TYPE], Bool bIsForwards);
+
+  Bool  isEof ();                                           ///< check for end-of-file
+  Bool  isFail();                                           ///< check for failure
+
+
+};
+
+#endif // __TVIDEOIOYUV__
+
Index: /tags/SHM-9.0/source/Lib/libmd5/MD5.h
===================================================================
--- /tags/SHM-9.0/source/Lib/libmd5/MD5.h	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/libmd5/MD5.h	(revision 1088)
@@ -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-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#pragma once
+#include "libmd5.h"
+#include <string>
+
+//! \ingroup libMD5
+//! \{
+
+static const UInt MD5_DIGEST_STRING_LENGTH=16;
+
+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[MD5_DIGEST_STRING_LENGTH])
+  {
+    MD5Final(digest, &m_state);
+  }
+
+private:
+  context_md5_t m_state;
+};
+
+
+//! \}
Index: /tags/SHM-9.0/source/Lib/libmd5/libmd5.c
===================================================================
--- /tags/SHM-9.0/source/Lib/libmd5/libmd5.c	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/libmd5/libmd5.c	(revision 1088)
@@ -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: /tags/SHM-9.0/source/Lib/libmd5/libmd5.h
===================================================================
--- /tags/SHM-9.0/source/Lib/libmd5/libmd5.h	(revision 1088)
+++ /tags/SHM-9.0/source/Lib/libmd5/libmd5.h	(revision 1088)
@@ -0,0 +1,58 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.  
+ *
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#pragma once
+#include <stdint.h>
+
+//! \ingroup libMD5
+//! \{
+
+typedef struct _context_md5_t {
+  uint32_t buf[4];
+  uint32_t bits[2];
+  union {
+    unsigned char b8[64];
+    uint32_t b32[16];
+  } in;
+} context_md5_t;
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+void MD5Init(context_md5_t *ctx);
+void MD5Update(context_md5_t *ctx, unsigned char *buf, unsigned len);
+void MD5Final(unsigned char digest[16], context_md5_t *ctx);
+#ifdef __cplusplus
+}
+#endif
+
+//! \}
