source: 3DVCSoftware/branches/HTM-15.1-MV-draft-4/source/Lib/TLibEncoder/TEncCu.cpp @ 1389

Last change on this file since 1389 was 1325, checked in by tech, 10 years ago

Removed 3D-HEVC.

  • 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
371  // get Original YUV data from picture
372  m_ppcOrigYuv[uiDepth]->copyFromPicYuv( pcPic->getPicYuvOrg(), rpcBestCU->getCtuRsAddr(), rpcBestCU->getZorderIdxInCtu() );
373
374  // variable for Cbf fast mode PU decision
375  Bool    doNotBlockPu = true;
376  Bool    earlyDetectionSkipMode = false;
377
378  const UInt uiLPelX   = rpcBestCU->getCUPelX();
379  const UInt uiRPelX   = uiLPelX + rpcBestCU->getWidth(0)  - 1;
380  const UInt uiTPelY   = rpcBestCU->getCUPelY();
381  const UInt uiBPelY   = uiTPelY + rpcBestCU->getHeight(0) - 1;
382  const UInt uiWidth   = rpcBestCU->getWidth(0);
383
384#if H_MV_ENC_DEC_TRAC
385#if ENC_DEC_TRACE
386    stopAtPos  ( rpcBestCU->getSlice()->getPOC(), 
387                 rpcBestCU->getSlice()->getLayerId(), 
388                 rpcBestCU->getCUPelX(),
389                 rpcBestCU->getCUPelY(),
390                 rpcBestCU->getWidth(0), 
391                 rpcBestCU->getHeight(0) );
392#endif
393#endif
394
395  Int iBaseQP = xComputeQP( rpcBestCU, uiDepth );
396  Int iMinQP;
397  Int iMaxQP;
398  Bool isAddLowestQP = false;
399
400  const UInt numberValidComponents = rpcBestCU->getPic()->getNumberValidComponents();
401
402  if( uiDepth <= pps.getMaxCuDQPDepth() )
403  {
404    Int idQP = m_pcEncCfg->getMaxDeltaQP();
405    iMinQP = Clip3( -sps.getQpBDOffset(CHANNEL_TYPE_LUMA), MAX_QP, iBaseQP-idQP );
406    iMaxQP = Clip3( -sps.getQpBDOffset(CHANNEL_TYPE_LUMA), MAX_QP, iBaseQP+idQP );
407  }
408  else
409  {
410    iMinQP = rpcTempCU->getQP(0);
411    iMaxQP = rpcTempCU->getQP(0);
412  }
413
414  if ( m_pcEncCfg->getUseRateCtrl() )
415  {
416    iMinQP = m_pcRateCtrl->getRCQP();
417    iMaxQP = m_pcRateCtrl->getRCQP();
418  }
419
420  // transquant-bypass (TQB) processing loop variable initialisation ---
421
422  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.
423
424  if ( (pps.getTransquantBypassEnableFlag()) )
425  {
426    isAddLowestQP = true; // mark that the first iteration is to cost TQB mode.
427    iMinQP = iMinQP - 1;  // increase loop variable range by 1, to allow testing of TQB mode along with other QPs
428    if ( m_pcEncCfg->getCUTransquantBypassFlagForceValue() )
429    {
430      iMaxQP = iMinQP;
431    }
432  }
433
434
435  TComSlice * pcSlice = rpcTempCU->getPic()->getSlice(rpcTempCU->getPic()->getCurrSliceIdx());
436
437  const Bool bBoundary = !( uiRPelX < sps.getPicWidthInLumaSamples() && uiBPelY < sps.getPicHeightInLumaSamples() );
438  if ( !bBoundary )
439  {
440    for (Int iQP=iMinQP; iQP<=iMaxQP; iQP++)
441    {
442      const Bool bIsLosslessMode = isAddLowestQP && (iQP == iMinQP);
443
444      if (bIsLosslessMode)
445      {
446        iQP = lowestQP;
447      }
448
449
450      m_cuChromaQpOffsetIdxPlus1 = 0;
451      if (pcSlice->getUseChromaQpAdj())
452      {
453        /* Pre-estimation of chroma QP based on input block activity may be performed
454         * here, using for example m_ppcOrigYuv[uiDepth] */
455        /* To exercise the current code, the index used for adjustment is based on
456         * block position
457         */
458        Int lgMinCuSize = sps.getLog2MinCodingBlockSize() +
459                          std::max<Int>(0, sps.getLog2DiffMaxMinCodingBlockSize()-Int(pps.getPpsRangeExtension().getDiffCuChromaQpOffsetDepth()));
460        m_cuChromaQpOffsetIdxPlus1 = ((uiLPelX >> lgMinCuSize) + (uiTPelY >> lgMinCuSize)) % (pps.getPpsRangeExtension().getChromaQpOffsetListLen() + 1);
461      }
462
463      rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
464
465      // do inter modes, SKIP and 2Nx2N
466      if( rpcBestCU->getSlice()->getSliceType() != I_SLICE )
467      {
468        // 2Nx2N
469        if(m_pcEncCfg->getUseEarlySkipDetection())
470        {
471          xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2Nx2N DEBUG_STRING_PASS_INTO(sDebug) );
472          rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );//by Competition for inter_2Nx2N
473        }
474        // SKIP
475        xCheckRDCostMerge2Nx2N( rpcBestCU, rpcTempCU DEBUG_STRING_PASS_INTO(sDebug), &earlyDetectionSkipMode );//by Merge for inter_2Nx2N
476
477        rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
478
479        if(!m_pcEncCfg->getUseEarlySkipDetection())
480        {
481          // 2Nx2N, NxN
482
483          xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2Nx2N DEBUG_STRING_PASS_INTO(sDebug) );
484          rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
485
486          if(m_pcEncCfg->getUseCbfFastMode())
487          {
488            doNotBlockPu = rpcBestCU->getQtRootCbf( 0 ) != 0;
489          }
490        }
491      }
492
493      if (bIsLosslessMode) // Restore loop variable if lossless mode was searched.
494      {
495        iQP = iMinQP;
496      }
497    }
498
499    if(!earlyDetectionSkipMode)
500    {
501      for (Int iQP=iMinQP; iQP<=iMaxQP; iQP++)
502      {
503        const Bool bIsLosslessMode = isAddLowestQP && (iQP == iMinQP); // If lossless, then iQP is irrelevant for subsequent modules.
504
505        if (bIsLosslessMode)
506        {
507          iQP = lowestQP;
508        }
509
510        rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
511
512        // do inter modes, NxN, 2NxN, and Nx2N
513        if( rpcBestCU->getSlice()->getSliceType() != I_SLICE )
514        {
515          // 2Nx2N, NxN
516
517          if(!( (rpcBestCU->getWidth(0)==8) && (rpcBestCU->getHeight(0)==8) ))
518          {
519            if( uiDepth == sps.getLog2DiffMaxMinCodingBlockSize() && doNotBlockPu
520)
521            {
522
523              xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_NxN DEBUG_STRING_PASS_INTO(sDebug)   );
524              rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
525
526            }
527          }
528
529          if(doNotBlockPu
530)
531          {
532            xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_Nx2N DEBUG_STRING_PASS_INTO(sDebug)  );
533            rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
534
535            if(m_pcEncCfg->getUseCbfFastMode() && rpcBestCU->getPartitionSize(0) == SIZE_Nx2N )
536            {
537              doNotBlockPu = rpcBestCU->getQtRootCbf( 0 ) != 0;
538            }
539          }
540          if(doNotBlockPu
541)
542          {
543
544            xCheckRDCostInter      ( rpcBestCU, rpcTempCU, SIZE_2NxN DEBUG_STRING_PASS_INTO(sDebug)  );
545
546            rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
547
548            if(m_pcEncCfg->getUseCbfFastMode() && rpcBestCU->getPartitionSize(0) == SIZE_2NxN)
549            {
550              doNotBlockPu = rpcBestCU->getQtRootCbf( 0 ) != 0;
551            }
552          }
553
554          //! Try AMP (SIZE_2NxnU, SIZE_2NxnD, SIZE_nLx2N, SIZE_nRx2N)
555          if(sps.getUseAMP() && uiDepth < sps.getLog2DiffMaxMinCodingBlockSize() )
556          {
557#if AMP_ENC_SPEEDUP
558            Bool bTestAMP_Hor = false, bTestAMP_Ver = false;
559
560#if AMP_MRG
561            Bool bTestMergeAMP_Hor = false, bTestMergeAMP_Ver = false;
562
563            deriveTestModeAMP (rpcBestCU, eParentPartSize, bTestAMP_Hor, bTestAMP_Ver, bTestMergeAMP_Hor, bTestMergeAMP_Ver);
564#else
565            deriveTestModeAMP (rpcBestCU, eParentPartSize, bTestAMP_Hor, bTestAMP_Ver);
566#endif
567
568            //! Do horizontal AMP
569            if ( bTestAMP_Hor )
570            {
571              if(doNotBlockPu
572)
573              {
574                xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2NxnU DEBUG_STRING_PASS_INTO(sDebug) );
575                rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
576                if(m_pcEncCfg->getUseCbfFastMode() && rpcBestCU->getPartitionSize(0) == SIZE_2NxnU )
577                {
578                  doNotBlockPu = rpcBestCU->getQtRootCbf( 0 ) != 0;
579                }
580              }
581              if(doNotBlockPu
582)
583              {
584                xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2NxnD DEBUG_STRING_PASS_INTO(sDebug) );
585
586                rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
587
588                if(m_pcEncCfg->getUseCbfFastMode() && rpcBestCU->getPartitionSize(0) == SIZE_2NxnD )
589                {
590                  doNotBlockPu = rpcBestCU->getQtRootCbf( 0 ) != 0;
591                }
592              }
593            }
594#if AMP_MRG
595            else if ( bTestMergeAMP_Hor )
596            {
597              if(doNotBlockPu
598)
599              {
600
601                xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2NxnU DEBUG_STRING_PASS_INTO(sDebug), true );
602
603                rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
604                if(m_pcEncCfg->getUseCbfFastMode() && rpcBestCU->getPartitionSize(0) == SIZE_2NxnU )
605                {
606                  doNotBlockPu = rpcBestCU->getQtRootCbf( 0 ) != 0;
607                }
608              }
609              if(doNotBlockPu
610)
611              {
612                xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2NxnD DEBUG_STRING_PASS_INTO(sDebug), true );
613                rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
614
615                if(m_pcEncCfg->getUseCbfFastMode() && rpcBestCU->getPartitionSize(0) == SIZE_2NxnD )
616                {
617                  doNotBlockPu = rpcBestCU->getQtRootCbf( 0 ) != 0;
618                }
619              }
620            }
621#endif
622
623            //! Do horizontal AMP
624            if ( bTestAMP_Ver )
625            {
626              if(doNotBlockPu
627)
628              {
629                xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_nLx2N DEBUG_STRING_PASS_INTO(sDebug) );
630
631                rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
632                if(m_pcEncCfg->getUseCbfFastMode() && rpcBestCU->getPartitionSize(0) == SIZE_nLx2N )
633                {
634                  doNotBlockPu = rpcBestCU->getQtRootCbf( 0 ) != 0;
635                }
636              }
637              if(doNotBlockPu
638)
639              {
640                xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_nRx2N DEBUG_STRING_PASS_INTO(sDebug) );
641                rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
642              }
643            }
644#if AMP_MRG
645            else if ( bTestMergeAMP_Ver )
646            {
647              if(doNotBlockPu
648)
649              {
650                xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_nLx2N DEBUG_STRING_PASS_INTO(sDebug), true );
651                rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
652                if(m_pcEncCfg->getUseCbfFastMode() && rpcBestCU->getPartitionSize(0) == SIZE_nLx2N )
653                {
654                  doNotBlockPu = rpcBestCU->getQtRootCbf( 0 ) != 0;
655                }
656              }
657              if(doNotBlockPu
658)
659              {
660
661                xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_nRx2N DEBUG_STRING_PASS_INTO(sDebug), true );
662                rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
663
664              }
665            }
666#endif
667
668#else
669
670            xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2NxnU );
671            rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
672            xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2NxnD );
673            rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
674            xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_nLx2N );
675            rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
676            xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_nRx2N );
677            rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
678
679
680#endif
681          }
682        }
683
684        // do normal intra modes
685        // speedup for inter frames
686        Double intraCost = 0.0;
687
688        if((rpcBestCU->getSlice()->getSliceType() == I_SLICE)                                     ||
689           ((!m_pcEncCfg->getDisableIntraPUsInInterSlices()) && (
690           (rpcBestCU->getCbf( 0, COMPONENT_Y  ) != 0)                                            ||
691          ((rpcBestCU->getCbf( 0, COMPONENT_Cb ) != 0) && (numberValidComponents > COMPONENT_Cb)) ||
692          ((rpcBestCU->getCbf( 0, COMPONENT_Cr ) != 0) && (numberValidComponents > COMPONENT_Cr))   // avoid very complex intra if it is unlikely
693            )))
694        {
695          xCheckRDCostIntra( rpcBestCU, rpcTempCU, intraCost, SIZE_2Nx2N DEBUG_STRING_PASS_INTO(sDebug) );
696
697          rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
698          if( uiDepth == sps.getLog2DiffMaxMinCodingBlockSize() )
699          {
700            if( rpcTempCU->getWidth(0) > ( 1 << sps.getQuadtreeTULog2MinSize() ) )
701            {
702              Double tmpIntraCost;
703              xCheckRDCostIntra( rpcBestCU, rpcTempCU, tmpIntraCost, SIZE_NxN DEBUG_STRING_PASS_INTO(sDebug)   );
704
705              intraCost = std::min(intraCost, tmpIntraCost);
706              rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
707            }
708          }
709        }
710
711        // test PCM
712        if(sps.getUsePCM()
713          && rpcTempCU->getWidth(0) <= (1<<sps.getPCMLog2MaxSize())
714          && rpcTempCU->getWidth(0) >= (1<<sps.getPCMLog2MinSize()) )
715        {
716          UInt uiRawBits = getTotalBits(rpcBestCU->getWidth(0), rpcBestCU->getHeight(0), rpcBestCU->getPic()->getChromaFormat(), sps.getBitDepths().recon);
717          UInt uiBestBits = rpcBestCU->getTotalBits();
718          if((uiBestBits > uiRawBits) || (rpcBestCU->getTotalCost() > m_pcRdCost->calcRdCost(uiRawBits, 0)))
719
720          {
721            xCheckIntraPCM (rpcBestCU, rpcTempCU);
722            rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
723          }
724        }
725        if (bIsLosslessMode) // Restore loop variable if lossless mode was searched.
726        {
727          iQP = iMinQP;
728        }
729      }
730    }
731
732    if( rpcBestCU->getTotalCost()!=MAX_DOUBLE )
733    {
734      m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[uiDepth][CI_NEXT_BEST]);
735      m_pcEntropyCoder->resetBits();
736      m_pcEntropyCoder->encodeSplitFlag( rpcBestCU, 0, uiDepth, true );
737      rpcBestCU->getTotalBits() += m_pcEntropyCoder->getNumberOfWrittenBits(); // split bits
738      rpcBestCU->getTotalBins() += ((TEncBinCABAC *)((TEncSbac*)m_pcEntropyCoder->m_pcEntropyCoderIf)->getEncBinIf())->getBinsCoded();
739      rpcBestCU->getTotalCost()  = m_pcRdCost->calcRdCost( rpcBestCU->getTotalBits(), rpcBestCU->getTotalDistortion() );
740      m_pcRDGoOnSbacCoder->store(m_pppcRDSbacCoder[uiDepth][CI_NEXT_BEST]);
741    }
742  }
743
744  // copy original YUV samples to PCM buffer
745  if( rpcBestCU->getTotalCost()!=MAX_DOUBLE && rpcBestCU->isLosslessCoded(0) && (rpcBestCU->getIPCMFlag(0) == false))
746  {
747    xFillPCMBuffer(rpcBestCU, m_ppcOrigYuv[uiDepth]);
748  }
749
750  if( uiDepth == pps.getMaxCuDQPDepth() )
751  {
752    Int idQP = m_pcEncCfg->getMaxDeltaQP();
753    iMinQP = Clip3( -sps.getQpBDOffset(CHANNEL_TYPE_LUMA), MAX_QP, iBaseQP-idQP );
754    iMaxQP = Clip3( -sps.getQpBDOffset(CHANNEL_TYPE_LUMA), MAX_QP, iBaseQP+idQP );
755  }
756  else if( uiDepth < pps.getMaxCuDQPDepth() )
757  {
758    iMinQP = iBaseQP;
759    iMaxQP = iBaseQP;
760  }
761  else
762  {
763    const Int iStartQP = rpcTempCU->getQP(0);
764    iMinQP = iStartQP;
765    iMaxQP = iStartQP;
766  }
767
768  if ( m_pcEncCfg->getUseRateCtrl() )
769  {
770    iMinQP = m_pcRateCtrl->getRCQP();
771    iMaxQP = m_pcRateCtrl->getRCQP();
772  }
773
774  if ( m_pcEncCfg->getCUTransquantBypassFlagForceValue() )
775  {
776    iMaxQP = iMinQP; // If all TUs are forced into using transquant bypass, do not loop here.
777  }
778  const Bool bSubBranch = bBoundary || !( m_pcEncCfg->getUseEarlyCU() && rpcBestCU->getTotalCost()!=MAX_DOUBLE && rpcBestCU->isSkipped(0) );
779  if( bSubBranch && uiDepth < sps.getLog2DiffMaxMinCodingBlockSize() && (!getFastDeltaQp() || uiWidth > fastDeltaQPCuMaxSize || bBoundary))
780  {
781    // further split
782    for (Int iQP=iMinQP; iQP<=iMaxQP; iQP++)
783    {
784      const Bool bIsLosslessMode = false; // False at this level. Next level down may set it to true.
785
786      rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
787
788      UChar       uhNextDepth         = uiDepth+1;
789      TComDataCU* pcSubBestPartCU     = m_ppcBestCU[uhNextDepth];
790      TComDataCU* pcSubTempPartCU     = m_ppcTempCU[uhNextDepth];
791      DEBUG_STRING_NEW(sTempDebug)
792
793      for ( UInt uiPartUnitIdx = 0; uiPartUnitIdx < 4; uiPartUnitIdx++ )
794      {
795        pcSubBestPartCU->initSubCU( rpcTempCU, uiPartUnitIdx, uhNextDepth, iQP );           // clear sub partition datas or init.
796        pcSubTempPartCU->initSubCU( rpcTempCU, uiPartUnitIdx, uhNextDepth, iQP );           // clear sub partition datas or init.
797
798        if( ( pcSubBestPartCU->getCUPelX() < sps.getPicWidthInLumaSamples() ) && ( pcSubBestPartCU->getCUPelY() < sps.getPicHeightInLumaSamples() ) )
799        {
800          if ( 0 == uiPartUnitIdx) //initialize RD with previous depth buffer
801          {
802            m_pppcRDSbacCoder[uhNextDepth][CI_CURR_BEST]->load(m_pppcRDSbacCoder[uiDepth][CI_CURR_BEST]);
803          }
804          else
805          {
806            m_pppcRDSbacCoder[uhNextDepth][CI_CURR_BEST]->load(m_pppcRDSbacCoder[uhNextDepth][CI_NEXT_BEST]);
807          }
808
809#if AMP_ENC_SPEEDUP
810          DEBUG_STRING_NEW(sChild)
811          if ( !(rpcBestCU->getTotalCost()!=MAX_DOUBLE && rpcBestCU->isInter(0)) )
812          {
813            xCompressCU( pcSubBestPartCU, pcSubTempPartCU, uhNextDepth DEBUG_STRING_PASS_INTO(sChild), NUMBER_OF_PART_SIZES );
814          }
815          else
816          {
817
818            xCompressCU( pcSubBestPartCU, pcSubTempPartCU, uhNextDepth DEBUG_STRING_PASS_INTO(sChild), rpcBestCU->getPartitionSize(0) );
819          }
820          DEBUG_STRING_APPEND(sTempDebug, sChild)
821#else
822          xCompressCU( pcSubBestPartCU, pcSubTempPartCU, uhNextDepth );
823#endif
824
825          rpcTempCU->copyPartFrom( pcSubBestPartCU, uiPartUnitIdx, uhNextDepth );         // Keep best part data to current temporary data.
826          xCopyYuv2Tmp( pcSubBestPartCU->getTotalNumPart()*uiPartUnitIdx, uhNextDepth );
827        }
828        else
829        {
830          pcSubBestPartCU->copyToPic( uhNextDepth );
831          rpcTempCU->copyPartFrom( pcSubBestPartCU, uiPartUnitIdx, uhNextDepth );
832        }
833      }
834
835      m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[uhNextDepth][CI_NEXT_BEST]);
836      if( !bBoundary )
837      {
838        m_pcEntropyCoder->resetBits();
839        m_pcEntropyCoder->encodeSplitFlag( rpcTempCU, 0, uiDepth, true );
840
841        rpcTempCU->getTotalBits() += m_pcEntropyCoder->getNumberOfWrittenBits(); // split bits
842        rpcTempCU->getTotalBins() += ((TEncBinCABAC *)((TEncSbac*)m_pcEntropyCoder->m_pcEntropyCoderIf)->getEncBinIf())->getBinsCoded();
843      }
844        rpcTempCU->getTotalCost()  = m_pcRdCost->calcRdCost( rpcTempCU->getTotalBits(), rpcTempCU->getTotalDistortion() );
845
846      if( uiDepth == pps.getMaxCuDQPDepth() && pps.getUseDQP())
847      {
848        Bool hasResidual = false;
849        for( UInt uiBlkIdx = 0; uiBlkIdx < rpcTempCU->getTotalNumPart(); uiBlkIdx ++)
850        {
851          if( (     rpcTempCU->getCbf(uiBlkIdx, COMPONENT_Y)
852                || (rpcTempCU->getCbf(uiBlkIdx, COMPONENT_Cb) && (numberValidComponents > COMPONENT_Cb))
853                || (rpcTempCU->getCbf(uiBlkIdx, COMPONENT_Cr) && (numberValidComponents > COMPONENT_Cr)) ) )
854          {
855            hasResidual = true;
856            break;
857          }
858        }
859
860        if ( hasResidual )
861        {
862          m_pcEntropyCoder->resetBits();
863          m_pcEntropyCoder->encodeQP( rpcTempCU, 0, false );
864          rpcTempCU->getTotalBits() += m_pcEntropyCoder->getNumberOfWrittenBits(); // dQP bits
865          rpcTempCU->getTotalBins() += ((TEncBinCABAC *)((TEncSbac*)m_pcEntropyCoder->m_pcEntropyCoderIf)->getEncBinIf())->getBinsCoded();
866            rpcTempCU->getTotalCost()  = m_pcRdCost->calcRdCost( rpcTempCU->getTotalBits(), rpcTempCU->getTotalDistortion() );
867
868          Bool foundNonZeroCbf = false;
869          rpcTempCU->setQPSubCUs( rpcTempCU->getRefQP( 0 ), 0, uiDepth, foundNonZeroCbf );
870          assert( foundNonZeroCbf );
871        }
872        else
873        {
874          rpcTempCU->setQPSubParts( rpcTempCU->getRefQP( 0 ), 0, uiDepth ); // set QP to default QP
875        }
876      }
877
878      m_pcRDGoOnSbacCoder->store(m_pppcRDSbacCoder[uiDepth][CI_TEMP_BEST]);
879
880      // If the configuration being tested exceeds the maximum number of bytes for a slice / slice-segment, then
881      // a proper RD evaluation cannot be performed. Therefore, termination of the
882      // slice/slice-segment must be made prior to this CTU.
883      // This can be achieved by forcing the decision to be that of the rpcTempCU.
884      // The exception is each slice / slice-segment must have at least one CTU.
885      if (rpcBestCU->getTotalCost()!=MAX_DOUBLE)
886      {
887        const Bool isEndOfSlice        =    pcSlice->getSliceMode()==FIXED_NUMBER_OF_BYTES
888                                         && ((pcSlice->getSliceBits()+rpcBestCU->getTotalBits())>pcSlice->getSliceArgument()<<3)
889                                         && rpcBestCU->getCtuRsAddr() != pcPic->getPicSym()->getCtuTsToRsAddrMap(pcSlice->getSliceCurStartCtuTsAddr())
890                                         && rpcBestCU->getCtuRsAddr() != pcPic->getPicSym()->getCtuTsToRsAddrMap(pcSlice->getSliceSegmentCurStartCtuTsAddr());
891        const Bool isEndOfSliceSegment =    pcSlice->getSliceSegmentMode()==FIXED_NUMBER_OF_BYTES
892                                         && ((pcSlice->getSliceSegmentBits()+rpcBestCU->getTotalBits()) > pcSlice->getSliceSegmentArgument()<<3)
893                                         && rpcBestCU->getCtuRsAddr() != pcPic->getPicSym()->getCtuTsToRsAddrMap(pcSlice->getSliceSegmentCurStartCtuTsAddr());
894                                             // Do not need to check slice condition for slice-segment since a slice-segment is a subset of a slice.
895        if(isEndOfSlice||isEndOfSliceSegment)
896        {
897          rpcBestCU->getTotalCost()=MAX_DOUBLE;
898        }
899      }
900
901      xCheckBestMode( rpcBestCU, rpcTempCU, uiDepth DEBUG_STRING_PASS_INTO(sDebug) DEBUG_STRING_PASS_INTO(sTempDebug) DEBUG_STRING_PASS_INTO(false) ); // RD compare current larger prediction
902                                                                                                                                                       // with sub partitioned prediction.
903    }
904  }
905
906  DEBUG_STRING_APPEND(sDebug_, sDebug);
907
908  rpcBestCU->copyToPic(uiDepth);                                                     // Copy Best data to Picture for next partition prediction.
909
910  xCopyYuv2Pic( rpcBestCU->getPic(), rpcBestCU->getCtuRsAddr(), rpcBestCU->getZorderIdxInCtu(), uiDepth, uiDepth );   // Copy Yuv data to picture Yuv
911  if (bBoundary)
912  {
913    return;
914  }
915
916  // Assert if Best prediction mode is NONE
917  // Selected mode's RD-cost must be not MAX_DOUBLE.
918  assert( rpcBestCU->getPartitionSize ( 0 ) != NUMBER_OF_PART_SIZES       );
919  assert( rpcBestCU->getPredictionMode( 0 ) != NUMBER_OF_PREDICTION_MODES );
920  assert( rpcBestCU->getTotalCost     (   ) != MAX_DOUBLE                 );
921}
922
923/** finish encoding a cu and handle end-of-slice conditions
924 * \param pcCU
925 * \param uiAbsPartIdx
926 * \param uiDepth
927 * \returns Void
928 */
929Void TEncCu::finishCU( TComDataCU* pcCU, UInt uiAbsPartIdx )
930{
931  TComPic* pcPic = pcCU->getPic();
932  TComSlice * pcSlice = pcCU->getPic()->getSlice(pcCU->getPic()->getCurrSliceIdx());
933
934  //Calculate end address
935  const Int  currentCTUTsAddr = pcPic->getPicSym()->getCtuRsToTsAddrMap(pcCU->getCtuRsAddr());
936  const Bool isLastSubCUOfCtu = pcCU->isLastSubCUOfCtu(uiAbsPartIdx);
937  if ( isLastSubCUOfCtu )
938  {
939    // The 1-terminating bit is added to all streams, so don't add it here when it's 1.
940    // i.e. when the slice segment CurEnd CTU address is the current CTU address+1.
941    if (pcSlice->getSliceSegmentCurEndCtuTsAddr() != currentCTUTsAddr+1)
942    {
943      m_pcEntropyCoder->encodeTerminatingBit( 0 );
944    }
945  }
946}
947
948/** Compute QP for each CU
949 * \param pcCU Target CU
950 * \param uiDepth CU depth
951 * \returns quantization parameter
952 */
953Int TEncCu::xComputeQP( TComDataCU* pcCU, UInt uiDepth )
954{
955  Int iBaseQp = pcCU->getSlice()->getSliceQp();
956  Int iQpOffset = 0;
957  if ( m_pcEncCfg->getUseAdaptiveQP() )
958  {
959    TEncPic* pcEPic = dynamic_cast<TEncPic*>( pcCU->getPic() );
960    UInt uiAQDepth = min( uiDepth, pcEPic->getMaxAQDepth()-1 );
961    TEncPicQPAdaptationLayer* pcAQLayer = pcEPic->getAQLayer( uiAQDepth );
962    UInt uiAQUPosX = pcCU->getCUPelX() / pcAQLayer->getAQPartWidth();
963    UInt uiAQUPosY = pcCU->getCUPelY() / pcAQLayer->getAQPartHeight();
964    UInt uiAQUStride = pcAQLayer->getAQPartStride();
965    TEncQPAdaptationUnit* acAQU = pcAQLayer->getQPAdaptationUnit();
966
967    Double dMaxQScale = pow(2.0, m_pcEncCfg->getQPAdaptationRange()/6.0);
968    Double dAvgAct = pcAQLayer->getAvgActivity();
969    Double dCUAct = acAQU[uiAQUPosY * uiAQUStride + uiAQUPosX].getActivity();
970    Double dNormAct = (dMaxQScale*dCUAct + dAvgAct) / (dCUAct + dMaxQScale*dAvgAct);
971    Double dQpOffset = log(dNormAct) / log(2.0) * 6.0;
972    iQpOffset = Int(floor( dQpOffset + 0.49999 ));
973  }
974
975  return Clip3(-pcCU->getSlice()->getSPS()->getQpBDOffset(CHANNEL_TYPE_LUMA), MAX_QP, iBaseQp+iQpOffset );
976}
977
978/** encode a CU block recursively
979 * \param pcCU
980 * \param uiAbsPartIdx
981 * \param uiDepth
982 * \returns Void
983 */
984Void TEncCu::xEncodeCU( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
985{
986        TComPic   *const pcPic   = pcCU->getPic();
987        TComSlice *const pcSlice = pcCU->getSlice();
988  const TComSPS   &sps =*(pcSlice->getSPS());
989  const TComPPS   &pps =*(pcSlice->getPPS());
990
991  const UInt maxCUWidth  = sps.getMaxCUWidth();
992  const UInt maxCUHeight = sps.getMaxCUHeight();
993
994        Bool bBoundary = false;
995        UInt uiLPelX   = pcCU->getCUPelX() + g_auiRasterToPelX[ g_auiZscanToRaster[uiAbsPartIdx] ];
996  const UInt uiRPelX   = uiLPelX + (maxCUWidth>>uiDepth)  - 1;
997        UInt uiTPelY   = pcCU->getCUPelY() + g_auiRasterToPelY[ g_auiZscanToRaster[uiAbsPartIdx] ];
998  const UInt uiBPelY   = uiTPelY + (maxCUHeight>>uiDepth) - 1;
999
1000#if H_MV_ENC_DEC_TRAC
1001  DTRACE_CU_S("=========== coding_quadtree ===========\n")
1002  DTRACE_CU("x0", uiLPelX)
1003  DTRACE_CU("x1", uiTPelY)
1004  DTRACE_CU("log2CbSize", maxCUWidth>>uiDepth )
1005  DTRACE_CU("cqtDepth"  , uiDepth)
1006#endif
1007
1008  if( ( uiRPelX < sps.getPicWidthInLumaSamples() ) && ( uiBPelY < sps.getPicHeightInLumaSamples() ) )
1009  {
1010    m_pcEntropyCoder->encodeSplitFlag( pcCU, uiAbsPartIdx, uiDepth );
1011  }
1012  else
1013  {
1014    bBoundary = true;
1015  }
1016
1017  if( ( ( uiDepth < pcCU->getDepth( uiAbsPartIdx ) ) && ( uiDepth < sps.getLog2DiffMaxMinCodingBlockSize() ) ) || bBoundary )
1018  {
1019    UInt uiQNumParts = ( pcPic->getNumPartitionsInCtu() >> (uiDepth<<1) )>>2;
1020    if( uiDepth == pps.getMaxCuDQPDepth() && pps.getUseDQP())
1021    {
1022      setdQPFlag(true);
1023    }
1024
1025    if( uiDepth == pps.getPpsRangeExtension().getDiffCuChromaQpOffsetDepth() && pcSlice->getUseChromaQpAdj())
1026    {
1027      setCodeChromaQpAdjFlag(true);
1028    }
1029
1030    for ( UInt uiPartUnitIdx = 0; uiPartUnitIdx < 4; uiPartUnitIdx++, uiAbsPartIdx+=uiQNumParts )
1031    {
1032      uiLPelX   = pcCU->getCUPelX() + g_auiRasterToPelX[ g_auiZscanToRaster[uiAbsPartIdx] ];
1033      uiTPelY   = pcCU->getCUPelY() + g_auiRasterToPelY[ g_auiZscanToRaster[uiAbsPartIdx] ];
1034      if( ( uiLPelX < sps.getPicWidthInLumaSamples() ) && ( uiTPelY < sps.getPicHeightInLumaSamples() ) )
1035      {
1036        xEncodeCU( pcCU, uiAbsPartIdx, uiDepth+1 );
1037      }
1038    }
1039    return;
1040  }
1041
1042#if H_MV_ENC_DEC_TRAC
1043  DTRACE_CU_S("=========== coding_unit ===========\n")
1044#endif
1045
1046
1047  if( uiDepth <= pps.getMaxCuDQPDepth() && pps.getUseDQP())
1048  {
1049    setdQPFlag(true);
1050  }
1051
1052  if( uiDepth <= pps.getPpsRangeExtension().getDiffCuChromaQpOffsetDepth() && pcSlice->getUseChromaQpAdj())
1053  {
1054    setCodeChromaQpAdjFlag(true);
1055  }
1056
1057  if (pps.getTransquantBypassEnableFlag())
1058  {
1059    m_pcEntropyCoder->encodeCUTransquantBypassFlag( pcCU, uiAbsPartIdx );
1060  }
1061
1062  if( !pcSlice->isIntra() )
1063  {
1064    m_pcEntropyCoder->encodeSkipFlag( pcCU, uiAbsPartIdx );
1065  }
1066
1067  if( pcCU->isSkipped( uiAbsPartIdx ) )
1068  {
1069#if H_MV_ENC_DEC_TRAC
1070    DTRACE_PU_S("=========== prediction_unit ===========\n")
1071    DTRACE_PU("x0", uiLPelX)
1072    DTRACE_PU("x1", uiTPelY)
1073#endif
1074
1075    m_pcEntropyCoder->encodeMergeIndex( pcCU, uiAbsPartIdx );
1076
1077    finishCU(pcCU,uiAbsPartIdx);
1078    return;
1079  }
1080
1081  m_pcEntropyCoder->encodePredMode( pcCU, uiAbsPartIdx );
1082  m_pcEntropyCoder->encodePartSize( pcCU, uiAbsPartIdx, uiDepth );
1083
1084  if (pcCU->isIntra( uiAbsPartIdx ) && pcCU->getPartitionSize( uiAbsPartIdx ) == SIZE_2Nx2N )
1085  {
1086    m_pcEntropyCoder->encodeIPCMInfo( pcCU, uiAbsPartIdx );
1087
1088    if(pcCU->getIPCMFlag(uiAbsPartIdx))
1089    {
1090
1091      // Encode slice finish
1092      finishCU(pcCU,uiAbsPartIdx);
1093      return;
1094    }
1095  }
1096
1097  // prediction Info ( Intra : direction mode, Inter : Mv, reference idx )
1098  m_pcEntropyCoder->encodePredInfo( pcCU, uiAbsPartIdx );
1099
1100  // Encode Coefficients
1101  Bool bCodeDQP = getdQPFlag();
1102  Bool codeChromaQpAdj = getCodeChromaQpAdjFlag();
1103  m_pcEntropyCoder->encodeCoeff( pcCU, uiAbsPartIdx, uiDepth, bCodeDQP, codeChromaQpAdj );
1104  setCodeChromaQpAdjFlag( codeChromaQpAdj );
1105  setdQPFlag( bCodeDQP );
1106
1107
1108  // --- write terminating bit ---
1109  finishCU(pcCU,uiAbsPartIdx);
1110}
1111
1112Int xCalcHADs8x8_ISlice(Pel *piOrg, Int iStrideOrg)
1113{
1114  Int k, i, j, jj;
1115  Int diff[64], m1[8][8], m2[8][8], m3[8][8], iSumHad = 0;
1116
1117  for( k = 0; k < 64; k += 8 )
1118  {
1119    diff[k+0] = piOrg[0] ;
1120    diff[k+1] = piOrg[1] ;
1121    diff[k+2] = piOrg[2] ;
1122    diff[k+3] = piOrg[3] ;
1123    diff[k+4] = piOrg[4] ;
1124    diff[k+5] = piOrg[5] ;
1125    diff[k+6] = piOrg[6] ;
1126    diff[k+7] = piOrg[7] ;
1127
1128    piOrg += iStrideOrg;
1129  }
1130
1131  //horizontal
1132  for (j=0; j < 8; j++)
1133  {
1134    jj = j << 3;
1135    m2[j][0] = diff[jj  ] + diff[jj+4];
1136    m2[j][1] = diff[jj+1] + diff[jj+5];
1137    m2[j][2] = diff[jj+2] + diff[jj+6];
1138    m2[j][3] = diff[jj+3] + diff[jj+7];
1139    m2[j][4] = diff[jj  ] - diff[jj+4];
1140    m2[j][5] = diff[jj+1] - diff[jj+5];
1141    m2[j][6] = diff[jj+2] - diff[jj+6];
1142    m2[j][7] = diff[jj+3] - diff[jj+7];
1143
1144    m1[j][0] = m2[j][0] + m2[j][2];
1145    m1[j][1] = m2[j][1] + m2[j][3];
1146    m1[j][2] = m2[j][0] - m2[j][2];
1147    m1[j][3] = m2[j][1] - m2[j][3];
1148    m1[j][4] = m2[j][4] + m2[j][6];
1149    m1[j][5] = m2[j][5] + m2[j][7];
1150    m1[j][6] = m2[j][4] - m2[j][6];
1151    m1[j][7] = m2[j][5] - m2[j][7];
1152
1153    m2[j][0] = m1[j][0] + m1[j][1];
1154    m2[j][1] = m1[j][0] - m1[j][1];
1155    m2[j][2] = m1[j][2] + m1[j][3];
1156    m2[j][3] = m1[j][2] - m1[j][3];
1157    m2[j][4] = m1[j][4] + m1[j][5];
1158    m2[j][5] = m1[j][4] - m1[j][5];
1159    m2[j][6] = m1[j][6] + m1[j][7];
1160    m2[j][7] = m1[j][6] - m1[j][7];
1161  }
1162
1163  //vertical
1164  for (i=0; i < 8; i++)
1165  {
1166    m3[0][i] = m2[0][i] + m2[4][i];
1167    m3[1][i] = m2[1][i] + m2[5][i];
1168    m3[2][i] = m2[2][i] + m2[6][i];
1169    m3[3][i] = m2[3][i] + m2[7][i];
1170    m3[4][i] = m2[0][i] - m2[4][i];
1171    m3[5][i] = m2[1][i] - m2[5][i];
1172    m3[6][i] = m2[2][i] - m2[6][i];
1173    m3[7][i] = m2[3][i] - m2[7][i];
1174
1175    m1[0][i] = m3[0][i] + m3[2][i];
1176    m1[1][i] = m3[1][i] + m3[3][i];
1177    m1[2][i] = m3[0][i] - m3[2][i];
1178    m1[3][i] = m3[1][i] - m3[3][i];
1179    m1[4][i] = m3[4][i] + m3[6][i];
1180    m1[5][i] = m3[5][i] + m3[7][i];
1181    m1[6][i] = m3[4][i] - m3[6][i];
1182    m1[7][i] = m3[5][i] - m3[7][i];
1183
1184    m2[0][i] = m1[0][i] + m1[1][i];
1185    m2[1][i] = m1[0][i] - m1[1][i];
1186    m2[2][i] = m1[2][i] + m1[3][i];
1187    m2[3][i] = m1[2][i] - m1[3][i];
1188    m2[4][i] = m1[4][i] + m1[5][i];
1189    m2[5][i] = m1[4][i] - m1[5][i];
1190    m2[6][i] = m1[6][i] + m1[7][i];
1191    m2[7][i] = m1[6][i] - m1[7][i];
1192  }
1193
1194  for (i = 0; i < 8; i++)
1195  {
1196    for (j = 0; j < 8; j++)
1197    {
1198      iSumHad += abs(m2[i][j]);
1199    }
1200  }
1201  iSumHad -= abs(m2[0][0]);
1202  iSumHad =(iSumHad+2)>>2;
1203  return(iSumHad);
1204}
1205
1206Int  TEncCu::updateCtuDataISlice(TComDataCU* pCtu, Int width, Int height)
1207{
1208  Int  xBl, yBl;
1209  const Int iBlkSize = 8;
1210
1211  Pel* pOrgInit   = pCtu->getPic()->getPicYuvOrg()->getAddr(COMPONENT_Y, pCtu->getCtuRsAddr(), 0);
1212  Int  iStrideOrig = pCtu->getPic()->getPicYuvOrg()->getStride(COMPONENT_Y);
1213  Pel  *pOrg;
1214
1215  Int iSumHad = 0;
1216  for ( yBl=0; (yBl+iBlkSize)<=height; yBl+= iBlkSize)
1217  {
1218    for ( xBl=0; (xBl+iBlkSize)<=width; xBl+= iBlkSize)
1219    {
1220      pOrg = pOrgInit + iStrideOrig*yBl + xBl;
1221      iSumHad += xCalcHADs8x8_ISlice(pOrg, iStrideOrig);
1222    }
1223  }
1224  return(iSumHad);
1225}
1226
1227/** check RD costs for a CU block encoded with merge
1228 * \param rpcBestCU
1229 * \param rpcTempCU
1230 * \param earlyDetectionSkipMode
1231 */
1232Void TEncCu::xCheckRDCostMerge2Nx2N( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU DEBUG_STRING_FN_DECLARE(sDebug), Bool *earlyDetectionSkipMode )
1233{
1234  assert( rpcTempCU->getSlice()->getSliceType() != I_SLICE );
1235  if(getFastDeltaQp())
1236  {
1237    return;   // never check merge in fast deltaqp mode
1238  }
1239
1240#if NH_MV
1241  D_PRINT_INC_INDENT( g_traceModeCheck, "xCheckRDCostMerge2Nx2N" );
1242#endif
1243
1244  TComMvField  cMvFieldNeighbours[2 * MRG_MAX_NUM_CANDS]; // double length for mv of both lists
1245  UChar uhInterDirNeighbours[MRG_MAX_NUM_CANDS];
1246  Int numValidMergeCand = 0;
1247  const Bool bTransquantBypassFlag = rpcTempCU->getCUTransquantBypass(0);
1248
1249  for( UInt ui = 0; ui < rpcTempCU->getSlice()->getMaxNumMergeCand(); ++ui )
1250  {
1251    uhInterDirNeighbours[ui] = 0;
1252  }
1253  UChar uhDepth = rpcTempCU->getDepth( 0 );
1254
1255
1256  rpcTempCU->setPartSizeSubParts( SIZE_2Nx2N, 0, uhDepth ); // interprets depth relative to CTU level
1257
1258
1259  rpcTempCU->getInterMergeCandidates( 0, 0, cMvFieldNeighbours,uhInterDirNeighbours, numValidMergeCand );
1260
1261  Int mergeCandBuffer[MRG_MAX_NUM_CANDS];
1262  for( UInt ui = 0; ui < numValidMergeCand; ++ui )
1263  {
1264    mergeCandBuffer[ui] = 0;
1265  }
1266
1267  Bool bestIsSkip = false;
1268
1269  UInt iteration;
1270  if ( rpcTempCU->isLosslessCoded(0))
1271  {
1272    iteration = 1;
1273  }
1274  else
1275  {
1276    iteration = 2;
1277  }
1278  DEBUG_STRING_NEW(bestStr)
1279
1280
1281  for( UInt uiNoResidual = 0; uiNoResidual < iteration; ++uiNoResidual )
1282  {
1283#if NH_MV
1284    D_PRINT_INC_INDENT ( g_traceModeCheck, "uiNoResidual: " + n2s( uiNoResidual) );
1285#endif
1286
1287    for( UInt uiMergeCand = 0; uiMergeCand < numValidMergeCand; ++uiMergeCand )
1288    {
1289#if NH_MV
1290      D_PRINT_INC_INDENT ( g_traceModeCheck, "uiMergeCand: "+  n2s(uiMergeCand) );
1291#endif
1292
1293      if(!(uiNoResidual==1 && mergeCandBuffer[uiMergeCand]==1))
1294      {
1295        if( !(bestIsSkip && uiNoResidual == 0) )
1296        {
1297          DEBUG_STRING_NEW(tmpStr)
1298          // set MC parameters
1299          rpcTempCU->setPredModeSubParts( MODE_INTER, 0, uhDepth ); // interprets depth relative to CTU level
1300          rpcTempCU->setCUTransquantBypassSubParts( bTransquantBypassFlag, 0, uhDepth );
1301          rpcTempCU->setChromaQpAdjSubParts( bTransquantBypassFlag ? 0 : m_cuChromaQpOffsetIdxPlus1, 0, uhDepth );
1302          rpcTempCU->setPartSizeSubParts( SIZE_2Nx2N, 0, uhDepth ); // interprets depth relative to CTU level
1303          rpcTempCU->setMergeFlagSubParts( true, 0, 0, uhDepth ); // interprets depth relative to CTU level
1304          rpcTempCU->setMergeIndexSubParts( uiMergeCand, 0, 0, uhDepth ); // interprets depth relative to CTU level
1305
1306          {
1307            rpcTempCU->setInterDirSubParts( uhInterDirNeighbours[uiMergeCand], 0, 0, uhDepth ); // interprets depth relative to CTU level
1308            rpcTempCU->getCUMvField( REF_PIC_LIST_0 )->setAllMvField( cMvFieldNeighbours[0 + 2*uiMergeCand], SIZE_2Nx2N, 0, 0 ); // interprets depth relative to rpcTempCU level
1309            rpcTempCU->getCUMvField( REF_PIC_LIST_1 )->setAllMvField( cMvFieldNeighbours[1 + 2*uiMergeCand], SIZE_2Nx2N, 0, 0 ); // interprets depth relative to rpcTempCU level
1310          }
1311          // do MC
1312          m_pcPredSearch->motionCompensation ( rpcTempCU, m_ppcPredYuvTemp[uhDepth] );
1313          // estimate residual and encode everything
1314          m_pcPredSearch->encodeResAndCalcRdInterCU( rpcTempCU,
1315                                                     m_ppcOrigYuv    [uhDepth],
1316                                                     m_ppcPredYuvTemp[uhDepth],
1317                                                     m_ppcResiYuvTemp[uhDepth],
1318                                                     m_ppcResiYuvBest[uhDepth],
1319                                                     m_ppcRecoYuvTemp[uhDepth],
1320                                                     (uiNoResidual != 0) DEBUG_STRING_PASS_INTO(tmpStr) );
1321
1322#if DEBUG_STRING
1323          DebugInterPredResiReco(tmpStr, *(m_ppcPredYuvTemp[uhDepth]), *(m_ppcResiYuvBest[uhDepth]), *(m_ppcRecoYuvTemp[uhDepth]), DebugStringGetPredModeMask(rpcTempCU->getPredictionMode(0)));
1324#endif
1325
1326          if ((uiNoResidual == 0) && (rpcTempCU->getQtRootCbf(0) == 0))
1327          {
1328            // If no residual when allowing for one, then set mark to not try case where residual is forced to 0
1329            mergeCandBuffer[uiMergeCand] = 1;
1330          }
1331          Int orgQP = rpcTempCU->getQP( 0 );
1332          xCheckDQP( rpcTempCU );
1333          xCheckBestMode(rpcBestCU, rpcTempCU, uhDepth DEBUG_STRING_PASS_INTO(bestStr) DEBUG_STRING_PASS_INTO(tmpStr));
1334
1335          rpcTempCU->initEstData( uhDepth, orgQP, bTransquantBypassFlag );
1336
1337          if( m_pcEncCfg->getUseFastDecisionForMerge() && !bestIsSkip )
1338          {
1339            bestIsSkip = rpcBestCU->getQtRootCbf(0) == 0;
1340          }
1341        }
1342      }
1343#if NH_MV
1344      D_DEC_INDENT( g_traceModeCheck ); 
1345#endif
1346    }
1347
1348    if(uiNoResidual == 0 && m_pcEncCfg->getUseEarlySkipDetection())
1349    {
1350      if(rpcBestCU->getQtRootCbf( 0 ) == 0)
1351      {
1352        if( rpcBestCU->getMergeFlag( 0 ))
1353        {
1354          *earlyDetectionSkipMode = true;
1355        }
1356        else if(m_pcEncCfg->getFastSearch() != SELECTIVE)
1357        {
1358          Int absoulte_MV=0;
1359          for ( UInt uiRefListIdx = 0; uiRefListIdx < 2; uiRefListIdx++ )
1360          {
1361            if ( rpcBestCU->getSlice()->getNumRefIdx( RefPicList( uiRefListIdx ) ) > 0 )
1362            {
1363              TComCUMvField* pcCUMvField = rpcBestCU->getCUMvField(RefPicList( uiRefListIdx ));
1364              Int iHor = pcCUMvField->getMvd( 0 ).getAbsHor();
1365              Int iVer = pcCUMvField->getMvd( 0 ).getAbsVer();
1366              absoulte_MV+=iHor+iVer;
1367            }
1368          }
1369
1370          if(absoulte_MV == 0)
1371          {
1372            *earlyDetectionSkipMode = true;
1373          }
1374        }
1375      }
1376    }
1377#if NH_MV
1378    D_DEC_INDENT( g_traceModeCheck ); 
1379#endif
1380  }
1381  DEBUG_STRING_APPEND(sDebug, bestStr)
1382#if NH_MV
1383 D_DEC_INDENT( g_traceModeCheck );
1384#endif
1385}
1386
1387
1388#if AMP_MRG
1389Void TEncCu::xCheckRDCostInter( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, PartSize ePartSize DEBUG_STRING_FN_DECLARE(sDebug), Bool bUseMRG)
1390#else
1391Void TEncCu::xCheckRDCostInter( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, PartSize ePartSize )
1392#endif
1393{
1394  DEBUG_STRING_NEW(sTest)
1395
1396  if(getFastDeltaQp())
1397  {
1398    const TComSPS &sps=*(rpcTempCU->getSlice()->getSPS());
1399    const UInt fastDeltaQPCuMaxSize = Clip3(sps.getMaxCUHeight()>>(sps.getLog2DiffMaxMinCodingBlockSize()), sps.getMaxCUHeight(), 32u);
1400    if(ePartSize != SIZE_2Nx2N || rpcTempCU->getWidth( 0 ) > fastDeltaQPCuMaxSize)
1401    {
1402      return; // only check necessary 2Nx2N Inter in fast deltaqp mode
1403    }
1404  }
1405
1406#if NH_MV
1407  D_PRINT_INC_INDENT(g_traceModeCheck,   "xCheckRDCostInter; ePartSize:" + n2s( ePartSize) );
1408#endif
1409
1410
1411  // prior to this, rpcTempCU will have just been reset using rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
1412  UChar uhDepth = rpcTempCU->getDepth( 0 );
1413  rpcTempCU->setPartSizeSubParts  ( ePartSize,  0, uhDepth );
1414  rpcTempCU->setPredModeSubParts  ( MODE_INTER, 0, uhDepth );
1415  rpcTempCU->setChromaQpAdjSubParts( rpcTempCU->getCUTransquantBypass(0) ? 0 : m_cuChromaQpOffsetIdxPlus1, 0, uhDepth );
1416#if AMP_MRG
1417  rpcTempCU->setMergeAMP (true);
1418  m_pcPredSearch->predInterSearch ( rpcTempCU, m_ppcOrigYuv[uhDepth], m_ppcPredYuvTemp[uhDepth], m_ppcResiYuvTemp[uhDepth], m_ppcRecoYuvTemp[uhDepth] DEBUG_STRING_PASS_INTO(sTest), false, bUseMRG );
1419
1420#else
1421  m_pcPredSearch->predInterSearch ( rpcTempCU, m_ppcOrigYuv[uhDepth], m_ppcPredYuvTemp[uhDepth], m_ppcResiYuvTemp[uhDepth], m_ppcRecoYuvTemp[uhDepth] );
1422#endif
1423
1424#if AMP_MRG
1425  if ( !rpcTempCU->getMergeAMP() )
1426  {
1427    {
1428#if NH_MV
1429        D_DEC_INDENT( g_traceModeCheck ); 
1430#endif
1431    return;
1432  }
1433  }
1434#endif
1435
1436  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) );
1437    rpcTempCU->getTotalCost()  = m_pcRdCost->calcRdCost( rpcTempCU->getTotalBits(), rpcTempCU->getTotalDistortion() );
1438
1439#if DEBUG_STRING
1440  DebugInterPredResiReco(sTest, *(m_ppcPredYuvTemp[uhDepth]), *(m_ppcResiYuvBest[uhDepth]), *(m_ppcRecoYuvTemp[uhDepth]), DebugStringGetPredModeMask(rpcTempCU->getPredictionMode(0)));
1441#endif
1442
1443  xCheckDQP( rpcTempCU );
1444  xCheckBestMode(rpcBestCU, rpcTempCU, uhDepth DEBUG_STRING_PASS_INTO(sDebug) DEBUG_STRING_PASS_INTO(sTest));
1445#if NH_MV
1446  D_DEC_INDENT( g_traceModeCheck ); 
1447#endif
1448}
1449
1450
1451Void TEncCu::xCheckRDCostIntra( TComDataCU *&rpcBestCU,
1452                                TComDataCU *&rpcTempCU,
1453                                Double      &cost,
1454                                PartSize     eSize
1455                                DEBUG_STRING_FN_DECLARE(sDebug)
1456                              )
1457{
1458  DEBUG_STRING_NEW(sTest)
1459
1460  if(getFastDeltaQp())
1461  {
1462    const TComSPS &sps=*(rpcTempCU->getSlice()->getSPS());
1463    const UInt fastDeltaQPCuMaxSize = Clip3(sps.getMaxCUHeight()>>(sps.getLog2DiffMaxMinCodingBlockSize()), sps.getMaxCUHeight(), 32u);
1464    if(rpcTempCU->getWidth( 0 ) > fastDeltaQPCuMaxSize)
1465    {
1466      return; // only check necessary 2Nx2N Intra in fast deltaqp mode
1467    }
1468  }
1469#if NH_MV
1470  D_PRINT_INC_INDENT (g_traceModeCheck, "xCheckRDCostIntra; eSize: " + n2s(eSize) );
1471#endif
1472
1473  UInt uiDepth = rpcTempCU->getDepth( 0 );
1474
1475  rpcTempCU->setSkipFlagSubParts( false, 0, uiDepth );
1476
1477
1478  rpcTempCU->setPartSizeSubParts( eSize, 0, uiDepth );
1479  rpcTempCU->setPredModeSubParts( MODE_INTRA, 0, uiDepth );
1480  rpcTempCU->setChromaQpAdjSubParts( rpcTempCU->getCUTransquantBypass(0) ? 0 : m_cuChromaQpOffsetIdxPlus1, 0, uiDepth );
1481
1482  Pel resiLuma[NUMBER_OF_STORED_RESIDUAL_TYPES][MAX_CU_SIZE * MAX_CU_SIZE];
1483
1484  m_pcPredSearch->estIntraPredLumaQT( rpcTempCU, m_ppcOrigYuv[uiDepth], m_ppcPredYuvTemp[uiDepth], m_ppcResiYuvTemp[uiDepth], m_ppcRecoYuvTemp[uiDepth], resiLuma DEBUG_STRING_PASS_INTO(sTest) 
1485                                    );
1486
1487  m_ppcRecoYuvTemp[uiDepth]->copyToPicComponent(COMPONENT_Y, rpcTempCU->getPic()->getPicYuvRec(), rpcTempCU->getCtuRsAddr(), rpcTempCU->getZorderIdxInCtu() );
1488
1489  if (rpcBestCU->getPic()->getChromaFormat()!=CHROMA_400)
1490  {
1491    m_pcPredSearch->estIntraPredChromaQT( rpcTempCU, m_ppcOrigYuv[uiDepth], m_ppcPredYuvTemp[uiDepth], m_ppcResiYuvTemp[uiDepth], m_ppcRecoYuvTemp[uiDepth], resiLuma DEBUG_STRING_PASS_INTO(sTest) );
1492  }
1493 
1494
1495  m_pcEntropyCoder->resetBits();
1496
1497  if ( rpcTempCU->getSlice()->getPPS()->getTransquantBypassEnableFlag())
1498  {
1499    m_pcEntropyCoder->encodeCUTransquantBypassFlag( rpcTempCU, 0,          true );
1500  }
1501  m_pcEntropyCoder->encodeSkipFlag ( rpcTempCU, 0,          true );
1502    m_pcEntropyCoder->encodePredMode( rpcTempCU, 0,          true );
1503    m_pcEntropyCoder->encodePartSize( rpcTempCU, 0, uiDepth, true );
1504    m_pcEntropyCoder->encodePredInfo( rpcTempCU, 0 );
1505    m_pcEntropyCoder->encodeIPCMInfo(rpcTempCU, 0, true );
1506
1507    // Encode Coefficients
1508    Bool bCodeDQP = getdQPFlag();
1509    Bool codeChromaQpAdjFlag = getCodeChromaQpAdjFlag();
1510    m_pcEntropyCoder->encodeCoeff( rpcTempCU, 0, uiDepth, bCodeDQP, codeChromaQpAdjFlag );
1511    setCodeChromaQpAdjFlag( codeChromaQpAdjFlag );
1512    setdQPFlag( bCodeDQP );
1513  m_pcRDGoOnSbacCoder->store(m_pppcRDSbacCoder[uiDepth][CI_TEMP_BEST]);
1514
1515  rpcTempCU->getTotalBits() = m_pcEntropyCoder->getNumberOfWrittenBits();
1516  rpcTempCU->getTotalBins() = ((TEncBinCABAC *)((TEncSbac*)m_pcEntropyCoder->m_pcEntropyCoderIf)->getEncBinIf())->getBinsCoded();
1517    rpcTempCU->getTotalCost() = m_pcRdCost->calcRdCost( rpcTempCU->getTotalBits(), rpcTempCU->getTotalDistortion() );
1518
1519  xCheckDQP( rpcTempCU );
1520
1521  cost = rpcTempCU->getTotalCost();
1522
1523  xCheckBestMode(rpcBestCU, rpcTempCU, uiDepth DEBUG_STRING_PASS_INTO(sDebug) DEBUG_STRING_PASS_INTO(sTest));
1524
1525#if NH_MV
1526  D_DEC_INDENT( g_traceModeCheck ); 
1527#endif
1528}
1529
1530
1531/** Check R-D costs for a CU with PCM mode.
1532 * \param rpcBestCU pointer to best mode CU data structure
1533 * \param rpcTempCU pointer to testing mode CU data structure
1534 * \returns Void
1535 *
1536 * \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.
1537 */
1538Void TEncCu::xCheckIntraPCM( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU )
1539{
1540  if(getFastDeltaQp())
1541  {
1542    const TComSPS &sps=*(rpcTempCU->getSlice()->getSPS());
1543    const UInt fastDeltaQPCuMaxPCMSize = Clip3((UInt)1<<sps.getPCMLog2MinSize(), (UInt)1<<sps.getPCMLog2MaxSize(), 32u);
1544    if (rpcTempCU->getWidth( 0 ) > fastDeltaQPCuMaxPCMSize)
1545    {
1546      return;   // only check necessary PCM in fast deltaqp mode
1547    }
1548  }
1549 
1550  UInt uiDepth = rpcTempCU->getDepth( 0 );
1551
1552  rpcTempCU->setSkipFlagSubParts( false, 0, uiDepth );
1553  rpcTempCU->setIPCMFlag(0, true);
1554  rpcTempCU->setIPCMFlagSubParts (true, 0, rpcTempCU->getDepth(0));
1555  rpcTempCU->setPartSizeSubParts( SIZE_2Nx2N, 0, uiDepth );
1556  rpcTempCU->setPredModeSubParts( MODE_INTRA, 0, uiDepth );
1557  rpcTempCU->setTrIdxSubParts ( 0, 0, uiDepth );
1558  rpcTempCU->setChromaQpAdjSubParts( rpcTempCU->getCUTransquantBypass(0) ? 0 : m_cuChromaQpOffsetIdxPlus1, 0, uiDepth );
1559
1560  m_pcPredSearch->IPCMSearch( rpcTempCU, m_ppcOrigYuv[uiDepth], m_ppcPredYuvTemp[uiDepth], m_ppcResiYuvTemp[uiDepth], m_ppcRecoYuvTemp[uiDepth]);
1561
1562  m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[uiDepth][CI_CURR_BEST]);
1563
1564  m_pcEntropyCoder->resetBits();
1565
1566  if ( rpcTempCU->getSlice()->getPPS()->getTransquantBypassEnableFlag())
1567  {
1568    m_pcEntropyCoder->encodeCUTransquantBypassFlag( rpcTempCU, 0,          true );
1569  }
1570
1571  m_pcEntropyCoder->encodeSkipFlag ( rpcTempCU, 0,          true );
1572  m_pcEntropyCoder->encodePredMode ( rpcTempCU, 0,          true );
1573  m_pcEntropyCoder->encodePartSize ( rpcTempCU, 0, uiDepth, true );
1574  m_pcEntropyCoder->encodeIPCMInfo ( rpcTempCU, 0, true );
1575  m_pcRDGoOnSbacCoder->store(m_pppcRDSbacCoder[uiDepth][CI_TEMP_BEST]);
1576
1577  rpcTempCU->getTotalBits() = m_pcEntropyCoder->getNumberOfWrittenBits();
1578  rpcTempCU->getTotalBins() = ((TEncBinCABAC *)((TEncSbac*)m_pcEntropyCoder->m_pcEntropyCoderIf)->getEncBinIf())->getBinsCoded();
1579    rpcTempCU->getTotalCost() = m_pcRdCost->calcRdCost( rpcTempCU->getTotalBits(), rpcTempCU->getTotalDistortion() );
1580
1581  xCheckDQP( rpcTempCU );
1582  DEBUG_STRING_NEW(a)
1583  DEBUG_STRING_NEW(b)
1584  xCheckBestMode(rpcBestCU, rpcTempCU, uiDepth DEBUG_STRING_PASS_INTO(a) DEBUG_STRING_PASS_INTO(b));
1585}
1586
1587/** check whether current try is the best with identifying the depth of current try
1588 * \param rpcBestCU
1589 * \param rpcTempCU
1590 * \param uiDepth
1591 */
1592Void TEncCu::xCheckBestMode( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, UInt uiDepth DEBUG_STRING_FN_DECLARE(sParent) DEBUG_STRING_FN_DECLARE(sTest) DEBUG_STRING_PASS_INTO(Bool bAddSizeInfo) )
1593{
1594  if( rpcTempCU->getTotalCost() < rpcBestCU->getTotalCost() )
1595  {
1596    TComYuv* pcYuv;
1597    // Change Information data
1598    TComDataCU* pcCU = rpcBestCU;
1599    rpcBestCU = rpcTempCU;
1600    rpcTempCU = pcCU;
1601
1602    // Change Prediction data
1603    pcYuv = m_ppcPredYuvBest[uiDepth];
1604    m_ppcPredYuvBest[uiDepth] = m_ppcPredYuvTemp[uiDepth];
1605    m_ppcPredYuvTemp[uiDepth] = pcYuv;
1606
1607    // Change Reconstruction data
1608    pcYuv = m_ppcRecoYuvBest[uiDepth];
1609    m_ppcRecoYuvBest[uiDepth] = m_ppcRecoYuvTemp[uiDepth];
1610    m_ppcRecoYuvTemp[uiDepth] = pcYuv;
1611
1612    pcYuv = NULL;
1613    pcCU  = NULL;
1614
1615    // store temp best CI for next CU coding
1616    m_pppcRDSbacCoder[uiDepth][CI_TEMP_BEST]->store(m_pppcRDSbacCoder[uiDepth][CI_NEXT_BEST]);
1617
1618
1619#if DEBUG_STRING
1620    DEBUG_STRING_SWAP(sParent, sTest)
1621    const PredMode predMode=rpcBestCU->getPredictionMode(0);
1622    if ((DebugOptionList::DebugString_Structure.getInt()&DebugStringGetPredModeMask(predMode)) && bAddSizeInfo)
1623    {
1624      std::stringstream ss(stringstream::out);
1625      ss <<"###: " << (predMode==MODE_INTRA?"Intra   ":"Inter   ") << partSizeToString[rpcBestCU->getPartitionSize(0)] << " CU at " << rpcBestCU->getCUPelX() << ", " << rpcBestCU->getCUPelY() << " width=" << UInt(rpcBestCU->getWidth(0)) << std::endl;
1626      sParent+=ss.str();
1627    }
1628#endif
1629  }
1630}
1631
1632Void TEncCu::xCheckDQP( TComDataCU* pcCU )
1633{
1634  UInt uiDepth = pcCU->getDepth( 0 );
1635
1636  const TComPPS &pps = *(pcCU->getSlice()->getPPS());
1637  if ( pps.getUseDQP() && uiDepth <= pps.getMaxCuDQPDepth() )
1638  {
1639    if ( pcCU->getQtRootCbf( 0) )
1640    {
1641      m_pcEntropyCoder->resetBits();
1642      m_pcEntropyCoder->encodeQP( pcCU, 0, false );
1643      pcCU->getTotalBits() += m_pcEntropyCoder->getNumberOfWrittenBits(); // dQP bits
1644      pcCU->getTotalBins() += ((TEncBinCABAC *)((TEncSbac*)m_pcEntropyCoder->m_pcEntropyCoderIf)->getEncBinIf())->getBinsCoded();
1645        pcCU->getTotalCost() = m_pcRdCost->calcRdCost( pcCU->getTotalBits(), pcCU->getTotalDistortion() );
1646    }
1647    else
1648    {
1649      pcCU->setQPSubParts( pcCU->getRefQP( 0 ), 0, uiDepth ); // set QP to default QP
1650    }
1651  }
1652}
1653
1654Void TEncCu::xCopyAMVPInfo (AMVPInfo* pSrc, AMVPInfo* pDst)
1655{
1656  pDst->iN = pSrc->iN;
1657  for (Int i = 0; i < pSrc->iN; i++)
1658  {
1659    pDst->m_acMvCand[i] = pSrc->m_acMvCand[i];
1660  }
1661}
1662Void TEncCu::xCopyYuv2Pic(TComPic* rpcPic, UInt uiCUAddr, UInt uiAbsPartIdx, UInt uiDepth, UInt uiSrcDepth )
1663{
1664  UInt uiAbsPartIdxInRaster = g_auiZscanToRaster[uiAbsPartIdx];
1665  UInt uiSrcBlkWidth = rpcPic->getNumPartInCtuWidth() >> (uiSrcDepth);
1666  UInt uiBlkWidth    = rpcPic->getNumPartInCtuWidth() >> (uiDepth);
1667  UInt uiPartIdxX = ( ( uiAbsPartIdxInRaster % rpcPic->getNumPartInCtuWidth() ) % uiSrcBlkWidth) / uiBlkWidth;
1668  UInt uiPartIdxY = ( ( uiAbsPartIdxInRaster / rpcPic->getNumPartInCtuWidth() ) % uiSrcBlkWidth) / uiBlkWidth;
1669  UInt uiPartIdx = uiPartIdxY * ( uiSrcBlkWidth / uiBlkWidth ) + uiPartIdxX;
1670  m_ppcRecoYuvBest[uiSrcDepth]->copyToPicYuv( rpcPic->getPicYuvRec (), uiCUAddr, uiAbsPartIdx, uiDepth - uiSrcDepth, uiPartIdx);
1671
1672#if ENC_DEC_TRACE && H_MV_ENC_DEC_TRAC
1673  Bool oldtraceCopyBack = g_traceCopyBack;
1674  g_traceCopyBack = false; 
1675#endif
1676  m_ppcPredYuvBest[uiSrcDepth]->copyToPicYuv( rpcPic->getPicYuvPred (), uiCUAddr, uiAbsPartIdx, uiDepth - uiSrcDepth, uiPartIdx);
1677
1678#if ENC_DEC_TRACE && H_MV_ENC_DEC_TRAC
1679  g_traceCopyBack = oldtraceCopyBack; 
1680#endif
1681}
1682
1683Void TEncCu::xCopyYuv2Tmp( UInt uiPartUnitIdx, UInt uiNextDepth )
1684{
1685  UInt uiCurrDepth = uiNextDepth - 1;
1686  m_ppcRecoYuvBest[uiNextDepth]->copyToPartYuv( m_ppcRecoYuvTemp[uiCurrDepth], uiPartUnitIdx );
1687  m_ppcPredYuvBest[uiNextDepth]->copyToPartYuv( m_ppcPredYuvBest[uiCurrDepth], uiPartUnitIdx);
1688}
1689
1690/** Function for filling the PCM buffer of a CU using its original sample array
1691 * \param pCU pointer to current CU
1692 * \param pOrgYuv pointer to original sample array
1693 */
1694Void TEncCu::xFillPCMBuffer     ( TComDataCU* pCU, TComYuv* pOrgYuv )
1695{
1696  const ChromaFormat format = pCU->getPic()->getChromaFormat();
1697  const UInt numberValidComponents = getNumberValidComponents(format);
1698  for (UInt componentIndex = 0; componentIndex < numberValidComponents; componentIndex++)
1699  {
1700    const ComponentID component = ComponentID(componentIndex);
1701
1702    const UInt width  = pCU->getWidth(0)  >> getComponentScaleX(component, format);
1703    const UInt height = pCU->getHeight(0) >> getComponentScaleY(component, format);
1704
1705    Pel *source      = pOrgYuv->getAddr(component, 0, width);
1706    Pel *destination = pCU->getPCMSample(component);
1707
1708    const UInt sourceStride = pOrgYuv->getStride(component);
1709
1710    for (Int line = 0; line < height; line++)
1711    {
1712      for (Int column = 0; column < width; column++)
1713      {
1714        destination[column] = source[column];
1715      }
1716
1717      source      += sourceStride;
1718      destination += width;
1719    }
1720  }
1721}
1722
1723#if ADAPTIVE_QP_SELECTION
1724/** Collect ARL statistics from one block
1725  */
1726Int TEncCu::xTuCollectARLStats(TCoeff* rpcCoeff, TCoeff* rpcArlCoeff, Int NumCoeffInCU, Double* cSum, UInt* numSamples )
1727{
1728  for( Int n = 0; n < NumCoeffInCU; n++ )
1729  {
1730    TCoeff u = abs( rpcCoeff[ n ] );
1731    TCoeff absc = rpcArlCoeff[ n ];
1732
1733    if( u != 0 )
1734    {
1735      if( u < LEVEL_RANGE )
1736      {
1737        cSum[ u ] += ( Double )absc;
1738        numSamples[ u ]++;
1739      }
1740      else
1741      {
1742        cSum[ LEVEL_RANGE ] += ( Double )absc - ( Double )( u << ARL_C_PRECISION );
1743        numSamples[ LEVEL_RANGE ]++;
1744      }
1745    }
1746  }
1747
1748  return 0;
1749}
1750
1751//! Collect ARL statistics from one CTU
1752Void TEncCu::xCtuCollectARLStats(TComDataCU* pCtu )
1753{
1754  Double cSum[ LEVEL_RANGE + 1 ];     //: the sum of DCT coefficients corresponding to data type and quantization output
1755  UInt numSamples[ LEVEL_RANGE + 1 ]; //: the number of coefficients corresponding to data type and quantization output
1756
1757  TCoeff* pCoeffY = pCtu->getCoeff(COMPONENT_Y);
1758  TCoeff* pArlCoeffY = pCtu->getArlCoeff(COMPONENT_Y);
1759  const TComSPS &sps = *(pCtu->getSlice()->getSPS());
1760
1761  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.
1762  const UInt uiMinNumCoeffInCU = 1 << uiMinCUWidth;                          // NOTE: ed - what is this?
1763
1764  memset( cSum, 0, sizeof( Double )*(LEVEL_RANGE+1) );
1765  memset( numSamples, 0, sizeof( UInt )*(LEVEL_RANGE+1) );
1766
1767  // Collect stats to cSum[][] and numSamples[][]
1768  for(Int i = 0; i < pCtu->getTotalNumPart(); i ++ )
1769  {
1770    UInt uiTrIdx = pCtu->getTransformIdx(i);
1771
1772    if(pCtu->isInter(i) && pCtu->getCbf( i, COMPONENT_Y, uiTrIdx ) )
1773    {
1774      xTuCollectARLStats(pCoeffY, pArlCoeffY, uiMinNumCoeffInCU, cSum, numSamples);
1775    }//Note that only InterY is processed. QP rounding is based on InterY data only.
1776
1777    pCoeffY  += uiMinNumCoeffInCU;
1778    pArlCoeffY  += uiMinNumCoeffInCU;
1779  }
1780
1781  for(Int u=1; u<LEVEL_RANGE;u++)
1782  {
1783    m_pcTrQuant->getSliceSumC()[u] += cSum[ u ] ;
1784    m_pcTrQuant->getSliceNSamples()[u] += numSamples[ u ] ;
1785  }
1786  m_pcTrQuant->getSliceSumC()[LEVEL_RANGE] += cSum[ LEVEL_RANGE ] ;
1787  m_pcTrQuant->getSliceNSamples()[LEVEL_RANGE] += numSamples[ LEVEL_RANGE ] ;
1788}
1789#endif
1790
1791//! \}
Note: See TracBrowser for help on using the repository browser.