source: SHVCSoftware/branches/SHM-dev/source/Lib/TLibEncoder/TEncSampleAdaptiveOffset.cpp @ 1442

Last change on this file since 1442 was 1442, checked in by seregin, 9 years ago

port rev 4590

  • Property svn:eol-style set to native
File size: 44.6 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#if SVC_EXTENSION
323      getBlkStats(component, pPic->getSlice(0)->getBitDepth(toChannelType(component)), blkStats[ctuRsAddr][component]
324#else
325      getBlkStats(component, pPic->getPicSym()->getSPS().getBitDepth(toChannelType(component)), blkStats[ctuRsAddr][component]
326#endif
327                , srcBlk, orgBlk, srcStride, orgStride, (width  >> componentScaleX), (height >> componentScaleY)
328                , isLeftAvail,  isRightAvail, isAboveAvail, isBelowAvail, isAboveLeftAvail, isAboveRightAvail
329                , isCalculatePreDeblockSamples
330                );
331
332    }
333  }
334}
335
336Void TEncSampleAdaptiveOffset::decidePicParams(Bool* sliceEnabled, Int picTempLayer, const Double saoEncodingRate, const Double saoEncodingRateChroma)
337{
338  //decide sliceEnabled[compIdx]
339  const Int numberOfComponents = getNumberValidComponents(m_chromaFormatIDC);
340  for (Int compIdx = 0; compIdx < MAX_NUM_COMPONENT; compIdx++)
341  {
342    sliceEnabled[compIdx] = false;
343  }
344
345  for (Int compIdx = 0; compIdx < numberOfComponents; compIdx++)
346  {
347    // reset flags & counters
348    sliceEnabled[compIdx] = true;
349
350    if (saoEncodingRate>0.0)
351    {
352      if (saoEncodingRateChroma>0.0)
353      {
354        // decide slice-level on/off based on previous results
355        if( (picTempLayer > 0)
356          && (m_saoDisabledRate[compIdx][picTempLayer-1] > ((compIdx==COMPONENT_Y) ? saoEncodingRate : saoEncodingRateChroma)) )
357        {
358          sliceEnabled[compIdx] = false;
359        }
360      }
361      else
362      {
363        // decide slice-level on/off based on previous results
364        if( (picTempLayer > 0)
365          && (m_saoDisabledRate[COMPONENT_Y][0] > saoEncodingRate) )
366        {
367          sliceEnabled[compIdx] = false;
368        }
369      }
370    }
371  }
372}
373
374Int64 TEncSampleAdaptiveOffset::getDistortion(const Int channelBitDepth, Int typeIdc, Int typeAuxInfo, Int* invQuantOffset, SAOStatData& statData)
375{
376  Int64 dist        = 0;
377  Int shift         = 2 * DISTORTION_PRECISION_ADJUSTMENT(channelBitDepth - 8);
378
379  switch(typeIdc)
380  {
381    case SAO_TYPE_EO_0:
382    case SAO_TYPE_EO_90:
383    case SAO_TYPE_EO_135:
384    case SAO_TYPE_EO_45:
385      {
386        for (Int offsetIdx=0; offsetIdx<NUM_SAO_EO_CLASSES; offsetIdx++)
387        {
388          dist += estSaoDist( statData.count[offsetIdx], invQuantOffset[offsetIdx], statData.diff[offsetIdx], shift);
389        }
390      }
391      break;
392    case SAO_TYPE_BO:
393      {
394        for (Int offsetIdx=typeAuxInfo; offsetIdx<typeAuxInfo+4; offsetIdx++)
395        {
396          Int bandIdx = offsetIdx % NUM_SAO_BO_CLASSES ;
397          dist += estSaoDist( statData.count[bandIdx], invQuantOffset[bandIdx], statData.diff[bandIdx], shift);
398        }
399      }
400      break;
401    default:
402      {
403        printf("Not a supported type");
404        assert(0);
405        exit(-1);
406      }
407  }
408
409  return dist;
410}
411
412inline Int64 TEncSampleAdaptiveOffset::estSaoDist(Int64 count, Int64 offset, Int64 diffSum, Int shift)
413{
414  return (( count*offset*offset-diffSum*offset*2 ) >> shift);
415}
416
417
418inline Int TEncSampleAdaptiveOffset::estIterOffset(Int typeIdx, Double lambda, Int offsetInput, Int64 count, Int64 diffSum, Int shift, Int bitIncrease, Int64& bestDist, Double& bestCost, Int offsetTh )
419{
420  Int iterOffset, tempOffset;
421  Int64 tempDist, tempRate;
422  Double tempCost, tempMinCost;
423  Int offsetOutput = 0;
424  iterOffset = offsetInput;
425  // 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.
426  tempMinCost = lambda;
427  while (iterOffset != 0)
428  {
429    // Calculate the bits required for signaling the offset
430    tempRate = (typeIdx == SAO_TYPE_BO) ? (abs((Int)iterOffset)+2) : (abs((Int)iterOffset)+1);
431    if (abs((Int)iterOffset)==offsetTh) //inclusive
432    {
433      tempRate --;
434    }
435    // Do the dequantization before distortion calculation
436    tempOffset  = iterOffset << bitIncrease;
437    tempDist    = estSaoDist( count, tempOffset, diffSum, shift);
438    tempCost    = ((Double)tempDist + lambda * (Double) tempRate);
439    if(tempCost < tempMinCost)
440    {
441      tempMinCost = tempCost;
442      offsetOutput = iterOffset;
443      bestDist = tempDist;
444      bestCost = tempCost;
445    }
446    iterOffset = (iterOffset > 0) ? (iterOffset-1):(iterOffset+1);
447  }
448  return offsetOutput;
449}
450
451Void TEncSampleAdaptiveOffset::deriveOffsets(ComponentID compIdx, const Int channelBitDepth, Int typeIdc, SAOStatData& statData, Int* quantOffsets, Int& typeAuxInfo)
452{
453  Int bitDepth = channelBitDepth;
454  Int shift    = 2 * DISTORTION_PRECISION_ADJUSTMENT(bitDepth-8);
455  Int offsetTh = TComSampleAdaptiveOffset::getMaxOffsetQVal(channelBitDepth);  //inclusive
456
457  ::memset(quantOffsets, 0, sizeof(Int)*MAX_NUM_SAO_CLASSES);
458
459  //derive initial offsets
460  Int numClasses = (typeIdc == SAO_TYPE_BO)?((Int)NUM_SAO_BO_CLASSES):((Int)NUM_SAO_EO_CLASSES);
461  for(Int classIdx=0; classIdx< numClasses; classIdx++)
462  {
463    if( (typeIdc != SAO_TYPE_BO) && (classIdx==SAO_CLASS_EO_PLAIN)  )
464    {
465      continue; //offset will be zero
466    }
467
468    if(statData.count[classIdx] == 0)
469    {
470      continue; //offset will be zero
471    }
472
473    quantOffsets[classIdx] = (Int) xRoundIbdi(bitDepth, (Double)( statData.diff[classIdx]<<(bitDepth-8))
474                                                                  /
475                                                          (Double)( statData.count[classIdx]<< m_offsetStepLog2[compIdx])
476                                               );
477    quantOffsets[classIdx] = Clip3(-offsetTh, offsetTh, quantOffsets[classIdx]);
478  }
479
480  // adjust offsets
481  switch(typeIdc)
482  {
483    case SAO_TYPE_EO_0:
484    case SAO_TYPE_EO_90:
485    case SAO_TYPE_EO_135:
486    case SAO_TYPE_EO_45:
487      {
488        Int64 classDist;
489        Double classCost;
490        for(Int classIdx=0; classIdx<NUM_SAO_EO_CLASSES; classIdx++)
491        {
492          if(classIdx==SAO_CLASS_EO_FULL_VALLEY && quantOffsets[classIdx] < 0)
493          {
494            quantOffsets[classIdx] =0;
495          }
496          if(classIdx==SAO_CLASS_EO_HALF_VALLEY && quantOffsets[classIdx] < 0)
497          {
498            quantOffsets[classIdx] =0;
499          }
500          if(classIdx==SAO_CLASS_EO_HALF_PEAK   && quantOffsets[classIdx] > 0)
501          {
502            quantOffsets[classIdx] =0;
503          }
504          if(classIdx==SAO_CLASS_EO_FULL_PEAK   && quantOffsets[classIdx] > 0)
505          {
506            quantOffsets[classIdx] =0;
507          }
508
509          if( quantOffsets[classIdx] != 0 ) //iterative adjustment only when derived offset is not zero
510          {
511            quantOffsets[classIdx] = estIterOffset( typeIdc, m_lambda[compIdx], quantOffsets[classIdx], statData.count[classIdx], statData.diff[classIdx], shift, m_offsetStepLog2[compIdx], classDist , classCost , offsetTh );
512          }
513        }
514
515        typeAuxInfo =0;
516      }
517      break;
518    case SAO_TYPE_BO:
519      {
520        Int64  distBOClasses[NUM_SAO_BO_CLASSES];
521        Double costBOClasses[NUM_SAO_BO_CLASSES];
522        ::memset(distBOClasses, 0, sizeof(Int64)*NUM_SAO_BO_CLASSES);
523        for(Int classIdx=0; classIdx< NUM_SAO_BO_CLASSES; classIdx++)
524        {
525          costBOClasses[classIdx]= m_lambda[compIdx];
526          if( quantOffsets[classIdx] != 0 ) //iterative adjustment only when derived offset is not zero
527          {
528            quantOffsets[classIdx] = estIterOffset( typeIdc, m_lambda[compIdx], quantOffsets[classIdx], statData.count[classIdx], statData.diff[classIdx], shift, m_offsetStepLog2[compIdx], distBOClasses[classIdx], costBOClasses[classIdx], offsetTh );
529          }
530        }
531
532        //decide the starting band index
533        Double minCost = MAX_DOUBLE, cost;
534        for(Int band=0; band< NUM_SAO_BO_CLASSES- 4+ 1; band++)
535        {
536          cost  = costBOClasses[band  ];
537          cost += costBOClasses[band+1];
538          cost += costBOClasses[band+2];
539          cost += costBOClasses[band+3];
540
541          if(cost < minCost)
542          {
543            minCost = cost;
544            typeAuxInfo = band;
545          }
546        }
547        //clear those unused classes
548        Int clearQuantOffset[NUM_SAO_BO_CLASSES];
549        ::memset(clearQuantOffset, 0, sizeof(Int)*NUM_SAO_BO_CLASSES);
550        for(Int i=0; i< 4; i++)
551        {
552          Int band = (typeAuxInfo+i)%NUM_SAO_BO_CLASSES;
553          clearQuantOffset[band] = quantOffsets[band];
554        }
555        ::memcpy(quantOffsets, clearQuantOffset, sizeof(Int)*NUM_SAO_BO_CLASSES);
556      }
557      break;
558    default:
559      {
560        printf("Not a supported type");
561        assert(0);
562        exit(-1);
563      }
564
565  }
566
567
568}
569
570Void 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)
571{
572  Double minCost, cost;
573  UInt previousWrittenBits;
574  const Int numberOfComponents = getNumberValidComponents(m_chromaFormatIDC);
575
576  Int64 dist[MAX_NUM_COMPONENT], modeDist[MAX_NUM_COMPONENT];
577  SAOOffset testOffset[MAX_NUM_COMPONENT];
578  Int invQuantOffset[MAX_NUM_SAO_CLASSES];
579  for(Int comp=0; comp < MAX_NUM_COMPONENT; comp++)
580  {
581    modeDist[comp] = 0;
582  }
583
584  //pre-encode merge flags
585  modeParam[COMPONENT_Y].modeIdc = SAO_MODE_OFF;
586  m_pcRDGoOnSbacCoder->load(cabacCoderRDO[inCabacLabel]);
587  m_pcRDGoOnSbacCoder->codeSAOBlkParam(modeParam, bitDepths, sliceEnabled, (mergeList[SAO_MERGE_LEFT]!= NULL), (mergeList[SAO_MERGE_ABOVE]!= NULL), true);
588  m_pcRDGoOnSbacCoder->store(cabacCoderRDO[SAO_CABACSTATE_BLK_MID]);
589
590    //------ luma --------//
591  {
592    const ComponentID compIdx = COMPONENT_Y;
593    //"off" case as initial cost
594    modeParam[compIdx].modeIdc = SAO_MODE_OFF;
595    m_pcRDGoOnSbacCoder->resetBits();
596    m_pcRDGoOnSbacCoder->codeSAOOffsetParam(compIdx, modeParam[compIdx], sliceEnabled[compIdx], bitDepths.recon[CHANNEL_TYPE_LUMA]);
597    modeDist[compIdx] = 0;
598    minCost= m_lambda[compIdx]*((Double)m_pcRDGoOnSbacCoder->getNumberOfWrittenBits());
599    m_pcRDGoOnSbacCoder->store(cabacCoderRDO[SAO_CABACSTATE_BLK_TEMP]);
600    if(sliceEnabled[compIdx])
601    {
602      for(Int typeIdc=0; typeIdc< NUM_SAO_NEW_TYPES; typeIdc++)
603      {
604        testOffset[compIdx].modeIdc = SAO_MODE_NEW;
605        testOffset[compIdx].typeIdc = typeIdc;
606
607        //derive coded offset
608        deriveOffsets(compIdx, bitDepths.recon[CHANNEL_TYPE_LUMA], typeIdc, blkStats[ctuRsAddr][compIdx][typeIdc], testOffset[compIdx].offset, testOffset[compIdx].typeAuxInfo);
609
610        //inversed quantized offsets
611        invertQuantOffsets(compIdx, typeIdc, testOffset[compIdx].typeAuxInfo, invQuantOffset, testOffset[compIdx].offset);
612
613        //get distortion
614        dist[compIdx] = getDistortion(bitDepths.recon[CHANNEL_TYPE_LUMA], testOffset[compIdx].typeIdc, testOffset[compIdx].typeAuxInfo, invQuantOffset, blkStats[ctuRsAddr][compIdx][typeIdc]);
615
616        //get rate
617        m_pcRDGoOnSbacCoder->load(cabacCoderRDO[SAO_CABACSTATE_BLK_MID]);
618        m_pcRDGoOnSbacCoder->resetBits();
619        m_pcRDGoOnSbacCoder->codeSAOOffsetParam(compIdx, testOffset[compIdx], sliceEnabled[compIdx], bitDepths.recon[CHANNEL_TYPE_LUMA]);
620        Int rate = m_pcRDGoOnSbacCoder->getNumberOfWrittenBits();
621        cost = (Double)dist[compIdx] + m_lambda[compIdx]*((Double)rate);
622        if(cost < minCost)
623        {
624          minCost = cost;
625          modeDist[compIdx] = dist[compIdx];
626          modeParam[compIdx]= testOffset[compIdx];
627          m_pcRDGoOnSbacCoder->store(cabacCoderRDO[SAO_CABACSTATE_BLK_TEMP]);
628        }
629      }
630    }
631    m_pcRDGoOnSbacCoder->load(cabacCoderRDO[SAO_CABACSTATE_BLK_TEMP]);
632    m_pcRDGoOnSbacCoder->store(cabacCoderRDO[SAO_CABACSTATE_BLK_MID]);
633  }
634
635  //------ chroma --------//
636//"off" case as initial cost
637  cost = 0;
638  previousWrittenBits = 0;
639  m_pcRDGoOnSbacCoder->resetBits();
640  for(UInt componentIndex = COMPONENT_Cb; componentIndex < numberOfComponents; componentIndex++)
641  {
642    const ComponentID component = ComponentID(componentIndex);
643
644    modeParam[component].modeIdc = SAO_MODE_OFF;
645    modeDist [component]         = 0;
646    m_pcRDGoOnSbacCoder->codeSAOOffsetParam(component, modeParam[component], sliceEnabled[component], bitDepths.recon[CHANNEL_TYPE_CHROMA]);
647   
648    const UInt currentWrittenBits = m_pcRDGoOnSbacCoder->getNumberOfWrittenBits();
649    cost += m_lambda[component] * (currentWrittenBits - previousWrittenBits);
650    previousWrittenBits = currentWrittenBits;
651  }
652
653  minCost = cost;
654
655  //doesn't need to store cabac status here since the whole CTU parameters will be re-encoded at the end of this function
656
657  for(Int typeIdc=0; typeIdc< NUM_SAO_NEW_TYPES; typeIdc++)
658  {
659    m_pcRDGoOnSbacCoder->load(cabacCoderRDO[SAO_CABACSTATE_BLK_MID]);
660    m_pcRDGoOnSbacCoder->resetBits();
661    previousWrittenBits = 0;
662    cost = 0;
663
664    for(UInt componentIndex = COMPONENT_Cb; componentIndex < numberOfComponents; componentIndex++)
665    {
666      const ComponentID component = ComponentID(componentIndex);
667      if(!sliceEnabled[component])
668      {
669        testOffset[component].modeIdc = SAO_MODE_OFF;
670        dist[component]= 0;
671        continue;
672      }
673      testOffset[component].modeIdc = SAO_MODE_NEW;
674      testOffset[component].typeIdc = typeIdc;
675
676      //derive offset & get distortion
677      deriveOffsets(component, bitDepths.recon[CHANNEL_TYPE_CHROMA], typeIdc, blkStats[ctuRsAddr][component][typeIdc], testOffset[component].offset, testOffset[component].typeAuxInfo);
678      invertQuantOffsets(component, typeIdc, testOffset[component].typeAuxInfo, invQuantOffset, testOffset[component].offset);
679      dist[component] = getDistortion(bitDepths.recon[CHANNEL_TYPE_CHROMA], typeIdc, testOffset[component].typeAuxInfo, invQuantOffset, blkStats[ctuRsAddr][component][typeIdc]);
680
681      m_pcRDGoOnSbacCoder->codeSAOOffsetParam(component, testOffset[component], sliceEnabled[component], bitDepths.recon[CHANNEL_TYPE_CHROMA]);
682
683      const UInt currentWrittenBits = m_pcRDGoOnSbacCoder->getNumberOfWrittenBits();
684      cost += dist[component] + (m_lambda[component] * (currentWrittenBits - previousWrittenBits));
685      previousWrittenBits = currentWrittenBits;
686    }
687
688    if(cost < minCost)
689    {
690      minCost = cost;
691      for(UInt componentIndex = COMPONENT_Cb; componentIndex < numberOfComponents; componentIndex++)
692      {
693        modeDist[componentIndex]  = dist[componentIndex];
694        modeParam[componentIndex] = testOffset[componentIndex];
695      }
696    }
697
698  } // SAO_TYPE loop
699
700  //----- re-gen rate & normalized cost----//
701  modeNormCost = 0;
702  for(UInt componentIndex = COMPONENT_Y; componentIndex < numberOfComponents; componentIndex++)
703  {
704    modeNormCost += (Double)modeDist[componentIndex] / m_lambda[componentIndex];
705  }
706
707  m_pcRDGoOnSbacCoder->load(cabacCoderRDO[inCabacLabel]);
708  m_pcRDGoOnSbacCoder->resetBits();
709  m_pcRDGoOnSbacCoder->codeSAOBlkParam(modeParam, bitDepths, sliceEnabled, (mergeList[SAO_MERGE_LEFT]!= NULL), (mergeList[SAO_MERGE_ABOVE]!= NULL), false);
710  modeNormCost += (Double)m_pcRDGoOnSbacCoder->getNumberOfWrittenBits();
711}
712
713Void 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)
714{
715  modeNormCost = MAX_DOUBLE;
716
717  Double cost;
718  SAOBlkParam testBlkParam;
719  const Int numberOfComponents = getNumberValidComponents(m_chromaFormatIDC);
720
721  for(Int mergeType=0; mergeType< NUM_SAO_MERGE_TYPES; mergeType++)
722  {
723    if(mergeList[mergeType] == NULL)
724    {
725      continue;
726    }
727
728    testBlkParam = *(mergeList[mergeType]);
729    //normalized distortion
730    Double normDist=0;
731    for(Int compIdx = 0; compIdx < numberOfComponents; compIdx++)
732    {
733      testBlkParam[compIdx].modeIdc = SAO_MODE_MERGE;
734      testBlkParam[compIdx].typeIdc = mergeType;
735
736      SAOOffset& mergedOffsetParam = (*(mergeList[mergeType]))[compIdx];
737
738      if( mergedOffsetParam.modeIdc != SAO_MODE_OFF)
739      {
740        //offsets have been reconstructed. Don't call inversed quantization function.
741        normDist += (((Double)getDistortion(bitDepths.recon[toChannelType(ComponentID(compIdx))], mergedOffsetParam.typeIdc, mergedOffsetParam.typeAuxInfo, mergedOffsetParam.offset, blkStats[ctuRsAddr][compIdx][mergedOffsetParam.typeIdc]))
742                       /m_lambda[compIdx]
743                    );
744      }
745
746    }
747
748    //rate
749    m_pcRDGoOnSbacCoder->load(cabacCoderRDO[inCabacLabel]);
750    m_pcRDGoOnSbacCoder->resetBits();
751    m_pcRDGoOnSbacCoder->codeSAOBlkParam(testBlkParam, bitDepths, sliceEnabled, (mergeList[SAO_MERGE_LEFT]!= NULL), (mergeList[SAO_MERGE_ABOVE]!= NULL), false);
752    Int rate = m_pcRDGoOnSbacCoder->getNumberOfWrittenBits();
753
754    cost = normDist+(Double)rate;
755
756    if(cost < modeNormCost)
757    {
758      modeNormCost = cost;
759      modeParam    = testBlkParam;
760      m_pcRDGoOnSbacCoder->store(cabacCoderRDO[SAO_CABACSTATE_BLK_TEMP]);
761    }
762  }
763
764  m_pcRDGoOnSbacCoder->load(cabacCoderRDO[SAO_CABACSTATE_BLK_TEMP]);
765}
766
767Void TEncSampleAdaptiveOffset::decideBlkParams(TComPic* pic, Bool* sliceEnabled, SAOStatData*** blkStats, TComPicYuv* srcYuv, TComPicYuv* resYuv,
768                                               SAOBlkParam* reconParams, SAOBlkParam* codedParams, const Bool bTestSAODisableAtPictureLevel,
769                                               const Double saoEncodingRate, const Double saoEncodingRateChroma)
770{
771  Bool allBlksDisabled = true;
772  const Int numberOfComponents = getNumberValidComponents(m_chromaFormatIDC);
773  for(Int compId = COMPONENT_Y; compId < numberOfComponents; compId++)
774  {
775    if (sliceEnabled[compId])
776    {
777      allBlksDisabled = false;
778    }
779  }
780
781  m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[ SAO_CABACSTATE_PIC_INIT ]);
782
783  SAOBlkParam modeParam;
784  Double minCost, modeCost;
785
786
787  Double totalCost = 0; // Used if bTestSAODisableAtPictureLevel==true
788
789  for(Int ctuRsAddr=0; ctuRsAddr< m_numCTUsPic; ctuRsAddr++)
790  {
791    if(allBlksDisabled)
792    {
793      codedParams[ctuRsAddr].reset();
794      continue;
795    }
796
797    m_pcRDGoOnSbacCoder->store(m_pppcRDSbacCoder[ SAO_CABACSTATE_BLK_CUR ]);
798
799    //get merge list
800    SAOBlkParam* mergeList[NUM_SAO_MERGE_TYPES] = { NULL };
801    getMergeList(pic, ctuRsAddr, reconParams, mergeList);
802
803    minCost = MAX_DOUBLE;
804    for(Int mode=0; mode < NUM_SAO_MODES; mode++)
805    {
806      switch(mode)
807      {
808      case SAO_MODE_OFF:
809        {
810          continue; //not necessary, since all-off case will be tested in SAO_MODE_NEW case.
811        }
812        break;
813      case SAO_MODE_NEW:
814        {
815#if SVC_EXTENSION
816          deriveModeNewRDO(pic->getSlice(0)->getBitDepths(), ctuRsAddr, mergeList, sliceEnabled, blkStats, modeParam, modeCost, m_pppcRDSbacCoder, SAO_CABACSTATE_BLK_CUR);
817#else
818          deriveModeNewRDO(pic->getPicSym()->getSPS().getBitDepths(), ctuRsAddr, mergeList, sliceEnabled, blkStats, modeParam, modeCost, m_pppcRDSbacCoder, SAO_CABACSTATE_BLK_CUR);
819#endif
820
821        }
822        break;
823      case SAO_MODE_MERGE:
824        {
825#if SVC_EXTENSION
826          deriveModeMergeRDO(pic->getSlice(0)->getBitDepths(), ctuRsAddr, mergeList, sliceEnabled, blkStats , modeParam, modeCost, m_pppcRDSbacCoder, SAO_CABACSTATE_BLK_CUR);
827#else
828          deriveModeMergeRDO(pic->getPicSym()->getSPS().getBitDepths(), ctuRsAddr, mergeList, sliceEnabled, blkStats , modeParam, modeCost, m_pppcRDSbacCoder, SAO_CABACSTATE_BLK_CUR);
829#endif
830        }
831        break;
832      default:
833        {
834          printf("Not a supported SAO mode\n");
835          assert(0);
836          exit(-1);
837        }
838      }
839
840      if(modeCost < minCost)
841      {
842        minCost = modeCost;
843        codedParams[ctuRsAddr] = modeParam;
844        m_pcRDGoOnSbacCoder->store(m_pppcRDSbacCoder[ SAO_CABACSTATE_BLK_NEXT ]);
845      }
846    } //mode
847
848    totalCost += minCost;
849
850    m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[ SAO_CABACSTATE_BLK_NEXT ]);
851
852    //apply reconstructed offsets
853    reconParams[ctuRsAddr] = codedParams[ctuRsAddr];
854    reconstructBlkSAOParam(reconParams[ctuRsAddr], mergeList);
855    offsetCTU(ctuRsAddr, srcYuv, resYuv, reconParams[ctuRsAddr], pic);
856  } //ctuRsAddr
857
858  if (!allBlksDisabled && (totalCost >= 0) && bTestSAODisableAtPictureLevel) //SAO has not beneficial in this case - disable it
859  {
860    for(Int ctuRsAddr = 0; ctuRsAddr < m_numCTUsPic; ctuRsAddr++)
861    {
862      codedParams[ctuRsAddr].reset();
863    }
864
865    for (UInt componentIndex = 0; componentIndex < MAX_NUM_COMPONENT; componentIndex++)
866    {
867      sliceEnabled[componentIndex] = false;
868    }
869
870    m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[ SAO_CABACSTATE_PIC_INIT ]);
871  }
872
873  if (saoEncodingRate > 0.0)
874  {
875    Int picTempLayer = pic->getSlice(0)->getDepth();
876    Int numCtusForSAOOff[MAX_NUM_COMPONENT];
877
878    for (Int compIdx = 0; compIdx < numberOfComponents; compIdx++)
879    {
880      numCtusForSAOOff[compIdx] = 0;
881      for(Int ctuRsAddr=0; ctuRsAddr< m_numCTUsPic; ctuRsAddr++)
882      {
883        if( reconParams[ctuRsAddr][compIdx].modeIdc == SAO_MODE_OFF)
884        {
885          numCtusForSAOOff[compIdx]++;
886        }
887      }
888    }
889    if (saoEncodingRateChroma > 0.0)
890    {
891      for (Int compIdx = 0; compIdx < numberOfComponents; compIdx++)
892      {
893        m_saoDisabledRate[compIdx][picTempLayer] = (Double)numCtusForSAOOff[compIdx]/(Double)m_numCTUsPic;
894      }
895    }
896    else if (picTempLayer == 0)
897    {
898      m_saoDisabledRate[COMPONENT_Y][0] = (Double)(numCtusForSAOOff[COMPONENT_Y]+numCtusForSAOOff[COMPONENT_Cb]+numCtusForSAOOff[COMPONENT_Cr])/(Double)(m_numCTUsPic*3);
899    }
900  }
901}
902
903
904Void TEncSampleAdaptiveOffset::getBlkStats(const ComponentID compIdx, const Int channelBitDepth, SAOStatData* statsDataTypes
905                        , Pel* srcBlk, Pel* orgBlk, Int srcStride, Int orgStride, Int width, Int height
906                        , Bool isLeftAvail,  Bool isRightAvail, Bool isAboveAvail, Bool isBelowAvail, Bool isAboveLeftAvail, Bool isAboveRightAvail
907                        , Bool isCalculatePreDeblockSamples
908                        )
909{
910  if(m_lineBufWidth != m_maxCUWidth)
911  {
912    m_lineBufWidth = m_maxCUWidth;
913
914    if (m_signLineBuf1)
915    {
916      delete[] m_signLineBuf1;
917      m_signLineBuf1 = NULL;
918    }
919    m_signLineBuf1 = new SChar[m_lineBufWidth+1];
920
921    if (m_signLineBuf2)
922    {
923      delete[] m_signLineBuf2;
924      m_signLineBuf2 = NULL;
925    }
926    m_signLineBuf2 = new SChar[m_lineBufWidth+1];
927  }
928
929  Int x,y, startX, startY, endX, endY, edgeType, firstLineStartX, firstLineEndX;
930  SChar signLeft, signRight, signDown;
931  Int64 *diff, *count;
932  Pel *srcLine, *orgLine;
933  Int* skipLinesR = m_skipLinesR[compIdx];
934  Int* skipLinesB = m_skipLinesB[compIdx];
935
936  for(Int typeIdx=0; typeIdx< NUM_SAO_NEW_TYPES; typeIdx++)
937  {
938    SAOStatData& statsData= statsDataTypes[typeIdx];
939    statsData.reset();
940
941    srcLine = srcBlk;
942    orgLine = orgBlk;
943    diff    = statsData.diff;
944    count   = statsData.count;
945    switch(typeIdx)
946    {
947    case SAO_TYPE_EO_0:
948      {
949        diff +=2;
950        count+=2;
951        endY   = (isBelowAvail) ? (height - skipLinesB[typeIdx]) : height;
952        startX = (!isCalculatePreDeblockSamples) ? (isLeftAvail  ? 0 : 1)
953                                                 : (isRightAvail ? (width - skipLinesR[typeIdx]) : (width - 1))
954                                                 ;
955        endX   = (!isCalculatePreDeblockSamples) ? (isRightAvail ? (width - skipLinesR[typeIdx]) : (width - 1))
956                                                 : (isRightAvail ? width : (width - 1))
957                                                 ;
958        for (y=0; y<endY; y++)
959        {
960          signLeft = (SChar)sgn(srcLine[startX] - srcLine[startX-1]);
961          for (x=startX; x<endX; x++)
962          {
963            signRight =  (SChar)sgn(srcLine[x] - srcLine[x+1]);
964            edgeType  =  signRight + signLeft;
965            signLeft  = -signRight;
966
967            diff [edgeType] += (orgLine[x] - srcLine[x]);
968            count[edgeType] ++;
969          }
970          srcLine  += srcStride;
971          orgLine  += orgStride;
972        }
973        if(isCalculatePreDeblockSamples)
974        {
975          if(isBelowAvail)
976          {
977            startX = isLeftAvail  ? 0 : 1;
978            endX   = isRightAvail ? width : (width -1);
979
980            for(y=0; y<skipLinesB[typeIdx]; y++)
981            {
982              signLeft = (SChar)sgn(srcLine[startX] - srcLine[startX-1]);
983              for (x=startX; x<endX; x++)
984              {
985                signRight =  (SChar)sgn(srcLine[x] - srcLine[x+1]);
986                edgeType  =  signRight + signLeft;
987                signLeft  = -signRight;
988
989                diff [edgeType] += (orgLine[x] - srcLine[x]);
990                count[edgeType] ++;
991              }
992              srcLine  += srcStride;
993              orgLine  += orgStride;
994            }
995          }
996        }
997      }
998      break;
999    case SAO_TYPE_EO_90:
1000      {
1001        diff +=2;
1002        count+=2;
1003        SChar *signUpLine = m_signLineBuf1;
1004
1005        startX = (!isCalculatePreDeblockSamples) ? 0
1006                                                 : (isRightAvail ? (width - skipLinesR[typeIdx]) : width)
1007                                                 ;
1008        startY = isAboveAvail ? 0 : 1;
1009        endX   = (!isCalculatePreDeblockSamples) ? (isRightAvail ? (width - skipLinesR[typeIdx]) : width)
1010                                                 : width
1011                                                 ;
1012        endY   = isBelowAvail ? (height - skipLinesB[typeIdx]) : (height - 1);
1013        if (!isAboveAvail)
1014        {
1015          srcLine += srcStride;
1016          orgLine += orgStride;
1017        }
1018
1019        Pel* srcLineAbove = srcLine - srcStride;
1020        for (x=startX; x<endX; x++)
1021        {
1022          signUpLine[x] = (SChar)sgn(srcLine[x] - srcLineAbove[x]);
1023        }
1024
1025        Pel* srcLineBelow;
1026        for (y=startY; y<endY; y++)
1027        {
1028          srcLineBelow = srcLine + srcStride;
1029
1030          for (x=startX; x<endX; x++)
1031          {
1032            signDown  = (SChar)sgn(srcLine[x] - srcLineBelow[x]);
1033            edgeType  = signDown + signUpLine[x];
1034            signUpLine[x]= -signDown;
1035
1036            diff [edgeType] += (orgLine[x] - srcLine[x]);
1037            count[edgeType] ++;
1038          }
1039          srcLine += srcStride;
1040          orgLine += orgStride;
1041        }
1042        if(isCalculatePreDeblockSamples)
1043        {
1044          if(isBelowAvail)
1045          {
1046            startX = 0;
1047            endX   = width;
1048
1049            for(y=0; y<skipLinesB[typeIdx]; y++)
1050            {
1051              srcLineBelow = srcLine + srcStride;
1052              srcLineAbove = srcLine - srcStride;
1053
1054              for (x=startX; x<endX; x++)
1055              {
1056                edgeType = sgn(srcLine[x] - srcLineBelow[x]) + sgn(srcLine[x] - srcLineAbove[x]);
1057                diff [edgeType] += (orgLine[x] - srcLine[x]);
1058                count[edgeType] ++;
1059              }
1060              srcLine  += srcStride;
1061              orgLine  += orgStride;
1062            }
1063          }
1064        }
1065
1066      }
1067      break;
1068    case SAO_TYPE_EO_135:
1069      {
1070        diff +=2;
1071        count+=2;
1072        SChar *signUpLine, *signDownLine, *signTmpLine;
1073
1074        signUpLine  = m_signLineBuf1;
1075        signDownLine= m_signLineBuf2;
1076
1077        startX = (!isCalculatePreDeblockSamples) ? (isLeftAvail  ? 0 : 1)
1078                                                 : (isRightAvail ? (width - skipLinesR[typeIdx]) : (width - 1))
1079                                                 ;
1080
1081        endX   = (!isCalculatePreDeblockSamples) ? (isRightAvail ? (width - skipLinesR[typeIdx]): (width - 1))
1082                                                 : (isRightAvail ? width : (width - 1))
1083                                                 ;
1084        endY   = isBelowAvail ? (height - skipLinesB[typeIdx]) : (height - 1);
1085
1086        //prepare 2nd line's upper sign
1087        Pel* srcLineBelow = srcLine + srcStride;
1088        for (x=startX; x<endX+1; x++)
1089        {
1090          signUpLine[x] = (SChar)sgn(srcLineBelow[x] - srcLine[x-1]);
1091        }
1092
1093        //1st line
1094        Pel* srcLineAbove = srcLine - srcStride;
1095        firstLineStartX = (!isCalculatePreDeblockSamples) ? (isAboveLeftAvail ? 0    : 1) : startX;
1096        firstLineEndX   = (!isCalculatePreDeblockSamples) ? (isAboveAvail     ? endX : 1) : endX;
1097        for(x=firstLineStartX; x<firstLineEndX; x++)
1098        {
1099          edgeType = sgn(srcLine[x] - srcLineAbove[x-1]) - signUpLine[x+1];
1100          diff [edgeType] += (orgLine[x] - srcLine[x]);
1101          count[edgeType] ++;
1102        }
1103        srcLine  += srcStride;
1104        orgLine  += orgStride;
1105
1106
1107        //middle lines
1108        for (y=1; y<endY; y++)
1109        {
1110          srcLineBelow = srcLine + srcStride;
1111
1112          for (x=startX; x<endX; x++)
1113          {
1114            signDown = (SChar)sgn(srcLine[x] - srcLineBelow[x+1]);
1115            edgeType = signDown + signUpLine[x];
1116            diff [edgeType] += (orgLine[x] - srcLine[x]);
1117            count[edgeType] ++;
1118
1119            signDownLine[x+1] = -signDown;
1120          }
1121          signDownLine[startX] = (SChar)sgn(srcLineBelow[startX] - srcLine[startX-1]);
1122
1123          signTmpLine  = signUpLine;
1124          signUpLine   = signDownLine;
1125          signDownLine = signTmpLine;
1126
1127          srcLine += srcStride;
1128          orgLine += orgStride;
1129        }
1130        if(isCalculatePreDeblockSamples)
1131        {
1132          if(isBelowAvail)
1133          {
1134            startX = isLeftAvail  ? 0     : 1 ;
1135            endX   = isRightAvail ? width : (width -1);
1136
1137            for(y=0; y<skipLinesB[typeIdx]; y++)
1138            {
1139              srcLineBelow = srcLine + srcStride;
1140              srcLineAbove = srcLine - srcStride;
1141
1142              for (x=startX; x< endX; x++)
1143              {
1144                edgeType = sgn(srcLine[x] - srcLineBelow[x+1]) + sgn(srcLine[x] - srcLineAbove[x-1]);
1145                diff [edgeType] += (orgLine[x] - srcLine[x]);
1146                count[edgeType] ++;
1147              }
1148              srcLine  += srcStride;
1149              orgLine  += orgStride;
1150            }
1151          }
1152        }
1153      }
1154      break;
1155    case SAO_TYPE_EO_45:
1156      {
1157        diff +=2;
1158        count+=2;
1159        SChar *signUpLine = m_signLineBuf1+1;
1160
1161        startX = (!isCalculatePreDeblockSamples) ? (isLeftAvail  ? 0 : 1)
1162                                                 : (isRightAvail ? (width - skipLinesR[typeIdx]) : (width - 1))
1163                                                 ;
1164        endX   = (!isCalculatePreDeblockSamples) ? (isRightAvail ? (width - skipLinesR[typeIdx]) : (width - 1))
1165                                                 : (isRightAvail ? width : (width - 1))
1166                                                 ;
1167        endY   = isBelowAvail ? (height - skipLinesB[typeIdx]) : (height - 1);
1168
1169        //prepare 2nd line upper sign
1170        Pel* srcLineBelow = srcLine + srcStride;
1171        for (x=startX-1; x<endX; x++)
1172        {
1173          signUpLine[x] = (SChar)sgn(srcLineBelow[x] - srcLine[x+1]);
1174        }
1175
1176
1177        //first line
1178        Pel* srcLineAbove = srcLine - srcStride;
1179        firstLineStartX = (!isCalculatePreDeblockSamples) ? (isAboveAvail ? startX : endX)
1180                                                          : startX
1181                                                          ;
1182        firstLineEndX   = (!isCalculatePreDeblockSamples) ? ((!isRightAvail && isAboveRightAvail) ? width : endX)
1183                                                          : endX
1184                                                          ;
1185        for(x=firstLineStartX; x<firstLineEndX; x++)
1186        {
1187          edgeType = sgn(srcLine[x] - srcLineAbove[x+1]) - signUpLine[x-1];
1188          diff [edgeType] += (orgLine[x] - srcLine[x]);
1189          count[edgeType] ++;
1190        }
1191
1192        srcLine += srcStride;
1193        orgLine += orgStride;
1194
1195        //middle lines
1196        for (y=1; y<endY; y++)
1197        {
1198          srcLineBelow = srcLine + srcStride;
1199
1200          for(x=startX; x<endX; x++)
1201          {
1202            signDown = (SChar)sgn(srcLine[x] - srcLineBelow[x-1]);
1203            edgeType = signDown + signUpLine[x];
1204
1205            diff [edgeType] += (orgLine[x] - srcLine[x]);
1206            count[edgeType] ++;
1207
1208            signUpLine[x-1] = -signDown;
1209          }
1210          signUpLine[endX-1] = (SChar)sgn(srcLineBelow[endX-1] - srcLine[endX]);
1211          srcLine  += srcStride;
1212          orgLine  += orgStride;
1213        }
1214        if(isCalculatePreDeblockSamples)
1215        {
1216          if(isBelowAvail)
1217          {
1218            startX = isLeftAvail  ? 0     : 1 ;
1219            endX   = isRightAvail ? width : (width -1);
1220
1221            for(y=0; y<skipLinesB[typeIdx]; y++)
1222            {
1223              srcLineBelow = srcLine + srcStride;
1224              srcLineAbove = srcLine - srcStride;
1225
1226              for (x=startX; x<endX; x++)
1227              {
1228                edgeType = sgn(srcLine[x] - srcLineBelow[x-1]) + sgn(srcLine[x] - srcLineAbove[x+1]);
1229                diff [edgeType] += (orgLine[x] - srcLine[x]);
1230                count[edgeType] ++;
1231              }
1232              srcLine  += srcStride;
1233              orgLine  += orgStride;
1234            }
1235          }
1236        }
1237      }
1238      break;
1239    case SAO_TYPE_BO:
1240      {
1241        startX = (!isCalculatePreDeblockSamples)?0
1242                                                :( isRightAvail?(width- skipLinesR[typeIdx]):width)
1243                                                ;
1244        endX   = (!isCalculatePreDeblockSamples)?(isRightAvail ? (width - skipLinesR[typeIdx]) : width )
1245                                                :width
1246                                                ;
1247        endY = isBelowAvail ? (height- skipLinesB[typeIdx]) : height;
1248        Int shiftBits = channelBitDepth - NUM_SAO_BO_CLASSES_LOG2;
1249        for (y=0; y< endY; y++)
1250        {
1251          for (x=startX; x< endX; x++)
1252          {
1253
1254            Int bandIdx= srcLine[x] >> shiftBits;
1255            diff [bandIdx] += (orgLine[x] - srcLine[x]);
1256            count[bandIdx] ++;
1257          }
1258          srcLine += srcStride;
1259          orgLine += orgStride;
1260        }
1261        if(isCalculatePreDeblockSamples)
1262        {
1263          if(isBelowAvail)
1264          {
1265            startX = 0;
1266            endX   = width;
1267
1268            for(y= 0; y< skipLinesB[typeIdx]; y++)
1269            {
1270              for (x=startX; x< endX; x++)
1271              {
1272                Int bandIdx= srcLine[x] >> shiftBits;
1273                diff [bandIdx] += (orgLine[x] - srcLine[x]);
1274                count[bandIdx] ++;
1275              }
1276              srcLine  += srcStride;
1277              orgLine  += orgStride;
1278
1279            }
1280
1281          }
1282        }
1283      }
1284      break;
1285    default:
1286      {
1287        printf("Not a supported SAO types\n");
1288        assert(0);
1289        exit(-1);
1290      }
1291    }
1292  }
1293}
1294
1295
1296//! \}
Note: See TracBrowser for help on using the repository browser.