Coverage Report

Created: 2026-12-01 06:52

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/work/vvenc/source/Lib/EncoderLib/EncPicture.cpp
Line
Count
Source
1
/* -----------------------------------------------------------------------------
2
The copyright in this software is being made available under the Clear BSD
3
License, included below. No patent rights, trademark rights and/or 
4
other Intellectual Property Rights other than the copyrights concerning 
5
the Software are granted under this license.
6
7
The Clear BSD License
8
9
Copyright (c) 2019-2026, Fraunhofer-Gesellschaft zur Förderung der angewandten Forschung e.V. & The VVenC Authors.
10
All rights reserved.
11
12
Redistribution and use in source and binary forms, with or without modification,
13
are permitted (subject to the limitations in the disclaimer below) provided that
14
the following conditions are met:
15
16
     * Redistributions of source code must retain the above copyright notice,
17
     this list of conditions and the following disclaimer.
18
19
     * Redistributions in binary form must reproduce the above copyright
20
     notice, this list of conditions and the following disclaimer in the
21
     documentation and/or other materials provided with the distribution.
22
23
     * Neither the name of the copyright holder nor the names of its
24
     contributors may be used to endorse or promote products derived from this
25
     software without specific prior written permission.
26
27
NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY
28
THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
29
CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
30
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
31
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
32
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
33
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
34
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
35
BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
36
IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
37
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
38
POSSIBILITY OF SUCH DAMAGE.
39
40
41
------------------------------------------------------------------------------------------- */
42
43
44
/** \file     EncPicture.cpp
45
    \brief    encode picture
46
*/
47
48
#include "EncPicture.h"
49
#include "EncGOP.h"
50
#include "CommonLib/UnitTools.h"
51
#include "CommonLib/CommonDef.h"
52
#include "CommonLib/dtrace_buffer.h"
53
#include "CommonLib/dtrace_codingstruct.h"
54
55
//! \ingroup EncoderLib
56
//! \{
57
58
namespace vvenc {
59
60
#ifdef TRACE_ENABLE_ITT
61
static __itt_string_handle* itt_handle_start = __itt_string_handle_create( "PicEnc" );
62
static __itt_domain* itt_domain_picEncoder   = __itt_domain_create( "PictureEncoder" );
63
#endif
64
65
// ---------------------------------------------------------------------------------------------------------------------
66
67
void EncPicture::init( const VVEncCfg& encCfg,
68
                       std::vector<int>* const globalCtuQpVector,
69
                       const SPS& sps,
70
                       const PPS& pps,
71
                       RateCtrl& rateCtrl,
72
                       NoMallocThreadPool* threadPool,
73
                       ThreadRsrcPool& threadRsrc,
74
                       std::function<void( Picture& )> apsReady )
75
5.72k
{
76
5.72k
  m_pcEncCfg = &encCfg;
77
78
5.72k
  if( encCfg.m_alf || encCfg.m_ccalf )
79
5.72k
    m_ALF       .init( encCfg, pps, m_CABACEstimator, m_CtxCache, threadPool );
80
81
5.72k
  m_SliceEncoder.init( encCfg, sps, pps, globalCtuQpVector, m_LoopFilter, m_ALF, rateCtrl, threadPool, threadRsrc, &m_ctuTasksDoneCounter );
82
5.72k
  m_pcRateCtrl = &rateCtrl;
83
84
  // With IFP, the pictures that predict their ALF APSs from this one need its APSs, which are final once the ALF and
85
  // CC-ALF filters are derived from the first CTU lines. They get them then, not at the end of the picture.
86
5.72k
  if( encCfg.m_ifpLines && encCfg.m_alf && encCfg.m_alfTempPred )
87
0
  {
88
0
    m_SliceEncoder.m_alfFiltersDerived = [this, apsReady]( Picture& pic )
89
0
    {
90
0
      if( !pic.picApsGlobal )
91
0
        return;
92
0
      pic.picApsMap.setApsIdStart( m_ALF.getApsIdStart() );
93
0
      xCopyApsToGlobal( pic );
94
0
      m_apsCopiedEarly = true;
95
0
      apsReady( pic );
96
0
    };
97
0
  }
98
5.72k
}
99
100
101
void EncPicture::compressPicture( Picture& pic, EncGOP& gopEncoder )
102
1.43k
{
103
1.43k
  PROFILER_SCOPE_TOP_LEVEL_EXT( 1, g_timeProfiler, P_TOP_LEVEL, pic.cs );
104
1.43k
  ITT_TASKSTART( itt_domain_picEncoder, itt_handle_start );
105
106
1.43k
  pic.encTime.startTimer();
107
108
1.43k
  pic.createEncodingBuffers();
109
  // Reserve the picture-level CU and TU lists for one unit per 4x4 block, which avoids growing them
110
  // while the CTU results are appended. They are only needed while the picture is encoded, and
111
  // finalizePicture releases them.
112
1.43k
  pic.cs->allocateVectorsAtPicLevel();
113
1.43k
  pic.cs->createCoeffs();
114
1.43k
  pic.cs->createTempBuffers( true );
115
1.43k
  pic.cs->initStructData( MAX_INT, false, nullptr );
116
117
  // compress picture
118
1.43k
  xInitPicEncoder( pic );
119
120
  // compress current slice
121
1.43k
  pic.cs->slice = pic.slices[0];
122
1.43k
  std::fill( pic.ctuSlice.begin(), pic.ctuSlice.end(), pic.slices[0] );
123
1.43k
  m_SliceEncoder.compressSlice( &pic );
124
125
1.43k
  ITT_TASKEND( itt_domain_picEncoder, itt_handle_start );
126
1.43k
}
127
128
// What the pictures referencing this one read besides the reconstruction and motion: the CC-ALF parameters in the slice
129
// and the ALF APSs in the global list. After it the picture can be referenced (isReconstructed).
130
void EncPicture::finalizeReference( Picture& pic )
131
1.43k
{
132
1.43k
  PROFILER_SCOPE_TOP_LEVEL_EXT( 1, g_timeProfiler, P_TOP_LEVEL, pic.cs );
133
1.43k
  CodingStructure& cs = *(pic.cs);
134
1.43k
  Slice* slice        = pic.slices[0];
135
  // ALF
136
1.43k
  if( slice->sps->alfEnabled )
137
1.43k
  {
138
#ifdef TRACE_ENABLE_ITT
139
    std::stringstream ss;
140
    ss << "ALF_post_" << slice->poc;
141
    __itt_string_handle* itt_handle_post = __itt_string_handle_create( ss.str().c_str() );
142
#endif
143
1.43k
    pic.picApsMap.setApsIdStart( m_ALF.getApsIdStart() );
144
145
1.43k
    cs.slice->ccAlfFilterParam      = m_ALF.getCcAlfFilterParam();
146
1.43k
    cs.slice->ccAlfFilterControl[0] = m_ALF.getCcAlfControlIdc(COMP_Cb);
147
1.43k
    cs.slice->ccAlfFilterControl[1] = m_ALF.getCcAlfControlIdc(COMP_Cr);
148
149
1.43k
    DTRACE( g_trace_ctx, D_CRC, "ALF" );
150
1.43k
    DTRACE_CRC( g_trace_ctx, D_CRC, cs, cs.getRecoBuf() );
151
1.43k
    DTRACE_PIC_COMP( D_REC_CB_LUMA_ALF,   cs, cs.getRecoBuf(), COMP_Y  );
152
1.43k
    DTRACE_PIC_COMP( D_REC_CB_CHROMA_ALF, cs, cs.getRecoBuf(), COMP_Cb );
153
1.43k
    DTRACE_PIC_COMP( D_REC_CB_CHROMA_ALF, cs, cs.getRecoBuf(), COMP_Cr );
154
1.43k
  }
155
156
  // copy ALF APSs to global list, unless that was done at the ALF derivation (IFP), as pictures may read them already
157
1.43k
  CHECK( m_pcEncCfg->m_alf && m_pcEncCfg->m_alfTempPred && !pic.picApsGlobal, "Missing APS from top level" );
158
1.43k
  if( pic.picApsGlobal && !m_apsCopiedEarly )
159
1.43k
  {
160
1.43k
    xCopyApsToGlobal( pic );
161
1.43k
  }
162
1.43k
  m_apsCopiedEarly = false;
163
1.43k
}
164
165
// The serial rest of the picture's encoding, which the pictures referencing it do not read.
166
void EncPicture::finalizePicture( Picture& pic )
167
1.43k
{
168
1.43k
  PROFILER_SCOPE_TOP_LEVEL_EXT( 1, g_timeProfiler, P_TOP_LEVEL, pic.cs );
169
1.43k
  const Slice* slice = pic.slices[0];
170
171
  // write picture
172
1.43k
  DTRACE_UPDATE( g_trace_ctx, std::make_pair( "bsfinal", 1 ) );
173
1.43k
  xWriteSliceData( pic );
174
1.43k
  DTRACE_UPDATE( g_trace_ctx, std::make_pair( "bsfinal", 0 ) );
175
176
1.43k
  xCalcDistortion( pic, *slice->sps );
177
178
  // finalize
179
1.43k
  if ( m_pcEncCfg->m_useAMaxBT )
180
0
  {
181
0
    pic.picBlkStat.storeBlkSize( pic );
182
0
  }
183
184
  // cleanup
185
1.43k
  pic.cs->releaseIntermediateData();
186
1.43k
  pic.cs->releaseVectorsAtPicLevel();
187
1.43k
  pic.cs->destroyTempBuffers();
188
1.43k
  pic.cs->destroyCoeffs();
189
  // Later pictures read only the colocated motion field of this one.
190
1.43k
  pic.cs->destroyFullMotionBuf();
191
192
1.43k
  pic.encTime.stopTimer();
193
1.43k
}
194
195
void EncPicture::xCopyApsToGlobal( Picture& pic )
196
1.43k
{
197
1.43k
  CHECK( pic.picApsGlobal->poc != pic.poc, "Global APS POC must be consistent with picture poc" );
198
1.43k
  const ParameterSetMap<APS>& src = pic.picApsMap;
199
1.43k
  ParameterSetMap<APS>&       dst = pic.picApsGlobal->apsMap;
200
12.8k
  for( int i = 0; i < ALF_CTB_MAX_NUM_APS; i++ )
201
11.4k
  {
202
11.4k
    const int apsMapIdx = ( i << NUM_APS_TYPE_LEN ) + ALF_APS;
203
11.4k
    const APS* srcAPS = src.getPS( apsMapIdx );
204
11.4k
    if( srcAPS )
205
0
    {
206
0
      APS* dstAPS = dst.allocatePS( apsMapIdx );
207
0
      *dstAPS = *srcAPS;
208
0
    }
209
11.4k
  }
210
1.43k
  dst.setApsIdStart( src.getApsIdStart() );
211
1.43k
}
212
213
uint64_t findDistortionPlane( const CPelBuf& pic0, const CPelBuf& pic1, uint32_t rshift )
214
4.29k
{
215
4.29k
  uint64_t uiTotalDiff;
216
4.29k
  const  Pel*  pSrc0 = pic0.bufAt(0, 0);
217
4.29k
  const  Pel*  pSrc1 = pic1.bufAt(0, 0);
218
219
4.29k
  CHECK(pic0.width  != pic1.width , "Unspecified error");
220
4.29k
  CHECK(pic0.height != pic1.height, "Unspecified error");
221
222
4.29k
  if( rshift > 0 )
223
0
  {
224
0
    uiTotalDiff = 0;
225
0
    for (int y = 0; y < pic0.height; y++)
226
0
    {
227
0
      for (int x = 0; x < pic0.width; x++)
228
0
      {
229
0
        Intermediate_Int iTemp = pSrc0[x] - pSrc1[x];
230
0
        uiTotalDiff += uint64_t((iTemp * iTemp) >> rshift);
231
0
      }
232
0
      pSrc0 += pic0.stride;
233
0
      pSrc1 += pic1.stride;
234
0
    }
235
0
  }
236
4.29k
  else
237
4.29k
  {
238
4.29k
    uiTotalDiff = g_pelBufOP.sumSquaredError( pSrc0, pic0.stride, pSrc1, pic1.stride, pic0.width, pic0.height );
239
4.29k
  }
240
241
4.29k
  return uiTotalDiff;
242
4.29k
}
243
244
void EncPicture::xCalcDistortion( Picture& pic, const SPS& sps )
245
1.43k
{
246
1.43k
  const CPelUnitBuf cPicD = pic.getRecoBuf();
247
1.43k
  const CPelUnitBuf org   = pic.getOrigBuf();
248
1.43k
  const ChromaFormat formatD = cPicD.chromaFormat;
249
1.43k
  const ChromaFormat format  = sps.chromaFormatIdc;
250
251
5.72k
  for (int comp = 0; comp < getNumberValidComponents(formatD); comp++)
252
4.29k
  {
253
4.29k
    const ComponentID compID = ComponentID(comp);
254
4.29k
    const CPelBuf&    p = cPicD.get(compID);
255
4.29k
    const CPelBuf&    o = org.get(compID);
256
257
4.29k
    CHECK(!( p.width  == o.width), "Unspecified error");
258
4.29k
    CHECK(!( p.height == o.height), "Unspecified error");
259
260
4.29k
    const uint32_t   width  = p.width  - (m_pcEncCfg->m_aiPad[ 0 ] >> getComponentScaleX(compID, format));
261
4.29k
    const uint32_t   height = p.height - (m_pcEncCfg->m_aiPad[ 1 ] >> getComponentScaleY(compID, format));
262
263
    // create new buffers with correct dimensions
264
4.29k
    const CPelBuf recPB(p.bufAt(0, 0), p.stride, width, height);
265
4.29k
    const CPelBuf orgPB(o.bufAt(0, 0), o.stride, width, height);
266
4.29k
    const uint32_t    bitDepth = sps.bitDepths[toChannelType(compID)];
267
    //pic.ssd[comp] = findDistortionPlane(recPB, orgPB, 0);
268
4.29k
    const uint64_t uiSSDtemp = findDistortionPlane(recPB, orgPB, 0);
269
4.29k
    const uint32_t maxval = 255 << (bitDepth - 8);
270
4.29k
    const uint32_t size   = width * height;
271
4.29k
    const double fRefValue = (double)maxval * maxval * size;
272
4.29k
    pic.psnr[comp] = uiSSDtemp ? 10.0 * log10(fRefValue / (double)uiSSDtemp) : MAX_DOUBLE;
273
4.29k
    pic.mse [comp] = (double)uiSSDtemp / size;
274
4.29k
  }
275
1.43k
}
276
277
void EncPicture::xInitPicEncoder( Picture& pic )
278
1.43k
{
279
1.43k
  Slice* slice = pic.cs->slice;
280
281
1.43k
  CHECK( slice != pic.slices[0], "Slice pointers don't match!" );
282
283
1.43k
  m_SliceEncoder.initPic( &pic );
284
285
1.43k
  xInitSliceColFromL0Flag( slice );
286
1.43k
  xInitSliceCheckLDC     ( slice );
287
288
1.43k
  if( slice->sps->alfEnabled )
289
1.43k
  {
290
2.86k
    for (int s = 0; s < (int)pic.slices.size(); s++)
291
1.43k
    {
292
1.43k
      pic.slices[s]->alfEnabled[COMP_Y] = false;
293
1.43k
    }
294
1.43k
  }
295
1.43k
}
296
297
298
void EncPicture::xInitSliceColFromL0Flag( Slice* slice ) const
299
1.43k
{
300
1.43k
  if( m_pcEncCfg->m_rprRASLtoolSwitch )
301
0
  {
302
0
    return;
303
0
  }
304
305
1.43k
  if ( slice->sliceType == VVENC_B_SLICE )
306
0
  {
307
0
    const int refIdx = 0; // Zero always assumed
308
0
    const Picture* refPicL0 = slice->getRefPic( REF_PIC_LIST_0, refIdx );
309
0
    const Picture* refPicL1 = slice->getRefPic( REF_PIC_LIST_1, refIdx );
310
0
    slice->colFromL0Flag = ( refPicL0->slices[ 0 ]->sliceQp > refPicL1->slices[ 0 ]->sliceQp );
311
0
  }
312
1.43k
}
313
314
315
void EncPicture::xInitSliceCheckLDC( Slice* slice ) const
316
1.43k
{
317
1.43k
  if ( slice->sliceType == VVENC_B_SLICE )
318
0
  {
319
0
    bool bLowDelay = true;
320
0
    int  iCurrPOC  = slice->poc;
321
0
    int  iRefIdx   = 0;
322
323
0
    for ( iRefIdx = 0; iRefIdx < slice->numRefIdx[ REF_PIC_LIST_0 ] && bLowDelay; iRefIdx++ )
324
0
    {
325
0
      if ( slice->getRefPic( REF_PIC_LIST_0, iRefIdx )->getPOC() > iCurrPOC )
326
0
      {
327
0
        bLowDelay = false;
328
0
      }
329
0
    }
330
0
    for ( iRefIdx = 0; iRefIdx < slice->numRefIdx[ REF_PIC_LIST_1 ] && bLowDelay; iRefIdx++ )
331
0
    {
332
0
      if ( slice->getRefPic( REF_PIC_LIST_1, iRefIdx )->getPOC() > iCurrPOC )
333
0
      {
334
0
        bLowDelay = false;
335
0
      }
336
0
    }
337
338
0
    slice->checkLDC = bLowDelay;
339
0
  }
340
1.43k
  else
341
1.43k
  {
342
1.43k
    slice->checkLDC = true;
343
1.43k
  }
344
1.43k
}
345
346
void EncPicture::xWriteSliceData( Picture& pic )
347
1.43k
{
348
1.43k
  const int numSlices = (int)pic.slices.size();
349
350
1.43k
  pic.sliceDataStreams.clear();
351
1.43k
  pic.sliceDataStreams.resize( numSlices );
352
1.43k
  pic.sliceDataNumBins = 0;
353
354
2.86k
  for ( int i = 0; i < numSlices; i++ )
355
1.43k
  {
356
    // set current slice
357
1.43k
    pic.cs->slice = pic.slices[i];
358
1.43k
    m_SliceEncoder.encodeSliceData( &pic );
359
1.43k
  }
360
1.43k
}
361
362
} // namespace vvenc
363
364
//! \}
365