source: 3DVCSoftware/trunk/source/Lib/TLibEncoder/TEncSampleAdaptiveOffset.cpp @ 1313

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

Merged 14.1-update-dev1@1312.

File size: 45.3 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/**
35 \file     TEncSampleAdaptiveOffset.cpp
36 \brief       estimation part of sample adaptive offset class
37 */
38#include "TEncSampleAdaptiveOffset.h"
39#include <string.h>
40#include <stdlib.h>
41#include <stdio.h>
42#include <math.h>
43
44//! \ingroup TLibEncoder
45//! \{
46
47
48//! rounding with IBDI
49inline Double xRoundIbdi2(Int bitDepth, Double x)
50{
51  return ((x)>0) ? (Int)(((Int)(x)+(1<<(bitDepth-8-1)))/(1<<(bitDepth-8))) : ((Int)(((Int)(x)-(1<<(bitDepth-8-1)))/(1<<(bitDepth-8))));
52}
53
54inline Double xRoundIbdi(Int bitDepth, Double x)
55{
56  return (bitDepth > 8 ? xRoundIbdi2(bitDepth, (x)) : ((x)>=0 ? ((Int)((x)+0.5)) : ((Int)((x)-0.5)))) ;
57}
58
59
60TEncSampleAdaptiveOffset::TEncSampleAdaptiveOffset()
61{
62  m_pppcRDSbacCoder = NULL;
63  m_pcRDGoOnSbacCoder = NULL;
64  m_pppcBinCoderCABAC = NULL;
65  m_statData = NULL;
66  m_preDBFstatData = NULL;
67}
68
69TEncSampleAdaptiveOffset::~TEncSampleAdaptiveOffset()
70{
71  destroyEncData();
72}
73
74Void TEncSampleAdaptiveOffset::createEncData(Bool isPreDBFSamplesUsed)
75{
76
77  //cabac coder for RDO
78  m_pppcRDSbacCoder = new TEncSbac* [NUM_SAO_CABACSTATE_LABELS];
79#if FAST_BIT_EST
80  m_pppcBinCoderCABAC = new TEncBinCABACCounter* [NUM_SAO_CABACSTATE_LABELS];
81#else
82  m_pppcBinCoderCABAC = new TEncBinCABAC* [NUM_SAO_CABACSTATE_LABELS];
83#endif
84
85  for(Int cs=0; cs < NUM_SAO_CABACSTATE_LABELS; cs++)
86  {
87    m_pppcRDSbacCoder[cs] = new TEncSbac;
88#if FAST_BIT_EST
89    m_pppcBinCoderCABAC[cs] = new TEncBinCABACCounter;
90#else
91    m_pppcBinCoderCABAC[cs] = new TEncBinCABAC;
92#endif
93    m_pppcRDSbacCoder   [cs]->init( m_pppcBinCoderCABAC [cs] );
94  }
95
96
97  //statistics
98  m_statData = new SAOStatData**[m_numCTUsPic];
99  for(Int i=0; i< m_numCTUsPic; i++)
100  {
101    m_statData[i] = new SAOStatData*[MAX_NUM_COMPONENT];
102    for(Int compIdx=0; compIdx < MAX_NUM_COMPONENT; compIdx++)
103    {
104      m_statData[i][compIdx] = new SAOStatData[NUM_SAO_NEW_TYPES];
105    }
106  }
107  if(isPreDBFSamplesUsed)
108  {
109    m_preDBFstatData = new SAOStatData**[m_numCTUsPic];
110    for(Int i=0; i< m_numCTUsPic; i++)
111    {
112      m_preDBFstatData[i] = new SAOStatData*[MAX_NUM_COMPONENT];
113      for(Int compIdx=0; compIdx < MAX_NUM_COMPONENT; compIdx++)
114      {
115        m_preDBFstatData[i][compIdx] = new SAOStatData[NUM_SAO_NEW_TYPES];
116      }
117    }
118
119  }
120
121  ::memset(m_saoDisabledRate, 0, sizeof(m_saoDisabledRate));
122
123  for(Int typeIdc=0; typeIdc < NUM_SAO_NEW_TYPES; typeIdc++)
124  {
125    m_skipLinesR[COMPONENT_Y ][typeIdc]= 5;
126    m_skipLinesR[COMPONENT_Cb][typeIdc]= m_skipLinesR[COMPONENT_Cr][typeIdc]= 3;
127
128    m_skipLinesB[COMPONENT_Y ][typeIdc]= 4;
129    m_skipLinesB[COMPONENT_Cb][typeIdc]= m_skipLinesB[COMPONENT_Cr][typeIdc]= 2;
130
131    if(isPreDBFSamplesUsed)
132    {
133      switch(typeIdc)
134      {
135      case SAO_TYPE_EO_0:
136        {
137          m_skipLinesR[COMPONENT_Y ][typeIdc]= 5;
138          m_skipLinesR[COMPONENT_Cb][typeIdc]= m_skipLinesR[COMPONENT_Cr][typeIdc]= 3;
139
140          m_skipLinesB[COMPONENT_Y ][typeIdc]= 3;
141          m_skipLinesB[COMPONENT_Cb][typeIdc]= m_skipLinesB[COMPONENT_Cr][typeIdc]= 1;
142        }
143        break;
144      case SAO_TYPE_EO_90:
145        {
146          m_skipLinesR[COMPONENT_Y ][typeIdc]= 4;
147          m_skipLinesR[COMPONENT_Cb][typeIdc]= m_skipLinesR[COMPONENT_Cr][typeIdc]= 2;
148
149          m_skipLinesB[COMPONENT_Y ][typeIdc]= 4;
150          m_skipLinesB[COMPONENT_Cb][typeIdc]= m_skipLinesB[COMPONENT_Cr][typeIdc]= 2;
151        }
152        break;
153      case SAO_TYPE_EO_135:
154      case SAO_TYPE_EO_45:
155        {
156          m_skipLinesR[COMPONENT_Y ][typeIdc]= 5;
157          m_skipLinesR[COMPONENT_Cb][typeIdc]= m_skipLinesR[COMPONENT_Cr][typeIdc]= 3;
158
159          m_skipLinesB[COMPONENT_Y ][typeIdc]= 4;
160          m_skipLinesB[COMPONENT_Cb][typeIdc]= m_skipLinesB[COMPONENT_Cr][typeIdc]= 2;
161        }
162        break;
163      case SAO_TYPE_BO:
164        {
165          m_skipLinesR[COMPONENT_Y ][typeIdc]= 4;
166          m_skipLinesR[COMPONENT_Cb][typeIdc]= m_skipLinesR[COMPONENT_Cr][typeIdc]= 2;
167
168          m_skipLinesB[COMPONENT_Y ][typeIdc]= 3;
169          m_skipLinesB[COMPONENT_Cb][typeIdc]= m_skipLinesB[COMPONENT_Cr][typeIdc]= 1;
170        }
171        break;
172      default:
173        {
174          printf("Not a supported type");
175          assert(0);
176          exit(-1);
177        }
178      }
179    }
180  }
181
182}
183
184Void TEncSampleAdaptiveOffset::destroyEncData()
185{
186  if(m_pppcRDSbacCoder != NULL)
187  {
188    for (Int cs = 0; cs < NUM_SAO_CABACSTATE_LABELS; cs ++ )
189    {
190      delete m_pppcRDSbacCoder[cs];
191    }
192    delete[] m_pppcRDSbacCoder; m_pppcRDSbacCoder = NULL;
193  }
194
195  if(m_pppcBinCoderCABAC != NULL)
196  {
197    for (Int cs = 0; cs < NUM_SAO_CABACSTATE_LABELS; cs ++ )
198    {
199      delete m_pppcBinCoderCABAC[cs];
200    }
201    delete[] m_pppcBinCoderCABAC; m_pppcBinCoderCABAC = NULL;
202  }
203
204  if(m_statData != NULL)
205  {
206    for(Int i=0; i< m_numCTUsPic; i++)
207    {
208      for(Int compIdx=0; compIdx< MAX_NUM_COMPONENT; compIdx++)
209      {
210        delete[] m_statData[i][compIdx];
211      }
212      delete[] m_statData[i];
213    }
214    delete[] m_statData; m_statData = NULL;
215  }
216  if(m_preDBFstatData != NULL)
217  {
218    for(Int i=0; i< m_numCTUsPic; i++)
219    {
220      for(Int compIdx=0; compIdx< MAX_NUM_COMPONENT; compIdx++)
221      {
222        delete[] m_preDBFstatData[i][compIdx];
223      }
224      delete[] m_preDBFstatData[i];
225    }
226    delete[] m_preDBFstatData; m_preDBFstatData = NULL;
227  }
228}
229
230Void TEncSampleAdaptiveOffset::initRDOCabacCoder(TEncSbac* pcRDGoOnSbacCoder, TComSlice* pcSlice)
231{
232  m_pcRDGoOnSbacCoder = pcRDGoOnSbacCoder;
233  m_pcRDGoOnSbacCoder->resetEntropy(pcSlice);
234  m_pcRDGoOnSbacCoder->resetBits();
235
236  m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[SAO_CABACSTATE_PIC_INIT]);
237}
238
239
240
241Void TEncSampleAdaptiveOffset::SAOProcess(TComPic* pPic, Bool* sliceEnabled, const Double *lambdas, const Bool bTestSAODisableAtPictureLevel, const Double saoEncodingRate, const Double saoEncodingRateChroma, Bool isPreDBFSamplesUsed )
242{
243  TComPicYuv* orgYuv= pPic->getPicYuvOrg();
244  TComPicYuv* resYuv= pPic->getPicYuvRec();
245  memcpy(m_lambda, lambdas, sizeof(m_lambda));
246  TComPicYuv* srcYuv = m_tempPicYuv;
247  resYuv->copyToPic(srcYuv);
248  srcYuv->setBorderExtension(false);
249  srcYuv->extendPicBorder();
250
251  //collect statistics
252  getStatistics(m_statData, orgYuv, srcYuv, pPic);
253  if(isPreDBFSamplesUsed)
254  {
255    addPreDBFStatistics(m_statData);
256  }
257  //slice on/off
258  decidePicParams(sliceEnabled, pPic->getSlice(0)->getDepth(), saoEncodingRate, saoEncodingRateChroma);
259
260  //block on/off
261  SAOBlkParam* reconParams = new SAOBlkParam[m_numCTUsPic]; //temporary parameter buffer for storing reconstructed SAO parameters
262  decideBlkParams(pPic, sliceEnabled, m_statData, srcYuv, resYuv, reconParams, pPic->getPicSym()->getSAOBlkParam(), bTestSAODisableAtPictureLevel, saoEncodingRate, saoEncodingRateChroma);
263  delete[] reconParams;
264}
265
266Void TEncSampleAdaptiveOffset::getPreDBFStatistics(TComPic* pPic)
267{
268  getStatistics(m_preDBFstatData, pPic->getPicYuvOrg(), pPic->getPicYuvRec(), pPic, true);
269}
270
271Void TEncSampleAdaptiveOffset::addPreDBFStatistics(SAOStatData*** blkStats)
272{
273  for(Int n=0; n< m_numCTUsPic; n++)
274  {
275    for(Int compIdx=0; compIdx < MAX_NUM_COMPONENT; compIdx++)
276    {
277      for(Int typeIdc=0; typeIdc < NUM_SAO_NEW_TYPES; typeIdc++)
278      {
279        blkStats[n][compIdx][typeIdc] += m_preDBFstatData[n][compIdx][typeIdc];
280      }
281    }
282  }
283}
284
285Void TEncSampleAdaptiveOffset::getStatistics(SAOStatData*** blkStats, TComPicYuv* orgYuv, TComPicYuv* srcYuv, TComPic* pPic, Bool isCalculatePreDeblockSamples)
286{
287  Bool isLeftAvail,isRightAvail,isAboveAvail,isBelowAvail,isAboveLeftAvail,isAboveRightAvail,isBelowLeftAvail,isBelowRightAvail;
288
289  const Int numberOfComponents = getNumberValidComponents(m_chromaFormatIDC);
290
291  for(Int ctuRsAddr= 0; ctuRsAddr < m_numCTUsPic; ctuRsAddr++)
292  {
293    Int yPos   = (ctuRsAddr / m_numCTUInWidth)*m_maxCUHeight;
294    Int xPos   = (ctuRsAddr % m_numCTUInWidth)*m_maxCUWidth;
295    Int height = (yPos + m_maxCUHeight > m_picHeight)?(m_picHeight- yPos):m_maxCUHeight;
296    Int width  = (xPos + m_maxCUWidth  > m_picWidth )?(m_picWidth - xPos):m_maxCUWidth;
297
298    pPic->getPicSym()->deriveLoopFilterBoundaryAvailibility(ctuRsAddr, isLeftAvail,isRightAvail,isAboveAvail,isBelowAvail,isAboveLeftAvail,isAboveRightAvail,isBelowLeftAvail,isBelowRightAvail);
299
300    //NOTE: The number of skipped lines during gathering CTU statistics depends on the slice boundary availabilities.
301    //For simplicity, here only picture boundaries are considered.
302
303    isRightAvail      = (xPos + m_maxCUWidth  < m_picWidth );
304    isBelowAvail      = (yPos + m_maxCUHeight < m_picHeight);
305    isBelowRightAvail = (isRightAvail && isBelowAvail);
306    isBelowLeftAvail  = ((xPos > 0) && (isBelowAvail));
307    isAboveRightAvail = ((yPos > 0) && (isRightAvail));
308
309    for(Int compIdx = 0; compIdx < numberOfComponents; compIdx++)
310    {
311      const ComponentID component = ComponentID(compIdx);
312
313      const UInt componentScaleX = getComponentScaleX(component, pPic->getChromaFormat());
314      const UInt componentScaleY = getComponentScaleY(component, pPic->getChromaFormat());
315
316      Int  srcStride  = srcYuv->getStride(component);
317      Pel* srcBlk     = srcYuv->getAddr(component) + ((yPos >> componentScaleY) * srcStride) + (xPos >> componentScaleX);
318
319      Int  orgStride  = orgYuv->getStride(component);
320      Pel* orgBlk     = orgYuv->getAddr(component) + ((yPos >> componentScaleY) * orgStride) + (xPos >> componentScaleX);
321
322      getBlkStats(component, pPic->getPicSym()->getSPS().getBitDepth(toChannelType(component)), blkStats[ctuRsAddr][component]
323                , srcBlk, orgBlk, srcStride, orgStride, (width  >> componentScaleX), (height >> componentScaleY)
324                , isLeftAvail,  isRightAvail, isAboveAvail, isBelowAvail, isAboveLeftAvail, isAboveRightAvail
325                , isCalculatePreDeblockSamples
326                );
327
328    }
329  }
330}
331
332Void TEncSampleAdaptiveOffset::decidePicParams(Bool* sliceEnabled, Int picTempLayer, const Double saoEncodingRate, const Double saoEncodingRateChroma)
333{
334  //decide sliceEnabled[compIdx]
335  const Int numberOfComponents = getNumberValidComponents(m_chromaFormatIDC);
336  for (Int compIdx = 0; compIdx < MAX_NUM_COMPONENT; compIdx++)
337  {
338    sliceEnabled[compIdx] = false;
339  }
340
341  for (Int compIdx = 0; compIdx < numberOfComponents; compIdx++)
342  {
343    // reset flags & counters
344    sliceEnabled[compIdx] = true;
345
346    if (saoEncodingRate>0.0)
347    {
348      if (saoEncodingRateChroma>0.0)
349      {
350    // decide slice-level on/off based on previous results
351    if( (picTempLayer > 0)
352          && (m_saoDisabledRate[compIdx][picTempLayer-1] > ((compIdx==COMPONENT_Y) ? saoEncodingRate : saoEncodingRateChroma)) )
353    {
354      sliceEnabled[compIdx] = false;
355    }
356      }
357      else
358      {
359    // decide slice-level on/off based on previous results
360    if( (picTempLayer > 0)
361          && (m_saoDisabledRate[COMPONENT_Y][0] > saoEncodingRate) )
362    {
363      sliceEnabled[compIdx] = false;
364    }
365      }
366    }
367  }
368}
369
370Int64 TEncSampleAdaptiveOffset::getDistortion(const Int channelBitDepth, Int typeIdc, Int typeAuxInfo, Int* invQuantOffset, SAOStatData& statData)
371{
372  Int64 dist        = 0;
373  Int shift         = 2 * DISTORTION_PRECISION_ADJUSTMENT(channelBitDepth - 8);
374
375  switch(typeIdc)
376  {
377    case SAO_TYPE_EO_0:
378    case SAO_TYPE_EO_90:
379    case SAO_TYPE_EO_135:
380    case SAO_TYPE_EO_45:
381      {
382        for (Int offsetIdx=0; offsetIdx<NUM_SAO_EO_CLASSES; offsetIdx++)
383        {
384          dist += estSaoDist( statData.count[offsetIdx], invQuantOffset[offsetIdx], statData.diff[offsetIdx], shift);
385        }
386      }
387      break;
388    case SAO_TYPE_BO:
389      {
390        for (Int offsetIdx=typeAuxInfo; offsetIdx<typeAuxInfo+4; offsetIdx++)
391        {
392          Int bandIdx = offsetIdx % NUM_SAO_BO_CLASSES ;
393          dist += estSaoDist( statData.count[bandIdx], invQuantOffset[bandIdx], statData.diff[bandIdx], shift);
394        }
395      }
396      break;
397    default:
398      {
399        printf("Not a supported type");
400        assert(0);
401        exit(-1);
402      }
403  }
404
405  return dist;
406}
407
408inline Int64 TEncSampleAdaptiveOffset::estSaoDist(Int64 count, Int64 offset, Int64 diffSum, Int shift)
409{
410  return (( count*offset*offset-diffSum*offset*2 ) >> shift);
411}
412
413
414inline Int TEncSampleAdaptiveOffset::estIterOffset(Int typeIdx, Double lambda, Int offsetInput, Int64 count, Int64 diffSum, Int shift, Int bitIncrease, Int64& bestDist, Double& bestCost, Int offsetTh )
415{
416  Int iterOffset, tempOffset;
417  Int64 tempDist, tempRate;
418  Double tempCost, tempMinCost;
419  Int offsetOutput = 0;
420  iterOffset = offsetInput;
421  // Assuming sending quantized value 0 results in zero offset and sending the value zero needs 1 bit. entropy coder can be used to measure the exact rate here.
422  tempMinCost = lambda;
423  while (iterOffset != 0)
424  {
425    // Calculate the bits required for signaling the offset
426    tempRate = (typeIdx == SAO_TYPE_BO) ? (abs((Int)iterOffset)+2) : (abs((Int)iterOffset)+1);
427    if (abs((Int)iterOffset)==offsetTh) //inclusive
428    {
429      tempRate --;
430    }
431    // Do the dequantization before distortion calculation
432    tempOffset  = iterOffset << bitIncrease;
433    tempDist    = estSaoDist( count, tempOffset, diffSum, shift);
434    tempCost    = ((Double)tempDist + lambda * (Double) tempRate);
435    if(tempCost < tempMinCost)
436    {
437      tempMinCost = tempCost;
438      offsetOutput = iterOffset;
439      bestDist = tempDist;
440      bestCost = tempCost;
441    }
442    iterOffset = (iterOffset > 0) ? (iterOffset-1):(iterOffset+1);
443  }
444  return offsetOutput;
445}
446
447Void TEncSampleAdaptiveOffset::deriveOffsets(ComponentID compIdx, const Int channelBitDepth, Int typeIdc, SAOStatData& statData, Int* quantOffsets, Int& typeAuxInfo)
448{
449  Int bitDepth = channelBitDepth;
450  Int shift    = 2 * DISTORTION_PRECISION_ADJUSTMENT(bitDepth-8);
451  Int offsetTh = TComSampleAdaptiveOffset::getMaxOffsetQVal(channelBitDepth);  //inclusive
452
453  ::memset(quantOffsets, 0, sizeof(Int)*MAX_NUM_SAO_CLASSES);
454
455  //derive initial offsets
456  Int numClasses = (typeIdc == SAO_TYPE_BO)?((Int)NUM_SAO_BO_CLASSES):((Int)NUM_SAO_EO_CLASSES);
457  for(Int classIdx=0; classIdx< numClasses; classIdx++)
458  {
459    if( (typeIdc != SAO_TYPE_BO) && (classIdx==SAO_CLASS_EO_PLAIN)  )
460    {
461      continue; //offset will be zero
462    }
463
464    if(statData.count[classIdx] == 0)
465    {
466      continue; //offset will be zero
467    }
468
469    quantOffsets[classIdx] = (Int) xRoundIbdi(bitDepth, (Double)( statData.diff[classIdx]<<(bitDepth-8))
470                                                                  /
471                                                          (Double)( statData.count[classIdx]<< m_offsetStepLog2[compIdx])
472                                               );
473    quantOffsets[classIdx] = Clip3(-offsetTh, offsetTh, quantOffsets[classIdx]);
474  }
475
476  // adjust offsets
477  switch(typeIdc)
478  {
479    case SAO_TYPE_EO_0:
480    case SAO_TYPE_EO_90:
481    case SAO_TYPE_EO_135:
482    case SAO_TYPE_EO_45:
483      {
484        Int64 classDist;
485        Double classCost;
486        for(Int classIdx=0; classIdx<NUM_SAO_EO_CLASSES; classIdx++)
487        {
488          if(classIdx==SAO_CLASS_EO_FULL_VALLEY && quantOffsets[classIdx] < 0)
489          {
490            quantOffsets[classIdx] =0;
491          }
492          if(classIdx==SAO_CLASS_EO_HALF_VALLEY && quantOffsets[classIdx] < 0)
493          {
494            quantOffsets[classIdx] =0;
495          }
496          if(classIdx==SAO_CLASS_EO_HALF_PEAK   && quantOffsets[classIdx] > 0)
497          {
498            quantOffsets[classIdx] =0;
499          }
500          if(classIdx==SAO_CLASS_EO_FULL_PEAK   && quantOffsets[classIdx] > 0)
501          {
502            quantOffsets[classIdx] =0;
503          }
504
505          if( quantOffsets[classIdx] != 0 ) //iterative adjustment only when derived offset is not zero
506          {
507            quantOffsets[classIdx] = estIterOffset( typeIdc, m_lambda[compIdx], quantOffsets[classIdx], statData.count[classIdx], statData.diff[classIdx], shift, m_offsetStepLog2[compIdx], classDist , classCost , offsetTh );
508          }
509        }
510
511        typeAuxInfo =0;
512      }
513      break;
514    case SAO_TYPE_BO:
515      {
516        Int64  distBOClasses[NUM_SAO_BO_CLASSES];
517        Double costBOClasses[NUM_SAO_BO_CLASSES];
518        ::memset(distBOClasses, 0, sizeof(Int64)*NUM_SAO_BO_CLASSES);
519        for(Int classIdx=0; classIdx< NUM_SAO_BO_CLASSES; classIdx++)
520        {
521          costBOClasses[classIdx]= m_lambda[compIdx];
522          if( quantOffsets[classIdx] != 0 ) //iterative adjustment only when derived offset is not zero
523          {
524            quantOffsets[classIdx] = estIterOffset( typeIdc, m_lambda[compIdx], quantOffsets[classIdx], statData.count[classIdx], statData.diff[classIdx], shift, m_offsetStepLog2[compIdx], distBOClasses[classIdx], costBOClasses[classIdx], offsetTh );
525          }
526        }
527
528        //decide the starting band index
529        Double minCost = MAX_DOUBLE, cost;
530        for(Int band=0; band< NUM_SAO_BO_CLASSES- 4+ 1; band++)
531        {
532          cost  = costBOClasses[band  ];
533          cost += costBOClasses[band+1];
534          cost += costBOClasses[band+2];
535          cost += costBOClasses[band+3];
536
537          if(cost < minCost)
538          {
539            minCost = cost;
540            typeAuxInfo = band;
541          }
542        }
543        //clear those unused classes
544        Int clearQuantOffset[NUM_SAO_BO_CLASSES];
545        ::memset(clearQuantOffset, 0, sizeof(Int)*NUM_SAO_BO_CLASSES);
546        for(Int i=0; i< 4; i++)
547        {
548          Int band = (typeAuxInfo+i)%NUM_SAO_BO_CLASSES;
549          clearQuantOffset[band] = quantOffsets[band];
550        }
551        ::memcpy(quantOffsets, clearQuantOffset, sizeof(Int)*NUM_SAO_BO_CLASSES);
552      }
553      break;
554    default:
555      {
556        printf("Not a supported type");
557        assert(0);
558        exit(-1);
559      }
560
561  }
562
563
564}
565
566Void TEncSampleAdaptiveOffset::deriveModeNewRDO(const BitDepths &bitDepths, Int ctuRsAddr, SAOBlkParam* mergeList[NUM_SAO_MERGE_TYPES], Bool* sliceEnabled, SAOStatData*** blkStats, SAOBlkParam& modeParam, Double& modeNormCost, TEncSbac** cabacCoderRDO, Int inCabacLabel)
567{
568  Double minCost, cost;
569  UInt previousWrittenBits;
570  const Int numberOfComponents = getNumberValidComponents(m_chromaFormatIDC);
571
572  Int64 dist[MAX_NUM_COMPONENT], modeDist[MAX_NUM_COMPONENT];
573  SAOOffset testOffset[MAX_NUM_COMPONENT];
574  Int invQuantOffset[MAX_NUM_SAO_CLASSES];
575  for(Int comp=0; comp < MAX_NUM_COMPONENT; comp++)
576  {
577    modeDist[comp] = 0;
578  }
579
580  //pre-encode merge flags
581  modeParam[COMPONENT_Y].modeIdc = SAO_MODE_OFF;
582  m_pcRDGoOnSbacCoder->load(cabacCoderRDO[inCabacLabel]);
583  m_pcRDGoOnSbacCoder->codeSAOBlkParam(modeParam, bitDepths, sliceEnabled, (mergeList[SAO_MERGE_LEFT]!= NULL), (mergeList[SAO_MERGE_ABOVE]!= NULL), true);
584  m_pcRDGoOnSbacCoder->store(cabacCoderRDO[SAO_CABACSTATE_BLK_MID]);
585
586    //------ luma --------//
587  {
588    const ComponentID compIdx = COMPONENT_Y;
589    //"off" case as initial cost
590    modeParam[compIdx].modeIdc = SAO_MODE_OFF;
591    m_pcRDGoOnSbacCoder->resetBits();
592    m_pcRDGoOnSbacCoder->codeSAOOffsetParam(compIdx, modeParam[compIdx], sliceEnabled[compIdx], bitDepths.recon[CHANNEL_TYPE_LUMA]);
593    modeDist[compIdx] = 0;
594    minCost= m_lambda[compIdx]*((Double)m_pcRDGoOnSbacCoder->getNumberOfWrittenBits());
595    m_pcRDGoOnSbacCoder->store(cabacCoderRDO[SAO_CABACSTATE_BLK_TEMP]);
596    if(sliceEnabled[compIdx])
597    {
598      for(Int typeIdc=0; typeIdc< NUM_SAO_NEW_TYPES; typeIdc++)
599      {
600        testOffset[compIdx].modeIdc = SAO_MODE_NEW;
601        testOffset[compIdx].typeIdc = typeIdc;
602
603        //derive coded offset
604        deriveOffsets(compIdx, bitDepths.recon[CHANNEL_TYPE_LUMA], typeIdc, blkStats[ctuRsAddr][compIdx][typeIdc], testOffset[compIdx].offset, testOffset[compIdx].typeAuxInfo);
605
606        //inversed quantized offsets
607        invertQuantOffsets(compIdx, typeIdc, testOffset[compIdx].typeAuxInfo, invQuantOffset, testOffset[compIdx].offset);
608
609        //get distortion
610        dist[compIdx] = getDistortion(bitDepths.recon[CHANNEL_TYPE_LUMA], testOffset[compIdx].typeIdc, testOffset[compIdx].typeAuxInfo, invQuantOffset, blkStats[ctuRsAddr][compIdx][typeIdc]);
611
612        //get rate
613        m_pcRDGoOnSbacCoder->load(cabacCoderRDO[SAO_CABACSTATE_BLK_MID]);
614        m_pcRDGoOnSbacCoder->resetBits();
615        m_pcRDGoOnSbacCoder->codeSAOOffsetParam(compIdx, testOffset[compIdx], sliceEnabled[compIdx], bitDepths.recon[CHANNEL_TYPE_LUMA]);
616        Int rate = m_pcRDGoOnSbacCoder->getNumberOfWrittenBits();
617        cost = (Double)dist[compIdx] + m_lambda[compIdx]*((Double)rate);
618        if(cost < minCost)
619        {
620          minCost = cost;
621          modeDist[compIdx] = dist[compIdx];
622          modeParam[compIdx]= testOffset[compIdx];
623          m_pcRDGoOnSbacCoder->store(cabacCoderRDO[SAO_CABACSTATE_BLK_TEMP]);
624        }
625      }
626    }
627    m_pcRDGoOnSbacCoder->load(cabacCoderRDO[SAO_CABACSTATE_BLK_TEMP]);
628    m_pcRDGoOnSbacCoder->store(cabacCoderRDO[SAO_CABACSTATE_BLK_MID]);
629  }
630
631  //------ chroma --------//
632//"off" case as initial cost
633  cost = 0;
634  previousWrittenBits = 0;
635  m_pcRDGoOnSbacCoder->resetBits();
636  for(UInt componentIndex = COMPONENT_Cb; componentIndex < numberOfComponents; componentIndex++)
637  {
638    const ComponentID component = ComponentID(componentIndex);
639
640    modeParam[component].modeIdc = SAO_MODE_OFF;
641    modeDist [component]         = 0;
642    m_pcRDGoOnSbacCoder->codeSAOOffsetParam(component, modeParam[component], sliceEnabled[component], bitDepths.recon[CHANNEL_TYPE_CHROMA]);
643   
644    const UInt currentWrittenBits = m_pcRDGoOnSbacCoder->getNumberOfWrittenBits();
645    cost += m_lambda[component] * (currentWrittenBits - previousWrittenBits);
646    previousWrittenBits = currentWrittenBits;
647  }
648
649  minCost = cost;
650
651  //doesn't need to store cabac status here since the whole CTU parameters will be re-encoded at the end of this function
652
653  for(Int typeIdc=0; typeIdc< NUM_SAO_NEW_TYPES; typeIdc++)
654  {
655    m_pcRDGoOnSbacCoder->load(cabacCoderRDO[SAO_CABACSTATE_BLK_MID]);
656    m_pcRDGoOnSbacCoder->resetBits();
657    previousWrittenBits = 0;
658    cost = 0;
659
660    for(UInt componentIndex = COMPONENT_Cb; componentIndex < numberOfComponents; componentIndex++)
661    {
662      const ComponentID component = ComponentID(componentIndex);
663      if(!sliceEnabled[component])
664      {
665        testOffset[component].modeIdc = SAO_MODE_OFF;
666        dist[component]= 0;
667        continue;
668      }
669      testOffset[component].modeIdc = SAO_MODE_NEW;
670      testOffset[component].typeIdc = typeIdc;
671
672      //derive offset & get distortion
673      deriveOffsets(component, bitDepths.recon[CHANNEL_TYPE_CHROMA], typeIdc, blkStats[ctuRsAddr][component][typeIdc], testOffset[component].offset, testOffset[component].typeAuxInfo);
674      invertQuantOffsets(component, typeIdc, testOffset[component].typeAuxInfo, invQuantOffset, testOffset[component].offset);
675      dist[component] = getDistortion(bitDepths.recon[CHANNEL_TYPE_CHROMA], typeIdc, testOffset[component].typeAuxInfo, invQuantOffset, blkStats[ctuRsAddr][component][typeIdc]);
676
677      m_pcRDGoOnSbacCoder->codeSAOOffsetParam(component, testOffset[component], sliceEnabled[component], bitDepths.recon[CHANNEL_TYPE_CHROMA]);
678
679      const UInt currentWrittenBits = m_pcRDGoOnSbacCoder->getNumberOfWrittenBits();
680      cost += dist[component] + (m_lambda[component] * (currentWrittenBits - previousWrittenBits));
681      previousWrittenBits = currentWrittenBits;
682    }
683
684    if(cost < minCost)
685    {
686      minCost = cost;
687      for(UInt componentIndex = COMPONENT_Cb; componentIndex < numberOfComponents; componentIndex++)
688      {
689        modeDist[componentIndex]  = dist[componentIndex];
690        modeParam[componentIndex] = testOffset[componentIndex];
691      }
692    }
693
694  } // SAO_TYPE loop
695
696  //----- re-gen rate & normalized cost----//
697  modeNormCost = 0;
698  for(UInt componentIndex = COMPONENT_Y; componentIndex < numberOfComponents; componentIndex++)
699  {
700    modeNormCost += (Double)modeDist[componentIndex] / m_lambda[componentIndex];
701  }
702
703  m_pcRDGoOnSbacCoder->load(cabacCoderRDO[inCabacLabel]);
704  m_pcRDGoOnSbacCoder->resetBits();
705  m_pcRDGoOnSbacCoder->codeSAOBlkParam(modeParam, bitDepths, sliceEnabled, (mergeList[SAO_MERGE_LEFT]!= NULL), (mergeList[SAO_MERGE_ABOVE]!= NULL), false);
706  modeNormCost += (Double)m_pcRDGoOnSbacCoder->getNumberOfWrittenBits();
707}
708
709Void TEncSampleAdaptiveOffset::deriveModeMergeRDO(const BitDepths &bitDepths, Int ctuRsAddr, SAOBlkParam* mergeList[NUM_SAO_MERGE_TYPES], Bool* sliceEnabled, SAOStatData*** blkStats, SAOBlkParam& modeParam, Double& modeNormCost, TEncSbac** cabacCoderRDO, Int inCabacLabel)
710{
711  modeNormCost = MAX_DOUBLE;
712
713  Double cost;
714  SAOBlkParam testBlkParam;
715  const Int numberOfComponents = getNumberValidComponents(m_chromaFormatIDC);
716
717  for(Int mergeType=0; mergeType< NUM_SAO_MERGE_TYPES; mergeType++)
718  {
719    if(mergeList[mergeType] == NULL)
720    {
721      continue;
722    }
723
724    testBlkParam = *(mergeList[mergeType]);
725    //normalized distortion
726    Double normDist=0;
727    for(Int compIdx = 0; compIdx < numberOfComponents; compIdx++)
728    {
729      testBlkParam[compIdx].modeIdc = SAO_MODE_MERGE;
730      testBlkParam[compIdx].typeIdc = mergeType;
731
732      SAOOffset& mergedOffsetParam = (*(mergeList[mergeType]))[compIdx];
733
734      if( mergedOffsetParam.modeIdc != SAO_MODE_OFF)
735      {
736        //offsets have been reconstructed. Don't call inversed quantization function.
737        normDist += (((Double)getDistortion(bitDepths.recon[toChannelType(ComponentID(compIdx))], mergedOffsetParam.typeIdc, mergedOffsetParam.typeAuxInfo, mergedOffsetParam.offset, blkStats[ctuRsAddr][compIdx][mergedOffsetParam.typeIdc]))
738                       /m_lambda[compIdx]
739                    );
740      }
741
742    }
743
744    //rate
745    m_pcRDGoOnSbacCoder->load(cabacCoderRDO[inCabacLabel]);
746    m_pcRDGoOnSbacCoder->resetBits();
747    m_pcRDGoOnSbacCoder->codeSAOBlkParam(testBlkParam, bitDepths, sliceEnabled, (mergeList[SAO_MERGE_LEFT]!= NULL), (mergeList[SAO_MERGE_ABOVE]!= NULL), false);
748    Int rate = m_pcRDGoOnSbacCoder->getNumberOfWrittenBits();
749
750    cost = normDist+(Double)rate;
751
752    if(cost < modeNormCost)
753    {
754      modeNormCost = cost;
755      modeParam    = testBlkParam;
756      m_pcRDGoOnSbacCoder->store(cabacCoderRDO[SAO_CABACSTATE_BLK_TEMP]);
757    }
758  }
759
760  m_pcRDGoOnSbacCoder->load(cabacCoderRDO[SAO_CABACSTATE_BLK_TEMP]);
761}
762
763Void TEncSampleAdaptiveOffset::decideBlkParams(TComPic* pic, Bool* sliceEnabled, SAOStatData*** blkStats, TComPicYuv* srcYuv, TComPicYuv* resYuv,
764                                               SAOBlkParam* reconParams, SAOBlkParam* codedParams, const Bool bTestSAODisableAtPictureLevel,
765                                               const Double saoEncodingRate, const Double saoEncodingRateChroma)
766{
767  Bool allBlksDisabled = true;
768  const Int numberOfComponents = getNumberValidComponents(m_chromaFormatIDC);
769  for(Int compId = COMPONENT_Y; compId < numberOfComponents; compId++)
770  {
771    if (sliceEnabled[compId])
772    {
773      allBlksDisabled = false;
774    }
775  }
776
777  m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[ SAO_CABACSTATE_PIC_INIT ]);
778
779  SAOBlkParam modeParam;
780  Double minCost, modeCost;
781
782
783  Double totalCost = 0; // Used if bTestSAODisableAtPictureLevel==true
784
785  for(Int ctuRsAddr=0; ctuRsAddr< m_numCTUsPic; ctuRsAddr++)
786  {
787    if(allBlksDisabled)
788    {
789      codedParams[ctuRsAddr].reset();
790      continue;
791    }
792
793    m_pcRDGoOnSbacCoder->store(m_pppcRDSbacCoder[ SAO_CABACSTATE_BLK_CUR ]);
794
795    //get merge list
796    SAOBlkParam* mergeList[NUM_SAO_MERGE_TYPES] = { NULL };
797    getMergeList(pic, ctuRsAddr, reconParams, mergeList);
798
799    minCost = MAX_DOUBLE;
800    for(Int mode=0; mode < NUM_SAO_MODES; mode++)
801    {
802      switch(mode)
803      {
804      case SAO_MODE_OFF:
805        {
806          continue; //not necessary, since all-off case will be tested in SAO_MODE_NEW case.
807        }
808        break;
809      case SAO_MODE_NEW:
810        {
811          deriveModeNewRDO(pic->getPicSym()->getSPS().getBitDepths(), ctuRsAddr, mergeList, sliceEnabled, blkStats, modeParam, modeCost, m_pppcRDSbacCoder, SAO_CABACSTATE_BLK_CUR);
812
813        }
814        break;
815      case SAO_MODE_MERGE:
816        {
817          deriveModeMergeRDO(pic->getPicSym()->getSPS().getBitDepths(), ctuRsAddr, mergeList, sliceEnabled, blkStats , modeParam, modeCost, m_pppcRDSbacCoder, SAO_CABACSTATE_BLK_CUR);
818        }
819        break;
820      default:
821        {
822          printf("Not a supported SAO mode\n");
823          assert(0);
824          exit(-1);
825        }
826      }
827
828      D_PRINT_INDENT( g_traceSAOCost, "SAO mode " + n2s( mode ) + " Cost:  " + n2s( modeCost) );
829
830      if(modeCost < minCost)
831      {
832        minCost = modeCost;
833        codedParams[ctuRsAddr] = modeParam;
834        m_pcRDGoOnSbacCoder->store(m_pppcRDSbacCoder[ SAO_CABACSTATE_BLK_NEXT ]);
835      }
836    } //mode
837
838    totalCost += minCost;
839
840    m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[ SAO_CABACSTATE_BLK_NEXT ]);
841
842    //apply reconstructed offsets
843    reconParams[ctuRsAddr] = codedParams[ctuRsAddr];
844    reconstructBlkSAOParam(reconParams[ctuRsAddr], mergeList);
845    offsetCTU(ctuRsAddr, srcYuv, resYuv, reconParams[ctuRsAddr], pic);
846  } //ctuRsAddr
847
848  if (!allBlksDisabled && (totalCost >= 0) && bTestSAODisableAtPictureLevel) //SAO has not beneficial in this case - disable it
849  {
850    for(Int ctuRsAddr = 0; ctuRsAddr < m_numCTUsPic; ctuRsAddr++)
851    {
852      codedParams[ctuRsAddr].reset();
853    }
854
855    for (UInt componentIndex = 0; componentIndex < MAX_NUM_COMPONENT; componentIndex++)
856    {
857      sliceEnabled[componentIndex] = false;
858    }
859
860    m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[ SAO_CABACSTATE_PIC_INIT ]);
861  }
862
863  if (saoEncodingRate > 0.0)
864  {
865  Int picTempLayer = pic->getSlice(0)->getDepth();
866  Int numCtusForSAOOff[MAX_NUM_COMPONENT];
867
868  for (Int compIdx = 0; compIdx < numberOfComponents; compIdx++)
869  {
870    numCtusForSAOOff[compIdx] = 0;
871    for(Int ctuRsAddr=0; ctuRsAddr< m_numCTUsPic; ctuRsAddr++)
872    {
873      if( reconParams[ctuRsAddr][compIdx].modeIdc == SAO_MODE_OFF)
874      {
875        numCtusForSAOOff[compIdx]++;
876      }
877    }
878  }
879    if (saoEncodingRateChroma > 0.0)
880    {
881  for (Int compIdx = 0; compIdx < numberOfComponents; compIdx++)
882  {
883    m_saoDisabledRate[compIdx][picTempLayer] = (Double)numCtusForSAOOff[compIdx]/(Double)m_numCTUsPic;
884  }
885    }
886    else if (picTempLayer == 0)
887  {
888    m_saoDisabledRate[COMPONENT_Y][0] = (Double)(numCtusForSAOOff[COMPONENT_Y]+numCtusForSAOOff[COMPONENT_Cb]+numCtusForSAOOff[COMPONENT_Cr])/(Double)(m_numCTUsPic*3);
889  }
890  }
891}
892
893
894Void TEncSampleAdaptiveOffset::getBlkStats(const ComponentID compIdx, const Int channelBitDepth, SAOStatData* statsDataTypes
895                        , Pel* srcBlk, Pel* orgBlk, Int srcStride, Int orgStride, Int width, Int height
896                        , Bool isLeftAvail,  Bool isRightAvail, Bool isAboveAvail, Bool isBelowAvail, Bool isAboveLeftAvail, Bool isAboveRightAvail
897                        , Bool isCalculatePreDeblockSamples
898                        )
899{
900  if(m_lineBufWidth != m_maxCUWidth)
901  {
902    m_lineBufWidth = m_maxCUWidth;
903
904    if (m_signLineBuf1)
905    {
906      delete[] m_signLineBuf1;
907      m_signLineBuf1 = NULL;
908    }
909    m_signLineBuf1 = new Char[m_lineBufWidth+1];
910
911    if (m_signLineBuf2)
912    {
913      delete[] m_signLineBuf2;
914      m_signLineBuf2 = NULL;
915    }
916    m_signLineBuf2 = new Char[m_lineBufWidth+1];
917  }
918
919  Int x,y, startX, startY, endX, endY, edgeType, firstLineStartX, firstLineEndX;
920  Char signLeft, signRight, signDown;
921  Int64 *diff, *count;
922  Pel *srcLine, *orgLine;
923  Int* skipLinesR = m_skipLinesR[compIdx];
924  Int* skipLinesB = m_skipLinesB[compIdx];
925
926  for(Int typeIdx=0; typeIdx< NUM_SAO_NEW_TYPES; typeIdx++)
927  {
928    SAOStatData& statsData= statsDataTypes[typeIdx];
929    statsData.reset();
930
931    srcLine = srcBlk;
932    orgLine = orgBlk;
933    diff    = statsData.diff;
934    count   = statsData.count;
935    switch(typeIdx)
936    {
937    case SAO_TYPE_EO_0:
938      {
939        diff +=2;
940        count+=2;
941        endY   = (isBelowAvail) ? (height - skipLinesB[typeIdx]) : height;
942        startX = (!isCalculatePreDeblockSamples) ? (isLeftAvail  ? 0 : 1)
943                                                 : (isRightAvail ? (width - skipLinesR[typeIdx]) : (width - 1))
944                                                 ;
945        endX   = (!isCalculatePreDeblockSamples) ? (isRightAvail ? (width - skipLinesR[typeIdx]) : (width - 1))
946                                                 : (isRightAvail ? width : (width - 1))
947                                                 ;
948        for (y=0; y<endY; y++)
949        {
950          signLeft = (Char)sgn(srcLine[startX] - srcLine[startX-1]);
951          for (x=startX; x<endX; x++)
952          {
953            signRight =  (Char)sgn(srcLine[x] - srcLine[x+1]);
954            edgeType  =  signRight + signLeft;
955            signLeft  = -signRight;
956
957            diff [edgeType] += (orgLine[x] - srcLine[x]);
958            count[edgeType] ++;
959          }
960          srcLine  += srcStride;
961          orgLine  += orgStride;
962        }
963        if(isCalculatePreDeblockSamples)
964        {
965          if(isBelowAvail)
966          {
967            startX = isLeftAvail  ? 0 : 1;
968            endX   = isRightAvail ? width : (width -1);
969
970            for(y=0; y<skipLinesB[typeIdx]; y++)
971            {
972              signLeft = (Char)sgn(srcLine[startX] - srcLine[startX-1]);
973              for (x=startX; x<endX; x++)
974              {
975                signRight =  (Char)sgn(srcLine[x] - srcLine[x+1]);
976                edgeType  =  signRight + signLeft;
977                signLeft  = -signRight;
978
979                diff [edgeType] += (orgLine[x] - srcLine[x]);
980                count[edgeType] ++;
981              }
982              srcLine  += srcStride;
983              orgLine  += orgStride;
984            }
985          }
986        }
987      }
988      break;
989    case SAO_TYPE_EO_90:
990      {
991        diff +=2;
992        count+=2;
993        Char *signUpLine = m_signLineBuf1;
994
995        startX = (!isCalculatePreDeblockSamples) ? 0
996                                                 : (isRightAvail ? (width - skipLinesR[typeIdx]) : width)
997                                                 ;
998        startY = isAboveAvail ? 0 : 1;
999        endX   = (!isCalculatePreDeblockSamples) ? (isRightAvail ? (width - skipLinesR[typeIdx]) : width)
1000                                                 : width
1001                                                 ;
1002        endY   = isBelowAvail ? (height - skipLinesB[typeIdx]) : (height - 1);
1003        if (!isAboveAvail)
1004        {
1005          srcLine += srcStride;
1006          orgLine += orgStride;
1007        }
1008
1009        Pel* srcLineAbove = srcLine - srcStride;
1010        for (x=startX; x<endX; x++)
1011        {
1012          signUpLine[x] = (Char)sgn(srcLine[x] - srcLineAbove[x]);
1013        }
1014
1015        Pel* srcLineBelow;
1016        for (y=startY; y<endY; y++)
1017        {
1018          srcLineBelow = srcLine + srcStride;
1019
1020          for (x=startX; x<endX; x++)
1021          {
1022            signDown  = (Char)sgn(srcLine[x] - srcLineBelow[x]); 
1023            edgeType  = signDown + signUpLine[x];
1024            signUpLine[x]= -signDown;
1025
1026            diff [edgeType] += (orgLine[x] - srcLine[x]);
1027            count[edgeType] ++;
1028          }
1029          srcLine += srcStride;
1030          orgLine += orgStride;
1031        }
1032        if(isCalculatePreDeblockSamples)
1033        {
1034          if(isBelowAvail)
1035          {
1036            startX = 0;
1037            endX   = width;
1038
1039            for(y=0; y<skipLinesB[typeIdx]; y++)
1040            {
1041              srcLineBelow = srcLine + srcStride;
1042              srcLineAbove = srcLine - srcStride;
1043
1044              for (x=startX; x<endX; x++)
1045              {
1046                edgeType = sgn(srcLine[x] - srcLineBelow[x]) + sgn(srcLine[x] - srcLineAbove[x]);
1047                diff [edgeType] += (orgLine[x] - srcLine[x]);
1048                count[edgeType] ++;
1049              }
1050              srcLine  += srcStride;
1051              orgLine  += orgStride;
1052            }
1053          }
1054        }
1055
1056      }
1057      break;
1058    case SAO_TYPE_EO_135:
1059      {
1060        diff +=2;
1061        count+=2;
1062        Char *signUpLine, *signDownLine, *signTmpLine;
1063
1064        signUpLine  = m_signLineBuf1;
1065        signDownLine= m_signLineBuf2;
1066
1067        startX = (!isCalculatePreDeblockSamples) ? (isLeftAvail  ? 0 : 1)
1068                                                 : (isRightAvail ? (width - skipLinesR[typeIdx]) : (width - 1))
1069                                                 ;
1070
1071        endX   = (!isCalculatePreDeblockSamples) ? (isRightAvail ? (width - skipLinesR[typeIdx]): (width - 1))
1072                                                 : (isRightAvail ? width : (width - 1))
1073                                                 ;
1074        endY   = isBelowAvail ? (height - skipLinesB[typeIdx]) : (height - 1);
1075
1076        //prepare 2nd line's upper sign
1077        Pel* srcLineBelow = srcLine + srcStride;
1078        for (x=startX; x<endX+1; x++)
1079        {
1080          signUpLine[x] = (Char)sgn(srcLineBelow[x] - srcLine[x-1]);
1081        }
1082
1083        //1st line
1084        Pel* srcLineAbove = srcLine - srcStride;
1085        firstLineStartX = (!isCalculatePreDeblockSamples) ? (isAboveLeftAvail ? 0    : 1) : startX;
1086        firstLineEndX   = (!isCalculatePreDeblockSamples) ? (isAboveAvail     ? endX : 1) : endX;
1087        for(x=firstLineStartX; x<firstLineEndX; x++)
1088        {
1089          edgeType = sgn(srcLine[x] - srcLineAbove[x-1]) - signUpLine[x+1];
1090          diff [edgeType] += (orgLine[x] - srcLine[x]);
1091          count[edgeType] ++;
1092        }
1093        srcLine  += srcStride;
1094        orgLine  += orgStride;
1095
1096
1097        //middle lines
1098        for (y=1; y<endY; y++)
1099        {
1100          srcLineBelow = srcLine + srcStride;
1101
1102          for (x=startX; x<endX; x++)
1103          {
1104            signDown = (Char)sgn(srcLine[x] - srcLineBelow[x+1]);
1105            edgeType = signDown + signUpLine[x];
1106            diff [edgeType] += (orgLine[x] - srcLine[x]);
1107            count[edgeType] ++;
1108
1109            signDownLine[x+1] = -signDown;
1110          }
1111          signDownLine[startX] = (Char)sgn(srcLineBelow[startX] - srcLine[startX-1]);
1112
1113          signTmpLine  = signUpLine;
1114          signUpLine   = signDownLine;
1115          signDownLine = signTmpLine;
1116
1117          srcLine += srcStride;
1118          orgLine += orgStride;
1119        }
1120        if(isCalculatePreDeblockSamples)
1121        {
1122          if(isBelowAvail)
1123          {
1124            startX = isLeftAvail  ? 0     : 1 ;
1125            endX   = isRightAvail ? width : (width -1);
1126
1127            for(y=0; y<skipLinesB[typeIdx]; y++)
1128            {
1129              srcLineBelow = srcLine + srcStride;
1130              srcLineAbove = srcLine - srcStride;
1131
1132              for (x=startX; x< endX; x++)
1133              {
1134                edgeType = sgn(srcLine[x] - srcLineBelow[x+1]) + sgn(srcLine[x] - srcLineAbove[x-1]);
1135                diff [edgeType] += (orgLine[x] - srcLine[x]);
1136                count[edgeType] ++;
1137              }
1138              srcLine  += srcStride;
1139              orgLine  += orgStride;
1140            }
1141          }
1142        }
1143      }
1144      break;
1145    case SAO_TYPE_EO_45:
1146      {
1147        diff +=2;
1148        count+=2;
1149        Char *signUpLine = m_signLineBuf1+1;
1150
1151        startX = (!isCalculatePreDeblockSamples) ? (isLeftAvail  ? 0 : 1)
1152                                                 : (isRightAvail ? (width - skipLinesR[typeIdx]) : (width - 1))
1153                                                 ;
1154        endX   = (!isCalculatePreDeblockSamples) ? (isRightAvail ? (width - skipLinesR[typeIdx]) : (width - 1))
1155                                                 : (isRightAvail ? width : (width - 1))
1156                                                 ;
1157        endY   = isBelowAvail ? (height - skipLinesB[typeIdx]) : (height - 1);
1158
1159        //prepare 2nd line upper sign
1160        Pel* srcLineBelow = srcLine + srcStride;
1161        for (x=startX-1; x<endX; x++)
1162        {
1163          signUpLine[x] = (Char)sgn(srcLineBelow[x] - srcLine[x+1]);
1164        }
1165
1166
1167        //first line
1168        Pel* srcLineAbove = srcLine - srcStride;
1169        firstLineStartX = (!isCalculatePreDeblockSamples) ? (isAboveAvail ? startX : endX)
1170                                                          : startX
1171                                                          ;
1172        firstLineEndX   = (!isCalculatePreDeblockSamples) ? ((!isRightAvail && isAboveRightAvail) ? width : endX)
1173                                                          : endX
1174                                                          ;
1175        for(x=firstLineStartX; x<firstLineEndX; x++)
1176        {
1177          edgeType = sgn(srcLine[x] - srcLineAbove[x+1]) - signUpLine[x-1];
1178          diff [edgeType] += (orgLine[x] - srcLine[x]);
1179          count[edgeType] ++;
1180        }
1181
1182        srcLine += srcStride;
1183        orgLine += orgStride;
1184
1185        //middle lines
1186        for (y=1; y<endY; y++)
1187        {
1188          srcLineBelow = srcLine + srcStride;
1189
1190          for(x=startX; x<endX; x++)
1191          {
1192            signDown = (Char)sgn(srcLine[x] - srcLineBelow[x-1]);
1193            edgeType = signDown + signUpLine[x];
1194
1195            diff [edgeType] += (orgLine[x] - srcLine[x]);
1196            count[edgeType] ++;
1197
1198            signUpLine[x-1] = -signDown;
1199          }
1200          signUpLine[endX-1] = (Char)sgn(srcLineBelow[endX-1] - srcLine[endX]);
1201          srcLine  += srcStride;
1202          orgLine  += orgStride;
1203        }
1204        if(isCalculatePreDeblockSamples)
1205        {
1206          if(isBelowAvail)
1207          {
1208            startX = isLeftAvail  ? 0     : 1 ;
1209            endX   = isRightAvail ? width : (width -1);
1210
1211            for(y=0; y<skipLinesB[typeIdx]; y++)
1212            {
1213              srcLineBelow = srcLine + srcStride;
1214              srcLineAbove = srcLine - srcStride;
1215
1216              for (x=startX; x<endX; x++)
1217              {
1218                edgeType = sgn(srcLine[x] - srcLineBelow[x-1]) + sgn(srcLine[x] - srcLineAbove[x+1]);
1219                diff [edgeType] += (orgLine[x] - srcLine[x]);
1220                count[edgeType] ++;
1221              }
1222              srcLine  += srcStride;
1223              orgLine  += orgStride;
1224            }
1225          }
1226        }
1227      }
1228      break;
1229    case SAO_TYPE_BO:
1230      {
1231        startX = (!isCalculatePreDeblockSamples)?0
1232                                                :( isRightAvail?(width- skipLinesR[typeIdx]):width)
1233                                                ;
1234        endX   = (!isCalculatePreDeblockSamples)?(isRightAvail ? (width - skipLinesR[typeIdx]) : width )
1235                                                :width
1236                                                ;
1237        endY = isBelowAvail ? (height- skipLinesB[typeIdx]) : height;
1238        Int shiftBits = channelBitDepth - NUM_SAO_BO_CLASSES_LOG2;
1239        for (y=0; y< endY; y++)
1240        {
1241          for (x=startX; x< endX; x++)
1242          {
1243
1244            Int bandIdx= srcLine[x] >> shiftBits;
1245            diff [bandIdx] += (orgLine[x] - srcLine[x]);
1246            count[bandIdx] ++;
1247          }
1248          srcLine += srcStride;
1249          orgLine += orgStride;
1250        }
1251        if(isCalculatePreDeblockSamples)
1252        {
1253          if(isBelowAvail)
1254          {
1255            startX = 0;
1256            endX   = width;
1257
1258            for(y= 0; y< skipLinesB[typeIdx]; y++)
1259            {
1260              for (x=startX; x< endX; x++)
1261              {
1262                Int bandIdx= srcLine[x] >> shiftBits;
1263                diff [bandIdx] += (orgLine[x] - srcLine[x]);
1264                count[bandIdx] ++;
1265              }
1266              srcLine  += srcStride;
1267              orgLine  += orgStride;
1268
1269            }
1270
1271          }
1272        }
1273      }
1274      break;
1275    default:
1276      {
1277        printf("Not a supported SAO types\n");
1278        assert(0);
1279        exit(-1);
1280      }
1281    }
1282  }
1283}
1284
1285
1286//! \}
Note: See TracBrowser for help on using the repository browser.