/* The copyright in this software is being made available under the BSD
 * License, included below. This software may be subject to other third party
 * and contributor rights, including patent rights, and no such rights are
 * granted under this license.
 *
 * Copyright (c) 2010-2014, ITU/ISO/IEC
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *  * Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 *  * Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
 *    be used to endorse or promote products derived from this software without
 *    specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
 * THE POSSIBILITY OF SUCH DAMAGE.
 */

/** \file     TDecCu.cpp
    \brief    CU decoder class
*/

#include "TDecCu.h"
#include "TLibCommon/TComTU.h"

//! \ingroup TLibDecoder
//! \{

// ====================================================================================================================
// Constructor / destructor / create / destroy
// ====================================================================================================================

TDecCu::TDecCu()
{
  m_ppcYuvResi = NULL;
  m_ppcYuvReco = NULL;
  m_ppcCU      = NULL;
}

TDecCu::~TDecCu()
{
}

Void TDecCu::init( TDecEntropy* pcEntropyDecoder, TComTrQuant* pcTrQuant, TComPrediction* pcPrediction)
{
  m_pcEntropyDecoder  = pcEntropyDecoder;
  m_pcTrQuant         = pcTrQuant;
  m_pcPrediction      = pcPrediction;
}

/**
 \param    uiMaxDepth    total number of allowable depth
 \param    uiMaxWidth    largest CU width
 \param    uiMaxHeight   largest CU height
 */
Void TDecCu::create( UInt uiMaxDepth, UInt uiMaxWidth, UInt uiMaxHeight, ChromaFormat chromaFormatIDC )
{
  m_uiMaxDepth = uiMaxDepth+1;

  m_ppcYuvResi = new TComYuv*[m_uiMaxDepth-1];
  m_ppcYuvReco = new TComYuv*[m_uiMaxDepth-1];
  m_ppcCU      = new TComDataCU*[m_uiMaxDepth-1];

  UInt uiNumPartitions;
  for ( UInt ui = 0; ui < m_uiMaxDepth-1; ui++ )
  {
    uiNumPartitions = 1<<( ( m_uiMaxDepth - ui - 1 )<<1 );
    UInt uiWidth  = uiMaxWidth  >> ui;
    UInt uiHeight = uiMaxHeight >> ui;

    m_ppcYuvResi[ui] = new TComYuv;    m_ppcYuvResi[ui]->create( uiWidth, uiHeight, chromaFormatIDC );
    m_ppcYuvReco[ui] = new TComYuv;    m_ppcYuvReco[ui]->create( uiWidth, uiHeight, chromaFormatIDC );
    m_ppcCU     [ui] = new TComDataCU; m_ppcCU     [ui]->create( chromaFormatIDC, uiNumPartitions, uiWidth, uiHeight, true, uiMaxWidth >> (m_uiMaxDepth - 1) );
  }

  m_bDecodeDQP = false;
  m_IsChromaQpAdjCoded = false;

  // initialize partition order.
  UInt* piTmp = &g_auiZscanToRaster[0];
  initZscanToRaster(m_uiMaxDepth, 1, 0, piTmp);
  initRasterToZscan( uiMaxWidth, uiMaxHeight, m_uiMaxDepth );

  // initialize conversion matrix from partition index to pel
  initRasterToPelXY( uiMaxWidth, uiMaxHeight, m_uiMaxDepth );
}

Void TDecCu::destroy()
{
  for ( UInt ui = 0; ui < m_uiMaxDepth-1; ui++ )
  {
    m_ppcYuvResi[ui]->destroy(); delete m_ppcYuvResi[ui]; m_ppcYuvResi[ui] = NULL;
    m_ppcYuvReco[ui]->destroy(); delete m_ppcYuvReco[ui]; m_ppcYuvReco[ui] = NULL;
    m_ppcCU     [ui]->destroy(); delete m_ppcCU     [ui]; m_ppcCU     [ui] = NULL;
  }

  delete [] m_ppcYuvResi; m_ppcYuvResi = NULL;
  delete [] m_ppcYuvReco; m_ppcYuvReco = NULL;
  delete [] m_ppcCU     ; m_ppcCU      = NULL;
}

// ====================================================================================================================
// Public member functions
// ====================================================================================================================

/** \param    pcCU        pointer of CU data
 \param    ruiIsLast   last data?
 */
Void TDecCu::decodeCU( TComDataCU* pcCU, UInt& ruiIsLast )
{
  if ( pcCU->getSlice()->getPPS()->getUseDQP() )
  {
    setdQPFlag(true);
  }

  if ( pcCU->getSlice()->getUseChromaQpAdj() )
  {
    setIsChromaQpAdjCoded(true);
  }

  // start from the top level CU
  xDecodeCU( pcCU, 0, 0, ruiIsLast);
}

/** \param    pcCU        pointer of CU data
 */
Void TDecCu::decompressCU( TComDataCU* pcCU )
{
  xDecompressCU( pcCU, 0,  0 );
}

// ====================================================================================================================
// Protected member functions
// ====================================================================================================================

/**decode end-of-slice flag
 * \param pcCU
 * \param uiAbsPartIdx
 * \param uiDepth
 * \returns Bool
 */
Bool TDecCu::xDecodeSliceEnd( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth)
{
  UInt uiIsLast;
  TComPic* pcPic = pcCU->getPic();
  TComSlice * pcSlice = pcPic->getSlice(pcPic->getCurrSliceIdx());
  UInt uiCurNumParts    = pcPic->getNumPartInCU() >> (uiDepth<<1);
  UInt uiWidth = pcSlice->getSPS()->getPicWidthInLumaSamples();
  UInt uiHeight = pcSlice->getSPS()->getPicHeightInLumaSamples();
  UInt uiGranularityWidth = g_uiMaxCUWidth;
  UInt uiPosX = pcCU->getCUPelX() + g_auiRasterToPelX[ g_auiZscanToRaster[uiAbsPartIdx] ];
  UInt uiPosY = pcCU->getCUPelY() + g_auiRasterToPelY[ g_auiZscanToRaster[uiAbsPartIdx] ];

  if(((uiPosX+pcCU->getWidth(uiAbsPartIdx))%uiGranularityWidth==0||(uiPosX+pcCU->getWidth(uiAbsPartIdx)==uiWidth))
    &&((uiPosY+pcCU->getHeight(uiAbsPartIdx))%uiGranularityWidth==0||(uiPosY+pcCU->getHeight(uiAbsPartIdx)==uiHeight)))
  {
    m_pcEntropyDecoder->decodeTerminatingBit( uiIsLast );
  }
  else
  {
    uiIsLast=0;
  }

  if(uiIsLast > 0)
  {
    if(pcSlice->isNextSliceSegment()&&!pcSlice->isNextSlice())
    {
      pcSlice->setSliceSegmentCurEndCUAddr(pcCU->getSCUAddr()+uiAbsPartIdx+uiCurNumParts);
    }
    else
    {
      pcSlice->setSliceCurEndCUAddr(pcCU->getSCUAddr()+uiAbsPartIdx+uiCurNumParts);
      pcSlice->setSliceSegmentCurEndCUAddr(pcCU->getSCUAddr()+uiAbsPartIdx+uiCurNumParts);
    }
  }

  return uiIsLast>0;
}

/** decode CU block recursively
 * \param pcCU
 * \param uiAbsPartIdx
 * \param uiDepth
 * \returns Void
 */

Void TDecCu::xDecodeCU( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, UInt& ruiIsLast)
{
  TComPic* pcPic = pcCU->getPic();
  UInt uiCurNumParts    = pcPic->getNumPartInCU() >> (uiDepth<<1);
  UInt uiQNumParts      = uiCurNumParts>>2;

  Bool bBoundary = false;
  UInt uiLPelX   = pcCU->getCUPelX() + g_auiRasterToPelX[ g_auiZscanToRaster[uiAbsPartIdx] ];
  UInt uiRPelX   = uiLPelX + (g_uiMaxCUWidth>>uiDepth)  - 1;
  UInt uiTPelY   = pcCU->getCUPelY() + g_auiRasterToPelY[ g_auiZscanToRaster[uiAbsPartIdx] ];
  UInt uiBPelY   = uiTPelY + (g_uiMaxCUHeight>>uiDepth) - 1;

  TComSlice * pcSlice = pcCU->getPic()->getSlice(pcCU->getPic()->getCurrSliceIdx());
  Bool bStartInCU = pcCU->getSCUAddr()+uiAbsPartIdx+uiCurNumParts>pcSlice->getSliceSegmentCurStartCUAddr()&&pcCU->getSCUAddr()+uiAbsPartIdx<pcSlice->getSliceSegmentCurStartCUAddr();
  if((!bStartInCU) && ( uiRPelX < pcSlice->getSPS()->getPicWidthInLumaSamples() ) && ( uiBPelY < pcSlice->getSPS()->getPicHeightInLumaSamples() ) )
  {
    m_pcEntropyDecoder->decodeSplitFlag( pcCU, uiAbsPartIdx, uiDepth );
  }
  else
  {
    bBoundary = true;
  }

  if( ( ( uiDepth < pcCU->getDepth( uiAbsPartIdx ) ) && ( uiDepth < g_uiMaxCUDepth - g_uiAddCUDepth ) ) || bBoundary )
  {
    UInt uiIdx = uiAbsPartIdx;
    if( (g_uiMaxCUWidth>>uiDepth) == pcCU->getSlice()->getPPS()->getMinCuDQPSize() && pcCU->getSlice()->getPPS()->getUseDQP())
    {
      setdQPFlag(true);
      pcCU->setQPSubParts( pcCU->getRefQP(uiAbsPartIdx), uiAbsPartIdx, uiDepth ); // set QP to default QP
    }

    if( (g_uiMaxCUWidth>>uiDepth) == pcCU->getSlice()->getPPS()->getMinCuChromaQpAdjSize() && pcCU->getSlice()->getUseChromaQpAdj() )
    {
      setIsChromaQpAdjCoded(true);
    }

    for ( UInt uiPartUnitIdx = 0; uiPartUnitIdx < 4; uiPartUnitIdx++ )
    {
      uiLPelX   = pcCU->getCUPelX() + g_auiRasterToPelX[ g_auiZscanToRaster[uiIdx] ];
      uiTPelY   = pcCU->getCUPelY() + g_auiRasterToPelY[ g_auiZscanToRaster[uiIdx] ];

      Bool bSubInSlice = pcCU->getSCUAddr()+uiIdx+uiQNumParts>pcSlice->getSliceSegmentCurStartCUAddr();
      if ( bSubInSlice )
      {
        if ( !ruiIsLast && ( uiLPelX < pcCU->getSlice()->getSPS()->getPicWidthInLumaSamples() ) && ( uiTPelY < pcCU->getSlice()->getSPS()->getPicHeightInLumaSamples() ) )
        {
          xDecodeCU( pcCU, uiIdx, uiDepth+1, ruiIsLast );
        }
        else
        {
          pcCU->setOutsideCUPart( uiIdx, uiDepth+1 );
        }
      }

      uiIdx += uiQNumParts;
    }
    if( (g_uiMaxCUWidth>>uiDepth) == pcCU->getSlice()->getPPS()->getMinCuDQPSize() && pcCU->getSlice()->getPPS()->getUseDQP())
    {
      if ( getdQPFlag() )
      {
        UInt uiQPSrcPartIdx;
        if ( pcPic->getCU( pcCU->getAddr() )->getSliceSegmentStartCU(uiAbsPartIdx) != pcSlice->getSliceSegmentCurStartCUAddr() )
        {
          uiQPSrcPartIdx = pcSlice->getSliceSegmentCurStartCUAddr() % pcPic->getNumPartInCU();
        }
        else
        {
          uiQPSrcPartIdx = uiAbsPartIdx;
        }
        pcCU->setQPSubParts( pcCU->getRefQP( uiQPSrcPartIdx ), uiAbsPartIdx, uiDepth ); // set QP to default QP
      }
    }
    return;
  }

  if( (g_uiMaxCUWidth>>uiDepth) >= pcCU->getSlice()->getPPS()->getMinCuDQPSize() && pcCU->getSlice()->getPPS()->getUseDQP())
  {
    setdQPFlag(true);
    pcCU->setQPSubParts( pcCU->getRefQP(uiAbsPartIdx), uiAbsPartIdx, uiDepth ); // set QP to default QP
  }

  if( (g_uiMaxCUWidth>>uiDepth) >= pcCU->getSlice()->getPPS()->getMinCuChromaQpAdjSize() && pcCU->getSlice()->getUseChromaQpAdj() )
  {
    setIsChromaQpAdjCoded(true);
  }

  if (pcCU->getSlice()->getPPS()->getTransquantBypassEnableFlag())
  {
    m_pcEntropyDecoder->decodeCUTransquantBypassFlag( pcCU, uiAbsPartIdx, uiDepth );
  }

  // decode CU mode and the partition size
  if( !pcCU->getSlice()->isIntra())
  {
    m_pcEntropyDecoder->decodeSkipFlag( pcCU, uiAbsPartIdx, uiDepth );
  }


  if( pcCU->isSkipped(uiAbsPartIdx) )
  {
    m_ppcCU[uiDepth]->copyInterPredInfoFrom( pcCU, uiAbsPartIdx, REF_PIC_LIST_0 );
    m_ppcCU[uiDepth]->copyInterPredInfoFrom( pcCU, uiAbsPartIdx, REF_PIC_LIST_1 );
    TComMvField cMvFieldNeighbours[MRG_MAX_NUM_CANDS << 1]; // double length for mv of both lists
    UChar uhInterDirNeighbours[MRG_MAX_NUM_CANDS];
    Int numValidMergeCand = 0;
    for( UInt ui = 0; ui < m_ppcCU[uiDepth]->getSlice()->getMaxNumMergeCand(); ++ui )
    {
      uhInterDirNeighbours[ui] = 0;
    }
    m_pcEntropyDecoder->decodeMergeIndex( pcCU, 0, uiAbsPartIdx, uiDepth );
    UInt uiMergeIndex = pcCU->getMergeIndex(uiAbsPartIdx);
    m_ppcCU[uiDepth]->getInterMergeCandidates( 0, 0, cMvFieldNeighbours, uhInterDirNeighbours, numValidMergeCand, uiMergeIndex );
    pcCU->setInterDirSubParts( uhInterDirNeighbours[uiMergeIndex], uiAbsPartIdx, 0, uiDepth );

    TComMv cTmpMv( 0, 0 );
    for ( UInt uiRefListIdx = 0; uiRefListIdx < 2; uiRefListIdx++ )
    {
      if ( pcCU->getSlice()->getNumRefIdx( RefPicList( uiRefListIdx ) ) > 0 )
      {
        pcCU->setMVPIdxSubParts( 0, RefPicList( uiRefListIdx ), uiAbsPartIdx, 0, uiDepth);
        pcCU->setMVPNumSubParts( 0, RefPicList( uiRefListIdx ), uiAbsPartIdx, 0, uiDepth);
        pcCU->getCUMvField( RefPicList( uiRefListIdx ) )->setAllMvd( cTmpMv, SIZE_2Nx2N, uiAbsPartIdx, uiDepth );
        pcCU->getCUMvField( RefPicList( uiRefListIdx ) )->setAllMvField( cMvFieldNeighbours[ 2*uiMergeIndex + uiRefListIdx ], SIZE_2Nx2N, uiAbsPartIdx, uiDepth );
      }
    }
    xFinishDecodeCU( pcCU, uiAbsPartIdx, uiDepth, ruiIsLast );
    return;
  }
#if ITRI_MULTI_SAMPLE_MODE
  if (!pcCU->isSkipped(uiAbsPartIdx))
	  m_pcEntropyDecoder->decodetwoSampleFlag(pcCU, uiAbsPartIdx, uiDepth);
  if (!pcCU->getTwoSampleFlag(uiAbsPartIdx))
  {
#endif
  if (pcCU->getSlice()->getSPS()->getUseIntraBlockCopy())
  {
    m_pcEntropyDecoder->decodeIntraBCFlag( pcCU, uiAbsPartIdx, 0, uiDepth );
  }

  if ( pcCU->isIntraBC( uiAbsPartIdx ) )
  {
    pcCU->setSizeSubParts( g_uiMaxCUWidth>>uiDepth, g_uiMaxCUHeight>>uiDepth, uiAbsPartIdx, uiDepth );
    m_pcEntropyDecoder->decodePartSizeIntraBC( pcCU, uiAbsPartIdx, uiDepth );

    const PartSize ePartSize = pcCU->getPartitionSize( uiAbsPartIdx );
    const UInt uiPUOffset = ( g_auiPUOffset[UInt( ePartSize )] << ( ( pcCU->getSlice()->getSPS()->getMaxCUDepth() - uiDepth ) << 1 ) ) >> 4;
    const UInt iNumPart = pcCU->getNumPartitions( uiAbsPartIdx );

    UInt tempOffset = uiAbsPartIdx;
    for( UInt iPartIdx = 0; iPartIdx < iNumPart ; ++iPartIdx )
    {
      m_pcEntropyDecoder->decodeIntraBC( pcCU, tempOffset, iPartIdx, uiDepth );
      tempOffset += uiPUOffset;
    }
  }
  else
  {
    m_pcEntropyDecoder->decodePredMode( pcCU, uiAbsPartIdx, uiDepth );

#if SCM__R0348_PALETTE_MODE
    if (pcCU->getPLTModeFlag(uiAbsPartIdx) )
    {
      Bool bCodeDQP = getdQPFlag();
      setdQPFlag(bCodeDQP);
      xFinishDecodeCU( pcCU, uiAbsPartIdx, uiDepth, ruiIsLast );
      return;
    }
#endif
    m_pcEntropyDecoder->decodePartSize( pcCU, uiAbsPartIdx, uiDepth );

    if (pcCU->isIntra( uiAbsPartIdx ) && pcCU->getPartitionSize( uiAbsPartIdx ) == SIZE_2Nx2N )
    {
      m_pcEntropyDecoder->decodeIPCMInfo( pcCU, uiAbsPartIdx, uiDepth );

      if(pcCU->getIPCMFlag(uiAbsPartIdx))
      {
        xFinishDecodeCU( pcCU, uiAbsPartIdx, uiDepth, ruiIsLast );
        return;
      }
    }

    // prediction mode ( Intra : direction mode, Inter : Mv, reference idx )
    m_pcEntropyDecoder->decodePredInfo( pcCU, uiAbsPartIdx, uiDepth, m_ppcCU[uiDepth]);
  }

  // Coefficient decoding
  Bool bCodeDQP = getdQPFlag();
  Bool isChromaQpAdjCoded = getIsChromaQpAdjCoded();
  m_pcEntropyDecoder->decodeCoeff( pcCU, uiAbsPartIdx, uiDepth, bCodeDQP, isChromaQpAdjCoded );
  setIsChromaQpAdjCoded( isChromaQpAdjCoded );
  setdQPFlag( bCodeDQP );
#if ITRI_MULTI_SAMPLE_MODE
  }
#endif
  xFinishDecodeCU( pcCU, uiAbsPartIdx, uiDepth, ruiIsLast );
}

Void TDecCu::xFinishDecodeCU( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, UInt& ruiIsLast)
{
  if(  pcCU->getSlice()->getPPS()->getUseDQP())
  {
    pcCU->setQPSubParts( getdQPFlag()?pcCU->getRefQP(uiAbsPartIdx):pcCU->getCodedQP(), uiAbsPartIdx, uiDepth ); // set QP
  }

  if (pcCU->getSlice()->getUseChromaQpAdj() && !getIsChromaQpAdjCoded())
  {
    pcCU->setChromaQpAdjSubParts( pcCU->getCodedChromaQpAdj(), uiAbsPartIdx, uiDepth ); // set QP
  }

  ruiIsLast = xDecodeSliceEnd( pcCU, uiAbsPartIdx, uiDepth);
}

Void TDecCu::xDecompressCU( TComDataCU* pcLCU, UInt uiAbsPartIdx,  UInt uiDepth )
{
  TComPic* pcPic = pcLCU->getPic();

  Bool bBoundary = false;
  UInt uiLPelX   = pcLCU->getCUPelX() + g_auiRasterToPelX[ g_auiZscanToRaster[uiAbsPartIdx] ];
  UInt uiRPelX   = uiLPelX + (g_uiMaxCUWidth>>uiDepth)  - 1;
  UInt uiTPelY   = pcLCU->getCUPelY() + g_auiRasterToPelY[ g_auiZscanToRaster[uiAbsPartIdx] ];
  UInt uiBPelY   = uiTPelY + (g_uiMaxCUHeight>>uiDepth) - 1;

  UInt uiCurNumParts    = pcPic->getNumPartInCU() >> (uiDepth<<1);
  TComSlice * pcSlice = pcLCU->getPic()->getSlice(pcLCU->getPic()->getCurrSliceIdx());
  Bool bStartInCU = pcLCU->getSCUAddr()+uiAbsPartIdx+uiCurNumParts>pcSlice->getSliceSegmentCurStartCUAddr()&&pcLCU->getSCUAddr()+uiAbsPartIdx<pcSlice->getSliceSegmentCurStartCUAddr();
  if(bStartInCU||( uiRPelX >= pcSlice->getSPS()->getPicWidthInLumaSamples() ) || ( uiBPelY >= pcSlice->getSPS()->getPicHeightInLumaSamples() ) )
  {
    bBoundary = true;
  }

  if( ( ( uiDepth < pcLCU->getDepth( uiAbsPartIdx ) ) && ( uiDepth < g_uiMaxCUDepth - g_uiAddCUDepth ) ) || bBoundary )
  {
    UInt uiNextDepth = uiDepth + 1;
    UInt uiQNumParts = pcLCU->getTotalNumPart() >> (uiNextDepth<<1);
    UInt uiIdx = uiAbsPartIdx;
    for ( UInt uiPartIdx = 0; uiPartIdx < 4; uiPartIdx++ )
    {
      uiLPelX = pcLCU->getCUPelX() + g_auiRasterToPelX[ g_auiZscanToRaster[uiIdx] ];
      uiTPelY = pcLCU->getCUPelY() + g_auiRasterToPelY[ g_auiZscanToRaster[uiIdx] ];

      Bool binSlice = ((pcLCU->getSCUAddr() + uiIdx + uiQNumParts) > pcSlice->getSliceSegmentCurStartCUAddr()) && ((pcLCU->getSCUAddr() + uiIdx) < pcSlice->getSliceSegmentCurEndCUAddr());
      if(binSlice&&( uiLPelX < pcSlice->getSPS()->getPicWidthInLumaSamples() ) && ( uiTPelY < pcSlice->getSPS()->getPicHeightInLumaSamples() ) )
      {
        xDecompressCU(pcLCU, uiIdx, uiNextDepth );
      }

      uiIdx += uiQNumParts;
    }
    return;
  }

  // Residual reconstruction
  m_ppcYuvResi[uiDepth]->clear();

  m_ppcCU[uiDepth]->copySubCU( pcLCU, uiAbsPartIdx, uiDepth );

  switch( m_ppcCU[uiDepth]->getPredictionMode(0) )
  {
    case MODE_INTER:
      xReconInter( m_ppcCU[uiDepth], uiDepth );
      break;
    case MODE_INTRA:
      xReconIntraQT( m_ppcCU[uiDepth], uiDepth );
      break;
    case MODE_INTRABC:
      xReconIntraBC( m_ppcCU[uiDepth], uiDepth );
      break;
    default:
      assert(0);
      break;
  }

#ifdef DEBUG_STRING
  const PredMode predMode=m_ppcCU[uiDepth]->getPredictionMode(0);
  if (DebugOptionList::DebugString_Structure.getInt()&DebugStringGetPredModeMask(predMode))
  {
    PartSize eSize=m_ppcCU[uiDepth]->getPartitionSize(0);
    std::ostream &ss(std::cout);

    ss <<"###: " << (predMode==MODE_INTRA?"Intra   ":(predMode==MODE_INTER?"Inter   ":"IntraBC ")) << partSizeToString[eSize] << " CU at " << m_ppcCU[uiDepth]->getCUPelX() << ", " << m_ppcCU[uiDepth]->getCUPelY() << " width=" << UInt(m_ppcCU[uiDepth]->getWidth(0)) << std::endl;
  }
#endif

#if ITRI_MULTI_SAMPLE_MODE
#if SCM__R0348_PALETTE_MODE || ITRI_MULTI_SAMPLE_MODE
  if (m_ppcCU[uiDepth]->getPLTModeFlag(0) == false && m_ppcCU[uiDepth]->getTwoSampleFlag(0) == false)
#endif
#else
#if SCM__R0348_PALETTE_MODE
  if (m_ppcCU[uiDepth]->getPLTModeFlag(0) == false)
#endif
#endif
  if ( m_ppcCU[uiDepth]->isLosslessCoded(0) && (m_ppcCU[uiDepth]->getIPCMFlag(0) == false))
  {
    xFillPCMBuffer(m_ppcCU[uiDepth], uiDepth);
  }

  xCopyToPic( m_ppcCU[uiDepth], pcPic, uiAbsPartIdx, uiDepth );
}

Void TDecCu::xReconInter( TComDataCU* pcCU, UInt uiDepth )
{

  // inter prediction
  m_pcPrediction->motionCompensation( pcCU, m_ppcYuvReco[uiDepth] );

#ifdef DEBUG_STRING
  const Int debugPredModeMask=DebugStringGetPredModeMask(MODE_INTER);
  if (DebugOptionList::DebugString_Pred.getInt()&debugPredModeMask) printBlockToStream(std::cout, "###inter-pred: ", *(m_ppcYuvReco[uiDepth]));
#endif

  // inter recon
  xDecodeInterTexture( pcCU, uiDepth );

#ifdef DEBUG_STRING
  if (DebugOptionList::DebugString_Resi.getInt()&debugPredModeMask) printBlockToStream(std::cout, "###inter-resi: ", *(m_ppcYuvResi[uiDepth]));
#endif

  // clip for only non-zero cbp case
  if  ( pcCU->getQtRootCbf( 0) )
  {
#if SCM__R0147_ADAPTIVE_COLOR_TRANSFORM
    if(pcCU->getColorTransform( 0 ))
    {
      m_ppcYuvResi[uiDepth]->convert(0, 0, pcCU->getWidth( 0 ), false, pcCU->isLosslessCoded(0));
    }
#endif
    m_ppcYuvReco[uiDepth]->addClip( m_ppcYuvReco[uiDepth], m_ppcYuvResi[uiDepth], 0, pcCU->getWidth( 0 ) );
  }
  else
  {
    m_ppcYuvReco[uiDepth]->copyPartToPartYuv( m_ppcYuvReco[uiDepth],0, pcCU->getWidth( 0 ),pcCU->getHeight( 0 ));
  }
#ifdef DEBUG_STRING
  if (DebugOptionList::DebugString_Reco.getInt()&debugPredModeMask) printBlockToStream(std::cout, "###inter-reco: ", *(m_ppcYuvReco[uiDepth]));
#endif

}

#if ITRI_MULTI_SAMPLE_MODE
Void TDecCu::xReconIntratwoSample(TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth)
{
	TComYuv* pcRecoYuv = m_ppcYuvReco[uiDepth];
	TComYuv* pcPredYuv = m_ppcYuvReco[uiDepth];
	//construction of sample candidates
	Int index = 0;
#if ITRI_CAND_ESTABLISHMENT==1
	Pel Neighbours_Y[ITRI_MULTI_SAMPLE_MODE_CANDIDATE_LIST_SIZE];
	Pel Neighbours_Cb[ITRI_MULTI_SAMPLE_MODE_CANDIDATE_LIST_SIZE];
	Pel Neighbours_Cr[ITRI_MULTI_SAMPLE_MODE_CANDIDATE_LIST_SIZE];
	Int neighborIdxCnt = 0;
	Pel allNeighbours[3][257];
	if (!pcCU->getNeighSample(0, uiAbsPartIdx, allNeighbours[0], allNeighbours[1], allNeighbours[2], neighborIdxCnt))
	{
		assert(neighborIdxCnt == 0);
		index = 0;
	}
	else
		index = neighborIdxCnt;

	Pel *paOrig[3];
	paOrig[0] = allNeighbours[0];
	paOrig[1] = allNeighbours[1];
	paOrig[2] = allNeighbours[2];
	UInt uiPLTSize = 1;
	if (index > 0)
	{
		deriveNeighborPLT(pcCU, Neighbours_Y, Neighbours_Cb, Neighbours_Cr, paOrig, pcCU->getWidth(0), pcCU->getHeight(0), pcCU->getHeight(0), uiPLTSize, neighborIdxCnt);
		index = uiPLTSize;
	}
#elif ITRI_CAND_ESTABLISHMENT==2
	Pel Neighbours_Y[ITRI_MULTI_SAMPLE_MODE_CANDIDATE_LIST_SIZE];
	Pel Neighbours_Cb[ITRI_MULTI_SAMPLE_MODE_CANDIDATE_LIST_SIZE];
	Pel Neighbours_Cr[ITRI_MULTI_SAMPLE_MODE_CANDIDATE_LIST_SIZE];
	Int neighborIdxCnt = 0;
	Pel allNeighbours[3][129];
	if (!pcCU->getNeighSample(0, uiAbsPartIdx, allNeighbours[0], allNeighbours[1], allNeighbours[2], neighborIdxCnt))
	{
		assert(neighborIdxCnt == 0);
		index = 0;
	}
	else
		index = neighborIdxCnt;

	//construction of sample candidates
	if (index > 0)
	{
		Neighbours_Y[0] = allNeighbours[0][0];
		Neighbours_Cb[0] = allNeighbours[1][0];
		Neighbours_Cr[0] = allNeighbours[2][0];
		UInt uiNumColor = 1;
		Bool bRepeatedColor;
		for (Int i = index - 1; i >= 1; i--)
		{
			Neighbours_Y[uiNumColor] = allNeighbours[0][i];
			Neighbours_Cb[uiNumColor] = allNeighbours[1][i];
			Neighbours_Cr[uiNumColor] = allNeighbours[2][i];
			bRepeatedColor = false;
			for (Int j = 0; j < uiNumColor; j++)
			{
				if ((Neighbours_Y[uiNumColor] == Neighbours_Y[j]) && (Neighbours_Cb[uiNumColor] == Neighbours_Cb[j]) && (Neighbours_Cr[uiNumColor] == Neighbours_Cr[j]))
				{
					bRepeatedColor = true;
					break;
				}
			}

			if (!bRepeatedColor)
				uiNumColor++;

			if (uiNumColor == ITRI_MULTI_SAMPLE_MODE_CANDIDATE_LIST_SIZE)
				break;
		}
		index = uiNumColor;
	}
#elif ITRI_CAND_ESTABLISHMENT==3
	Pel Neighbours_Y[ITRI_MULTI_SAMPLE_MODE_CANDIDATE_LIST_SIZE];
	Pel Neighbours_Cb[ITRI_MULTI_SAMPLE_MODE_CANDIDATE_LIST_SIZE];
	Pel Neighbours_Cr[ITRI_MULTI_SAMPLE_MODE_CANDIDATE_LIST_SIZE];

	Int uiPLTSizePrev = pcCU->getPLTSize(CHANNEL_TYPE_LUMA, 0);

	if (uiPLTSizePrev > 0)
	{
		for (Int i = 0; i < uiPLTSizePrev; i++)
		{
			Neighbours_Y[index] = pcCU->getPLT(0, 0, i);
			Neighbours_Cb[index] = pcCU->getPLT(1, 0, i);
			Neighbours_Cr[index] = pcCU->getPLT(2, 0, i);
			index++;
			if (index == ITRI_MULTI_SAMPLE_MODE_CANDIDATE_LIST_SIZE)
				break;
		}
	}
#elif ITRI_CAND_ESTABLISHMENT==4
	Pel Neighbours_Y[ITRI_MULTI_SAMPLE_MODE_CANDIDATE_LIST_SIZE];
	Pel Neighbours_Cb[ITRI_MULTI_SAMPLE_MODE_CANDIDATE_LIST_SIZE];
	Pel Neighbours_Cr[ITRI_MULTI_SAMPLE_MODE_CANDIDATE_LIST_SIZE];
	Int neighborIdxCnt = 0;
	Pel allNeighbours[3][129];
	if (!pcCU->getNeighSample(0, uiAbsPartIdx, allNeighbours[0], allNeighbours[1], allNeighbours[2], neighborIdxCnt))
	{
		assert(neighborIdxCnt == 0);
		index = 0;
	}
	else
		index = neighborIdxCnt;

	//construction of sample candidates
	if (index > 0)
	{
		Pel *paOrig[3];
		paOrig[0] = allNeighbours[0];
		paOrig[1] = allNeighbours[1];
		paOrig[2] = allNeighbours[2];
		UInt uiPLTSize = 1;
		deriveNeighborPLT(pcCU, Neighbours_Y, Neighbours_Cb, Neighbours_Cr, paOrig, pcCU->getWidth(0), pcCU->getHeight(0), pcCU->getHeight(0), uiPLTSize, neighborIdxCnt);

		UInt uiNumColor = 1;
		Bool bRepeatedColor;
		for (Int i = index - 1; i >= 0; i--)
		{
			Neighbours_Y[uiNumColor] = allNeighbours[0][i];
			Neighbours_Cb[uiNumColor] = allNeighbours[1][i];
			Neighbours_Cr[uiNumColor] = allNeighbours[2][i];
			bRepeatedColor = false;
			for (Int j = 0; j < uiNumColor; j++)
			{
				if ((Neighbours_Y[uiNumColor] == Neighbours_Y[j]) && (Neighbours_Cb[uiNumColor] == Neighbours_Cb[j]) && (Neighbours_Cr[uiNumColor] == Neighbours_Cr[j]))
				{
					bRepeatedColor = true;
					break;
				}
			}

			if (!bRepeatedColor)
				uiNumColor++;

			if (uiNumColor == ITRI_MULTI_SAMPLE_MODE_CANDIDATE_LIST_SIZE)
				break;
		}
		index = uiNumColor;
	}
#else
	Pel Neighbours_Y[5];
	Pel Neighbours_Cb[5];
	Pel Neighbours_Cr[5];
	for (Int i = 0; i < 5; i++)
	{
		if (!pcCU->getNeighSample(0, uiAbsPartIdx, &testY, &testCb, &testCr, i))
		{
			continue;
		}
		Neighbours_Y[index] = testY;
		Neighbours_Cb[index] = testCb;
		Neighbours_Cr[index] = testCr;
		index++;
		for (Int j = 0; j<index - 1; j++)
		{
			if ((Neighbours_Y[index - 1] == Neighbours_Y[j]) && (Neighbours_Cb[index - 1] == Neighbours_Cb[j]) && (Neighbours_Cr[index - 1] == Neighbours_Cr[j]))
			{
				index--;
				break;
			}
		}
	}
#endif

#if ITRI_DEFAULT_FROM_PALETTE
	if (index < ITRI_MULTI_SAMPLE_MODE_CANDIDATE_LIST_SIZE)
	{
		Int uiPLTSizePrev = pcCU->getPLTSize(CHANNEL_TYPE_LUMA, 0);

		Bool bRepeatedColor;
		if (uiPLTSizePrev > 0)
		{
			for (Int i = 0; i < uiPLTSizePrev; i++)
			{
				Neighbours_Y[index] = pcCU->getPLT(0, 0, i);
				Neighbours_Cb[index] = pcCU->getPLT(1, 0, i);
				Neighbours_Cr[index] = pcCU->getPLT(2, 0, i);
				bRepeatedColor = false;
				for (Int j = 0; j < index; j++)
				{
					if (Neighbours_Y[index] == Neighbours_Y[j] && Neighbours_Cb[index] == Neighbours_Cb[j] && Neighbours_Cr[index] == Neighbours_Cr[j])
					{
						bRepeatedColor = true;
						break;
					}
				}

				if (!bRepeatedColor)
					index++;

				if (index == ITRI_MULTI_SAMPLE_MODE_CANDIDATE_LIST_SIZE)
					break;
			}
		}
	}
#endif

#if ITRI_MULTI_SAMPLE_MODE
	if (index == 0)
	{
		Neighbours_Y[index] = 1 << (g_bitDepth[CHANNEL_TYPE_LUMA] - 1);
		Neighbours_Cb[index] = 1 << (g_bitDepth[CHANNEL_TYPE_CHROMA] - 1);
		Neighbours_Cr[index] = 1 << (g_bitDepth[CHANNEL_TYPE_CHROMA] - 1);
		index++;
	}
#else
	if (index == 0)
	{
		Neighbours_Y[index] = 1 << (g_bitDepth[CHANNEL_TYPE_LUMA] - 1);
		Neighbours_Cb[index] = 1 << (g_bitDepth[CHANNEL_TYPE_CHROMA] - 1);
		Neighbours_Cr[index] = 1 << (g_bitDepth[CHANNEL_TYPE_CHROMA] - 1);
		index++;
	}

	//generate dummy candidates, encoder never selects the dummy ones
	for (; index<ITRI_MULTI_SAMPLE_MODE_CANDIDATE_LIST_SIZE; index++)
	{
		Neighbours_Y[index] = 1 << (g_bitDepth[CHANNEL_TYPE_LUMA] - 1);
		Neighbours_Cb[index] = 1 << (g_bitDepth[CHANNEL_TYPE_CHROMA] - 1);
		Neighbours_Cr[index] = 1 << (g_bitDepth[CHANNEL_TYPE_CHROMA] - 1);
	}
#endif

	for (UInt ch = 0; ch < pcCU->getPic()->getNumberValidComponents(); ch++)
	{
		const ComponentID compID = ComponentID(ch);
		UInt uiStride = pcRecoYuv->getStride(compID);
		UInt uiRecIPredStride = pcCU->getPic()->getPicYuvRec()->getStride(compID);
		Pel* piPred = pcPredYuv->getAddr(compID, uiAbsPartIdx);
		Pel* piReco = pcRecoYuv->getAddr(compID, uiAbsPartIdx);
		Pel* pRecIPred = pcCU->getPic()->getPicYuvRec()->getAddr(compID, pcCU->getAddr(), pcCU->getZorderIdxInCU() + uiAbsPartIdx);
		const UInt width = pcCU->getWidth(0) >> pcCU->getPic()->getComponentScaleX(compID);
		const UInt height = pcCU->getHeight(0) >> pcCU->getPic()->getComponentScaleY(compID);
#if ITRI_MULTI_SAMPLE_MODE
		const UInt minCoeffSizeY = pcCU->getPic()->getMinCUWidth() * pcCU->getPic()->getMinCUHeight();
		const UInt offset = minCoeffSizeY * uiAbsPartIdx;
		Pel *pLevel = pcCU->getLevel(COMPONENT_Y) + offset;
		UInt uiIdx = 0;
		Int iTestSampleIdx = pcCU->gettwoSampleValue(uiAbsPartIdx);
#endif
		for (UInt uiY = 0; uiY < height; uiY++)
		{
			for (UInt uiX = 0; uiX < width; uiX++)
			{
#if ITRI_MULTI_SAMPLE_MODE
				uiIdx = (uiY << pcCU->getPic()->getComponentScaleY(compID))*(width << pcCU->getPic()->getComponentScaleX(compID)) + (uiX << pcCU->getPic()->getComponentScaleX(compID));
#endif
				switch (ch)
				{
				case 0:
#if ITRI_MULTI_SAMPLE_MODE
					piReco[uiX] = pRecIPred[uiX] = piPred[uiX] = (iTestSampleIdx) ? Neighbours_Y[pLevel[uiIdx]] : Neighbours_Y[0];
#else
					piReco[uiX] = pRecIPred[uiX] = piPred[uiX] = Neighbours_Y[(Int)pcCU->gettwoSampleValue(uiAbsPartIdx)];
#endif
					break;
				case 1:
#if ITRI_MULTI_SAMPLE_MODE
					piReco[uiX] = pRecIPred[uiX] = piPred[uiX] = (iTestSampleIdx) ? Neighbours_Cb[pLevel[uiIdx]] : Neighbours_Cb[0];
#else
					piReco[uiX] = pRecIPred[uiX] = piPred[uiX] = Neighbours_Cb[(Int)pcCU->gettwoSampleValue(uiAbsPartIdx)];
#endif
					break;
				case 2:
#if ITRI_MULTI_SAMPLE_MODE
					piReco[uiX] = pRecIPred[uiX] = piPred[uiX] = (iTestSampleIdx) ? Neighbours_Cr[pLevel[uiIdx]] : Neighbours_Cr[0];
#else     
					piReco[uiX] = pRecIPred[uiX] = piPred[uiX] = Neighbours_Cr[(Int)pcCU->gettwoSampleValue(uiAbsPartIdx)];
#endif     
					break;
				default:
					assert(0);
					break;

				}
			}
			piPred += uiStride;
			piReco += uiStride;
			pRecIPred += uiRecIPredStride;
		}
	}
}
#if ITRI_CAND_ESTABLISHMENT==1 || ITRI_CAND_ESTABLISHMENT==4
Void  TDecCu::deriveNeighborPLT(TComDataCU* pcCU, Pel* PaletteY, Pel* PaletteU, Pel* PaletteV, Pel* pSrc[3], UInt uiWidth, UInt uiHeight, UInt uiStride, UInt &uiPLTSize, Int neighborIdxCnt)
{
	Int iErrorLimit = 0;
	UInt uiTotalSize = neighborIdxCnt;
#if ITRI_CAND_ESTABLISHMENT==4
	UInt uiDictMaxSize = 1;
#else
	UInt uiDictMaxSize = ITRI_MULTI_SAMPLE_MODE_CANDIDATE_LIST_SIZE;
#endif
	SortingElement sElement;
	SortingElement *psList = new SortingElement[uiTotalSize];
#if ITRI_CAND_ESTABLISHMENT==4
	SortingElement *pListSort = new SortingElement[1 + 1];
#else
	SortingElement *pListSort = new SortingElement[ITRI_MULTI_SAMPLE_MODE_CANDIDATE_LIST_SIZE + 1];
#endif
	UInt uiIdx = 0;
	UInt uiPos;
	for (UInt uiX = 0; uiX < uiTotalSize; uiX++)
	{
		uiPos = uiX;
		sElement.setAll(pSrc[0][uiPos], pSrc[1][uiPos], pSrc[2][uiPos]);
		Int i = 0;
		for (i = uiIdx - 1; i >= 0; i--)
		{
			if (psList[i].almostEqualData(sElement, iErrorLimit))
			{
				psList[i].uiCnt++;

				break;
			}
		}
		if (i == -1)
		{
			psList[uiIdx].copyDataFrom(sElement);

			psList[uiIdx].uiCnt++;

			uiIdx++;
		}
	}

	for (Int i = 0; i < uiDictMaxSize; i++)
	{
		pListSort[i].uiCnt = 0;
		pListSort[i].setAll(0, 0, 0);
	}
	//bubble sorting
	for (Int i = 0; i < uiTotalSize; i++)
	{
		pListSort[uiDictMaxSize].copyAllFrom(psList[i]);
		for (Int j = uiDictMaxSize; j > 0; j--)
		{
			if (pListSort[j].uiCnt > pListSort[j - 1].uiCnt)
			{
				sElement.copyAllFrom(pListSort[j - 1]);
				pListSort[j - 1].copyAllFrom(pListSort[j]);
				pListSort[j].copyAllFrom(sElement);
			}
			else
			{
				break;
			}
		}
	}

#if ITRI_CAND_ESTABLISHMENT==4
	uiPLTSize = 1;
	for (Int i = 0; i < 1; i++)
#else
	uiPLTSize = ITRI_MULTI_SAMPLE_MODE_CANDIDATE_LIST_SIZE;
	for (Int i = 0; i < ITRI_MULTI_SAMPLE_MODE_CANDIDATE_LIST_SIZE; i++)
#endif
	{
		PaletteY[i] = pListSort[i].uiData[0];
		PaletteU[i] = pListSort[i].uiData[1];
		PaletteV[i] = pListSort[i].uiData[2];

		if (pListSort[i].uiCnt == 0)
		{
			uiPLTSize = i;
			break;
		}
	}

	delete[] psList;
	delete[] pListSort;
}
#endif
#endif

Void TDecCu::xReconIntraBC( TComDataCU* pcCU, UInt uiDepth )
{
  // intra prediction
  const UInt iNumPart = pcCU->getNumPartitions();
  for( Int iPartIdx = 0 ; iPartIdx < iNumPart ; ++iPartIdx )
  {
    m_pcPrediction->intraBlockCopy( pcCU, m_ppcYuvReco[uiDepth], iPartIdx );
  }

#ifdef DEBUG_STRING
  const Int debugPredModeMask=DebugStringGetPredModeMask(MODE_INTRABC);
  if (DebugOptionList::DebugString_Pred.getInt()&debugPredModeMask) printBlockToStream(std::cout, "###inter-pred: ", *(m_ppcYuvReco[uiDepth]));
#endif

  // texture recon
  xDecodeInterTexture( pcCU, uiDepth );

#ifdef DEBUG_STRING
  if (DebugOptionList::DebugString_Resi.getInt()&debugPredModeMask) printBlockToStream(std::cout, "###inter-resi: ", *(m_ppcYuvResi[uiDepth]));
#endif

  // clip for only non-zero cbp case
  if  ( pcCU->getQtRootCbf( 0) )
  {
#if SCM__R0147_ADAPTIVE_COLOR_TRANSFORM 
    if(pcCU->getColorTransform( 0 ))
    {
      m_ppcYuvResi[uiDepth]->convert(0, 0, pcCU->getWidth( 0 ),  false, pcCU->isLosslessCoded(0));
    }
#endif
    m_ppcYuvReco[uiDepth]->addClip( m_ppcYuvReco[uiDepth], m_ppcYuvResi[uiDepth], 0, pcCU->getWidth( 0 ) );
  }
  else
  {
    m_ppcYuvReco[uiDepth]->copyPartToPartYuv( m_ppcYuvReco[uiDepth],0, pcCU->getWidth( 0 ),pcCU->getHeight( 0 ));
  }
#ifdef DEBUG_STRING
  if (DebugOptionList::DebugString_Reco.getInt()&debugPredModeMask) printBlockToStream(std::cout, "###inter-reco: ", *(m_ppcYuvReco[uiDepth]));
#endif

}


Void
TDecCu::xIntraRecBlk(       TComYuv*    pcRecoYuv,
                            TComYuv*    pcPredYuv,
                            TComYuv*    pcResiYuv,
                      const ComponentID compID,
                            TComTU     &rTu)
{
  if (!rTu.ProcessComponentSection(compID)) return;
  const Bool       bIsLuma = isLuma(compID);


  TComDataCU *pcCU = rTu.getCU();
  const UInt uiAbsPartIdx=rTu.GetAbsPartIdxTU();

  const TComRectangle &tuRect  =rTu.getRect(compID);
  const UInt uiWidth           = tuRect.width;
  const UInt uiHeight          = tuRect.height;
  const UInt uiStride          = pcRecoYuv->getStride (compID);
        Pel* piPred            = pcPredYuv->getAddr( compID, uiAbsPartIdx );
  const ChromaFormat chFmt     = rTu.GetChromaFormat();

  if (uiWidth != uiHeight)
  {
    //------------------------------------------------

    //split at current level if dividing into square sub-TUs

    TComTURecurse subTURecurse(rTu, false, TComTU::VERTICAL_SPLIT, true, compID);

    //recurse further
    do
    {
      xIntraRecBlk(pcRecoYuv, pcPredYuv, pcResiYuv, compID, subTURecurse);
    }
    while (subTURecurse.nextSection(rTu));

    //------------------------------------------------

    return;
  }

  const UInt uiChPredMode  = pcCU->getIntraDir( toChannelType(compID), uiAbsPartIdx );
  const UInt uiChCodedMode = (uiChPredMode==DM_CHROMA_IDX && !bIsLuma) ? pcCU->getIntraDir(CHANNEL_TYPE_LUMA, getChromasCorrespondingPULumaIdx(uiAbsPartIdx, chFmt)) : uiChPredMode;
  const UInt uiChFinalMode = ((chFmt == CHROMA_422)       && !bIsLuma) ? g_chroma422IntraAngleMappingTable[uiChCodedMode] : uiChCodedMode;

  //===== init availability pattern =====
  Bool  bAboveAvail = false;
  Bool  bLeftAvail  = false;

  const Bool bUseFilteredPredictions=TComPrediction::filteringIntraReferenceSamples(compID, uiChFinalMode, uiWidth, uiHeight, chFmt, pcCU->getSlice()->getSPS()->getDisableIntraReferenceSmoothing());

#ifdef DEBUG_STRING
  std::ostream &ss(std::cout);
#endif

#if SCM__R0147_ADAPTIVE_COLOR_TRANSFORM
  assert( !pcCU->getColorTransform( 0 ));
#endif

  DEBUG_STRING_NEW(sTemp)
  m_pcPrediction->initAdiPatternChType( rTu, bAboveAvail, bLeftAvail, compID, bUseFilteredPredictions  DEBUG_STRING_PASS_INTO(sTemp) );


  //===== get prediction signal =====

  m_pcPrediction->predIntraAng( compID,   uiChFinalMode, 0 /* Decoder does not have an original image */, 0, piPred, uiStride, rTu, bAboveAvail, bLeftAvail, bUseFilteredPredictions );

#ifdef DEBUG_STRING
  ss << sTemp;
#endif

  //===== inverse transform =====
  Pel*      piResi            = pcResiYuv->getAddr( compID, uiAbsPartIdx );
  TCoeff*   pcCoeff           = pcCU->getCoeff(compID) + rTu.getCoefficientOffset(compID);//( uiNumCoeffInc * uiAbsPartIdx );

  const QpParam cQP(*pcCU, compID);


  DEBUG_STRING_NEW(sDebug);
#ifdef DEBUG_STRING
  const Int debugPredModeMask=DebugStringGetPredModeMask(MODE_INTRA);
  std::string *psDebug=(DebugOptionList::DebugString_InvTran.getInt()&debugPredModeMask) ? &sDebug : 0;
#endif

  if (pcCU->getCbf(uiAbsPartIdx, compID, rTu.GetTransformDepthRel()) != 0)
  {
    m_pcTrQuant->invTransformNxN( rTu, compID, piResi, uiStride, pcCoeff, cQP DEBUG_STRING_PASS_INTO(psDebug) );
  }
  else
  {
    for (UInt y = 0; y < uiHeight; y++)
      for (UInt x = 0; x < uiWidth; x++)
      {
        piResi[(y * uiStride) + x] = 0;
      }
  }

#ifdef DEBUG_STRING
  if (psDebug)
    ss << (*psDebug);
#endif

  //===== reconstruction =====
  const UInt uiRecIPredStride  = pcCU->getPic()->getPicYuvRec()->getStride(compID);

  const Bool useCrossComponentPrediction = isChroma(compID) && (pcCU->getCrossComponentPredictionAlpha(uiAbsPartIdx, compID) != 0);
  const Pel* pResiLuma  = pcResiYuv->getAddr( COMPONENT_Y, uiAbsPartIdx );
  const Int  strideLuma = pcResiYuv->getStride( COMPONENT_Y );

        Pel* pPred      = piPred;
        Pel* pResi      = piResi;
        Pel* pReco      = pcRecoYuv->getAddr( compID, uiAbsPartIdx );
        Pel* pRecIPred  = pcCU->getPic()->getPicYuvRec()->getAddr( compID, pcCU->getAddr(), pcCU->getZorderIdxInCU() + uiAbsPartIdx );


#ifdef DEBUG_STRING
  const Bool bDebugPred=((DebugOptionList::DebugString_Pred.getInt()&debugPredModeMask) && DEBUG_STRING_CHANNEL_CONDITION(compID));
  const Bool bDebugResi=((DebugOptionList::DebugString_Resi.getInt()&debugPredModeMask) && DEBUG_STRING_CHANNEL_CONDITION(compID));
  const Bool bDebugReco=((DebugOptionList::DebugString_Reco.getInt()&debugPredModeMask) && DEBUG_STRING_CHANNEL_CONDITION(compID));
  if (bDebugPred || bDebugResi || bDebugReco)
    ss << "###: " << "CompID: " << compID << " pred mode (ch/fin): " << uiChPredMode << "/" << uiChFinalMode << " absPartIdx: " << rTu.GetAbsPartIdxTU() << std::endl;
#endif

#if RExt__O0043_BEST_EFFORT_DECODING
  const Int bitDepthDelta = g_bitDepthInStream[toChannelType(compID)] - g_bitDepth[toChannelType(compID)];
#endif
  const Int clipbd = g_bitDepth[toChannelType(compID)];

  if( useCrossComponentPrediction )
  {
    TComTrQuant::crossComponentPrediction( rTu, compID, pResiLuma, piResi, piResi, uiWidth, uiHeight, strideLuma, uiStride, uiStride, true );
  }

  for( UInt uiY = 0; uiY < uiHeight; uiY++ )
  {
#ifdef DEBUG_STRING
    if (bDebugPred || bDebugResi || bDebugReco) ss << "###: ";

    if (bDebugPred)
    {
      ss << " - pred: ";
      for( UInt uiX = 0; uiX < uiWidth; uiX++ )
      {
        ss << pPred[ uiX ] << ", ";
      }
    }
    if (bDebugResi) ss << " - resi: ";
#endif

    for( UInt uiX = 0; uiX < uiWidth; uiX++ )
    {
#ifdef DEBUG_STRING
      if (bDebugResi)
        ss << pResi[ uiX ] << ", ";
#endif
#if RExt__O0043_BEST_EFFORT_DECODING
      pReco    [ uiX ] = ClipBD( rightShiftEvenRounding<Pel>(pPred[ uiX ] + pResi[ uiX ], bitDepthDelta), clipbd );
#else
      pReco    [ uiX ] = ClipBD( pPred[ uiX ] + pResi[ uiX ], clipbd );
#endif
      pRecIPred[ uiX ] = pReco[ uiX ];
    }
#ifdef DEBUG_STRING
    if (bDebugReco)
    {
      ss << " - reco: ";
      for( UInt uiX = 0; uiX < uiWidth; uiX++ )
      {
        ss << pReco[ uiX ] << ", ";
      }
    }

    if (bDebugPred || bDebugResi || bDebugReco)
      ss << "\n";
#endif
    pPred     += uiStride;
    pResi     += uiStride;
    pReco     += uiStride;
    pRecIPred += uiRecIPredStride;
  }
}
#if SCM__R0147_ADAPTIVE_COLOR_TRANSFORM
Void
TDecCu::xIntraRecBlk( TComYuv*    pcRecoYuv,
                      TComYuv*    pcPredYuv,
                      TComYuv*    pcResiYuv,
                      TComTU     &rTu)
{
  TComDataCU         *pcCU        = rTu.getCU();
  const UInt         uiAbsPartIdx = rTu.GetAbsPartIdxTU();
  const ChromaFormat chFmt        = rTu.GetChromaFormat();
  Bool bModifyQP = !pcCU->isLosslessCoded(0) && pcCU->getColorTransform( 0 );


  for(UInt ch = 0; ch < MAX_NUM_COMPONENT; ch++)
  {
    ComponentID         compID   = ComponentID(ch);
    const TComRectangle &tuRect  = rTu.getRect(compID);
    const UInt          uiWidth  = tuRect.width;
    const UInt          uiHeight = tuRect.height;
    const Bool          bIsLuma  = isLuma(compID);
    assert( uiWidth == uiHeight );

    Pel*                piPred   = pcPredYuv->getAddr( compID, uiAbsPartIdx );
    Pel*                piResi   = pcResiYuv->getAddr( compID, uiAbsPartIdx );
    TCoeff*             pcCoeff  = pcCU->getCoeff(compID) + rTu.getCoefficientOffset(compID);
    const UInt          uiStride = pcPredYuv->getStride( compID );

    //===== get prediction signal =====
    const UInt uiChPredMode  = pcCU->getIntraDir( toChannelType(compID), uiAbsPartIdx );
    const UInt uiChFinalMode = (uiChPredMode == DM_CHROMA_IDX && !bIsLuma) ? pcCU->getIntraDir(CHANNEL_TYPE_LUMA, getChromasCorrespondingPULumaIdx(uiAbsPartIdx, chFmt)) : uiChPredMode;

    Bool  bAboveAvail = false;
    Bool  bLeftAvail  = false;

    const Bool bUseFilteredPredictions = TComPrediction::filteringIntraReferenceSamples(compID, uiChFinalMode, uiWidth, uiHeight, chFmt, pcCU->getSlice()->getSPS()->getDisableIntraReferenceSmoothing()); 
    m_pcPrediction->initAdiPatternChType( rTu, bAboveAvail, bLeftAvail, compID, bUseFilteredPredictions ); 
    m_pcPrediction->predIntraAng( compID,   uiChFinalMode, 0, 0, piPred, uiStride, rTu, bAboveAvail, bLeftAvail, bUseFilteredPredictions );

    //===== inverse transform =====
    QpParam cQP(*pcCU, compID);
    if(bModifyQP)
    {
      cQP.Qp = cQP.Qp + (compID==COMPONENT_Cr? SCM__R0147_DELTA_QP_FOR_YCgCo_TRANS_V:SCM__R0147_DELTA_QP_FOR_YCgCo_TRANS);
      cQP.per = cQP.Qp/6;
      cQP.rem= cQP.Qp%6;   
      m_pcTrQuant->adjustBitDepthandLambdaForColorTrans(SCM__R0147_DELTA_QP_FOR_YCgCo_TRANS);
    }
    if (pcCU->getCbf(uiAbsPartIdx, compID, rTu.GetTransformDepthRel()) != 0)
    {
      m_pcTrQuant->invTransformNxN( rTu, compID, piResi, uiStride, pcCoeff, cQP );
    }
    else
    {
      for ( UInt y = 0; y < uiHeight; y++ )
      {
        for ( UInt x = 0; x < uiWidth; x++ )
        {
          piResi[(y * uiStride) + x] = 0;
        }
      }
    }
    const Bool useCrossComponentPrediction = isChroma(compID) && (pcCU->getCrossComponentPredictionAlpha(uiAbsPartIdx, compID) != 0);
    if( useCrossComponentPrediction ) 
    {
      const Pel* pResiLuma                      = pcResiYuv->getAddr( COMPONENT_Y, uiAbsPartIdx );
      const Int  strideLuma                     = pcResiYuv->getStride( COMPONENT_Y );
      TComTrQuant::crossComponentPrediction( rTu, compID, pResiLuma, piResi, piResi, uiWidth, uiHeight, strideLuma, uiStride, uiStride, true );
    }    
    if(bModifyQP)
    {
      m_pcTrQuant->adjustBitDepthandLambdaForColorTrans(- SCM__R0147_DELTA_QP_FOR_YCgCo_TRANS);
    }
  }


  if( pcCU->getColorTransform(uiAbsPartIdx) && (pcCU->getCbf(uiAbsPartIdx,COMPONENT_Y)||pcCU->getCbf(uiAbsPartIdx,COMPONENT_Cb)|| pcCU->getCbf(uiAbsPartIdx,COMPONENT_Cr)))
  {
    pcResiYuv->convert(rTu.getRect(COMPONENT_Y).x0, rTu.getRect(COMPONENT_Y).y0, rTu.getRect(COMPONENT_Y).width, false, pcCU->isLosslessCoded(uiAbsPartIdx));
  }

  //===== reconstruction =====

  for(UInt ch = 0; ch < MAX_NUM_COMPONENT; ch++)
  {
    ComponentID         compID           = ComponentID(ch);
    const TComRectangle &tuRect          = rTu.getRect(compID);
    const UInt          uiWidth          = tuRect.width;
    const UInt          uiHeight         = tuRect.height;
    Pel*                pPred            = pcPredYuv->getAddr( compID, uiAbsPartIdx );
    Pel*                pResi            = pcResiYuv->getAddr( compID, uiAbsPartIdx );
    Pel*                pReco            = pcRecoYuv->getAddr( compID, uiAbsPartIdx );
    Pel*                pRecIPred        = pcCU->getPic()->getPicYuvRec()->getAddr( compID, pcCU->getAddr(), pcCU->getZorderIdxInCU() + uiAbsPartIdx );
    const UInt          uiStride         = pcResiYuv->getStride( compID );
    const UInt          uiRecIPredStride = pcCU->getPic()->getPicYuvRec()->getStride(compID);
    const Int           clipbd           = g_bitDepth[toChannelType(compID)];
    for( UInt uiY = 0; uiY < uiHeight; uiY++ )
    {
      for( UInt uiX = 0; uiX < uiWidth; uiX++ )
      {
        pReco    [ uiX ] = ClipBD( pPred[ uiX ] + pResi[ uiX ], clipbd );
        pRecIPred[ uiX ] = pReco[ uiX ];
      }

      pPred     += uiStride;
      pResi     += uiStride;
      pReco     += uiStride;
      pRecIPred += uiRecIPredStride;
    }
  }

}
#endif

Void
TDecCu::xReconIntraQT( TComDataCU* pcCU, UInt uiDepth )
{
#if ITRI_MULTI_SAMPLE_MODE
	if (m_ppcCU[uiDepth]->getTwoSampleFlag(0))
	{
		xReconIntratwoSample(pcCU, 0, uiDepth);
		return;
	}
#endif
  if (pcCU->getIPCMFlag(0))
  {
    xReconPCM( pcCU, uiDepth );
    return;
  }
#if SCM__R0348_PALETTE_MODE
  if (pcCU->getPLTModeFlag(0))
  {
    ChromaFormat cCF = pcCU->getPic()->getSlice(0)->getSPS()->getChromaFormatIdc();
    if (cCF !=CHROMA_444)
    {
      xReconPLTModeLuma   (pcCU, uiDepth);
      xReconPLTModeChroma (pcCU, uiDepth);
    }
    else
    {
      xReconPLTMode (pcCU, uiDepth);
    }
  
    return;
  }
#endif
#if SCM__R0147_ADAPTIVE_COLOR_TRANSFORM
  if( !pcCU->getSlice()->getSPS()->getUseColorTrans () )
  {
#endif
  const UInt numChType = pcCU->getPic()->getChromaFormat()!=CHROMA_400 ? 2 : 1;
  for (UInt chType=CHANNEL_TYPE_LUMA; chType<numChType; chType++)
  {
    const ChannelType chanType=ChannelType(chType);
    const Bool NxNPUHas4Parts = ::isChroma(chanType) ? enable4ChromaPUsInIntraNxNCU(pcCU->getPic()->getChromaFormat()) : true;
    const UInt uiInitTrDepth = ( pcCU->getPartitionSize(0) != SIZE_2Nx2N && NxNPUHas4Parts ? 1 : 0 );

    TComTURecurse tuRecurseCU(pcCU, 0);
    TComTURecurse tuRecurseWithPU(tuRecurseCU, false, (uiInitTrDepth==0)?TComTU::DONT_SPLIT : TComTU::QUAD_SPLIT);

    do
    {
      xIntraRecQT( m_ppcYuvReco[uiDepth], m_ppcYuvReco[uiDepth], m_ppcYuvResi[uiDepth], chanType, tuRecurseWithPU );
    } while (tuRecurseWithPU.nextSection(tuRecurseCU));
  }
#if SCM__R0147_ADAPTIVE_COLOR_TRANSFORM
  }
  else
  {
    assert( pcCU->getPic()->getChromaFormat() == CHROMA_444 );
    const UInt uiInitTrDepth = ( pcCU->getPartitionSize(0) != SIZE_2Nx2N? 1 : 0 );

    TComTURecurse tuRecurseCU(pcCU, 0);
    TComTURecurse tuRecurseWithPU(tuRecurseCU, false, (uiInitTrDepth==0)?TComTU::DONT_SPLIT : TComTU::QUAD_SPLIT);

    do
    {
      xIntraRecQT( m_ppcYuvReco[uiDepth], m_ppcYuvReco[uiDepth], m_ppcYuvResi[uiDepth], tuRecurseWithPU );
    } while (tuRecurseWithPU.nextSection(tuRecurseCU));
  }
#endif
}



/** Function for deriving recontructed PU/CU chroma samples with QTree structure
 * \param pcCU pointer of current CU
 * \param uiTrDepth current tranform split depth
 * \param uiAbsPartIdx  part index
 * \param pcRecoYuv pointer to reconstructed sample arrays
 * \param pcPredYuv pointer to prediction sample arrays
 * \param pcResiYuv pointer to residue sample arrays
 *
 \ This function dervies recontructed PU/CU chroma samples with QTree recursive structure
 */

Void
TDecCu::xIntraRecQT(TComYuv*    pcRecoYuv,
                    TComYuv*    pcPredYuv,
                    TComYuv*    pcResiYuv,
                    const ChannelType chType,
                    TComTU     &rTu)
{
  UInt uiTrDepth    = rTu.GetTransformDepthRel();
  TComDataCU *pcCU  = rTu.getCU();
  UInt uiAbsPartIdx = rTu.GetAbsPartIdxTU();
  UInt uiTrMode     = pcCU->getTransformIdx( uiAbsPartIdx );
  if( uiTrMode == uiTrDepth )
  {
    if (isLuma(chType))
      xIntraRecBlk( pcRecoYuv, pcPredYuv, pcResiYuv, COMPONENT_Y,  rTu );
    else
    {
      const UInt numValidComp=getNumberValidComponents(rTu.GetChromaFormat());
      for(UInt compID=COMPONENT_Cb; compID<numValidComp; compID++)
      {
        xIntraRecBlk( pcRecoYuv, pcPredYuv, pcResiYuv, ComponentID(compID), rTu );
      }
    }
  }
  else
  {
    TComTURecurse tuRecurseChild(rTu, false);
    do
    {
      xIntraRecQT( pcRecoYuv, pcPredYuv, pcResiYuv, chType, tuRecurseChild );
    } while (tuRecurseChild.nextSection(rTu));
  }
}
#if SCM__R0147_ADAPTIVE_COLOR_TRANSFORM
Void
TDecCu::xIntraRecQT(TComYuv*    pcRecoYuv,
                    TComYuv*    pcPredYuv,
                    TComYuv*    pcResiYuv, 
                    TComTU      &rTu)
{
  UInt uiTrDepth    = rTu.GetTransformDepthRel();
  TComDataCU *pcCU  = rTu.getCU();
  UInt uiAbsPartIdx = rTu.GetAbsPartIdxTU();
  UInt uiTrMode     = pcCU->getTransformIdx( uiAbsPartIdx );

  if( uiTrMode == uiTrDepth ) 
    xIntraRecBlk( pcRecoYuv, pcPredYuv, pcResiYuv, rTu );
  else
  {
    TComTURecurse tuRecurseChild(rTu, false);
    do
    {
      xIntraRecQT( pcRecoYuv, pcPredYuv, pcResiYuv, tuRecurseChild );
    } while (tuRecurseChild.nextSection(rTu));
  }
}
#endif

Void TDecCu::xCopyToPic( TComDataCU* pcCU, TComPic* pcPic, UInt uiZorderIdx, UInt uiDepth )
{
  UInt uiCUAddr = pcCU->getAddr();

  m_ppcYuvReco[uiDepth]->copyToPicYuv  ( pcPic->getPicYuvRec (), uiCUAddr, uiZorderIdx );

  return;
}

Void TDecCu::xDecodeInterTexture ( TComDataCU* pcCU, UInt uiDepth )
{

  TComTURecurse tuRecur(pcCU, 0, uiDepth);

  for(UInt ch=0; ch<pcCU->getPic()->getNumberValidComponents(); ch++)
  {
    const ComponentID compID=ComponentID(ch);
    DEBUG_STRING_OUTPUT(std::cout, debug_reorder_data_token[pcCU->isIntraBC(0)?1:0][compID])

    // NOTE RExt - setQPForQuant was called here, but it has now been placed at the lowest level of decoding.
    m_pcTrQuant->invRecurTransformNxN ( compID, m_ppcYuvResi[uiDepth], tuRecur );
  }

  DEBUG_STRING_OUTPUT(std::cout, debug_reorder_data_token[pcCU->isIntraBC(0)?1:0][MAX_NUM_COMPONENT])
}
#if SCM__R0348_PALETTE_MODE
Void TDecCu::xDecodePLTTextureLumaChroma( TComDataCU* pcCU, const UInt uiPartIdx, Pel* pPalette,  Pel* pLevel, UChar *pSPoint, Pel *pPixelValue, Pel* piReco,const UInt uiStride, const UInt uiWidth, const UInt uiHeight, const ComponentID compID)
{
  Bool bLossless = pcCU->getCUTransquantBypass (uiPartIdx);
  Pel* piPicReco         = pcCU->getPic()->getPicYuvRec()->getAddr(compID, pcCU->getAddr(), pcCU->getZorderIdxInCU()+uiPartIdx);
  const UInt uiPicStride = pcCU->getPic()->getPicYuvRec()->getStride(compID);
  UInt uiIdx = 0;
  Pel iValue = 0;

  for(UInt uiY = 0; uiY < uiHeight; uiY++ )
  {
    for(UInt uiX = 0; uiX < uiWidth; uiX++ )
    {
      uiIdx = uiY * uiWidth + uiX;
      if (pSPoint[uiIdx] == PLT_ESCAPE)
      {
        if ( bLossless )
        {
          iValue = pPixelValue[uiIdx];
        }
        else
        {
          QpParam cQP(*pcCU, compID);
          Int iQP = cQP.Qp;
          Int iQPrem = iQP % 6;
          Int iQPper = iQP / 6;
          Int InvquantiserRightShift = (IQUANT_SHIFT - iQPper);
          Int iAdd = InvquantiserRightShift == 0 ? 0 : 1 << (InvquantiserRightShift - 1);
          iValue = ((pPixelValue[uiIdx]*g_invQuantScales[iQPrem] + iAdd)>>InvquantiserRightShift);
          iValue = Pel(ClipBD<Int>(iValue, g_bitDepth[compID?1:0]));
        }
      }
      else
      {
        iValue = pPalette[pLevel[uiIdx]];
      }
      piReco[uiX] = iValue;
      piPicReco[uiX] = iValue;
    }

    piReco += uiStride;
    piPicReco += uiPicStride;
  }
}

Void TDecCu::xDecodePLTTexture         ( TComDataCU* pcCU, const UInt uiPartIdx, Pel* pPalette,  Pel* pLevel, UChar *pSPoint, Pel *pPixelValue, Pel* piReco,const UInt uiStride, const UInt uiWidth, const UInt uiHeight, const ComponentID compID)
{
  Bool bLossless = pcCU->getCUTransquantBypass (uiPartIdx);
  Pel* piPicReco         = pcCU->getPic()->getPicYuvRec()->getAddr(compID, pcCU->getAddr(), pcCU->getZorderIdxInCU()+uiPartIdx);
  const UInt uiPicStride = pcCU->getPic()->getPicYuvRec()->getStride(compID);
  UInt uiIdx = 0;
  Pel iValue = 0;
  Bool bRotation = pcCU->getPLTScanRotationModeFlag(uiPartIdx);
  for(UInt uiY = 0; uiY < uiHeight; uiY++ )
  {
    for(UInt uiX = 0; uiX < uiWidth; uiX++ )
    {
      uiIdx = (uiY<<pcCU->getPic()->getComponentScaleY(compID))*(uiWidth<<pcCU->getPic()->getComponentScaleX(compID))+(uiX<<pcCU->getPic()->getComponentScaleX(compID));
      if (pSPoint[uiIdx] == PLT_ESCAPE)
      {
        if ( bLossless )
        {
          iValue = pPixelValue[uiIdx];
        }
        else
        {
          QpParam cQP(*pcCU, compID);
          Int iQP = cQP.Qp;
          Int iQPrem = iQP % 6;
          Int iQPper = iQP / 6;
          Int InvquantiserRightShift = (IQUANT_SHIFT - iQPper);
          Int iAdd = InvquantiserRightShift == 0 ? 0 : 1 << (InvquantiserRightShift - 1);
          iValue = ((pPixelValue[uiIdx]*g_invQuantScales[iQPrem] + iAdd)>>InvquantiserRightShift);
          iValue = Pel(ClipBD<Int>(iValue, g_bitDepth[compID?1:0]));
        }
      }
      else
      {
        iValue = pPalette[pLevel[uiIdx]];
      }
     if(bRotation)
     {
      piReco[uiX*uiStride+uiY] = iValue;
      piPicReco[uiX*uiPicStride+uiY] = iValue;
     }
     else
     {
      piReco[uiX] = iValue;
      piPicReco[uiX] = iValue;
     }
    }

    if(!bRotation)
    {
      piReco += uiStride;
      piPicReco += uiPicStride;
    }
  }
}

Void  TDecCu::xReconPLTModeLuma(TComDataCU* pcCU, UInt uiDepth)
{
  Pel  * pLevel, *pPalette, *pRecChannel;

  const UInt uiWidth = (g_uiMaxCUWidth >> uiDepth);
  const UInt uiHeight = (g_uiMaxCUHeight >> uiDepth);
  const UInt uiStride = m_ppcYuvResi[uiDepth]->getStride(COMPONENT_Y);

  pLevel = pcCU->getLevel(COMPONENT_Y);
  pPalette = pcCU->getPLT(COMPONENT_Y, 0);
  pRecChannel = m_ppcYuvReco[uiDepth]->getAddr(COMPONENT_Y);

  Pel *pPixelValue = pcCU->getLevel(COMPONENT_Y);
  xDecodePLTTextureLumaChroma(pcCU, 0, pPalette, pLevel, pcCU->getSPoint(COMPONENT_Y), pPixelValue, pRecChannel, uiStride, uiWidth, uiHeight, COMPONENT_Y);
}

Void  TDecCu::xReconPLTModeChroma(TComDataCU* pcCU, UInt uiDepth)
{
  Pel  * pLevel, *pPalette, *pRecChannel;
  for (UInt ch = 1; ch < pcCU->getPic()->getNumberValidComponents(); ch++)
  {
    const ComponentID compID = ComponentID(ch);
    const UInt uiWidth = (g_uiMaxCUWidth >> (uiDepth + m_ppcYuvResi[uiDepth]->getComponentScaleX(compID)));
    const UInt uiHeight = (g_uiMaxCUHeight >> (uiDepth + m_ppcYuvResi[uiDepth]->getComponentScaleY(compID)));
    const UInt uiStride = m_ppcYuvResi[uiDepth]->getStride(compID);

    pLevel = pcCU->getLevel(COMPONENT_Cb);
    pPalette = pcCU->getPLT(compID, 0);
    pRecChannel = m_ppcYuvReco[uiDepth]->getAddr(compID);
    Pel *pPixelValue = pcCU->getLevel(compID);
    xDecodePLTTextureLumaChroma(pcCU, 0, pPalette, pLevel, pcCU->getSPoint(compID), pPixelValue, pRecChannel, uiStride, uiWidth, uiHeight, compID);
  }
}

Void TDecCu::xReconPLTMode(TComDataCU *pcCU, UInt uiDepth)
{
  Pel *pLevel, *pPalette, *pRecChannel;
  for (UInt ch = 0; ch < pcCU->getPic()->getNumberValidComponents(); ch++)
  {
    const ComponentID compID = ComponentID(ch);
    const UInt uiWidth = (g_uiMaxCUWidth >> (uiDepth + m_ppcYuvResi[uiDepth]->getComponentScaleX(compID)));
    const UInt uiHeight = (g_uiMaxCUHeight >> (uiDepth + m_ppcYuvResi[uiDepth]->getComponentScaleY(compID)));
    const UInt uiStride = m_ppcYuvResi[uiDepth]->getStride(compID);

    pLevel = pcCU->getLevel(COMPONENT_Y);
    pPalette = pcCU->getPLT(compID, 0);
    pRecChannel = m_ppcYuvReco[uiDepth]->getAddr(compID);

    Pel *pPixelValue = pcCU->getLevel(compID);
    xDecodePLTTexture(pcCU, 0, pPalette, pLevel, pcCU->getSPoint(COMPONENT_Y), pPixelValue, pRecChannel, uiStride, uiWidth, uiHeight, compID);
  }
}
#endif
/** Function for deriving reconstructed luma/chroma samples of a PCM mode CU.
 * \param pcCU pointer to current CU
 * \param uiPartIdx part index
 * \param piPCM pointer to PCM code arrays
 * \param piReco pointer to reconstructed sample arrays
 * \param uiStride stride of reconstructed sample arrays
 * \param uiWidth CU width
 * \param uiHeight CU height
 * \param ttText texture component type
 * \returns Void
 */
Void TDecCu::xDecodePCMTexture( TComDataCU* pcCU, const UInt uiPartIdx, const Pel *piPCM, Pel* piReco, const UInt uiStride, const UInt uiWidth, const UInt uiHeight, const ComponentID compID)
{
        Pel* piPicReco         = pcCU->getPic()->getPicYuvRec()->getAddr(compID, pcCU->getAddr(), pcCU->getZorderIdxInCU()+uiPartIdx);
  const UInt uiPicStride       = pcCU->getPic()->getPicYuvRec()->getStride(compID);
  const UInt uiPcmLeftShiftBit = g_bitDepth[toChannelType(compID)] - pcCU->getSlice()->getSPS()->getPCMBitDepth(toChannelType(compID));

  for(UInt uiY = 0; uiY < uiHeight; uiY++ )
  {
    for(UInt uiX = 0; uiX < uiWidth; uiX++ )
    {
      piReco[uiX] = (piPCM[uiX] << uiPcmLeftShiftBit);
      piPicReco[uiX] = piReco[uiX];
    }
    piPCM += uiWidth;
    piReco += uiStride;
    piPicReco += uiPicStride;
  }
}

/** Function for reconstructing a PCM mode CU.
 * \param pcCU pointer to current CU
 * \param uiDepth CU Depth
 * \returns Void
 */
Void TDecCu::xReconPCM( TComDataCU* pcCU, UInt uiDepth )
{
  for (UInt ch=0; ch < pcCU->getPic()->getNumberValidComponents(); ch++)
  {
    const ComponentID compID = ComponentID(ch);
    const UInt width  = (g_uiMaxCUWidth >>(uiDepth+m_ppcYuvResi[uiDepth]->getComponentScaleX(compID)));
    const UInt height = (g_uiMaxCUHeight>>(uiDepth+m_ppcYuvResi[uiDepth]->getComponentScaleY(compID)));
    const UInt stride = m_ppcYuvResi[uiDepth]->getStride(compID);
    Pel * pPCMChannel = pcCU->getPCMSample(compID);
    Pel * pRecChannel = m_ppcYuvReco[uiDepth]->getAddr(compID);
    xDecodePCMTexture( pcCU, 0, pPCMChannel, pRecChannel, stride, width, height, compID );
  }
}

/** Function for filling the PCM buffer of a CU using its reconstructed sample array
 * \param pcCU pointer to current CU
 * \param uiDepth CU Depth
 * \returns Void
 */
Void TDecCu::xFillPCMBuffer(TComDataCU* pCU, UInt depth)
{
  const ChromaFormat format = pCU->getPic()->getChromaFormat();
  const UInt numValidComp=getNumberValidComponents(format);

  for (UInt componentIndex = 0; componentIndex < numValidComp; componentIndex++)
  {
    const ComponentID component = ComponentID(componentIndex);

    const UInt width  = g_uiMaxCUWidth  >> (depth + getComponentScaleX(component, format));
    const UInt height = g_uiMaxCUHeight >> (depth + getComponentScaleY(component, format));

    Pel *source      = m_ppcYuvReco[depth]->getAddr(component, 0, width);
    Pel *destination = pCU->getPCMSample(component);

    const UInt sourceStride = m_ppcYuvReco[depth]->getStride(component);

    for (Int line = 0; line < height; line++)
    {
      for (Int column = 0; column < width; column++)
      {
        destination[column] = source[column];
      }

      source      += sourceStride;
      destination += width;
    }
  }
}

//! \}
