source: 3DVCSoftware/branches/HTM-16.0-MV-draft-5/source/Lib/TLibEncoder/TEncCu.cpp

Last change on this file was 1390, checked in by tech, 9 years ago

Removed 3D.

  • Property svn:eol-style set to native
File size: 63.5 KB
Line 
1/* The copyright in this software is being made available under the BSD
2 * License, included below. This software may be subject to other third party
3 * and contributor rights, including patent rights, and no such rights are
4 * granted under this license.
5 *
6 * Copyright (c) 2010-2015, ITU/ISO/IEC
7 * All rights reserved.
8 *
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions are met:
11 *
12 *  * Redistributions of source code must retain the above copyright notice,
13 *    this list of conditions and the following disclaimer.
14 *  * Redistributions in binary form must reproduce the above copyright notice,
15 *    this list of conditions and the following disclaimer in the documentation
16 *    and/or other materials provided with the distribution.
17 *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
18 *    be used to endorse or promote products derived from this software without
19 *    specific prior written permission.
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
22 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
25 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
26 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
27 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
28 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
29 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
30 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
31 * THE POSSIBILITY OF SUCH DAMAGE.
32 */
33
34/** \file     TEncCu.cpp
35    \brief    Coding Unit (CU) encoder class
36*/
37
38#include <stdio.h>
39#include "TEncTop.h"
40#include "TEncCu.h"
41#include "TEncAnalyze.h"
42#include "TLibCommon/Debug.h"
43
44#include <cmath>
45#include <algorithm>
46using namespace std;
47
48
49//! \ingroup TLibEncoder
50//! \{
51
52// ====================================================================================================================
53// Constructor / destructor / create / destroy
54// ====================================================================================================================
55
56/**
57 \param    uhTotalDepth  total number of allowable depth
58 \param    uiMaxWidth    largest CU width
59 \param    uiMaxHeight   largest CU height
60 \param    chromaFormat  chroma format
61 */
62Void TEncCu::create(UChar uhTotalDepth, UInt uiMaxWidth, UInt uiMaxHeight, ChromaFormat chromaFormat)
63{
64  Int i;
65
66  m_uhTotalDepth   = uhTotalDepth + 1;
67  m_ppcBestCU      = new TComDataCU*[m_uhTotalDepth-1];
68  m_ppcTempCU      = new TComDataCU*[m_uhTotalDepth-1];
69
70
71  m_ppcPredYuvBest = new TComYuv*[m_uhTotalDepth-1];
72  m_ppcResiYuvBest = new TComYuv*[m_uhTotalDepth-1];
73  m_ppcRecoYuvBest = new TComYuv*[m_uhTotalDepth-1];
74  m_ppcPredYuvTemp = new TComYuv*[m_uhTotalDepth-1];
75  m_ppcResiYuvTemp = new TComYuv*[m_uhTotalDepth-1];
76  m_ppcRecoYuvTemp = new TComYuv*[m_uhTotalDepth-1];
77  m_ppcOrigYuv     = new TComYuv*[m_uhTotalDepth-1];
78
79  UInt uiNumPartitions;
80  for( i=0 ; i<m_uhTotalDepth-1 ; i++)
81  {
82    uiNumPartitions = 1<<( ( m_uhTotalDepth - i - 1 )<<1 );
83    UInt uiWidth  = uiMaxWidth  >> i;
84    UInt uiHeight = uiMaxHeight >> i;
85
86    m_ppcBestCU[i] = new TComDataCU; m_ppcBestCU[i]->create( chromaFormat, uiNumPartitions, uiWidth, uiHeight, false, uiMaxWidth >> (m_uhTotalDepth - 1) );
87    m_ppcTempCU[i] = new TComDataCU; m_ppcTempCU[i]->create( chromaFormat, uiNumPartitions, uiWidth, uiHeight, false, uiMaxWidth >> (m_uhTotalDepth - 1) );
88
89    m_ppcPredYuvBest[i] = new TComYuv; m_ppcPredYuvBest[i]->create(uiWidth, uiHeight, chromaFormat);
90    m_ppcResiYuvBest[i] = new TComYuv; m_ppcResiYuvBest[i]->create(uiWidth, uiHeight, chromaFormat);
91    m_ppcRecoYuvBest[i] = new TComYuv; m_ppcRecoYuvBest[i]->create(uiWidth, uiHeight, chromaFormat);
92
93    m_ppcPredYuvTemp[i] = new TComYuv; m_ppcPredYuvTemp[i]->create(uiWidth, uiHeight, chromaFormat);
94    m_ppcResiYuvTemp[i] = new TComYuv; m_ppcResiYuvTemp[i]->create(uiWidth, uiHeight, chromaFormat);
95    m_ppcRecoYuvTemp[i] = new TComYuv; m_ppcRecoYuvTemp[i]->create(uiWidth, uiHeight, chromaFormat);
96
97    m_ppcOrigYuv    [i] = new TComYuv; m_ppcOrigYuv    [i]->create(uiWidth, uiHeight, chromaFormat);
98
99  }
100
101  m_bEncodeDQP          = false;
102
103
104  m_stillToCodeChromaQpOffsetFlag  = false;
105  m_cuChromaQpOffsetIdxPlus1       = 0;
106  m_bFastDeltaQP                   = false;
107
108  // initialize partition order.
109  UInt* piTmp = &g_auiZscanToRaster[0];
110  initZscanToRaster( m_uhTotalDepth, 1, 0, piTmp);
111  initRasterToZscan( uiMaxWidth, uiMaxHeight, m_uhTotalDepth );
112
113  // initialize conversion matrix from partition index to pel
114  initRasterToPelXY( uiMaxWidth, uiMaxHeight, m_uhTotalDepth );
115}
116
117Void TEncCu::destroy()
118{
119  Int i;
120
121  for( i=0 ; i<m_uhTotalDepth-1 ; i++)
122  {
123    if(m_ppcBestCU[i])
124    {
125      m_ppcBestCU[i]->destroy();      delete m_ppcBestCU[i];      m_ppcBestCU[i] = NULL;
126    }
127    if(m_ppcTempCU[i])
128    {
129      m_ppcTempCU[i]->destroy();      delete m_ppcTempCU[i];      m_ppcTempCU[i] = NULL;
130    }
131    if(m_ppcPredYuvBest[i])
132    {
133      m_ppcPredYuvBest[i]->destroy(); delete m_ppcPredYuvBest[i]; m_ppcPredYuvBest[i] = NULL;
134    }
135    if(m_ppcResiYuvBest[i])
136    {
137      m_ppcResiYuvBest[i]->destroy(); delete m_ppcResiYuvBest[i]; m_ppcResiYuvBest[i] = NULL;
138    }
139    if(m_ppcRecoYuvBest[i])
140    {
141      m_ppcRecoYuvBest[i]->destroy(); delete m_ppcRecoYuvBest[i]; m_ppcRecoYuvBest[i] = NULL;
142    }
143    if(m_ppcPredYuvTemp[i])
144    {
145      m_ppcPredYuvTemp[i]->destroy(); delete m_ppcPredYuvTemp[i]; m_ppcPredYuvTemp[i] = NULL;
146    }
147    if(m_ppcResiYuvTemp[i])
148    {
149      m_ppcResiYuvTemp[i]->destroy(); delete m_ppcResiYuvTemp[i]; m_ppcResiYuvTemp[i] = NULL;
150    }
151    if(m_ppcRecoYuvTemp[i])
152    {
153      m_ppcRecoYuvTemp[i]->destroy(); delete m_ppcRecoYuvTemp[i]; m_ppcRecoYuvTemp[i] = NULL;
154    }
155    if(m_ppcOrigYuv[i])
156    {
157      m_ppcOrigYuv[i]->destroy();     delete m_ppcOrigYuv[i];     m_ppcOrigYuv[i] = NULL;
158    }
159  }
160  if(m_ppcBestCU)
161  {
162    delete [] m_ppcBestCU;
163    m_ppcBestCU = NULL;
164  }
165  if(m_ppcTempCU)
166  {
167    delete [] m_ppcTempCU;
168    m_ppcTempCU = NULL;
169  }
170
171  if(m_ppcPredYuvBest)
172  {
173    delete [] m_ppcPredYuvBest;
174    m_ppcPredYuvBest = NULL;
175  }
176  if(m_ppcResiYuvBest)
177  {
178    delete [] m_ppcResiYuvBest;
179    m_ppcResiYuvBest = NULL;
180  }
181  if(m_ppcRecoYuvBest)
182  {
183    delete [] m_ppcRecoYuvBest;
184    m_ppcRecoYuvBest = NULL;
185  }
186  if(m_ppcPredYuvTemp)
187  {
188    delete [] m_ppcPredYuvTemp;
189    m_ppcPredYuvTemp = NULL;
190  }
191  if(m_ppcResiYuvTemp)
192  {
193    delete [] m_ppcResiYuvTemp;
194    m_ppcResiYuvTemp = NULL;
195  }
196  if(m_ppcRecoYuvTemp)
197  {
198    delete [] m_ppcRecoYuvTemp;
199    m_ppcRecoYuvTemp = NULL;
200  }
201  if(m_ppcOrigYuv)
202  {
203    delete [] m_ppcOrigYuv;
204    m_ppcOrigYuv = NULL;
205  }
206}
207
208/** \param    pcEncTop      pointer of encoder class
209 */
210Void TEncCu::init( TEncTop* pcEncTop )
211{
212  m_pcEncCfg           = pcEncTop;
213  m_pcPredSearch       = pcEncTop->getPredSearch();
214  m_pcTrQuant          = pcEncTop->getTrQuant();
215  m_pcRdCost           = pcEncTop->getRdCost();
216
217  m_pcEntropyCoder     = pcEncTop->getEntropyCoder();
218  m_pcBinCABAC         = pcEncTop->getBinCABAC();
219
220  m_pppcRDSbacCoder    = pcEncTop->getRDSbacCoder();
221  m_pcRDGoOnSbacCoder  = pcEncTop->getRDGoOnSbacCoder();
222
223  m_pcRateCtrl         = pcEncTop->getRateCtrl();
224}
225
226// ====================================================================================================================
227// Public member functions
228// ====================================================================================================================
229
230/**
231 \param  pCtu pointer of CU data class
232 */
233Void TEncCu::compressCtu( TComDataCU* pCtu )
234{
235  // initialize CU data
236  m_ppcBestCU[0]->initCtu( pCtu->getPic(), pCtu->getCtuRsAddr() );
237  m_ppcTempCU[0]->initCtu( pCtu->getPic(), pCtu->getCtuRsAddr() );
238
239
240
241  // analysis of CU
242  DEBUG_STRING_NEW(sDebug)
243
244  xCompressCU( m_ppcBestCU[0], m_ppcTempCU[0], 0 DEBUG_STRING_PASS_INTO(sDebug) );
245  DEBUG_STRING_OUTPUT(std::cout, sDebug)
246
247#if ADAPTIVE_QP_SELECTION
248  if( m_pcEncCfg->getUseAdaptQpSelect() )
249  {
250    if(pCtu->getSlice()->getSliceType()!=I_SLICE) //IIII
251    {
252      xCtuCollectARLStats( pCtu );
253    }
254  }
255#endif
256}
257/** \param  pCtu  pointer of CU data class
258 */
259Void TEncCu::encodeCtu ( TComDataCU* pCtu )
260{
261  if ( pCtu->getSlice()->getPPS()->getUseDQP() )
262  {
263    setdQPFlag(true);
264  }
265
266  if ( pCtu->getSlice()->getUseChromaQpAdj() )
267  {
268    setCodeChromaQpAdjFlag(true);
269  }
270
271  // Encode CU data
272  xEncodeCU( pCtu, 0, 0 );
273}
274
275// ====================================================================================================================
276// Protected member functions
277// ====================================================================================================================
278//! Derive small set of test modes for AMP encoder speed-up
279#if AMP_ENC_SPEEDUP
280#if AMP_MRG
281Void TEncCu::deriveTestModeAMP (TComDataCU *pcBestCU, PartSize eParentPartSize, Bool &bTestAMP_Hor, Bool &bTestAMP_Ver, Bool &bTestMergeAMP_Hor, Bool &bTestMergeAMP_Ver)
282#else
283Void TEncCu::deriveTestModeAMP (TComDataCU *pcBestCU, PartSize eParentPartSize, Bool &bTestAMP_Hor, Bool &bTestAMP_Ver)
284#endif
285{
286  if ( pcBestCU->getPartitionSize(0) == SIZE_2NxN )
287  {
288    bTestAMP_Hor = true;
289  }
290  else if ( pcBestCU->getPartitionSize(0) == SIZE_Nx2N )
291  {
292    bTestAMP_Ver = true;
293  }
294  else if ( pcBestCU->getPartitionSize(0) == SIZE_2Nx2N && pcBestCU->getMergeFlag(0) == false && pcBestCU->isSkipped(0) == false )
295  {
296    bTestAMP_Hor = true;
297    bTestAMP_Ver = true;
298  }
299
300#if AMP_MRG
301  //! Utilizing the partition size of parent PU
302  if ( eParentPartSize >= SIZE_2NxnU && eParentPartSize <= SIZE_nRx2N )
303  {
304    bTestMergeAMP_Hor = true;
305    bTestMergeAMP_Ver = true;
306  }
307
308  if ( eParentPartSize == NUMBER_OF_PART_SIZES ) //! if parent is intra
309  {
310    if ( pcBestCU->getPartitionSize(0) == SIZE_2NxN )
311    {
312      bTestMergeAMP_Hor = true;
313    }
314    else if ( pcBestCU->getPartitionSize(0) == SIZE_Nx2N )
315    {
316      bTestMergeAMP_Ver = true;
317    }
318  }
319
320  if ( pcBestCU->getPartitionSize(0) == SIZE_2Nx2N && pcBestCU->isSkipped(0) == false )
321  {
322    bTestMergeAMP_Hor = true;
323    bTestMergeAMP_Ver = true;
324  }
325
326  if ( pcBestCU->getWidth(0) == 64 )
327  {
328    bTestAMP_Hor = false;
329    bTestAMP_Ver = false;
330  }
331#else
332  //! Utilizing the partition size of parent PU
333  if ( eParentPartSize >= SIZE_2NxnU && eParentPartSize <= SIZE_nRx2N )
334  {
335    bTestAMP_Hor = true;
336    bTestAMP_Ver = true;
337  }
338
339  if ( eParentPartSize == SIZE_2Nx2N )
340  {
341    bTestAMP_Hor = false;
342    bTestAMP_Ver = false;
343  }
344#endif
345}
346#endif
347
348
349// ====================================================================================================================
350// Protected member functions
351// ====================================================================================================================
352/** Compress a CU block recursively with enabling sub-CTU-level delta QP
353 *  - for loop of QP value to compress the current CU with all possible QP
354*/
355#if AMP_ENC_SPEEDUP
356Void TEncCu::xCompressCU( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, const UInt uiDepth DEBUG_STRING_FN_DECLARE(sDebug_), PartSize eParentPartSize )
357#else
358Void TEncCu::xCompressCU( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, const UInt uiDepth )
359#endif
360{
361  TComPic* pcPic = rpcBestCU->getPic();
362  DEBUG_STRING_NEW(sDebug)
363  const TComPPS &pps=*(rpcTempCU->getSlice()->getPPS());
364  const TComSPS &sps=*(rpcTempCU->getSlice()->getSPS());
365 
366  // These are only used if getFastDeltaQp() is true
367  const UInt fastDeltaQPCuMaxSize    = Clip3(sps.getMaxCUHeight()>>sps.getLog2DiffMaxMinCodingBlockSize(), sps.getMaxCUHeight(), 32u);
368
369
370  // get Original YUV data from picture
371  m_ppcOrigYuv[uiDepth]->copyFromPicYuv( pcPic->getPicYuvOrg(), rpcBestCU->getCtuRsAddr(), rpcBestCU->getZorderIdxInCtu() );
372
373  // variable for Cbf fast mode PU decision
374  Bool    doNotBlockPu = true;
375  Bool    earlyDetectionSkipMode = false;
376
377  const UInt uiLPelX   = rpcBestCU->getCUPelX();
378  const UInt uiRPelX   = uiLPelX + rpcBestCU->getWidth(0)  - 1;
379  const UInt uiTPelY   = rpcBestCU->getCUPelY();
380  const UInt uiBPelY   = uiTPelY + rpcBestCU->getHeight(0) - 1;
381  const UInt uiWidth   = rpcBestCU->getWidth(0);
382
383#if NH_MV_ENC_DEC_TRAC
384#if ENC_DEC_TRACE
385    stopAtPos  ( rpcBestCU->getSlice()->getPOC(), 
386                 rpcBestCU->getSlice()->getLayerId(), 
387                 rpcBestCU->getCUPelX(),
388                 rpcBestCU->getCUPelY(),
389                 rpcBestCU->getWidth(0), 
390                 rpcBestCU->getHeight(0) );
391#endif
392#endif
393
394  Int iBaseQP = xComputeQP( rpcBestCU, uiDepth );
395  Int iMinQP;
396  Int iMaxQP;
397  Bool isAddLowestQP = false;
398
399  const UInt numberValidComponents = rpcBestCU->getPic()->getNumberValidComponents();
400
401  if( uiDepth <= pps.getMaxCuDQPDepth() )
402  {
403    Int idQP = m_pcEncCfg->getMaxDeltaQP();
404    iMinQP = Clip3( -sps.getQpBDOffset(CHANNEL_TYPE_LUMA), MAX_QP, iBaseQP-idQP );
405    iMaxQP = Clip3( -sps.getQpBDOffset(CHANNEL_TYPE_LUMA), MAX_QP, iBaseQP+idQP );
406  }
407  else
408  {
409    iMinQP = rpcTempCU->getQP(0);
410    iMaxQP = rpcTempCU->getQP(0);
411  }
412
413  if ( m_pcEncCfg->getUseRateCtrl() )
414  {
415    iMinQP = m_pcRateCtrl->getRCQP();
416    iMaxQP = m_pcRateCtrl->getRCQP();
417  }
418
419  // transquant-bypass (TQB) processing loop variable initialisation ---
420
421  const Int lowestQP = iMinQP; // For TQB, use this QP which is the lowest non TQB QP tested (rather than QP'=0) - that way delta QPs are smaller, and TQB can be tested at all CU levels.
422
423  if ( (pps.getTransquantBypassEnableFlag()) )
424  {
425    isAddLowestQP = true; // mark that the first iteration is to cost TQB mode.
426    iMinQP = iMinQP - 1;  // increase loop variable range by 1, to allow testing of TQB mode along with other QPs
427    if ( m_pcEncCfg->getCUTransquantBypassFlagForceValue() )
428    {
429      iMaxQP = iMinQP;
430    }
431  }
432
433
434  TComSlice * pcSlice = rpcTempCU->getPic()->getSlice(rpcTempCU->getPic()->getCurrSliceIdx());
435
436  const Bool bBoundary = !( uiRPelX < sps.getPicWidthInLumaSamples() && uiBPelY < sps.getPicHeightInLumaSamples() );
437  if ( !bBoundary )
438  {
439    for (Int iQP=iMinQP; iQP<=iMaxQP; iQP++)
440    {
441      const Bool bIsLosslessMode = isAddLowestQP && (iQP == iMinQP);
442
443      if (bIsLosslessMode)
444      {
445        iQP = lowestQP;
446      }
447
448
449      m_cuChromaQpOffsetIdxPlus1 = 0;
450      if (pcSlice->getUseChromaQpAdj())
451      {
452        /* Pre-estimation of chroma QP based on input block activity may be performed
453         * here, using for example m_ppcOrigYuv[uiDepth] */
454        /* To exercise the current code, the index used for adjustment is based on
455         * block position
456         */
457        Int lgMinCuSize = sps.getLog2MinCodingBlockSize() +
458                          std::max<Int>(0, sps.getLog2DiffMaxMinCodingBlockSize()-Int(pps.getPpsRangeExtension().getDiffCuChromaQpOffsetDepth()));
459        m_cuChromaQpOffsetIdxPlus1 = ((uiLPelX >> lgMinCuSize) + (uiTPelY >> lgMinCuSize)) % (pps.getPpsRangeExtension().getChromaQpOffsetListLen() + 1);
460      }
461
462      rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
463
464      // do inter modes, SKIP and 2Nx2N
465      if( rpcBestCU->getSlice()->getSliceType() != I_SLICE )
466      {
467        // 2Nx2N
468        if(m_pcEncCfg->getUseEarlySkipDetection())
469        {
470          xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2Nx2N DEBUG_STRING_PASS_INTO(sDebug) );
471          rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );//by Competition for inter_2Nx2N
472        }
473        // SKIP
474        xCheckRDCostMerge2Nx2N( rpcBestCU, rpcTempCU DEBUG_STRING_PASS_INTO(sDebug), &earlyDetectionSkipMode );//by Merge for inter_2Nx2N
475
476        rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
477
478        if(!m_pcEncCfg->getUseEarlySkipDetection())
479        {
480          // 2Nx2N, NxN
481
482          xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2Nx2N DEBUG_STRING_PASS_INTO(sDebug) );
483          rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
484
485          if(m_pcEncCfg->getUseCbfFastMode())
486          {
487            doNotBlockPu = rpcBestCU->getQtRootCbf( 0 ) != 0;
488          }
489        }
490      }
491
492      if (bIsLosslessMode) // Restore loop variable if lossless mode was searched.
493      {
494        iQP = iMinQP;
495      }
496    }
497
498    if(!earlyDetectionSkipMode)
499    {
500      for (Int iQP=iMinQP; iQP<=iMaxQP; iQP++)
501      {
502        const Bool bIsLosslessMode = isAddLowestQP && (iQP == iMinQP); // If lossless, then iQP is irrelevant for subsequent modules.
503
504        if (bIsLosslessMode)
505        {
506          iQP = lowestQP;
507        }
508
509        rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
510
511        // do inter modes, NxN, 2NxN, and Nx2N
512        if( rpcBestCU->getSlice()->getSliceType() != I_SLICE )
513        {
514          // 2Nx2N, NxN
515
516          if(!( (rpcBestCU->getWidth(0)==8) && (rpcBestCU->getHeight(0)==8) ))
517          {
518            if( uiDepth == sps.getLog2DiffMaxMinCodingBlockSize() && doNotBlockPu
519)
520            {
521
522              xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_NxN DEBUG_STRING_PASS_INTO(sDebug)   );
523              rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
524
525            }
526          }
527
528          if(doNotBlockPu
529)
530          {
531            xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_Nx2N DEBUG_STRING_PASS_INTO(sDebug)  );
532            rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
533
534            if(m_pcEncCfg->getUseCbfFastMode() && rpcBestCU->getPartitionSize(0) == SIZE_Nx2N )
535            {
536              doNotBlockPu = rpcBestCU->getQtRootCbf( 0 ) != 0;
537            }
538          }
539          if(doNotBlockPu
540)
541          {
542
543            xCheckRDCostInter      ( rpcBestCU, rpcTempCU, SIZE_2NxN DEBUG_STRING_PASS_INTO(sDebug)  );
544
545            rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
546
547            if(m_pcEncCfg->getUseCbfFastMode() && rpcBestCU->getPartitionSize(0) == SIZE_2NxN)
548            {
549              doNotBlockPu = rpcBestCU->getQtRootCbf( 0 ) != 0;
550            }
551          }
552
553          //! Try AMP (SIZE_2NxnU, SIZE_2NxnD, SIZE_nLx2N, SIZE_nRx2N)
554          if(sps.getUseAMP() && uiDepth < sps.getLog2DiffMaxMinCodingBlockSize() )
555          {
556#if AMP_ENC_SPEEDUP
557            Bool bTestAMP_Hor = false, bTestAMP_Ver = false;
558
559#if AMP_MRG
560            Bool bTestMergeAMP_Hor = false, bTestMergeAMP_Ver = false;
561
562            deriveTestModeAMP (rpcBestCU, eParentPartSize, bTestAMP_Hor, bTestAMP_Ver, bTestMergeAMP_Hor, bTestMergeAMP_Ver);
563#else
564            deriveTestModeAMP (rpcBestCU, eParentPartSize, bTestAMP_Hor, bTestAMP_Ver);
565#endif
566
567            //! Do horizontal AMP
568            if ( bTestAMP_Hor )
569            {
570              if(doNotBlockPu
571)
572              {
573                xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2NxnU DEBUG_STRING_PASS_INTO(sDebug) );
574                rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
575                if(m_pcEncCfg->getUseCbfFastMode() && rpcBestCU->getPartitionSize(0) == SIZE_2NxnU )
576                {
577                  doNotBlockPu = rpcBestCU->getQtRootCbf( 0 ) != 0;
578                }
579              }
580              if(doNotBlockPu
581)
582              {
583                xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2NxnD DEBUG_STRING_PASS_INTO(sDebug) );
584
585                rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
586
587                if(m_pcEncCfg->getUseCbfFastMode() && rpcBestCU->getPartitionSize(0) == SIZE_2NxnD )
588                {
589                  doNotBlockPu = rpcBestCU->getQtRootCbf( 0 ) != 0;
590                }
591              }
592            }
593#if AMP_MRG
594            else if ( bTestMergeAMP_Hor )
595            {
596              if(doNotBlockPu
597)
598              {
599
600                xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2NxnU DEBUG_STRING_PASS_INTO(sDebug), true );
601
602                rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
603                if(m_pcEncCfg->getUseCbfFastMode() && rpcBestCU->getPartitionSize(0) == SIZE_2NxnU )
604                {
605                  doNotBlockPu = rpcBestCU->getQtRootCbf( 0 ) != 0;
606                }
607              }
608              if(doNotBlockPu
609)
610              {
611                xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2NxnD DEBUG_STRING_PASS_INTO(sDebug), true );
612                rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
613
614                if(m_pcEncCfg->getUseCbfFastMode() && rpcBestCU->getPartitionSize(0) == SIZE_2NxnD )
615                {
616                  doNotBlockPu = rpcBestCU->getQtRootCbf( 0 ) != 0;
617                }
618              }
619            }
620#endif
621
622            //! Do horizontal AMP
623            if ( bTestAMP_Ver )
624            {
625              if(doNotBlockPu
626)
627              {
628                xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_nLx2N DEBUG_STRING_PASS_INTO(sDebug) );
629
630                rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
631                if(m_pcEncCfg->getUseCbfFastMode() && rpcBestCU->getPartitionSize(0) == SIZE_nLx2N )
632                {
633                  doNotBlockPu = rpcBestCU->getQtRootCbf( 0 ) != 0;
634                }
635              }
636              if(doNotBlockPu
637)
638              {
639                xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_nRx2N DEBUG_STRING_PASS_INTO(sDebug) );
640                rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
641              }
642            }
643#if AMP_MRG
644            else if ( bTestMergeAMP_Ver )
645            {
646              if(doNotBlockPu
647)
648              {
649                xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_nLx2N DEBUG_STRING_PASS_INTO(sDebug), true );
650                rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
651                if(m_pcEncCfg->getUseCbfFastMode() && rpcBestCU->getPartitionSize(0) == SIZE_nLx2N )
652                {
653                  doNotBlockPu = rpcBestCU->getQtRootCbf( 0 ) != 0;
654                }
655              }
656              if(doNotBlockPu
657)
658              {
659
660                xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_nRx2N DEBUG_STRING_PASS_INTO(sDebug), true );
661                rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
662
663              }
664            }
665#endif
666
667#else
668
669            xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2NxnU );
670            rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
671            xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2NxnD );
672            rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
673            xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_nLx2N );
674            rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
675            xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_nRx2N );
676            rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
677
678
679#endif
680          }
681        }
682
683        // do normal intra modes
684        // speedup for inter frames
685        Double intraCost = 0.0;
686
687        if((rpcBestCU->getSlice()->getSliceType() == I_SLICE)                                     ||
688           ((!m_pcEncCfg->getDisableIntraPUsInInterSlices()) && (
689           (rpcBestCU->getCbf( 0, COMPONENT_Y  ) != 0)                                            ||
690          ((rpcBestCU->getCbf( 0, COMPONENT_Cb ) != 0) && (numberValidComponents > COMPONENT_Cb)) ||
691          ((rpcBestCU->getCbf( 0, COMPONENT_Cr ) != 0) && (numberValidComponents > COMPONENT_Cr))   // avoid very complex intra if it is unlikely
692            )))
693        {
694          xCheckRDCostIntra( rpcBestCU, rpcTempCU, intraCost, SIZE_2Nx2N DEBUG_STRING_PASS_INTO(sDebug) );
695
696          rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
697          if( uiDepth == sps.getLog2DiffMaxMinCodingBlockSize() )
698          {
699            if( rpcTempCU->getWidth(0) > ( 1 << sps.getQuadtreeTULog2MinSize() ) )
700            {
701              Double tmpIntraCost;
702              xCheckRDCostIntra( rpcBestCU, rpcTempCU, tmpIntraCost, SIZE_NxN DEBUG_STRING_PASS_INTO(sDebug)   );
703
704              intraCost = std::min(intraCost, tmpIntraCost);
705              rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
706            }
707          }
708        }
709
710        // test PCM
711        if(sps.getUsePCM()
712          && rpcTempCU->getWidth(0) <= (1<<sps.getPCMLog2MaxSize())
713          && rpcTempCU->getWidth(0) >= (1<<sps.getPCMLog2MinSize()) )
714        {
715          UInt uiRawBits = getTotalBits(rpcBestCU->getWidth(0), rpcBestCU->getHeight(0), rpcBestCU->getPic()->getChromaFormat(), sps.getBitDepths().recon);
716          UInt uiBestBits = rpcBestCU->getTotalBits();
717          if((uiBestBits > uiRawBits) || (rpcBestCU->getTotalCost() > m_pcRdCost->calcRdCost(uiRawBits, 0)))
718
719          {
720            xCheckIntraPCM (rpcBestCU, rpcTempCU);
721            rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
722          }
723        }
724        if (bIsLosslessMode) // Restore loop variable if lossless mode was searched.
725        {
726          iQP = iMinQP;
727        }
728      }
729    }
730
731    if( rpcBestCU->getTotalCost()!=MAX_DOUBLE )
732    {
733      m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[uiDepth][CI_NEXT_BEST]);
734      m_pcEntropyCoder->resetBits();
735      m_pcEntropyCoder->encodeSplitFlag( rpcBestCU, 0, uiDepth, true );
736      rpcBestCU->getTotalBits() += m_pcEntropyCoder->getNumberOfWrittenBits(); // split bits
737      rpcBestCU->getTotalBins() += ((TEncBinCABAC *)((TEncSbac*)m_pcEntropyCoder->m_pcEntropyCoderIf)->getEncBinIf())->getBinsCoded();
738      rpcBestCU->getTotalCost()  = m_pcRdCost->calcRdCost( rpcBestCU->getTotalBits(), rpcBestCU->getTotalDistortion() );
739      m_pcRDGoOnSbacCoder->store(m_pppcRDSbacCoder[uiDepth][CI_NEXT_BEST]);
740    }
741  }
742
743  // copy original YUV samples to PCM buffer
744  if( rpcBestCU->getTotalCost()!=MAX_DOUBLE && rpcBestCU->isLosslessCoded(0) && (rpcBestCU->getIPCMFlag(0) == false))
745  {
746    xFillPCMBuffer(rpcBestCU, m_ppcOrigYuv[uiDepth]);
747  }
748
749  if( uiDepth == pps.getMaxCuDQPDepth() )
750  {
751    Int idQP = m_pcEncCfg->getMaxDeltaQP();
752    iMinQP = Clip3( -sps.getQpBDOffset(CHANNEL_TYPE_LUMA), MAX_QP, iBaseQP-idQP );
753    iMaxQP = Clip3( -sps.getQpBDOffset(CHANNEL_TYPE_LUMA), MAX_QP, iBaseQP+idQP );
754  }
755  else if( uiDepth < pps.getMaxCuDQPDepth() )
756  {
757    iMinQP = iBaseQP;
758    iMaxQP = iBaseQP;
759  }
760  else
761  {
762    const Int iStartQP = rpcTempCU->getQP(0);
763    iMinQP = iStartQP;
764    iMaxQP = iStartQP;
765  }
766
767  if ( m_pcEncCfg->getUseRateCtrl() )
768  {
769    iMinQP = m_pcRateCtrl->getRCQP();
770    iMaxQP = m_pcRateCtrl->getRCQP();
771  }
772
773  if ( m_pcEncCfg->getCUTransquantBypassFlagForceValue() )
774  {
775    iMaxQP = iMinQP; // If all TUs are forced into using transquant bypass, do not loop here.
776  }
777  const Bool bSubBranch = bBoundary || !( m_pcEncCfg->getUseEarlyCU() && rpcBestCU->getTotalCost()!=MAX_DOUBLE && rpcBestCU->isSkipped(0) );
778  if( bSubBranch && uiDepth < sps.getLog2DiffMaxMinCodingBlockSize() && (!getFastDeltaQp() || uiWidth > fastDeltaQPCuMaxSize || bBoundary))
779  {
780    // further split
781    for (Int iQP=iMinQP; iQP<=iMaxQP; iQP++)
782    {
783      const Bool bIsLosslessMode = false; // False at this level. Next level down may set it to true.
784
785      rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
786
787      UChar       uhNextDepth         = uiDepth+1;
788      TComDataCU* pcSubBestPartCU     = m_ppcBestCU[uhNextDepth];
789      TComDataCU* pcSubTempPartCU     = m_ppcTempCU[uhNextDepth];
790      DEBUG_STRING_NEW(sTempDebug)
791
792      for ( UInt uiPartUnitIdx = 0; uiPartUnitIdx < 4; uiPartUnitIdx++ )
793      {
794        pcSubBestPartCU->initSubCU( rpcTempCU, uiPartUnitIdx, uhNextDepth, iQP );           // clear sub partition datas or init.
795        pcSubTempPartCU->initSubCU( rpcTempCU, uiPartUnitIdx, uhNextDepth, iQP );           // clear sub partition datas or init.
796
797        if( ( pcSubBestPartCU->getCUPelX() < sps.getPicWidthInLumaSamples() ) && ( pcSubBestPartCU->getCUPelY() < sps.getPicHeightInLumaSamples() ) )
798        {
799          if ( 0 == uiPartUnitIdx) //initialize RD with previous depth buffer
800          {
801            m_pppcRDSbacCoder[uhNextDepth][CI_CURR_BEST]->load(m_pppcRDSbacCoder[uiDepth][CI_CURR_BEST]);
802          }
803          else
804          {
805            m_pppcRDSbacCoder[uhNextDepth][CI_CURR_BEST]->load(m_pppcRDSbacCoder[uhNextDepth][CI_NEXT_BEST]);
806          }
807
808#if AMP_ENC_SPEEDUP
809          DEBUG_STRING_NEW(sChild)
810          if ( !(rpcBestCU->getTotalCost()!=MAX_DOUBLE && rpcBestCU->isInter(0)) )
811          {
812            xCompressCU( pcSubBestPartCU, pcSubTempPartCU, uhNextDepth DEBUG_STRING_PASS_INTO(sChild), NUMBER_OF_PART_SIZES );
813          }
814          else
815          {
816
817            xCompressCU( pcSubBestPartCU, pcSubTempPartCU, uhNextDepth DEBUG_STRING_PASS_INTO(sChild), rpcBestCU->getPartitionSize(0) );
818          }
819          DEBUG_STRING_APPEND(sTempDebug, sChild)
820#else
821          xCompressCU( pcSubBestPartCU, pcSubTempPartCU, uhNextDepth );
822#endif
823
824          rpcTempCU->copyPartFrom( pcSubBestPartCU, uiPartUnitIdx, uhNextDepth );         // Keep best part data to current temporary data.
825          xCopyYuv2Tmp( pcSubBestPartCU->getTotalNumPart()*uiPartUnitIdx, uhNextDepth );
826        }
827        else
828        {
829          pcSubBestPartCU->copyToPic( uhNextDepth );
830          rpcTempCU->copyPartFrom( pcSubBestPartCU, uiPartUnitIdx, uhNextDepth );
831        }
832      }
833
834      m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[uhNextDepth][CI_NEXT_BEST]);
835      if( !bBoundary )
836      {
837        m_pcEntropyCoder->resetBits();
838        m_pcEntropyCoder->encodeSplitFlag( rpcTempCU, 0, uiDepth, true );
839
840        rpcTempCU->getTotalBits() += m_pcEntropyCoder->getNumberOfWrittenBits(); // split bits
841        rpcTempCU->getTotalBins() += ((TEncBinCABAC *)((TEncSbac*)m_pcEntropyCoder->m_pcEntropyCoderIf)->getEncBinIf())->getBinsCoded();
842      }
843        rpcTempCU->getTotalCost()  = m_pcRdCost->calcRdCost( rpcTempCU->getTotalBits(), rpcTempCU->getTotalDistortion() );
844
845      if( uiDepth == pps.getMaxCuDQPDepth() && pps.getUseDQP())
846      {
847        Bool hasResidual = false;
848        for( UInt uiBlkIdx = 0; uiBlkIdx < rpcTempCU->getTotalNumPart(); uiBlkIdx ++)
849        {
850          if( (     rpcTempCU->getCbf(uiBlkIdx, COMPONENT_Y)
851                || (rpcTempCU->getCbf(uiBlkIdx, COMPONENT_Cb) && (numberValidComponents > COMPONENT_Cb))
852                || (rpcTempCU->getCbf(uiBlkIdx, COMPONENT_Cr) && (numberValidComponents > COMPONENT_Cr)) ) )
853          {
854            hasResidual = true;
855            break;
856          }
857        }
858
859        if ( hasResidual )
860        {
861          m_pcEntropyCoder->resetBits();
862          m_pcEntropyCoder->encodeQP( rpcTempCU, 0, false );
863          rpcTempCU->getTotalBits() += m_pcEntropyCoder->getNumberOfWrittenBits(); // dQP bits
864          rpcTempCU->getTotalBins() += ((TEncBinCABAC *)((TEncSbac*)m_pcEntropyCoder->m_pcEntropyCoderIf)->getEncBinIf())->getBinsCoded();
865            rpcTempCU->getTotalCost()  = m_pcRdCost->calcRdCost( rpcTempCU->getTotalBits(), rpcTempCU->getTotalDistortion() );
866
867          Bool foundNonZeroCbf = false;
868          rpcTempCU->setQPSubCUs( rpcTempCU->getRefQP( 0 ), 0, uiDepth, foundNonZeroCbf );
869          assert( foundNonZeroCbf );
870        }
871        else
872        {
873          rpcTempCU->setQPSubParts( rpcTempCU->getRefQP( 0 ), 0, uiDepth ); // set QP to default QP
874        }
875      }
876
877      m_pcRDGoOnSbacCoder->store(m_pppcRDSbacCoder[uiDepth][CI_TEMP_BEST]);
878
879      // If the configuration being tested exceeds the maximum number of bytes for a slice / slice-segment, then
880      // a proper RD evaluation cannot be performed. Therefore, termination of the
881      // slice/slice-segment must be made prior to this CTU.
882      // This can be achieved by forcing the decision to be that of the rpcTempCU.
883      // The exception is each slice / slice-segment must have at least one CTU.
884      if (rpcBestCU->getTotalCost()!=MAX_DOUBLE)
885      {
886        const Bool isEndOfSlice        =    pcSlice->getSliceMode()==FIXED_NUMBER_OF_BYTES
887                                         && ((pcSlice->getSliceBits()+rpcBestCU->getTotalBits())>pcSlice->getSliceArgument()<<3)
888                                         && rpcBestCU->getCtuRsAddr() != pcPic->getPicSym()->getCtuTsToRsAddrMap(pcSlice->getSliceCurStartCtuTsAddr())
889                                         && rpcBestCU->getCtuRsAddr() != pcPic->getPicSym()->getCtuTsToRsAddrMap(pcSlice->getSliceSegmentCurStartCtuTsAddr());
890        const Bool isEndOfSliceSegment =    pcSlice->getSliceSegmentMode()==FIXED_NUMBER_OF_BYTES
891                                         && ((pcSlice->getSliceSegmentBits()+rpcBestCU->getTotalBits()) > pcSlice->getSliceSegmentArgument()<<3)
892                                         && rpcBestCU->getCtuRsAddr() != pcPic->getPicSym()->getCtuTsToRsAddrMap(pcSlice->getSliceSegmentCurStartCtuTsAddr());
893                                             // Do not need to check slice condition for slice-segment since a slice-segment is a subset of a slice.
894        if(isEndOfSlice||isEndOfSliceSegment)
895        {
896          rpcBestCU->getTotalCost()=MAX_DOUBLE;
897        }
898      }
899
900      xCheckBestMode( rpcBestCU, rpcTempCU, uiDepth DEBUG_STRING_PASS_INTO(sDebug) DEBUG_STRING_PASS_INTO(sTempDebug) DEBUG_STRING_PASS_INTO(false) ); // RD compare current larger prediction
901                                                                                                                                                       // with sub partitioned prediction.
902    }
903  }
904
905  DEBUG_STRING_APPEND(sDebug_, sDebug);
906
907  rpcBestCU->copyToPic(uiDepth);                                                     // Copy Best data to Picture for next partition prediction.
908
909  xCopyYuv2Pic( rpcBestCU->getPic(), rpcBestCU->getCtuRsAddr(), rpcBestCU->getZorderIdxInCtu(), uiDepth, uiDepth );   // Copy Yuv data to picture Yuv
910  if (bBoundary)
911  {
912    return;
913  }
914
915  // Assert if Best prediction mode is NONE
916  // Selected mode's RD-cost must be not MAX_DOUBLE.
917  assert( rpcBestCU->getPartitionSize ( 0 ) != NUMBER_OF_PART_SIZES       );
918  assert( rpcBestCU->getPredictionMode( 0 ) != NUMBER_OF_PREDICTION_MODES );
919  assert( rpcBestCU->getTotalCost     (   ) != MAX_DOUBLE                 );
920}
921
922/** finish encoding a cu and handle end-of-slice conditions
923 * \param pcCU
924 * \param uiAbsPartIdx
925 * \param uiDepth
926 * \returns Void
927 */
928Void TEncCu::finishCU( TComDataCU* pcCU, UInt uiAbsPartIdx )
929{
930  TComPic* pcPic = pcCU->getPic();
931  TComSlice * pcSlice = pcCU->getPic()->getSlice(pcCU->getPic()->getCurrSliceIdx());
932
933  //Calculate end address
934  const Int  currentCTUTsAddr = pcPic->getPicSym()->getCtuRsToTsAddrMap(pcCU->getCtuRsAddr());
935  const Bool isLastSubCUOfCtu = pcCU->isLastSubCUOfCtu(uiAbsPartIdx);
936  if ( isLastSubCUOfCtu )
937  {
938    // The 1-terminating bit is added to all streams, so don't add it here when it's 1.
939    // i.e. when the slice segment CurEnd CTU address is the current CTU address+1.
940    if (pcSlice->getSliceSegmentCurEndCtuTsAddr() != currentCTUTsAddr+1)
941    {
942      m_pcEntropyCoder->encodeTerminatingBit( 0 );
943    }
944  }
945}
946
947/** Compute QP for each CU
948 * \param pcCU Target CU
949 * \param uiDepth CU depth
950 * \returns quantization parameter
951 */
952Int TEncCu::xComputeQP( TComDataCU* pcCU, UInt uiDepth )
953{
954  Int iBaseQp = pcCU->getSlice()->getSliceQp();
955  Int iQpOffset = 0;
956  if ( m_pcEncCfg->getUseAdaptiveQP() )
957  {
958    TEncPic* pcEPic = dynamic_cast<TEncPic*>( pcCU->getPic() );
959    UInt uiAQDepth = min( uiDepth, pcEPic->getMaxAQDepth()-1 );
960    TEncPicQPAdaptationLayer* pcAQLayer = pcEPic->getAQLayer( uiAQDepth );
961    UInt uiAQUPosX = pcCU->getCUPelX() / pcAQLayer->getAQPartWidth();
962    UInt uiAQUPosY = pcCU->getCUPelY() / pcAQLayer->getAQPartHeight();
963    UInt uiAQUStride = pcAQLayer->getAQPartStride();
964    TEncQPAdaptationUnit* acAQU = pcAQLayer->getQPAdaptationUnit();
965
966    Double dMaxQScale = pow(2.0, m_pcEncCfg->getQPAdaptationRange()/6.0);
967    Double dAvgAct = pcAQLayer->getAvgActivity();
968    Double dCUAct = acAQU[uiAQUPosY * uiAQUStride + uiAQUPosX].getActivity();
969    Double dNormAct = (dMaxQScale*dCUAct + dAvgAct) / (dCUAct + dMaxQScale*dAvgAct);
970    Double dQpOffset = log(dNormAct) / log(2.0) * 6.0;
971    iQpOffset = Int(floor( dQpOffset + 0.49999 ));
972  }
973
974  return Clip3(-pcCU->getSlice()->getSPS()->getQpBDOffset(CHANNEL_TYPE_LUMA), MAX_QP, iBaseQp+iQpOffset );
975}
976
977/** encode a CU block recursively
978 * \param pcCU
979 * \param uiAbsPartIdx
980 * \param uiDepth
981 * \returns Void
982 */
983Void TEncCu::xEncodeCU( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
984{
985        TComPic   *const pcPic   = pcCU->getPic();
986        TComSlice *const pcSlice = pcCU->getSlice();
987  const TComSPS   &sps =*(pcSlice->getSPS());
988  const TComPPS   &pps =*(pcSlice->getPPS());
989
990  const UInt maxCUWidth  = sps.getMaxCUWidth();
991  const UInt maxCUHeight = sps.getMaxCUHeight();
992
993        Bool bBoundary = false;
994        UInt uiLPelX   = pcCU->getCUPelX() + g_auiRasterToPelX[ g_auiZscanToRaster[uiAbsPartIdx] ];
995  const UInt uiRPelX   = uiLPelX + (maxCUWidth>>uiDepth)  - 1;
996        UInt uiTPelY   = pcCU->getCUPelY() + g_auiRasterToPelY[ g_auiZscanToRaster[uiAbsPartIdx] ];
997  const UInt uiBPelY   = uiTPelY + (maxCUHeight>>uiDepth) - 1;
998
999#if NH_MV_ENC_DEC_TRAC
1000  DTRACE_CU_S("=========== coding_quadtree ===========\n")
1001  DTRACE_CU("x0", uiLPelX)
1002  DTRACE_CU("x1", uiTPelY)
1003  DTRACE_CU("log2CbSize", maxCUWidth>>uiDepth )
1004  DTRACE_CU("cqtDepth"  , uiDepth)
1005#endif
1006
1007  if( ( uiRPelX < sps.getPicWidthInLumaSamples() ) && ( uiBPelY < sps.getPicHeightInLumaSamples() ) )
1008  {
1009    m_pcEntropyCoder->encodeSplitFlag( pcCU, uiAbsPartIdx, uiDepth );
1010  }
1011  else
1012  {
1013    bBoundary = true;
1014  }
1015
1016  if( ( ( uiDepth < pcCU->getDepth( uiAbsPartIdx ) ) && ( uiDepth < sps.getLog2DiffMaxMinCodingBlockSize() ) ) || bBoundary )
1017  {
1018    UInt uiQNumParts = ( pcPic->getNumPartitionsInCtu() >> (uiDepth<<1) )>>2;
1019    if( uiDepth == pps.getMaxCuDQPDepth() && pps.getUseDQP())
1020    {
1021      setdQPFlag(true);
1022    }
1023
1024    if( uiDepth == pps.getPpsRangeExtension().getDiffCuChromaQpOffsetDepth() && pcSlice->getUseChromaQpAdj())
1025    {
1026      setCodeChromaQpAdjFlag(true);
1027    }
1028
1029    for ( UInt uiPartUnitIdx = 0; uiPartUnitIdx < 4; uiPartUnitIdx++, uiAbsPartIdx+=uiQNumParts )
1030    {
1031      uiLPelX   = pcCU->getCUPelX() + g_auiRasterToPelX[ g_auiZscanToRaster[uiAbsPartIdx] ];
1032      uiTPelY   = pcCU->getCUPelY() + g_auiRasterToPelY[ g_auiZscanToRaster[uiAbsPartIdx] ];
1033      if( ( uiLPelX < sps.getPicWidthInLumaSamples() ) && ( uiTPelY < sps.getPicHeightInLumaSamples() ) )
1034      {
1035        xEncodeCU( pcCU, uiAbsPartIdx, uiDepth+1 );
1036      }
1037    }
1038    return;
1039  }
1040
1041#if NH_MV_ENC_DEC_TRAC
1042  DTRACE_CU_S("=========== coding_unit ===========\n")
1043#endif
1044
1045
1046  if( uiDepth <= pps.getMaxCuDQPDepth() && pps.getUseDQP())
1047  {
1048    setdQPFlag(true);
1049  }
1050
1051  if( uiDepth <= pps.getPpsRangeExtension().getDiffCuChromaQpOffsetDepth() && pcSlice->getUseChromaQpAdj())
1052  {
1053    setCodeChromaQpAdjFlag(true);
1054  }
1055
1056  if (pps.getTransquantBypassEnableFlag())
1057  {
1058    m_pcEntropyCoder->encodeCUTransquantBypassFlag( pcCU, uiAbsPartIdx );
1059  }
1060
1061  if( !pcSlice->isIntra() )
1062  {
1063    m_pcEntropyCoder->encodeSkipFlag( pcCU, uiAbsPartIdx );
1064  }
1065
1066  if( pcCU->isSkipped( uiAbsPartIdx ) )
1067  {
1068#if NH_MV_ENC_DEC_TRAC
1069    DTRACE_PU_S("=========== prediction_unit ===========\n")
1070    DTRACE_PU("x0", uiLPelX)
1071    DTRACE_PU("x1", uiTPelY)
1072#endif
1073
1074    m_pcEntropyCoder->encodeMergeIndex( pcCU, uiAbsPartIdx );
1075
1076    finishCU(pcCU,uiAbsPartIdx);
1077    return;
1078  }
1079
1080  m_pcEntropyCoder->encodePredMode( pcCU, uiAbsPartIdx );
1081  m_pcEntropyCoder->encodePartSize( pcCU, uiAbsPartIdx, uiDepth );
1082
1083  if (pcCU->isIntra( uiAbsPartIdx ) && pcCU->getPartitionSize( uiAbsPartIdx ) == SIZE_2Nx2N )
1084  {
1085    m_pcEntropyCoder->encodeIPCMInfo( pcCU, uiAbsPartIdx );
1086
1087    if(pcCU->getIPCMFlag(uiAbsPartIdx))
1088    {
1089
1090      // Encode slice finish
1091      finishCU(pcCU,uiAbsPartIdx);
1092      return;
1093    }
1094  }
1095
1096  // prediction Info ( Intra : direction mode, Inter : Mv, reference idx )
1097  m_pcEntropyCoder->encodePredInfo( pcCU, uiAbsPartIdx );
1098
1099  // Encode Coefficients
1100  Bool bCodeDQP = getdQPFlag();
1101  Bool codeChromaQpAdj = getCodeChromaQpAdjFlag();
1102  m_pcEntropyCoder->encodeCoeff( pcCU, uiAbsPartIdx, uiDepth, bCodeDQP, codeChromaQpAdj );
1103  setCodeChromaQpAdjFlag( codeChromaQpAdj );
1104  setdQPFlag( bCodeDQP );
1105
1106
1107  // --- write terminating bit ---
1108  finishCU(pcCU,uiAbsPartIdx);
1109}
1110
1111Int xCalcHADs8x8_ISlice(Pel *piOrg, Int iStrideOrg)
1112{
1113  Int k, i, j, jj;
1114  Int diff[64], m1[8][8], m2[8][8], m3[8][8], iSumHad = 0;
1115
1116  for( k = 0; k < 64; k += 8 )
1117  {
1118    diff[k+0] = piOrg[0] ;
1119    diff[k+1] = piOrg[1] ;
1120    diff[k+2] = piOrg[2] ;
1121    diff[k+3] = piOrg[3] ;
1122    diff[k+4] = piOrg[4] ;
1123    diff[k+5] = piOrg[5] ;
1124    diff[k+6] = piOrg[6] ;
1125    diff[k+7] = piOrg[7] ;
1126
1127    piOrg += iStrideOrg;
1128  }
1129
1130  //horizontal
1131  for (j=0; j < 8; j++)
1132  {
1133    jj = j << 3;
1134    m2[j][0] = diff[jj  ] + diff[jj+4];
1135    m2[j][1] = diff[jj+1] + diff[jj+5];
1136    m2[j][2] = diff[jj+2] + diff[jj+6];
1137    m2[j][3] = diff[jj+3] + diff[jj+7];
1138    m2[j][4] = diff[jj  ] - diff[jj+4];
1139    m2[j][5] = diff[jj+1] - diff[jj+5];
1140    m2[j][6] = diff[jj+2] - diff[jj+6];
1141    m2[j][7] = diff[jj+3] - diff[jj+7];
1142
1143    m1[j][0] = m2[j][0] + m2[j][2];
1144    m1[j][1] = m2[j][1] + m2[j][3];
1145    m1[j][2] = m2[j][0] - m2[j][2];
1146    m1[j][3] = m2[j][1] - m2[j][3];
1147    m1[j][4] = m2[j][4] + m2[j][6];
1148    m1[j][5] = m2[j][5] + m2[j][7];
1149    m1[j][6] = m2[j][4] - m2[j][6];
1150    m1[j][7] = m2[j][5] - m2[j][7];
1151
1152    m2[j][0] = m1[j][0] + m1[j][1];
1153    m2[j][1] = m1[j][0] - m1[j][1];
1154    m2[j][2] = m1[j][2] + m1[j][3];
1155    m2[j][3] = m1[j][2] - m1[j][3];
1156    m2[j][4] = m1[j][4] + m1[j][5];
1157    m2[j][5] = m1[j][4] - m1[j][5];
1158    m2[j][6] = m1[j][6] + m1[j][7];
1159    m2[j][7] = m1[j][6] - m1[j][7];
1160  }
1161
1162  //vertical
1163  for (i=0; i < 8; i++)
1164  {
1165    m3[0][i] = m2[0][i] + m2[4][i];
1166    m3[1][i] = m2[1][i] + m2[5][i];
1167    m3[2][i] = m2[2][i] + m2[6][i];
1168    m3[3][i] = m2[3][i] + m2[7][i];
1169    m3[4][i] = m2[0][i] - m2[4][i];
1170    m3[5][i] = m2[1][i] - m2[5][i];
1171    m3[6][i] = m2[2][i] - m2[6][i];
1172    m3[7][i] = m2[3][i] - m2[7][i];
1173
1174    m1[0][i] = m3[0][i] + m3[2][i];
1175    m1[1][i] = m3[1][i] + m3[3][i];
1176    m1[2][i] = m3[0][i] - m3[2][i];
1177    m1[3][i] = m3[1][i] - m3[3][i];
1178    m1[4][i] = m3[4][i] + m3[6][i];
1179    m1[5][i] = m3[5][i] + m3[7][i];
1180    m1[6][i] = m3[4][i] - m3[6][i];
1181    m1[7][i] = m3[5][i] - m3[7][i];
1182
1183    m2[0][i] = m1[0][i] + m1[1][i];
1184    m2[1][i] = m1[0][i] - m1[1][i];
1185    m2[2][i] = m1[2][i] + m1[3][i];
1186    m2[3][i] = m1[2][i] - m1[3][i];
1187    m2[4][i] = m1[4][i] + m1[5][i];
1188    m2[5][i] = m1[4][i] - m1[5][i];
1189    m2[6][i] = m1[6][i] + m1[7][i];
1190    m2[7][i] = m1[6][i] - m1[7][i];
1191  }
1192
1193  for (i = 0; i < 8; i++)
1194  {
1195    for (j = 0; j < 8; j++)
1196    {
1197      iSumHad += abs(m2[i][j]);
1198    }
1199  }
1200  iSumHad -= abs(m2[0][0]);
1201  iSumHad =(iSumHad+2)>>2;
1202  return(iSumHad);
1203}
1204
1205Int  TEncCu::updateCtuDataISlice(TComDataCU* pCtu, Int width, Int height)
1206{
1207  Int  xBl, yBl;
1208  const Int iBlkSize = 8;
1209
1210  Pel* pOrgInit   = pCtu->getPic()->getPicYuvOrg()->getAddr(COMPONENT_Y, pCtu->getCtuRsAddr(), 0);
1211  Int  iStrideOrig = pCtu->getPic()->getPicYuvOrg()->getStride(COMPONENT_Y);
1212  Pel  *pOrg;
1213
1214  Int iSumHad = 0;
1215  for ( yBl=0; (yBl+iBlkSize)<=height; yBl+= iBlkSize)
1216  {
1217    for ( xBl=0; (xBl+iBlkSize)<=width; xBl+= iBlkSize)
1218    {
1219      pOrg = pOrgInit + iStrideOrig*yBl + xBl;
1220      iSumHad += xCalcHADs8x8_ISlice(pOrg, iStrideOrig);
1221    }
1222  }
1223  return(iSumHad);
1224}
1225
1226/** check RD costs for a CU block encoded with merge
1227 * \param rpcBestCU
1228 * \param rpcTempCU
1229 * \param earlyDetectionSkipMode
1230 */
1231Void TEncCu::xCheckRDCostMerge2Nx2N( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU DEBUG_STRING_FN_DECLARE(sDebug), Bool *earlyDetectionSkipMode )
1232{
1233  assert( rpcTempCU->getSlice()->getSliceType() != I_SLICE );
1234  if(getFastDeltaQp())
1235  {
1236    return;   // never check merge in fast deltaqp mode
1237  }
1238
1239#if NH_MV
1240  D_PRINT_INC_INDENT( g_traceModeCheck, "xCheckRDCostMerge2Nx2N" );
1241#endif
1242
1243  TComMvField  cMvFieldNeighbours[2 * MRG_MAX_NUM_CANDS]; // double length for mv of both lists
1244  UChar uhInterDirNeighbours[MRG_MAX_NUM_CANDS];
1245  Int numValidMergeCand = 0;
1246  const Bool bTransquantBypassFlag = rpcTempCU->getCUTransquantBypass(0);
1247
1248  for( UInt ui = 0; ui < rpcTempCU->getSlice()->getMaxNumMergeCand(); ++ui )
1249  {
1250    uhInterDirNeighbours[ui] = 0;
1251  }
1252  UChar uhDepth = rpcTempCU->getDepth( 0 );
1253
1254
1255  rpcTempCU->setPartSizeSubParts( SIZE_2Nx2N, 0, uhDepth ); // interprets depth relative to CTU level
1256
1257
1258  rpcTempCU->getInterMergeCandidates( 0, 0, cMvFieldNeighbours,uhInterDirNeighbours, numValidMergeCand );
1259
1260  Int mergeCandBuffer[MRG_MAX_NUM_CANDS];
1261  for( UInt ui = 0; ui < numValidMergeCand; ++ui )
1262  {
1263    mergeCandBuffer[ui] = 0;
1264  }
1265
1266  Bool bestIsSkip = false;
1267
1268  UInt iteration;
1269  if ( rpcTempCU->isLosslessCoded(0))
1270  {
1271    iteration = 1;
1272  }
1273  else
1274  {
1275    iteration = 2;
1276  }
1277  DEBUG_STRING_NEW(bestStr)
1278
1279
1280  for( UInt uiNoResidual = 0; uiNoResidual < iteration; ++uiNoResidual )
1281  {
1282#if NH_MV
1283    D_PRINT_INC_INDENT ( g_traceModeCheck, "uiNoResidual: " + n2s( uiNoResidual) );
1284#endif
1285
1286    for( UInt uiMergeCand = 0; uiMergeCand < numValidMergeCand; ++uiMergeCand )
1287    {
1288#if NH_MV
1289      D_PRINT_INC_INDENT ( g_traceModeCheck, "uiMergeCand: "+  n2s(uiMergeCand) );
1290#endif
1291
1292      if(!(uiNoResidual==1 && mergeCandBuffer[uiMergeCand]==1))
1293      {
1294        if( !(bestIsSkip && uiNoResidual == 0) )
1295        {
1296          DEBUG_STRING_NEW(tmpStr)
1297          // set MC parameters
1298          rpcTempCU->setPredModeSubParts( MODE_INTER, 0, uhDepth ); // interprets depth relative to CTU level
1299          rpcTempCU->setCUTransquantBypassSubParts( bTransquantBypassFlag, 0, uhDepth );
1300          rpcTempCU->setChromaQpAdjSubParts( bTransquantBypassFlag ? 0 : m_cuChromaQpOffsetIdxPlus1, 0, uhDepth );
1301          rpcTempCU->setPartSizeSubParts( SIZE_2Nx2N, 0, uhDepth ); // interprets depth relative to CTU level
1302          rpcTempCU->setMergeFlagSubParts( true, 0, 0, uhDepth ); // interprets depth relative to CTU level
1303          rpcTempCU->setMergeIndexSubParts( uiMergeCand, 0, 0, uhDepth ); // interprets depth relative to CTU level
1304
1305          {
1306            rpcTempCU->setInterDirSubParts( uhInterDirNeighbours[uiMergeCand], 0, 0, uhDepth ); // interprets depth relative to CTU level
1307            rpcTempCU->getCUMvField( REF_PIC_LIST_0 )->setAllMvField( cMvFieldNeighbours[0 + 2*uiMergeCand], SIZE_2Nx2N, 0, 0 ); // interprets depth relative to rpcTempCU level
1308            rpcTempCU->getCUMvField( REF_PIC_LIST_1 )->setAllMvField( cMvFieldNeighbours[1 + 2*uiMergeCand], SIZE_2Nx2N, 0, 0 ); // interprets depth relative to rpcTempCU level
1309          }
1310          // do MC
1311          m_pcPredSearch->motionCompensation ( rpcTempCU, m_ppcPredYuvTemp[uhDepth] );
1312          // estimate residual and encode everything
1313          m_pcPredSearch->encodeResAndCalcRdInterCU( rpcTempCU,
1314                                                     m_ppcOrigYuv    [uhDepth],
1315                                                     m_ppcPredYuvTemp[uhDepth],
1316                                                     m_ppcResiYuvTemp[uhDepth],
1317                                                     m_ppcResiYuvBest[uhDepth],
1318                                                     m_ppcRecoYuvTemp[uhDepth],
1319                                                     (uiNoResidual != 0) DEBUG_STRING_PASS_INTO(tmpStr) );
1320
1321#if DEBUG_STRING
1322          DebugInterPredResiReco(tmpStr, *(m_ppcPredYuvTemp[uhDepth]), *(m_ppcResiYuvBest[uhDepth]), *(m_ppcRecoYuvTemp[uhDepth]), DebugStringGetPredModeMask(rpcTempCU->getPredictionMode(0)));
1323#endif
1324
1325          if ((uiNoResidual == 0) && (rpcTempCU->getQtRootCbf(0) == 0))
1326          {
1327            // If no residual when allowing for one, then set mark to not try case where residual is forced to 0
1328            mergeCandBuffer[uiMergeCand] = 1;
1329          }
1330          Int orgQP = rpcTempCU->getQP( 0 );
1331          xCheckDQP( rpcTempCU );
1332          xCheckBestMode(rpcBestCU, rpcTempCU, uhDepth DEBUG_STRING_PASS_INTO(bestStr) DEBUG_STRING_PASS_INTO(tmpStr));
1333
1334          rpcTempCU->initEstData( uhDepth, orgQP, bTransquantBypassFlag );
1335
1336          if( m_pcEncCfg->getUseFastDecisionForMerge() && !bestIsSkip )
1337          {
1338            bestIsSkip = rpcBestCU->getQtRootCbf(0) == 0;
1339          }
1340        }
1341      }
1342#if NH_MV
1343      D_DEC_INDENT( g_traceModeCheck ); 
1344#endif
1345    }
1346
1347    if(uiNoResidual == 0 && m_pcEncCfg->getUseEarlySkipDetection())
1348    {
1349      if(rpcBestCU->getQtRootCbf( 0 ) == 0)
1350      {
1351        if( rpcBestCU->getMergeFlag( 0 ))
1352        {
1353          *earlyDetectionSkipMode = true;
1354        }
1355        else if(m_pcEncCfg->getMotionEstimationSearchMethod() != MESEARCH_SELECTIVE)
1356        {
1357          Int absoulte_MV=0;
1358          for ( UInt uiRefListIdx = 0; uiRefListIdx < 2; uiRefListIdx++ )
1359          {
1360            if ( rpcBestCU->getSlice()->getNumRefIdx( RefPicList( uiRefListIdx ) ) > 0 )
1361            {
1362              TComCUMvField* pcCUMvField = rpcBestCU->getCUMvField(RefPicList( uiRefListIdx ));
1363              Int iHor = pcCUMvField->getMvd( 0 ).getAbsHor();
1364              Int iVer = pcCUMvField->getMvd( 0 ).getAbsVer();
1365              absoulte_MV+=iHor+iVer;
1366            }
1367          }
1368
1369          if(absoulte_MV == 0)
1370          {
1371            *earlyDetectionSkipMode = true;
1372          }
1373        }
1374      }
1375    }
1376#if NH_MV
1377    D_DEC_INDENT( g_traceModeCheck ); 
1378#endif
1379  }
1380  DEBUG_STRING_APPEND(sDebug, bestStr)
1381#if NH_MV
1382 D_DEC_INDENT( g_traceModeCheck );
1383#endif
1384}
1385
1386
1387#if AMP_MRG
1388Void TEncCu::xCheckRDCostInter( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, PartSize ePartSize DEBUG_STRING_FN_DECLARE(sDebug), Bool bUseMRG)
1389#else
1390Void TEncCu::xCheckRDCostInter( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, PartSize ePartSize )
1391#endif
1392{
1393  DEBUG_STRING_NEW(sTest)
1394
1395  if(getFastDeltaQp())
1396  {
1397    const TComSPS &sps=*(rpcTempCU->getSlice()->getSPS());
1398    const UInt fastDeltaQPCuMaxSize = Clip3(sps.getMaxCUHeight()>>(sps.getLog2DiffMaxMinCodingBlockSize()), sps.getMaxCUHeight(), 32u);
1399    if(ePartSize != SIZE_2Nx2N || rpcTempCU->getWidth( 0 ) > fastDeltaQPCuMaxSize)
1400    {
1401      return; // only check necessary 2Nx2N Inter in fast deltaqp mode
1402    }
1403  }
1404
1405#if NH_MV
1406  D_PRINT_INC_INDENT(g_traceModeCheck,   "xCheckRDCostInter; ePartSize:" + n2s( ePartSize) );
1407#endif
1408
1409
1410  // prior to this, rpcTempCU will have just been reset using rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
1411  UChar uhDepth = rpcTempCU->getDepth( 0 );
1412  rpcTempCU->setPartSizeSubParts  ( ePartSize,  0, uhDepth );
1413  rpcTempCU->setPredModeSubParts  ( MODE_INTER, 0, uhDepth );
1414  rpcTempCU->setChromaQpAdjSubParts( rpcTempCU->getCUTransquantBypass(0) ? 0 : m_cuChromaQpOffsetIdxPlus1, 0, uhDepth );
1415#if AMP_MRG
1416  rpcTempCU->setMergeAMP (true);
1417  m_pcPredSearch->predInterSearch ( rpcTempCU, m_ppcOrigYuv[uhDepth], m_ppcPredYuvTemp[uhDepth], m_ppcResiYuvTemp[uhDepth], m_ppcRecoYuvTemp[uhDepth] DEBUG_STRING_PASS_INTO(sTest), false, bUseMRG );
1418
1419#else
1420  m_pcPredSearch->predInterSearch ( rpcTempCU, m_ppcOrigYuv[uhDepth], m_ppcPredYuvTemp[uhDepth], m_ppcResiYuvTemp[uhDepth], m_ppcRecoYuvTemp[uhDepth] );
1421#endif
1422
1423#if AMP_MRG
1424  if ( !rpcTempCU->getMergeAMP() )
1425  {
1426    {
1427#if NH_MV
1428        D_DEC_INDENT( g_traceModeCheck ); 
1429#endif
1430    return;
1431  }
1432  }
1433#endif
1434
1435  m_pcPredSearch->encodeResAndCalcRdInterCU( rpcTempCU, m_ppcOrigYuv[uhDepth], m_ppcPredYuvTemp[uhDepth], m_ppcResiYuvTemp[uhDepth], m_ppcResiYuvBest[uhDepth], m_ppcRecoYuvTemp[uhDepth], false DEBUG_STRING_PASS_INTO(sTest) );
1436    rpcTempCU->getTotalCost()  = m_pcRdCost->calcRdCost( rpcTempCU->getTotalBits(), rpcTempCU->getTotalDistortion() );
1437
1438#if DEBUG_STRING
1439  DebugInterPredResiReco(sTest, *(m_ppcPredYuvTemp[uhDepth]), *(m_ppcResiYuvBest[uhDepth]), *(m_ppcRecoYuvTemp[uhDepth]), DebugStringGetPredModeMask(rpcTempCU->getPredictionMode(0)));
1440#endif
1441
1442  xCheckDQP( rpcTempCU );
1443  xCheckBestMode(rpcBestCU, rpcTempCU, uhDepth DEBUG_STRING_PASS_INTO(sDebug) DEBUG_STRING_PASS_INTO(sTest));
1444#if NH_MV
1445  D_DEC_INDENT( g_traceModeCheck ); 
1446#endif
1447}
1448
1449
1450Void TEncCu::xCheckRDCostIntra( TComDataCU *&rpcBestCU,
1451                                TComDataCU *&rpcTempCU,
1452                                Double      &cost,
1453                                PartSize     eSize
1454                                DEBUG_STRING_FN_DECLARE(sDebug)
1455                              )
1456{
1457  DEBUG_STRING_NEW(sTest)
1458
1459  if(getFastDeltaQp())
1460  {
1461    const TComSPS &sps=*(rpcTempCU->getSlice()->getSPS());
1462    const UInt fastDeltaQPCuMaxSize = Clip3(sps.getMaxCUHeight()>>(sps.getLog2DiffMaxMinCodingBlockSize()), sps.getMaxCUHeight(), 32u);
1463    if(rpcTempCU->getWidth( 0 ) > fastDeltaQPCuMaxSize)
1464    {
1465      return; // only check necessary 2Nx2N Intra in fast deltaqp mode
1466    }
1467  }
1468#if NH_MV
1469  D_PRINT_INC_INDENT (g_traceModeCheck, "xCheckRDCostIntra; eSize: " + n2s(eSize) );
1470#endif
1471
1472  UInt uiDepth = rpcTempCU->getDepth( 0 );
1473
1474  rpcTempCU->setSkipFlagSubParts( false, 0, uiDepth );
1475
1476
1477  rpcTempCU->setPartSizeSubParts( eSize, 0, uiDepth );
1478  rpcTempCU->setPredModeSubParts( MODE_INTRA, 0, uiDepth );
1479  rpcTempCU->setChromaQpAdjSubParts( rpcTempCU->getCUTransquantBypass(0) ? 0 : m_cuChromaQpOffsetIdxPlus1, 0, uiDepth );
1480
1481  Pel resiLuma[NUMBER_OF_STORED_RESIDUAL_TYPES][MAX_CU_SIZE * MAX_CU_SIZE];
1482
1483  m_pcPredSearch->estIntraPredLumaQT( rpcTempCU, m_ppcOrigYuv[uiDepth], m_ppcPredYuvTemp[uiDepth], m_ppcResiYuvTemp[uiDepth], m_ppcRecoYuvTemp[uiDepth], resiLuma DEBUG_STRING_PASS_INTO(sTest) 
1484                                    );
1485
1486  m_ppcRecoYuvTemp[uiDepth]->copyToPicComponent(COMPONENT_Y, rpcTempCU->getPic()->getPicYuvRec(), rpcTempCU->getCtuRsAddr(), rpcTempCU->getZorderIdxInCtu() );
1487
1488  if (rpcBestCU->getPic()->getChromaFormat()!=CHROMA_400)
1489  {
1490    m_pcPredSearch->estIntraPredChromaQT( rpcTempCU, m_ppcOrigYuv[uiDepth], m_ppcPredYuvTemp[uiDepth], m_ppcResiYuvTemp[uiDepth], m_ppcRecoYuvTemp[uiDepth], resiLuma DEBUG_STRING_PASS_INTO(sTest) );
1491  }
1492 
1493
1494  m_pcEntropyCoder->resetBits();
1495
1496  if ( rpcTempCU->getSlice()->getPPS()->getTransquantBypassEnableFlag())
1497  {
1498    m_pcEntropyCoder->encodeCUTransquantBypassFlag( rpcTempCU, 0,          true );
1499  }
1500  m_pcEntropyCoder->encodeSkipFlag ( rpcTempCU, 0,          true );
1501    m_pcEntropyCoder->encodePredMode( rpcTempCU, 0,          true );
1502    m_pcEntropyCoder->encodePartSize( rpcTempCU, 0, uiDepth, true );
1503    m_pcEntropyCoder->encodePredInfo( rpcTempCU, 0 );
1504    m_pcEntropyCoder->encodeIPCMInfo(rpcTempCU, 0, true );
1505
1506    // Encode Coefficients
1507    Bool bCodeDQP = getdQPFlag();
1508    Bool codeChromaQpAdjFlag = getCodeChromaQpAdjFlag();
1509    m_pcEntropyCoder->encodeCoeff( rpcTempCU, 0, uiDepth, bCodeDQP, codeChromaQpAdjFlag );
1510    setCodeChromaQpAdjFlag( codeChromaQpAdjFlag );
1511    setdQPFlag( bCodeDQP );
1512  m_pcRDGoOnSbacCoder->store(m_pppcRDSbacCoder[uiDepth][CI_TEMP_BEST]);
1513
1514  rpcTempCU->getTotalBits() = m_pcEntropyCoder->getNumberOfWrittenBits();
1515  rpcTempCU->getTotalBins() = ((TEncBinCABAC *)((TEncSbac*)m_pcEntropyCoder->m_pcEntropyCoderIf)->getEncBinIf())->getBinsCoded();
1516    rpcTempCU->getTotalCost() = m_pcRdCost->calcRdCost( rpcTempCU->getTotalBits(), rpcTempCU->getTotalDistortion() );
1517
1518  xCheckDQP( rpcTempCU );
1519
1520  cost = rpcTempCU->getTotalCost();
1521
1522  xCheckBestMode(rpcBestCU, rpcTempCU, uiDepth DEBUG_STRING_PASS_INTO(sDebug) DEBUG_STRING_PASS_INTO(sTest));
1523
1524#if NH_MV
1525  D_DEC_INDENT( g_traceModeCheck ); 
1526#endif
1527}
1528
1529
1530/** Check R-D costs for a CU with PCM mode.
1531 * \param rpcBestCU pointer to best mode CU data structure
1532 * \param rpcTempCU pointer to testing mode CU data structure
1533 * \returns Void
1534 *
1535 * \note Current PCM implementation encodes sample values in a lossless way. The distortion of PCM mode CUs are zero. PCM mode is selected if the best mode yields bits greater than that of PCM mode.
1536 */
1537Void TEncCu::xCheckIntraPCM( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU )
1538{
1539  if(getFastDeltaQp())
1540  {
1541    const TComSPS &sps=*(rpcTempCU->getSlice()->getSPS());
1542    const UInt fastDeltaQPCuMaxPCMSize = Clip3((UInt)1<<sps.getPCMLog2MinSize(), (UInt)1<<sps.getPCMLog2MaxSize(), 32u);
1543    if (rpcTempCU->getWidth( 0 ) > fastDeltaQPCuMaxPCMSize)
1544    {
1545      return;   // only check necessary PCM in fast deltaqp mode
1546    }
1547  }
1548 
1549  UInt uiDepth = rpcTempCU->getDepth( 0 );
1550
1551  rpcTempCU->setSkipFlagSubParts( false, 0, uiDepth );
1552  rpcTempCU->setIPCMFlag(0, true);
1553  rpcTempCU->setIPCMFlagSubParts (true, 0, rpcTempCU->getDepth(0));
1554  rpcTempCU->setPartSizeSubParts( SIZE_2Nx2N, 0, uiDepth );
1555  rpcTempCU->setPredModeSubParts( MODE_INTRA, 0, uiDepth );
1556  rpcTempCU->setTrIdxSubParts ( 0, 0, uiDepth );
1557  rpcTempCU->setChromaQpAdjSubParts( rpcTempCU->getCUTransquantBypass(0) ? 0 : m_cuChromaQpOffsetIdxPlus1, 0, uiDepth );
1558
1559  m_pcPredSearch->IPCMSearch( rpcTempCU, m_ppcOrigYuv[uiDepth], m_ppcPredYuvTemp[uiDepth], m_ppcResiYuvTemp[uiDepth], m_ppcRecoYuvTemp[uiDepth]);
1560
1561  m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[uiDepth][CI_CURR_BEST]);
1562
1563  m_pcEntropyCoder->resetBits();
1564
1565  if ( rpcTempCU->getSlice()->getPPS()->getTransquantBypassEnableFlag())
1566  {
1567    m_pcEntropyCoder->encodeCUTransquantBypassFlag( rpcTempCU, 0,          true );
1568  }
1569
1570  m_pcEntropyCoder->encodeSkipFlag ( rpcTempCU, 0,          true );
1571  m_pcEntropyCoder->encodePredMode ( rpcTempCU, 0,          true );
1572  m_pcEntropyCoder->encodePartSize ( rpcTempCU, 0, uiDepth, true );
1573  m_pcEntropyCoder->encodeIPCMInfo ( rpcTempCU, 0, true );
1574  m_pcRDGoOnSbacCoder->store(m_pppcRDSbacCoder[uiDepth][CI_TEMP_BEST]);
1575
1576  rpcTempCU->getTotalBits() = m_pcEntropyCoder->getNumberOfWrittenBits();
1577  rpcTempCU->getTotalBins() = ((TEncBinCABAC *)((TEncSbac*)m_pcEntropyCoder->m_pcEntropyCoderIf)->getEncBinIf())->getBinsCoded();
1578    rpcTempCU->getTotalCost() = m_pcRdCost->calcRdCost( rpcTempCU->getTotalBits(), rpcTempCU->getTotalDistortion() );
1579
1580  xCheckDQP( rpcTempCU );
1581  DEBUG_STRING_NEW(a)
1582  DEBUG_STRING_NEW(b)
1583  xCheckBestMode(rpcBestCU, rpcTempCU, uiDepth DEBUG_STRING_PASS_INTO(a) DEBUG_STRING_PASS_INTO(b));
1584}
1585
1586/** check whether current try is the best with identifying the depth of current try
1587 * \param rpcBestCU
1588 * \param rpcTempCU
1589 * \param uiDepth
1590 */
1591Void TEncCu::xCheckBestMode( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, UInt uiDepth DEBUG_STRING_FN_DECLARE(sParent) DEBUG_STRING_FN_DECLARE(sTest) DEBUG_STRING_PASS_INTO(Bool bAddSizeInfo) )
1592{
1593  if( rpcTempCU->getTotalCost() < rpcBestCU->getTotalCost() )
1594  {
1595    TComYuv* pcYuv;
1596    // Change Information data
1597    TComDataCU* pcCU = rpcBestCU;
1598    rpcBestCU = rpcTempCU;
1599    rpcTempCU = pcCU;
1600
1601    // Change Prediction data
1602    pcYuv = m_ppcPredYuvBest[uiDepth];
1603    m_ppcPredYuvBest[uiDepth] = m_ppcPredYuvTemp[uiDepth];
1604    m_ppcPredYuvTemp[uiDepth] = pcYuv;
1605
1606    // Change Reconstruction data
1607    pcYuv = m_ppcRecoYuvBest[uiDepth];
1608    m_ppcRecoYuvBest[uiDepth] = m_ppcRecoYuvTemp[uiDepth];
1609    m_ppcRecoYuvTemp[uiDepth] = pcYuv;
1610
1611    pcYuv = NULL;
1612    pcCU  = NULL;
1613
1614    // store temp best CI for next CU coding
1615    m_pppcRDSbacCoder[uiDepth][CI_TEMP_BEST]->store(m_pppcRDSbacCoder[uiDepth][CI_NEXT_BEST]);
1616
1617
1618#if DEBUG_STRING
1619    DEBUG_STRING_SWAP(sParent, sTest)
1620    const PredMode predMode=rpcBestCU->getPredictionMode(0);
1621    if ((DebugOptionList::DebugString_Structure.getInt()&DebugStringGetPredModeMask(predMode)) && bAddSizeInfo)
1622    {
1623      std::stringstream ss(stringstream::out);
1624      ss <<"###: " << (predMode==MODE_INTRA?"Intra   ":"Inter   ") << partSizeToString[rpcBestCU->getPartitionSize(0)] << " CU at " << rpcBestCU->getCUPelX() << ", " << rpcBestCU->getCUPelY() << " width=" << UInt(rpcBestCU->getWidth(0)) << std::endl;
1625      sParent+=ss.str();
1626    }
1627#endif
1628  }
1629}
1630
1631Void TEncCu::xCheckDQP( TComDataCU* pcCU )
1632{
1633  UInt uiDepth = pcCU->getDepth( 0 );
1634
1635  const TComPPS &pps = *(pcCU->getSlice()->getPPS());
1636  if ( pps.getUseDQP() && uiDepth <= pps.getMaxCuDQPDepth() )
1637  {
1638    if ( pcCU->getQtRootCbf( 0) )
1639    {
1640      m_pcEntropyCoder->resetBits();
1641      m_pcEntropyCoder->encodeQP( pcCU, 0, false );
1642      pcCU->getTotalBits() += m_pcEntropyCoder->getNumberOfWrittenBits(); // dQP bits
1643      pcCU->getTotalBins() += ((TEncBinCABAC *)((TEncSbac*)m_pcEntropyCoder->m_pcEntropyCoderIf)->getEncBinIf())->getBinsCoded();
1644        pcCU->getTotalCost() = m_pcRdCost->calcRdCost( pcCU->getTotalBits(), pcCU->getTotalDistortion() );
1645    }
1646    else
1647    {
1648      pcCU->setQPSubParts( pcCU->getRefQP( 0 ), 0, uiDepth ); // set QP to default QP
1649    }
1650  }
1651}
1652
1653Void TEncCu::xCopyAMVPInfo (AMVPInfo* pSrc, AMVPInfo* pDst)
1654{
1655  pDst->iN = pSrc->iN;
1656  for (Int i = 0; i < pSrc->iN; i++)
1657  {
1658    pDst->m_acMvCand[i] = pSrc->m_acMvCand[i];
1659  }
1660}
1661Void TEncCu::xCopyYuv2Pic(TComPic* rpcPic, UInt uiCUAddr, UInt uiAbsPartIdx, UInt uiDepth, UInt uiSrcDepth )
1662{
1663  UInt uiAbsPartIdxInRaster = g_auiZscanToRaster[uiAbsPartIdx];
1664  UInt uiSrcBlkWidth = rpcPic->getNumPartInCtuWidth() >> (uiSrcDepth);
1665  UInt uiBlkWidth    = rpcPic->getNumPartInCtuWidth() >> (uiDepth);
1666  UInt uiPartIdxX = ( ( uiAbsPartIdxInRaster % rpcPic->getNumPartInCtuWidth() ) % uiSrcBlkWidth) / uiBlkWidth;
1667  UInt uiPartIdxY = ( ( uiAbsPartIdxInRaster / rpcPic->getNumPartInCtuWidth() ) % uiSrcBlkWidth) / uiBlkWidth;
1668  UInt uiPartIdx = uiPartIdxY * ( uiSrcBlkWidth / uiBlkWidth ) + uiPartIdxX;
1669  m_ppcRecoYuvBest[uiSrcDepth]->copyToPicYuv( rpcPic->getPicYuvRec (), uiCUAddr, uiAbsPartIdx, uiDepth - uiSrcDepth, uiPartIdx);
1670
1671#if ENC_DEC_TRACE && NH_MV_ENC_DEC_TRAC
1672  Bool oldtraceCopyBack = g_traceCopyBack;
1673  g_traceCopyBack = false; 
1674#endif
1675  m_ppcPredYuvBest[uiSrcDepth]->copyToPicYuv( rpcPic->getPicYuvPred (), uiCUAddr, uiAbsPartIdx, uiDepth - uiSrcDepth, uiPartIdx);
1676
1677#if ENC_DEC_TRACE && NH_MV_ENC_DEC_TRAC
1678  g_traceCopyBack = oldtraceCopyBack; 
1679#endif
1680}
1681
1682Void TEncCu::xCopyYuv2Tmp( UInt uiPartUnitIdx, UInt uiNextDepth )
1683{
1684  UInt uiCurrDepth = uiNextDepth - 1;
1685  m_ppcRecoYuvBest[uiNextDepth]->copyToPartYuv( m_ppcRecoYuvTemp[uiCurrDepth], uiPartUnitIdx );
1686  m_ppcPredYuvBest[uiNextDepth]->copyToPartYuv( m_ppcPredYuvBest[uiCurrDepth], uiPartUnitIdx);
1687}
1688
1689/** Function for filling the PCM buffer of a CU using its original sample array
1690 * \param pCU pointer to current CU
1691 * \param pOrgYuv pointer to original sample array
1692 */
1693Void TEncCu::xFillPCMBuffer     ( TComDataCU* pCU, TComYuv* pOrgYuv )
1694{
1695  const ChromaFormat format = pCU->getPic()->getChromaFormat();
1696  const UInt numberValidComponents = getNumberValidComponents(format);
1697  for (UInt componentIndex = 0; componentIndex < numberValidComponents; componentIndex++)
1698  {
1699    const ComponentID component = ComponentID(componentIndex);
1700
1701    const UInt width  = pCU->getWidth(0)  >> getComponentScaleX(component, format);
1702    const UInt height = pCU->getHeight(0) >> getComponentScaleY(component, format);
1703
1704    Pel *source      = pOrgYuv->getAddr(component, 0, width);
1705    Pel *destination = pCU->getPCMSample(component);
1706
1707    const UInt sourceStride = pOrgYuv->getStride(component);
1708
1709    for (Int line = 0; line < height; line++)
1710    {
1711      for (Int column = 0; column < width; column++)
1712      {
1713        destination[column] = source[column];
1714      }
1715
1716      source      += sourceStride;
1717      destination += width;
1718    }
1719  }
1720}
1721
1722#if ADAPTIVE_QP_SELECTION
1723/** Collect ARL statistics from one block
1724  */
1725Int TEncCu::xTuCollectARLStats(TCoeff* rpcCoeff, TCoeff* rpcArlCoeff, Int NumCoeffInCU, Double* cSum, UInt* numSamples )
1726{
1727  for( Int n = 0; n < NumCoeffInCU; n++ )
1728  {
1729    TCoeff u = abs( rpcCoeff[ n ] );
1730    TCoeff absc = rpcArlCoeff[ n ];
1731
1732    if( u != 0 )
1733    {
1734      if( u < LEVEL_RANGE )
1735      {
1736        cSum[ u ] += ( Double )absc;
1737        numSamples[ u ]++;
1738      }
1739      else
1740      {
1741        cSum[ LEVEL_RANGE ] += ( Double )absc - ( Double )( u << ARL_C_PRECISION );
1742        numSamples[ LEVEL_RANGE ]++;
1743      }
1744    }
1745  }
1746
1747  return 0;
1748}
1749
1750//! Collect ARL statistics from one CTU
1751Void TEncCu::xCtuCollectARLStats(TComDataCU* pCtu )
1752{
1753  Double cSum[ LEVEL_RANGE + 1 ];     //: the sum of DCT coefficients corresponding to data type and quantization output
1754  UInt numSamples[ LEVEL_RANGE + 1 ]; //: the number of coefficients corresponding to data type and quantization output
1755
1756  TCoeff* pCoeffY = pCtu->getCoeff(COMPONENT_Y);
1757  TCoeff* pArlCoeffY = pCtu->getArlCoeff(COMPONENT_Y);
1758  const TComSPS &sps = *(pCtu->getSlice()->getSPS());
1759
1760  const UInt uiMinCUWidth = sps.getMaxCUWidth() >> sps.getMaxTotalCUDepth(); // NOTE: ed - this is not the minimum CU width. It is the square-root of the number of coefficients per part.
1761  const UInt uiMinNumCoeffInCU = 1 << uiMinCUWidth;                          // NOTE: ed - what is this?
1762
1763  memset( cSum, 0, sizeof( Double )*(LEVEL_RANGE+1) );
1764  memset( numSamples, 0, sizeof( UInt )*(LEVEL_RANGE+1) );
1765
1766  // Collect stats to cSum[][] and numSamples[][]
1767  for(Int i = 0; i < pCtu->getTotalNumPart(); i ++ )
1768  {
1769    UInt uiTrIdx = pCtu->getTransformIdx(i);
1770
1771    if(pCtu->isInter(i) && pCtu->getCbf( i, COMPONENT_Y, uiTrIdx ) )
1772    {
1773      xTuCollectARLStats(pCoeffY, pArlCoeffY, uiMinNumCoeffInCU, cSum, numSamples);
1774    }//Note that only InterY is processed. QP rounding is based on InterY data only.
1775
1776    pCoeffY  += uiMinNumCoeffInCU;
1777    pArlCoeffY  += uiMinNumCoeffInCU;
1778  }
1779
1780  for(Int u=1; u<LEVEL_RANGE;u++)
1781  {
1782    m_pcTrQuant->getSliceSumC()[u] += cSum[ u ] ;
1783    m_pcTrQuant->getSliceNSamples()[u] += numSamples[ u ] ;
1784  }
1785  m_pcTrQuant->getSliceSumC()[LEVEL_RANGE] += cSum[ LEVEL_RANGE ] ;
1786  m_pcTrQuant->getSliceNSamples()[LEVEL_RANGE] += numSamples[ LEVEL_RANGE ] ;
1787}
1788#endif
1789
1790//! \}
Note: See TracBrowser for help on using the repository browser.