Coverage Report

Created: 2026-12-01 06:52

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/work/vvenc/source/Lib/CommonLib/Contexts.h
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
/** \file     Contexts.h
43
 *  \brief    Classes providing probability descriptions and contexts (header)
44
 */
45
46
#pragma once
47
48
#include "CommonDef.h"
49
#include "Slice.h"
50
51
#include <utility>
52
#include <vector>
53
54
//! \ingroup CommonLib
55
//! \{
56
57
namespace vvenc {
58
59
static constexpr int     PROB_BITS   = 15;   // Nominal number of bits to represent probabilities
60
static constexpr int     PROB_BITS_0 = 10;   // Number of bits to represent 1st estimate
61
static constexpr int     PROB_BITS_1 = 14;   // Number of bits to represent 2nd estimate
62
static constexpr int     MASK_0      = ~(~0u << PROB_BITS_0) << (PROB_BITS - PROB_BITS_0);
63
static constexpr int     MASK_1      = ~(~0u << PROB_BITS_1) << (PROB_BITS - PROB_BITS_1);
64
static constexpr uint8_t DWS         = 8;   // 0x47 Default window sizes
65
66
struct BinFracBits
67
{
68
  uint32_t intBits[2];
69
};
70
71
72
class ProbModelTables
73
{
74
protected:
75
  static const BinFracBits m_binFracBits[256];
76
  static const uint8_t      m_RenormTable_32  [ 32];          // Std         MP   MPI
77
  static const uint16_t     m_upMove0         [ 16];          // ( 0x7fff >> rate ) & MASK_0
78
  static const uint16_t     m_upMove1         [ 16];          // ( 0x7fff >> rate ) & MASK_1
79
};
80
81
82
class BinProbModelBase : public ProbModelTables
83
{
84
public:
85
1.06M
  static uint32_t estFracBitsEP ()                    { return  (       1 << SCALE_BITS ); }
86
8.91M
  static uint32_t estFracBitsEP ( unsigned numBins )  { return  ( numBins << SCALE_BITS ); }
87
};
88
89
90
class BinProbModel : public BinProbModelBase
91
{
92
public:
93
  BinProbModel()
94
49.3M
  {
95
49.3M
    uint16_t half = 1 << (PROB_BITS - 1);
96
49.3M
    m_state[0]    = half;
97
49.3M
    m_state[1]    = half;
98
49.3M
    m_rate        = DWS;
99
49.3M
    m_padding     = 0;
100
49.3M
  }
101
102
public:
103
  void            init              ( int qp, int initId );
104
  void update(unsigned bin)
105
54.9M
  {
106
54.9M
    int rate0 = m_rate >> 4;
107
54.9M
    int rate1 = m_rate & 15;
108
109
54.9M
    m_state[0] -= ( m_state[0] >> rate0 ) & MASK_0;
110
54.9M
    m_state[1] -= ( m_state[1] >> rate1 ) & MASK_1;
111
112
54.9M
    const int mask = -static_cast< int >( bin );
113
54.9M
    m_state[0] += m_upMove0[rate0] & mask;
114
54.9M
    m_state[1] += m_upMove1[rate1] & mask;
115
54.9M
  }
116
  void setLog2WindowSize(uint8_t log2WindowSize)
117
5.36M
  {
118
5.36M
    int rate0 = 2 + ((log2WindowSize >> 2) & 3);
119
5.36M
    int rate1 = 3 + rate0 + (log2WindowSize&  3);
120
5.36M
    m_rate    = 16 * rate0 + rate1;
121
5.36M
    CHECK(rate1 > 9, "Second window size is too large!");
122
5.36M
  }
123
  void estFracBitsUpdate(unsigned bin, uint64_t &b)
124
54.5M
  {
125
54.5M
    b += estFracBits(bin);
126
54.5M
    update(bin);
127
54.5M
  }
128
54.5M
  uint32_t        estFracBits(unsigned bin) const { return getFracBitsArray().intBits[bin]; }
129
0
  static uint32_t estFracBitsTrm(unsigned bin) { return (bin ? 0x3bfbb : 0x0010c); }
130
151M
  const BinFracBits &getFracBitsArray() const { return m_binFracBits[state()]; }
131
public:
132
152M
  uint8_t state() const { return (m_state[0] + m_state[1]) >> 8; }
133
375k
  uint8_t mps() const { return state() >> 7; }
134
  uint8_t getLPS(unsigned range) const
135
375k
  {
136
375k
    uint16_t q = state();
137
375k
    if (q & 0x80)
138
63.8k
      q = q ^ 0xff;
139
375k
    return ((q >> 2) * (range >> 5) >> 1) + 4;
140
375k
  }
141
48.8k
  static uint8_t  getRenormBitsLPS  ( unsigned LPS )                    { return    m_RenormTable_32  [LPS>>3]; }
142
  //static uint8_t  getRenormBitsRange( unsigned range )                  { return    1; }
143
0
  uint16_t getState() const { return m_state[0] + m_state[1]; }
144
  void     setState(uint16_t pState)
145
0
  {
146
0
    m_state[0] = (pState >> 1) & MASK_0;
147
0
    m_state[1] = (pState >> 1) & MASK_1;
148
0
  }
149
public:
150
  uint64_t estFracExcessBits(const BinProbModel &r) const
151
0
  {
152
0
    int n = 2 * state() + 1;
153
0
    return ((512 - n) * r.estFracBits(0) + n * r.estFracBits(1) + 256) >> 9;
154
0
  }
155
private:
156
  uint16_t m_state[2];
157
  uint8_t  m_rate;
158
  uint8_t  m_padding;   // named and set so that all six bytes are defined: RateEstimator::initCtx compares them
159
};
160
161
162
class CtxSet
163
{
164
public:
165
1.79M
  CtxSet( uint16_t offset, uint16_t size ) : Offset( offset ), Size( size ) {}
166
23.5M
  CtxSet( const CtxSet& ctxSet ) : Offset( ctxSet.Offset ), Size( ctxSet.Size ) {}
167
  CtxSet( std::initializer_list<CtxSet> ctxSets );
168
public:
169
  uint16_t  operator()  ()  const
170
2.64M
  {
171
2.64M
    return Offset;
172
2.64M
  }
173
  uint16_t  operator()  ( uint16_t inc )  const
174
153M
  {
175
153M
    CHECKD( inc >= Size, "Specified context increment (" << inc << ") exceed range of context set [0;" << Size - 1 << "]." );
176
153M
    return Offset + inc;
177
153M
  }
178
  bool operator== ( const CtxSet& ctxSet ) const
179
0
  {
180
0
    return ( Offset == ctxSet.Offset && Size == ctxSet.Size );
181
0
  }
182
  bool operator!= ( const CtxSet& ctxSet ) const
183
0
  {
184
0
    return ( Offset != ctxSet.Offset || Size != ctxSet.Size );
185
0
  }
186
1.21M
  uint16_t size() const { return Size; }
187
public:
188
  uint16_t  Offset;
189
  uint16_t  Size;
190
};
191
192
193
class ContextSetCfg
194
{
195
public:
196
  // context sets: specify offset and size
197
  static const CtxSet   SplitFlag;
198
  static const CtxSet   SplitQtFlag;
199
  static const CtxSet   SplitHvFlag;
200
  static const CtxSet   Split12Flag;
201
  static const CtxSet   ModeConsFlag;
202
  static const CtxSet   SkipFlag;
203
204
  // keep these together to
205
  static const CtxSet   MergeFlag;
206
  static const CtxSet   RegularMergeFlag;
207
  static const CtxSet   MergeIdx;
208
  static const CtxSet   MmvdFlag;
209
  static const CtxSet   MmvdMergeIdx;
210
  static const CtxSet   MmvdStepMvpIdx;
211
  static const CtxSet   SubblockMergeFlag;
212
  static const CtxSet   AffMergeIdx;
213
214
  static const CtxSet   PredMode;
215
  static const CtxSet   CclmModeFlag;  
216
  static const CtxSet   CclmModeIdx;
217
  static const CtxSet   IntraChromaPredMode;
218
219
  // keep these for single cpy
220
  static const CtxSet   IntraLumaMpmFlag;
221
  static const CtxSet   IntraLumaPlanarFlag;
222
  static const CtxSet   MultiRefLineIdx;
223
  static const CtxSet   MipFlag;
224
  static const CtxSet   ISPMode;
225
226
  static const CtxSet   DeltaQP;
227
  static const CtxSet   InterDir;
228
  static const CtxSet   RefPic;
229
  static const CtxSet   AffineFlag;
230
  static const CtxSet   AffineType;
231
  static const CtxSet   Mvd;
232
  static const CtxSet   BDPCMMode;
233
  static const CtxSet   QtRootCbf;
234
  static const CtxSet   ACTFlag;
235
  static const CtxSet   QtCbf           [3];    // [ channel ]
236
  static const CtxSet   SigCoeffGroup   [2];    // [ ChannelType ]
237
  static const CtxSet   LastX           [2];    // [ ChannelType ]
238
  static const CtxSet   LastY           [2];    // [ ChannelType ]
239
  static const CtxSet   SigFlag         [6];    // [ ChannelType + State ]
240
  static const CtxSet   ParFlag         [2];    // [ ChannelType ]
241
  static const CtxSet   GtxFlag         [4];    // [ ChannelType + x ]
242
  static const CtxSet   TsSigCoeffGroup;
243
  static const CtxSet   TsSigFlag;
244
  static const CtxSet   TsParFlag;
245
  static const CtxSet   TsGtxFlag;
246
  static const CtxSet   TsLrg1Flag;
247
  static const CtxSet   TsResidualSign;
248
  static const CtxSet   MVPIdx;
249
  static const CtxSet   SaoMergeFlag;
250
  static const CtxSet   SaoTypeIdx;
251
  static const CtxSet   TransformSkipFlag;
252
  static const CtxSet   MTSIdx;
253
  static const CtxSet   LFNSTIdx;
254
  static const CtxSet   PLTFlag;
255
  static const CtxSet   SbtFlag;
256
  static const CtxSet   SbtQuadFlag;
257
  static const CtxSet   SbtHorFlag;
258
  static const CtxSet   SbtPosFlag;
259
  static const CtxSet   ChromaQpAdjFlag;
260
  static const CtxSet   ChromaQpAdjIdc;
261
  static const CtxSet   ImvFlag;
262
  static const CtxSet   BcwIdx;
263
  static const CtxSet   ctbAlfFlag;
264
  static const CtxSet   ctbAlfAlternative;
265
  static const CtxSet   AlfUseTemporalFilt;
266
  static const CtxSet   CcAlfFilterControlFlag;
267
  static const CtxSet   CiipFlag;
268
  static const CtxSet   SmvdFlag;
269
  static const CtxSet   IBCFlag;
270
  static const CtxSet   JointCbCrFlag;
271
  static const unsigned NumberOfContexts;
272
273
  // combined sets for less complex copying
274
  // NOTE: The contained CtxSet's should directly follow each other in the initalization list;
275
  //       otherwise, you will copy more elements than you want !!!
276
  static const CtxSet   Sao;
277
  static const CtxSet   Alf;
278
  static const CtxSet   MergeData;  // the contexts merge_flag and merge_data code
279
public:
280
  static const std::vector<uint8_t>&  getInitTable( unsigned initId );
281
private:
282
  static std::vector<std::vector<uint8_t> > sm_InitTables;
283
  static CtxSet addCtxSet( std::initializer_list<std::initializer_list<uint8_t> > initSet2d );
284
};
285
286
class CtxStore
287
{
288
public:
289
  CtxStore();
290
  CtxStore( bool dummy );
291
  CtxStore( const CtxStore& ctxStore );
292
public:
293
2.71M
  void copyFrom   ( const CtxStore& src )                        { checkInit(); ::memcpy( m_Ctx,               src.m_Ctx,               sizeof( BinProbModel ) * ContextSetCfg::NumberOfContexts ); }
294
3.01M
  void copyFrom   ( const CtxStore& src, const CtxSet& ctxSet )  { checkInit(); ::memcpy( m_Ctx+ctxSet.Offset, src.m_Ctx+ctxSet.Offset, sizeof( BinProbModel ) * ctxSet.Size ); }
295
  // exchanges the contexts of two stores without copying them (both get a buffer first, a default-constructed store has none)
296
389k
  void swap       ( CtxStore& other )                            { checkInit(); other.checkInit(); m_CtxBuffer.swap( other.m_CtxBuffer ); std::swap( m_Ctx, other.m_Ctx ); }
297
  void init       ( int qp, int initId );
298
  void setWinSizes( const std::vector<uint8_t>&   log2WindowSizes );
299
  void loadPStates( const std::vector<uint16_t>&  probStates );
300
  void savePStates( std::vector<uint16_t>&        probStates )  const;
301
302
941k
  const BinProbModel& operator[]      ( unsigned  ctxId  )  const { return m_Ctx[ctxId]; }
303
54.9M
  BinProbModel&       operator[]      ( unsigned  ctxId  )        { return m_Ctx[ctxId]; }
304
  uint32_t            estFracBits     ( unsigned  bin,
305
0
                                        unsigned  ctxId  )  const { return m_Ctx[ctxId].estFracBits(bin); }
306
307
96.7M
  const BinFracBits  &getFracBitsArray( unsigned  ctxId  )  const { return m_Ctx[ctxId].getFracBitsArray(); }
308
309
private:
310
6.51M
  inline void checkInit() { if( m_Ctx ) return; m_CtxBuffer.resize( ContextSetCfg::NumberOfContexts ); m_Ctx = m_CtxBuffer.data(); }
311
private:
312
  std::vector<BinProbModel> m_CtxBuffer;
313
  BinProbModel*             m_Ctx;
314
};
315
316
typedef CtxStore FracBitsAccess;
317
318
319
class Ctx;
320
class SubCtx
321
{
322
  friend class Ctx;
323
public:
324
3.01M
  SubCtx( const CtxSet& ctxSet, const Ctx& ctx ) : m_CtxSet( ctxSet          ), m_Ctx( ctx          ) {}
325
3.01M
  SubCtx( const SubCtx& subCtx )                 : m_CtxSet( subCtx.m_CtxSet ), m_Ctx( subCtx.m_Ctx ) {}
326
  const SubCtx& operator= ( const SubCtx& ) = delete;
327
private:
328
  const CtxSet  m_CtxSet;
329
  const Ctx&    m_Ctx;
330
};
331
332
class Ctx : public ContextSetCfg
333
{
334
public:
335
  Ctx();
336
  Ctx( const BinProbModel*    dummy );
337
  Ctx( const Ctx&                 ctx   );
338
339
public:
340
  const Ctx& operator= ( const Ctx& ctx )
341
2.71M
  {
342
2.71M
    m_CtxStore  .copyFrom( ctx.m_CtxStore);
343
2.71M
    return *this;
344
2.71M
  }
345
346
  // for a save whose source is overwritten before it is read again: O(1) instead of a copy of every context
347
  void swap( Ctx& other )
348
389k
  {
349
389k
    m_CtxStore  .swap( other.m_CtxStore );
350
389k
  }
351
352
  SubCtx operator= ( SubCtx&& subCtx )
353
3.01M
  {
354
3.01M
    m_CtxStore  .copyFrom( subCtx.m_Ctx.m_CtxStore,   subCtx.m_CtxSet );
355
3.01M
    return std::move(subCtx);
356
3.01M
  }
357
358
  void  init ( int qp, int initId )
359
14.5k
  {
360
14.5k
    m_CtxStore  .init( qp, initId );
361
14.5k
  }
362
363
  void  loadPStates( const std::vector<uint16_t>& probStates )
364
0
  {
365
0
    m_CtxStore  .loadPStates( probStates );
366
0
  }
367
368
  void  savePStates( std::vector<uint16_t>& probStates ) const
369
0
  {
370
0
    m_CtxStore  .savePStates( probStates );
371
0
  }
372
373
  void  initCtxAndWinSize( unsigned ctxId, const Ctx& ctx, const uint8_t winSize )
374
0
  {
375
0
    m_CtxStore  [ctxId] = ctx.m_CtxStore      [ctxId];
376
0
    m_CtxStore  [ctxId] . setLog2WindowSize   (winSize);
377
0
  }
378
379
public:
380
0
  const Ctx&            getCtx       ()     const { return *this; }
381
9.35M
  Ctx&                  getCtx       ()           { return *this; }
382
383
0
  explicit operator   const CtxStore&()     const { return m_CtxStore; }
384
1.11M
  explicit operator         CtxStore&()           { return m_CtxStore; }
385
386
1.05M
  const FracBitsAccess& getFracBitsAcess()  const { return m_CtxStore; }
387
388
private:
389
  CtxStore                      m_CtxStore;
390
};
391
392
393
394
typedef dynamic_cache<Ctx> CtxCache;
395
396
class TempCtx
397
{
398
  TempCtx( const TempCtx& ) = delete;
399
  const TempCtx& operator=( const TempCtx& ) = delete;
400
public:
401
1.47M
  TempCtx ( CtxCache* cache )                     : m_ctx( *cache->get() ), m_cache( cache ) {}
402
125k
  TempCtx ( CtxCache* cache, const Ctx& ctx    )  : m_ctx( *cache->get() ), m_cache( cache ) { m_ctx = ctx; }
403
269k
  TempCtx ( CtxCache* cache, SubCtx&&   subCtx )  : m_ctx( *cache->get() ), m_cache( cache ) { m_ctx = std::forward<SubCtx>(subCtx); }
404
1.86M
  ~TempCtx()                                      { m_cache->cache( &m_ctx ); }
405
337k
  const Ctx& operator=( const Ctx& ctx )          { return ( m_ctx = ctx ); }
406
547k
  SubCtx     operator=( SubCtx&&   subCtx )       { return m_ctx = std::forward<SubCtx>( subCtx ); }
407
2.32M
  operator const Ctx& ()           const          { return m_ctx; }
408
1.77M
  operator       Ctx& ()                          { return m_ctx; }
409
private:
410
  Ctx&      m_ctx;
411
  CtxCache* m_cache;
412
};
413
414
} // namespace vvenc
415
416
//! \}
417