Index: trunk/source/App/TAppDecoder/TAppDecCfg.cpp
===================================================================
--- trunk/source/App/TAppDecoder/TAppDecCfg.cpp	(revision 498)
+++ trunk/source/App/TAppDecoder/TAppDecCfg.cpp	(revision 540)
@@ -69,4 +69,7 @@
   string cfg_ReconFile [MAX_LAYERS];
   Int nLayerNum;
+#if OUTPUT_LAYER_SET_INDEX
+  Int olsIdx;
+#endif
 #if AVC_BASE
   string cfg_BLReconFile;
@@ -110,4 +113,7 @@
 #if SVC_EXTENSION
   ("LayerNum,-ls", nLayerNum, 1, "Number of layers to be decoded.")
+#if OUTPUT_LAYER_SET_INDEX
+  ("OutpuLayerSetIdx,-olsidx", olsIdx, -1, "Index of output layer set to be decoded.")
+#endif
 #endif 
   ("MaxTemporalLayer,t", m_iMaxTemporalLayer, -1, "Maximum Temporal Layer to be decoded. -1 to decode all layers")
@@ -138,4 +144,8 @@
   m_tgtLayerId = nLayerNum - 1;
   assert( m_tgtLayerId >= 0 );
+#if OUTPUT_LAYER_SET_INDEX  
+  this->getCommonDecoderParams()->setOutputLayerSetIdx( olsIdx       );
+  this->getCommonDecoderParams()->setTargetLayerId    ( m_tgtLayerId );
+#endif
   for(UInt layer=0; layer<= m_tgtLayerId; layer++)
   {
@@ -201,4 +211,7 @@
       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
   }
 
Index: trunk/source/App/TAppDecoder/TAppDecCfg.h
===================================================================
--- trunk/source/App/TAppDecoder/TAppDecCfg.h	(revision 498)
+++ trunk/source/App/TAppDecoder/TAppDecCfg.h	(revision 540)
@@ -91,4 +91,7 @@
   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 OUTPUT_LAYER_SET_INDEX
+  CommonDecoderParams             m_commonDecoderParams;
+#endif
 
 public:
@@ -120,4 +123,7 @@
   
   Bool  parseCfg        ( Int argc, Char* argv[] );   ///< initialize option class from configuration
+#if OUTPUT_LAYER_SET_INDEX
+  CommonDecoderParams* getCommonDecoderParams() {return &m_commonDecoderParams;}
+#endif
 };
 
Index: trunk/source/App/TAppDecoder/TAppDecTop.cpp
===================================================================
--- trunk/source/App/TAppDecoder/TAppDecTop.cpp	(revision 498)
+++ trunk/source/App/TAppDecoder/TAppDecTop.cpp	(revision 540)
@@ -145,4 +145,7 @@
   // 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 ) );
+
   for(UInt layer=0; layer<=m_tgtLayerId; layer++)
   {
@@ -223,5 +226,6 @@
       }
     }
-    if (bNewPicture || !bitstreamFile)
+
+    if (bNewPicture || !bitstreamFile || nalu.m_nalUnitType == NAL_UNIT_EOS)
     {
 #if O0194_DIFFERENT_BITDEPTH_EL_BL
@@ -230,5 +234,9 @@
       g_bitDepthC = g_bitDepthCLayer[curLayerId];
 #endif
-      m_acTDecTop[curLayerId].executeLoopFilters(poc, pcListPic);
+      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);
@@ -256,4 +264,8 @@
         xFlushOutput( pcListPic, curLayerId );
       }
+      if (nalu.m_nalUnitType == NAL_UNIT_EOS)
+      {
+        xFlushOutput( pcListPic, curLayerId );        
+      }
       // write reconstruction to file
       if(bNewPicture)
@@ -316,4 +328,5 @@
   // main decoder loop
   Bool openedReconFile = false; // reconstruction file not yet opened. (must be performed after SPS is seen)
+  Bool loopFiltered = false;
 
 #if SYNTAX_OUTPUT
@@ -384,7 +397,11 @@
       }
     }
-    if (bNewPicture || !bitstreamFile)
-    {
-      m_cTDecTop.executeLoopFilters(poc, pcListPic);
+    if (bNewPicture || !bitstreamFile || nalu.m_nalUnitType == NAL_UNIT_EOS)
+    {
+      if (!loopFiltered || bitstreamFile)
+      {
+        m_cTDecTop.executeLoopFilters(poc, pcListPic);
+      }
+      loopFiltered = (nalu.m_nalUnitType == NAL_UNIT_EOS);
     }
 
@@ -408,4 +425,8 @@
         xFlushOutput( pcListPic );
       }
+      if (nalu.m_nalUnitType == NAL_UNIT_EOS)
+      {
+        xFlushOutput( pcListPic );        
+      }
       // write reconstruction to file
       if(bNewPicture)
@@ -494,4 +515,7 @@
     m_acTDecTop[layer].setDecodedPictureHashSEIEnabled(m_decodedPictureHashSEIEnabled);
     m_acTDecTop[layer].setNumLayer( m_tgtLayerId + 1 );
+#if OUTPUT_LAYER_SET_INDEX
+    m_acTDecTop[layer].setCommonDecoderParams( this->getCommonDecoderParams() );
+#endif
   }
 
@@ -503,6 +527,6 @@
 
 /** \param pcListPic list of pictures to be written to file
-\todo            DYN_REF_FREE should be revised
-*/
+    \todo            DYN_REF_FREE should be revised
+ */
 #if SVC_EXTENSION
 Void TAppDecTop::xWriteOutput( TComList<TComPic*>* pcListPic, UInt layerId, UInt tId )
@@ -511,4 +535,9 @@
 #endif
 {
+  if (pcListPic->empty())
+  {
+    return;
+  }
+
   TComList<TComPic*>::iterator iterPic   = pcListPic->begin();
   Int numPicsNotYetDisplayed = 0;
@@ -730,5 +759,5 @@
 #endif
 {
-  if(!pcListPic)
+  if(!pcListPic || pcListPic->empty())
   {
     return;
Index: trunk/source/App/TAppDownConvert/DownConvert.cpp
===================================================================
--- trunk/source/App/TAppDownConvert/DownConvert.cpp	(revision 540)
+++ trunk/source/App/TAppDownConvert/DownConvert.cpp	(revision 540)
@@ -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-2013, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "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: trunk/source/App/TAppDownConvert/DownConvert.h
===================================================================
--- trunk/source/App/TAppDownConvert/DownConvert.h	(revision 540)
+++ trunk/source/App/TAppDownConvert/DownConvert.h	(revision 540)
@@ -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-2013, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#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: trunk/source/App/TAppDownConvert/TAppDownConvert.cpp
===================================================================
--- trunk/source/App/TAppDownConvert/TAppDownConvert.cpp	(revision 498)
+++ trunk/source/App/TAppDownConvert/TAppDownConvert.cpp	(revision 540)
@@ -35,437 +35,558 @@
     \brief    Down convert application main
 */
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <math.h>
-
-//! \ingroup TAppDecoder
-//! \{
-
-#define pi 3.1415926
-
-int get_mem2DPelWithPad(unsigned char ***array2D, int dim0, int dim1, int iPadY, int iPadX)
-{
-  int i;
-  unsigned char *curr = NULL;
-  int iHeight, iWidth;
-
-  iHeight = dim0+2*iPadY;
-  iWidth = dim1+2*iPadX;
-  (*array2D) = (unsigned char**)malloc(iHeight*sizeof(unsigned char*));
-  *(*array2D) = (unsigned char* )calloc(iHeight * iWidth, sizeof(unsigned char ));
-
-  (*array2D)[0] += iPadX;
-  curr = (*array2D)[0];
-  for(i = 1 ; i < iHeight; i++)
-  {
-    curr += iWidth;
-    (*array2D)[i] = curr;
-  }
-  (*array2D) = &((*array2D)[iPadY]);
-
+
+#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;
 }
 
-int 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* )calloc(iHeight * iWidth, sizeof(int ));
-
-  (*array2D)[0] += iPadX;
-  curr = (*array2D)[0];
-  for(i = 1 ; i < iHeight; i++)
-  {
-    curr += iWidth;
-    (*array2D)[i] = curr;
-  }
-  (*array2D) = &((*array2D)[iPadY]);
-
+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 free_mem2DPelWithPad(unsigned char **array2D, int iPadY, int iPadX)
-{
-  if (array2D)
-  {
-    if (*array2D)
-    {
-      free (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");
-  }
-}
-
-void free_mem2DintWithPad(int **array2D, int iPadY, int iPadX)
-{
-  if (array2D)
-  {
-    if (*array2D)
-    {
-      free (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");
-  }
-}
-
-void PadImgHorizontal(unsigned char **src, unsigned char **dst, int height, int width, int pad_h)
-{
-  int i, j;
-  unsigned char *BufSrc, *BufDst;
-
-  for (j=0;j<height;j++)
-  {    
-    BufDst = &(dst[j][-pad_h] );
-    BufSrc = src[j];
-    for (i=0;i<pad_h;i++)
-    {
-      *(BufDst++) = BufSrc[0];
-    }
-    memcpy(BufDst, BufSrc, width*sizeof(unsigned char));
-    BufDst += width;
-    for (i=0;i<pad_h;i++)
-    {
-      *(BufDst++) = BufSrc[width-1];
-    }
-  }
-}
-
-void FilterImg( unsigned char **src,
-                int           **temp,
-                unsigned char **dst,
-                int           height1,  
-                int           width1,  
-                int           M, 
-                int           N, 
-                int           **phase_filter,
-                int           length,
-                int           shift,
-                int           plane)
-{
-  int height2,width2;
-  int k,iSum;
-  int i0, div_i0, i1;
-  int j0, div_j0, j1;
-  int *p_filter;
-  unsigned char *p_src, *p_dst;
-  int **p_temp, *p_tmp;
-  int shift2 = (2*shift);
-  int shift_round = (1 << (2 * shift - 1));
-
-  height2 = (height1 * M) / N;
-  width2  = (width1  * M) / N;
-
-  // horizontal filtering
-  for(j1 = 0; j1 < height1; j1++)
-  {
-    i0=-N;
-    p_tmp = temp[j1];
-    for(i1 = 0; i1 < width2; i1++)
-    {
-      i0      += N;
-      div_i0   = (i0 / M);
-      p_src    = &src[j1][ div_i0 - (length >> 1)];
-      p_filter = phase_filter[i0 - div_i0 * M];
-      iSum     = 0;
-      for(k = 0; k < length; k++)
-      {
-        iSum += (*p_src++) * (*p_filter++);
-      }
-      *p_tmp++ = iSum;
-    }
-  }
-
-  // pad temp (vertical)
-  for (k=-(length>>1);k<0;k++)
-    memcpy(temp[k], temp[0], width2*sizeof(int));
-  for (k=height1;k<(height1+(length>>1));k++)
-    memcpy(temp[k], temp[k-1], (width2)* sizeof(int));
-
-  // vertical filtering
-  j0 = (plane == 0) ? -N : -(N-1);
-  
-  for(j1 = 0; j1 < height2; j1++)
-  {
-    j0      += N;
-    div_j0   = (j0 / M);
-    p_dst    = dst[j1];
-    p_temp   = &temp[div_j0 - (length>>1)];
-    p_filter = phase_filter[j0 - div_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++ = (unsigned char)(iSum > 255 ? 255 : iSum < 0 ? 0 : iSum);
-    }
-  }
-}
-
-// ====================================================================================================================
-// Main function
-// ====================================================================================================================
-
-int main(int argc, char *argv[])
-{
-  const int phase_filter_0[4][13]={
-    {0,  2,  -3,  -9,   6,  39,  58,  39,   6,  -9,  -3,  2,  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 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}    
-  };
-
-  int i,j;
-
-  int width_org,  width_org_c,  width_sampled,  width_sampled_c;
-  int height_org, height_org_c, height_sampled, height_sampled_c;
-  int size_org,   size_org_c,   size_sampled,   size_sampled_c;
-
-  unsigned char **Y1,    **U1,    **V1;
-  unsigned char **Y2,    **U2,    **V2;
-  unsigned char **temp_luma,    **temp_chroma;
-  int           **tempY, **tempU, **tempV;
-
-  int **phase_filter;
-  int log2_scaling_factor=7;
-
-  FILE * infile;
-  FILE * outfile;
-
-  int M = -1 ,N = -1;
-  int ratio = -1;
-  int Frames=0;
-  int totalFrames=0;
-  int StartFrame=0;
-  int Tap=13;
-
-  if (argc < 6)
-  {
-    printf("\nIncorrect number of arguments!!!\n\n");
-    printf("Syntax: \n");
-    printf("%s <input width> <input height> <input file> <output file> <downsampling method> [frames_to_process] [start_frame]\n\n", argv[0]);
-    printf("<downsampling method> 0: 2x downsampling, 1: 1.5x downsampling. \n");
-    printf("Examples: \n");
-    printf("%s 1920 1080 input_1920x1080_24p.yuv output_960x540_24p.yuv 0 \n", argv[0]);
-    printf("%s 1920 1080 input_1920x1080_24p.yuv output_1280x720_24p.yuv 1 \n", argv[0]);
-    return -1;
-  }
-
-  width_org  = atoi  (argv[1]);
-  height_org = atoi  (argv[2]);
-  infile     = fopen (argv[3], "rb");
-  outfile    = fopen (argv[4], "wb");
-  ratio      = atoi  (argv[5]); 
-
-  for(i=7; i<= argc; i++)
-  {
-    switch(i)
-    {
-    case 7:
-      Frames = atoi(argv[6]);
-      break;
-    case 8:
-      StartFrame = atoi(argv[7]);
-      break;
-    default:
-      printf("Too many input arguments");
-      break;
-    }
-  }
-
-  if( width_org < 4 || height_org < 4 )
-  {
-    printf("\ninput resolution is too small, exit\n");
-    return -1;
-  }
-  if ( infile == NULL || outfile == NULL )
-  {
-    printf("\ninput or output file is invalid, exit\n");
-    return -1;
-  }
-  if ((argc > 6) && (Frames < 1 || StartFrame < 0))
-  {
-    printf("input frame parameter error\n");
-    return -1;
-  }
-
-  switch( ratio )
-  {
-  default:
-    printf("\ndown sampling parameter %d is not supported (0: 2x downsampling, 1: 1.5x downsampling)\n", ratio);
-    return -1;
-  case 0:
-    M=4;
-    N=8;
-    break;
-  case 1:
-    M=8;
-    N=12;
-    break;
-  }
-
-  width_org_c      = width_org  >> 1;
-  height_org_c     = height_org >> 1;
-  width_sampled    = (width_org  * M) / N;
-  height_sampled   = (height_org * M) / N;
-  width_sampled_c  = width_sampled  >> 1;
-  height_sampled_c = height_sampled >> 1;
-  size_org         = height_org * width_org;
-  size_org_c       = height_org_c * width_org_c;
-  size_sampled     = height_sampled * width_sampled;
-  size_sampled_c   = height_sampled_c * width_sampled_c;
-
-  printf("\n=============================================================\n");
-  printf("\n Input  = %s", argv[3]);
-  printf("\n Output = %s", argv[4]);
-  printf("\n Rescaling input from (%d,%d) to (%d,%d) resolution\n", width_org, height_org, width_sampled, height_sampled);
-  printf("\n=============================================================\n\n");  
-
-  // construct phase filters
-  get_mem2DintWithPad (&phase_filter, M, Tap, 0, 0);
-
-  for (j=0;j<M;j++)
-    for (i=0;i<Tap;i++)
-      phase_filter[j][i]= ratio==0 ? phase_filter_0[j][i] :  phase_filter_1[j][i];
-
-  get_mem2DPelWithPad (&Y1, height_org,   width_org,   0, Tap>>1);
-  get_mem2DPelWithPad (&U1, height_org_c, width_org_c, 0, Tap>>1);
-  get_mem2DPelWithPad (&V1, height_org_c, width_org_c, 0, Tap>>1);
-
-  get_mem2DintWithPad (&tempY, height_org,   width_sampled,   Tap>>1, 0);
-  get_mem2DintWithPad (&tempU, height_org_c, width_sampled_c, Tap>>1, 0);
-  get_mem2DintWithPad (&tempV, height_org_c, width_sampled_c, Tap>>1, 0);
-
-  get_mem2DPelWithPad (&Y2, height_sampled,   width_sampled,  0,0);
-  get_mem2DPelWithPad (&U2, height_sampled_c, width_sampled_c,0,0);
-  get_mem2DPelWithPad (&V2, height_sampled_c, width_sampled_c,0,0);
-
-  get_mem2DPelWithPad (&temp_luma,   height_org,   width_org,  0,0);
-  get_mem2DPelWithPad (&temp_chroma, height_org_c, width_org_c,0,0);
-
-  if(StartFrame!=0)
-  {
-    for (i = 0; i < StartFrame; i ++)
-    {
-      fread(temp_luma[0], sizeof(unsigned char), size_org,     infile);
-      fread(temp_chroma[0], sizeof(unsigned char), size_org_c, infile);
-      fread(temp_chroma[0], sizeof(unsigned char), size_org_c, infile);
-      if (feof(infile))
-      {
-        printf("\nThe start frame number exceeds the file size\n");
-        return -1;
-      }
-    }
-    //fseek64(infile, (size_org * StartFrame * 3) >> 1,SEEK_SET);
-  }
-
-  if (Frames)
-  {
-    totalFrames = Frames;
-  }
-  else
-  {
-    totalFrames = 0x7FFF;
-  }
-
-  i = 0;
-  while(totalFrames)
-  {
-    
-    // read and pad Y
-    fread(temp_luma[0], sizeof(unsigned char), size_org,     infile);
-    PadImgHorizontal(temp_luma, Y1, height_org, width_org, Tap>>1);
-
-    // read and pad U
-    fread(temp_chroma[0], sizeof(unsigned char), size_org_c, infile);
-    PadImgHorizontal(temp_chroma, U1, height_org_c, width_org_c, Tap>>1);
-
-    // read and pad V
-    fread(temp_chroma[0], sizeof(unsigned char), size_org_c, infile);
-    PadImgHorizontal(temp_chroma, V1, height_org_c, width_org_c, Tap>>1);
-
-    if (feof(infile))
-    {
-      break;
-    }
-
-    fprintf(stdout,"Rescaling %dth frame\r", i);
-    fflush(stdout);
-
-    i ++;
-    totalFrames --;
-
-    FilterImg(Y1,tempY,Y2,height_org,  width_org,  M, N, phase_filter,Tap,log2_scaling_factor,0);
-    FilterImg(U1,tempU,U2,height_org_c,width_org_c,M, N, phase_filter,Tap,log2_scaling_factor,1);
-    FilterImg(V1,tempV,V2,height_org_c,width_org_c,M, N, phase_filter,Tap,log2_scaling_factor,2);
-
-    // write a sampled frame
-    fwrite(Y2[0], sizeof(unsigned char), size_sampled,     outfile);
-    fwrite(U2[0], sizeof(unsigned char), size_sampled_c, outfile);
-    fwrite(V2[0], sizeof(unsigned char), size_sampled_c, outfile);
-
-  }
-
-  printf("\nEnd of rescaling process.\n");
-
-  free_mem2DintWithPad (phase_filter, 0, 0);
-
-  free_mem2DPelWithPad (Y1, 0, Tap>>1);
-  free_mem2DPelWithPad (U1, 0, Tap>>1);
-  free_mem2DPelWithPad (V1, 0, Tap>>1);
-
-  free_mem2DintWithPad (tempY, Tap>>1, 0);
-  free_mem2DintWithPad (tempU, Tap>>1, 0);
-  free_mem2DintWithPad (tempV, Tap>>1, 0);
-
-  free_mem2DPelWithPad (Y2,0,0);
-  free_mem2DPelWithPad (U2,0,0);
-  free_mem2DPelWithPad (V2,0,0);
-
-  free_mem2DPelWithPad (temp_luma,  0,0);
-  free_mem2DPelWithPad (temp_chroma,0,0);
-
-  fclose(infile);
-  fclose(outfile);
-
+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: trunk/source/App/TAppEncoder/TAppEncCfg.cpp
===================================================================
--- trunk/source/App/TAppEncoder/TAppEncCfg.cpp	(revision 498)
+++ trunk/source/App/TAppEncoder/TAppEncCfg.cpp	(revision 540)
@@ -399,4 +399,7 @@
   string* cfg_predLayerIdsPtr    [MAX_LAYERS];
 #endif
+#if O0098_SCALED_REF_LAYER_ID
+  string    cfg_scaledRefLayerId [MAX_LAYERS];
+#endif
   string    cfg_scaledRefLayerLeftOffset [MAX_LAYERS];
   string    cfg_scaledRefLayerTopOffset [MAX_LAYERS];
@@ -405,4 +408,7 @@
   Int*      cfg_numScaledRefLayerOffsets[MAX_LAYERS];
 
+#if O0098_SCALED_REF_LAYER_ID
+  string*    cfg_scaledRefLayerIdPtr           [MAX_LAYERS];
+#endif
   string*    cfg_scaledRefLayerLeftOffsetPtr   [MAX_LAYERS];
   string*    cfg_scaledRefLayerTopOffsetPtr    [MAX_LAYERS];
@@ -471,4 +477,7 @@
     for(Int i = 0; i < MAX_LAYERS; i++)
     {
+#if O0098_SCALED_REF_LAYER_ID
+      cfg_scaledRefLayerIdPtr          [layer] = &cfg_scaledRefLayerId[layer]          ;
+#endif
       cfg_scaledRefLayerLeftOffsetPtr  [layer] = &cfg_scaledRefLayerLeftOffset[layer]  ;
       cfg_scaledRefLayerTopOffsetPtr   [layer] = &cfg_scaledRefLayerTopOffset[layer]   ;
@@ -582,4 +591,7 @@
 #endif
   ("NumScaledRefLayerOffsets%d",    cfg_numScaledRefLayerOffsets,     0, MAX_LAYERS,  "Number of scaled offset layer sets ")
+#if O0098_SCALED_REF_LAYER_ID
+  ("ScaledRefLayerId%d",           cfg_scaledRefLayerIdPtr,          string(""), MAX_LAYERS, "Layer ID of scaled base layer picture")
+#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")
@@ -602,5 +614,11 @@
   ("MaxTidRefPresentFlag", m_maxTidRefPresentFlag, true, "max_tid_ref_present_flag (0: not present, 1: present(default)) " )
   ("MaxTidIlRefPicsPlus1%d", cfg_maxTidIlRefPicsPlus1, 1, MAX_LAYERS, "allowed maximum temporal_id for inter-layer prediction")
-#endif 
+#endif
+#if O0223_PICTURE_TYPES_ALIGN_FLAG
+  ("CrossLayerPictureTypeAlignFlag", m_crossLayerPictureTypeAlignFlag, true, "align picture type across layers" )  
+#endif
+#if N0147_IRAP_ALIGN_FLAG
+    ("CrossLayerIrapAlignFlag", m_crossLayerIrapAlignFlag, true, "align IRAP across layers" )  
+#endif
 #if AVC_BASE
   ("AvcBase,-avc",            m_avcBaseLayerFlag,     0, "avc_base_layer_flag")
@@ -773,5 +791,7 @@
   ("MaxNumOffsetsPerPic",      m_maxNumOffsetsPerPic,       2048,  "Max number of SAO offset per picture (Default: 2048)")   
   ("SAOLcuBoundary",           m_saoLcuBoundary,            false, "0: right/bottom LCU boundary areas skipped from SAO parameter estimation, 1: non-deblocked pixels are used for those areas")
+#if !HM_CLEANUP_SAO
   ("SAOLcuBasedOptimization",  m_saoLcuBasedOptimization,   true,  "0: SAO picture-based optimization, 1: SAO LCU-based optimization ")
+#endif  
   ("SliceMode",                m_sliceMode,                0,     "0: Disable all Recon slice limits, 1: Enforce max # of LCUs, 2: Enforce max # of bytes, 3:specify tiles per dependent slice")
   ("SliceArgument",            m_sliceArgument,            0,     "Depending on SliceMode being:"
@@ -827,5 +847,4 @@
   ("FIS", m_useFastIntraScalable, false, "Fast Intra Decision for Scalable HEVC")
 #endif
-#if RATE_CONTROL_LAMBDA_DOMAIN
 #if RC_SHVC_HARMONIZATION
   ("RateControl%d", cfg_RCEnableRateControl, false, MAX_LAYERS, "Rate control: enable rate control for layer %d")
@@ -839,18 +858,9 @@
   ( "RateControl",         m_RCEnableRateControl,   false, "Rate control: enable rate control" )
   ( "TargetBitrate",       m_RCTargetBitrate,           0, "Rate control: target bitrate" )
-#if M0036_RC_IMPROVEMENT
   ( "KeepHierarchicalBit", m_RCKeepHierarchicalBit,     0, "Rate control: 0: equal bit allocation; 1: fixed ratio bit allocation; 2: adaptive ratio bit allocation" )
-#else
-  ( "KeepHierarchicalBit", m_RCKeepHierarchicalBit, false, "Rate control: keep hierarchical bit allocation in rate control algorithm" )
-#endif
   ( "LCULevelRateControl", m_RCLCULevelRC,           true, "Rate control: true: LCU level RC; false: picture level RC" )
   ( "RCLCUSeparateModel",  m_RCUseLCUSeparateModel,  true, "Rate control: use LCU level separate R-lambda model" )
   ( "InitialQP",           m_RCInitialQP,               0, "Rate control: initial QP" )
   ( "RCForceIntraQP",      m_RCForceIntraQP,        false, "Rate control: force intra QP to be equal to initial QP" )
-#endif
-#else
-  ("RateCtrl,-rc", m_enableRateCtrl, false, "Rate control on/off")
-  ("TargetBitrate,-tbr", m_targetBitrate, 0, "Input target bitrate")
-  ("NumLCUInUnit,-nu", m_numLCUInUnit, 0, "Number of LCUs in an Unit")
 #endif
 
@@ -954,8 +964,17 @@
   ("AdaptiveResolutionChange",     m_adaptiveResolutionChange, 0, "Adaptive resolution change frame number. Should coincide with EL RAP picture. (0: disable)")
 #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
   ;
@@ -1086,4 +1105,7 @@
     if(m_acLayerCfg[layer].m_numScaledRefLayerOffsets)
     {
+#if O0098_SCALED_REF_LAYER_ID
+      assert( strcmp(cfg_scaledRefLayerId[layer].c_str(),  ""));
+#endif
       assert( strcmp(cfg_scaledRefLayerLeftOffset[layer].c_str(),  "") ||
               strcmp(cfg_scaledRefLayerRightOffset[layer].c_str(), "") ||
@@ -1094,4 +1116,21 @@
 
     Int *tempArray = NULL;   // Contain the value 
+
+#if O0098_SCALED_REF_LAYER_ID
+    // ID //
+    if(strcmp(cfg_scaledRefLayerId[layer].c_str(),  ""))
+    {
+      cfgStringToArray( &tempArray, cfg_scaledRefLayerId[layer], m_acLayerCfg[layer].m_numScaledRefLayerOffsets, "ScaledRefLayerId");
+      if(tempArray)
+      {
+        for(Int i = 0; i < m_acLayerCfg[layer].m_numScaledRefLayerOffsets; i++)
+        {
+          m_acLayerCfg[layer].m_scaledRefLayerId[i] = tempArray[i];
+        }
+        delete [] tempArray; tempArray = NULL;
+      }
+    }
+#endif
+
     // Left offset //
     if(strcmp(cfg_scaledRefLayerLeftOffset[layer].c_str(),  ""))
@@ -2153,5 +2192,4 @@
   }
 
-#if RATE_CONTROL_LAMBDA_DOMAIN
 #if RC_SHVC_HARMONIZATION
   for ( Int layer=0; layer<m_numLayers; layer++ )
@@ -2184,17 +2222,4 @@
   }
 #endif
-#else
-  if(m_enableRateCtrl)
-  {
-    Int numLCUInWidth  = (m_iSourceWidth  / m_uiMaxCUWidth) + (( m_iSourceWidth  %  m_uiMaxCUWidth ) ? 1 : 0);
-    Int numLCUInHeight = (m_iSourceHeight / m_uiMaxCUHeight)+ (( m_iSourceHeight %  m_uiMaxCUHeight) ? 1 : 0);
-    Int numLCUInPic    =  numLCUInWidth * numLCUInHeight;
-
-    xConfirmPara( (numLCUInPic % m_numLCUInUnit) != 0, "total number of LCUs in a frame should be completely divided by NumLCUInUnit" );
-
-    m_iMaxDeltaQP       = MAX_DELTA_QP;
-    m_iMaxCuDQPDepth    = MAX_CUDQP_DEPTH;
-  }
-#endif
 
   xConfirmPara(!m_TransquantBypassEnableFlag && m_CUTransquantBypassFlagValue, "CUTransquantBypassFlagValue cannot be 1 when TransquantBypassEnableFlag is 0");
@@ -2284,4 +2309,14 @@
     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
@@ -2379,4 +2414,7 @@
   printf("Multiview                     : %d\n", m_scalabilityMask[1] );
   printf("Scalable                      : %d\n", m_scalabilityMask[2] );
+#if AVC_BASE
+  printf("Base layer                    : %s\n", m_avcBaseLayerFlag ? "AVC" : "HEVC");
+#endif
 #if AUXILIARY_PICTURES
   printf("Auxiliary pictures            : %d\n", m_scalabilityMask[3] );
@@ -2388,4 +2426,13 @@
 #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
+#if N0147_IRAP_ALIGN_FLAG
+  printf("Cross layer IRAP alignment    : %d\n", m_crossLayerIrapAlignFlag );
 #endif
   for(UInt layer=0; layer<m_numLayers; layer++)
@@ -2453,7 +2500,6 @@
 #endif
 #if O0215_PHASE_ALIGNMENT
-  printf("cross-layer sample alignment : %d\n", m_phaseAlignFlag);
-#endif
-#if RATE_CONTROL_LAMBDA_DOMAIN
+  printf("Cross-layer sample alignment : %d\n", m_phaseAlignFlag);
+#endif
 #if !RC_SHVC_HARMONIZATION
   printf("RateControl                  : %d\n", m_RCEnableRateControl );
@@ -2468,12 +2514,5 @@
   }
 #endif
-#else
-  printf("RateControl                  : %d\n", m_enableRateCtrl);
-  if(m_enableRateCtrl)
-  {
-    printf("TargetBitrate                : %d\n", m_targetBitrate);
-    printf("NumLCUInUnit                 : %d\n", m_numLCUInUnit);
-  }
-#endif
+
   printf("Max Num Merge Candidates     : %d\n", m_maxNumMergeCand);
   printf("\n");
@@ -2516,6 +2555,7 @@
   printf("PCM:%d ", (m_usePCM && (1<<m_uiPCMLog2MinSize) <= m_uiMaxCUWidth)? 1 : 0);
 #endif
+#if !HM_CLEANUP_SAO
   printf("SAOLcuBasedOptimization:%d ", (m_saoLcuBasedOptimization)?(1):(0));
-
+#endif
   printf("LosslessCuEnabled:%d ", (m_useLossless)? 1:0 );
   printf("WPP:%d ", (Int)m_useWeightedPred);
@@ -2535,9 +2575,4 @@
 #if SVC_EXTENSION
   printf("RecalQP:%d ", m_recalculateQPAccordingToLambda ? 1 : 0 );
-#if AVC_BASE
-  printf("AvcBase:%d ", m_avcBaseLayerFlag ? 1 : 0);
-#else
-  printf("AvcBase:%d ", 0);
-#endif
   printf("EL_RAP_SliceType: %d ", m_elRapSliceBEnabled);
   printf("REF_IDX_ME_ZEROMV: %d ", REF_IDX_ME_ZEROMV);
Index: trunk/source/App/TAppEncoder/TAppEncCfg.h
===================================================================
--- trunk/source/App/TAppEncoder/TAppEncCfg.h	(revision 498)
+++ trunk/source/App/TAppEncoder/TAppEncCfg.h	(revision 540)
@@ -187,5 +187,7 @@
   Int       m_maxNumOffsetsPerPic;                            ///< SAO maximun number of offset per picture
   Bool      m_saoLcuBoundary;                                 ///< SAO parameter estimation using non-deblocked pixels for LCU bottom and right boundary areas
+#if !HM_CLEANUP_SAO
   Bool      m_saoLcuBasedOptimization;                        ///< SAO LCU-based optimization
+#endif
   // coding tools (loop filter)
   Bool      m_bLoopFilterDisable;                             ///< flag for using deblocking filter
@@ -295,22 +297,12 @@
   Int       m_TMVPModeId;
   Int       m_signHideFlag;
-#if RATE_CONTROL_LAMBDA_DOMAIN
 #if !RC_SHVC_HARMONIZATION
   Bool      m_RCEnableRateControl;                ///< enable rate control or not
   Int       m_RCTargetBitrate;                    ///< target bitrate when rate control is enabled
-#if M0036_RC_IMPROVEMENT
   Int       m_RCKeepHierarchicalBit;              ///< 0: equal bit allocation; 1: fixed ratio bit allocation; 2: adaptive ratio bit allocation
-#else
-  Bool      m_RCKeepHierarchicalBit;              ///< whether keeping hierarchical bit allocation structure or not
-#endif
   Bool      m_RCLCULevelRC;                       ///< true: LCU level rate control; false: picture level rate control
   Bool      m_RCUseLCUSeparateModel;              ///< use separate R-lambda model at LCU level
   Int       m_RCInitialQP;                        ///< inital QP for rate control
   Bool      m_RCForceIntraQP;                     ///< force all intra picture to use initial QP or not
-#endif
-#else
-  Bool      m_enableRateCtrl;                                   ///< Flag for using rate control algorithm
-  Int       m_targetBitrate;                                 ///< target bitrate
-  Int       m_numLCUInUnit;                                  ///< Total number of LCUs in a frame should be completely divided by the NumLCUInUnit
 #endif
   Int       m_useScalingListId;                               ///< using quantization matrix
@@ -358,4 +350,7 @@
   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 O0153_ALT_OUTPUT_LAYER_FLAG
+  Bool      m_altOutputLayerFlag;                             ///< Specifies the value of alt_output_laye_flag in VPS extension
+#endif
 
 #if SVC_EXTENSION
@@ -373,4 +368,7 @@
 #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
@@ -386,5 +384,14 @@
 #endif
 #if O0215_PHASE_ALIGNMENT
-  bool m_phaseAlignFlag;
+  Bool m_phaseAlignFlag;
+#endif
+#if O0223_PICTURE_TYPES_ALIGN_FLAG
+  Bool m_crossLayerPictureTypeAlignFlag;
+#endif
+#if N0147_IRAP_ALIGN_FLAG
+  Bool m_crossLayerIrapAlignFlag;
+#endif
+#if O0149_CROSS_LAYER_BLA_FLAG
+  bool      m_crossLayerBLAFlag;
 #endif
 public:
Index: trunk/source/App/TAppEncoder/TAppEncLayerCfg.cpp
===================================================================
--- trunk/source/App/TAppEncoder/TAppEncLayerCfg.cpp	(revision 498)
+++ trunk/source/App/TAppEncoder/TAppEncLayerCfg.cpp	(revision 540)
@@ -53,4 +53,7 @@
   m_aiPad[1] = m_aiPad[0] = 0;
   m_numScaledRefLayerOffsets = 0;
+#if O0098_SCALED_REF_LAYER_ID
+  ::memset(m_scaledRefLayerId,           0, sizeof(m_scaledRefLayerId));
+#endif
   ::memset(m_scaledRefLayerLeftOffset,   0, sizeof(m_scaledRefLayerLeftOffset));
   ::memset(m_scaledRefLayerTopOffset,    0, sizeof(m_scaledRefLayerTopOffset));
Index: trunk/source/App/TAppEncoder/TAppEncLayerCfg.h
===================================================================
--- trunk/source/App/TAppEncoder/TAppEncLayerCfg.h	(revision 498)
+++ trunk/source/App/TAppEncoder/TAppEncLayerCfg.h	(revision 540)
@@ -95,4 +95,7 @@
   TAppEncCfg* m_cAppEncCfg;                                   ///< pointer to app encoder config
   Int       m_numScaledRefLayerOffsets  ;
+#if O0098_SCALED_REF_LAYER_ID
+  Int       m_scaledRefLayerId          [MAX_LAYERS];
+#endif
   Int       m_scaledRefLayerLeftOffset  [MAX_LAYERS];
   Int       m_scaledRefLayerTopOffset   [MAX_LAYERS];
Index: trunk/source/App/TAppEncoder/TAppEncTop.cpp
===================================================================
--- trunk/source/App/TAppEncoder/TAppEncTop.cpp	(revision 498)
+++ trunk/source/App/TAppEncoder/TAppEncTop.cpp	(revision 540)
@@ -90,4 +90,5 @@
     vps->setMaxDecPicBuffering             ( m_maxDecPicBuffering[i], i );
   }
+
 #if REPN_FORMAT_IN_VPS
   vps->setRepFormatIdxPresentFlag( true );   // Could be disabled to optimize in some cases.
@@ -148,4 +149,11 @@
   {
     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()  );
@@ -162,4 +170,7 @@
     repFormat->setBitDepthVpsLuma           ( getInternalBitDepthY()                        );  // Need modification to change for each layer
     repFormat->setBitDepthVpsChroma         ( getInternalBitDepthC()                        );  // Need modification to change for each layer
+#endif
+#if HIGHER_LAYER_IRAP_SKIP_FLAG
+    m_acTEncTop[mapIdxToLayer[idx]].setSkipPictureAtArcSwitch( m_skipPictureAtArcSwitch );
 #endif
   }
@@ -459,5 +470,7 @@
 
     m_acTEncTop[layer].setSaoLcuBoundary (m_saoLcuBoundary);
+#if !HM_CLEANUP_SAO
     m_acTEncTop[layer].setSaoLcuBasedOptimization (m_saoLcuBasedOptimization);
+#endif
     m_acTEncTop[layer].setPCMInputBitDepthFlag  ( m_bPCMInputBitDepthFlag);
     m_acTEncTop[layer].setPCMFilterDisableFlag  ( m_bPCMFilterDisableFlag);
@@ -535,5 +548,4 @@
     m_acTEncTop[layer].setScalingListFile            ( m_scalingListFile   );
     m_acTEncTop[layer].setSignHideFlag(m_signHideFlag);
-#if RATE_CONTROL_LAMBDA_DOMAIN
 #if RC_SHVC_HARMONIZATION
     m_acTEncTop[layer].setUseRateCtrl     (m_acLayerCfg[layer].getRCEnableRateControl());
@@ -552,9 +564,4 @@
     m_acTEncTop[layer].setInitialQP           ( m_RCInitialQP );
     m_acTEncTop[layer].setForceIntraQP        ( m_RCForceIntraQP );
-#endif
-#else
-    m_acTEncTop[layer].setUseRateCtrl     ( m_enableRateCtrl);
-    m_acTEncTop[layer].setTargetBitrate   ( m_targetBitrate);
-    m_acTEncTop[layer].setNumLCUInUnit    ( m_numLCUInUnit);
 #endif
     m_acTEncTop[layer].setTransquantBypassEnableFlag(m_TransquantBypassEnableFlag);
@@ -598,4 +605,7 @@
       for(Int i = 0; i < m_acLayerCfg[layer].m_numScaledRefLayerOffsets; i++)
       {
+#if O0098_SCALED_REF_LAYER_ID
+        m_acTEncTop[layer].setScaledRefLayerId(i, m_acLayerCfg[layer].m_scaledRefLayerId[i]);
+#endif
         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]);
@@ -607,4 +617,10 @@
 #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
   }
@@ -768,5 +784,7 @@
 
   m_cTEncTop.setSaoLcuBoundary (m_saoLcuBoundary);
+#if !HM_CLEANUP_SAO
   m_cTEncTop.setSaoLcuBasedOptimization (m_saoLcuBasedOptimization);
+#endif
   m_cTEncTop.setPCMInputBitDepthFlag  ( m_bPCMInputBitDepthFlag);
   m_cTEncTop.setPCMFilterDisableFlag  ( m_bPCMFilterDisableFlag);
@@ -836,5 +854,4 @@
   m_cTEncTop.setScalingListFile            ( m_scalingListFile   );
   m_cTEncTop.setSignHideFlag(m_signHideFlag);
-#if RATE_CONTROL_LAMBDA_DOMAIN
   m_cTEncTop.setUseRateCtrl         ( m_RCEnableRateControl );
   m_cTEncTop.setTargetBitrate       ( m_RCTargetBitrate );
@@ -844,9 +861,4 @@
   m_cTEncTop.setInitialQP           ( m_RCInitialQP );
   m_cTEncTop.setForceIntraQP        ( m_RCForceIntraQP );
-#else
-  m_cTEncTop.setUseRateCtrl     ( m_enableRateCtrl);
-  m_cTEncTop.setTargetBitrate   ( m_targetBitrate);
-  m_cTEncTop.setNumLCUInUnit    ( m_numLCUInUnit);
-#endif
   m_cTEncTop.setTransquantBypassEnableFlag(m_TransquantBypassEnableFlag);
   m_cTEncTop.setCUTransquantBypassFlagValue(m_CUTransquantBypassFlagValue);
@@ -1087,4 +1099,11 @@
 #endif
 #endif
+#if VPS_TSLAYERS
+    vps->setMaxTSLayersPresentFlag(true);
+    for( i = 0; i < MAX_VPS_LAYER_ID_PLUS1 - 1; i++ )
+    {
+        vps->setMaxTSLayersMinus1(i, vps->getMaxTLayers()-1);
+    }
+#endif
 #if N0120_MAX_TID_REF_PRESENT_FLAG
 #if N0120_MAX_TID_REF_CFG
@@ -1171,7 +1190,65 @@
   }
 #endif
+ #if VPS_DPB_SIZE_TABLE
+  // The Layer ID List variables can be derived here.  
+#if DERIVE_LAYER_ID_LIST_VARIABLES
+  vps->deriveLayerIdListVariables();
+#endif
+  vps->deriveNumberOfSubDpbs();
+  // Initialize dpb_size_table() for all ouput layer sets in the VPS extension
+  for(i = 1; i < vps->getNumOutputLayerSets(); i++)
+  {
+    Int layerSetId = vps->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 < vps->getMaxTLayers(); j++)
+    {
+
+      Int maxNumReorderPics = -1;
+      for(Int k = 0; k < vps->getNumSubDpbs(i); k++)
+      {
+        Int layerId = vps->getLayerSetLayerIdList(layerSetId, k); // k-th layer in the output layer set
+        vps->setMaxVpsDecPicBufferingMinus1( i, k, j,  m_acTEncTop[layerId].getMaxDecPicBuffering(j) - 1 );
+        maxNumReorderPics       = std::max( maxNumReorderPics, m_acTEncTop[layerId].getNumReorderPics(j));
+      }
+      vps->setMaxVpsNumReorderPics(i, j, maxNumReorderPics);
+      
+      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] |= ( maxNumReorderPics != vps->getMaxVpsNumReorderPics(i, j - 1) );
+        for(Int k = 0; k < vps->getNumSubDpbs(i) && !checkFlagInner[j]; k++)  // If checkFlagInner[j] is true, break and signal the values
+        {
+          checkFlagInner[j] |= ( vps->getMaxVpsDecPicBufferingMinus1(i, k, j - 1) != vps->getMaxVpsDecPicBufferingMinus1(i, k, j) );
+        }
+      }
+      // If checkFlagInner[j] = true, then some value needs to be signalled for the j-th sub-layer
+      vps->setSubLayerDpbInfoPresentFlag( i, j, checkFlagInner[j] );
+    }
+    for(Int j = 1; j < vps->getMaxTLayers(); j++) // Check if DPB info of any of non-zero sub-layers is signaled. If so set flag to one
+    {
+      if( vps->getSubLayerDpbInfoPresentFlag(i, j) )
+      {
+        checkFlagOuter = true;
+        break;
+      }
+    }
+    vps->setSubLayerFlagInfoPresentFlag( i, checkFlagOuter );
+  }
+#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() - 1; layerCtr++)
   {
@@ -1202,4 +1279,16 @@
         vps->setDirectDependencyType( layerCtr, refLayerCtr, ((m_acTEncTop[layerCtr].getSamplePredEnabledFlag(refLayerCtr) ? 1 : 0) |
                                                               (m_acTEncTop[layerCtr].getMotionPredEnabledFlag(refLayerCtr) ? 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
       }
       else
@@ -1210,10 +1299,15 @@
 #endif
   }
-#if IL_SL_SIGNALLING_N0371
-  for(i = 1; i < vps->getMaxLayers(); i++)
-  {
-    for(Int j = 0; j < i; j++)
-    {
-      vps->setScalingListLayerDependency( i, j, vps->checkLayerDependency( i,j ) );
+
+#if O0092_0094_DEPENDENCY_CONSTRAINT
+  for(UInt layerCtr = 1;layerCtr <= vps->getMaxLayers() - 1; layerCtr++)
+  {
+    vps->setNumRefLayers(vps->getLayerIdInNuh(layerCtr));   // identify the number of direct and indirect reference layers of current layer and set recursiveRefLayersFlags
+  }
+  if(vps->getMaxLayers() > MAX_REF_LAYERS)
+  {
+    for(UInt layerCtr = 1;layerCtr <= vps->getMaxLayers() - 1; layerCtr++)
+    {
+      assert( vps->getNumRefLayers(vps->getLayerIdInNuh(layerCtr)) <= MAX_REF_LAYERS);
     }
   }
@@ -1232,6 +1326,9 @@
     }
 #endif
+#if O0223_PICTURE_TYPES_ALIGN_FLAG
+    vps->setCrossLayerPictureTypeAlignFlag( m_crossLayerPictureTypeAlignFlag );
+#endif
 #if N0147_IRAP_ALIGN_FLAG
-    vps->setCrossLayerIrapAlignFlag(true);
+    vps->setCrossLayerIrapAlignFlag( m_crossLayerIrapAlignFlag );
     for(UInt layerCtr = 1;layerCtr <= vps->getMaxLayers() - 1; layerCtr++)
     {
@@ -1256,4 +1353,7 @@
 #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 !VPS_EXTN_OFFSET_CALC
@@ -1266,4 +1366,8 @@
 #if O0215_PHASE_ALIGNMENT
   vps->setPhaseAlignFlag( m_phaseAlignFlag );
+#endif
+
+#if O0153_ALT_OUTPUT_LAYER_FLAG
+  vps->setAltOuputLayerFlag( m_altOutputLayerFlag );
 #endif
 
@@ -2022,5 +2126,5 @@
     case NAL_UNIT_CODED_SLICE_TRAIL_R:
     case NAL_UNIT_CODED_SLICE_TRAIL_N:
-    case NAL_UNIT_CODED_SLICE_TLA_R:
+    case NAL_UNIT_CODED_SLICE_TSA_R:
     case NAL_UNIT_CODED_SLICE_TSA_N:
     case NAL_UNIT_CODED_SLICE_STSA_R:
