Coverage Report

Created: 2026-05-30 06:10

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/work/vvenc/source/Lib/EncoderLib/BinEncoder.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
45
#include "BinEncoder.h"
46
#include "CommonLib/Rom.h"
47
#include "CommonLib/dtrace_next.h"
48
49
//! \ingroup EncoderLib
50
//! \{
51
52
namespace vvenc {
53
54
BinCounter::BinCounter()
55
5.19k
  : m_CtxBinsCodedBuffer( Ctx::NumberOfContexts )
56
5.19k
  , m_NumBinsCtx        ( m_CtxBinsCodedBuffer.data() )
57
5.19k
  , m_NumBinsEP         ( 0 )
58
5.19k
  , m_NumBinsTrm        ( 0 )
59
5.19k
{}
60
61
62
void BinCounter::reset()
63
1.29k
{
64
480k
  for( std::size_t k = 0; k < m_CtxBinsCodedBuffer.size(); k++ )
65
478k
  {
66
478k
    m_NumBinsCtx[k] = 0;
67
478k
  }
68
1.29k
  m_NumBinsEP       = 0;
69
1.29k
  m_NumBinsTrm      = 0;
70
1.29k
}
71
72
73
uint32_t BinCounter::getAll() const
74
1.29k
{
75
1.29k
  uint32_t  count = m_NumBinsEP + m_NumBinsTrm;
76
480k
  for( std::size_t k = 0; k < m_CtxBinsCodedBuffer.size(); k++ )
77
478k
  {
78
478k
    count += m_NumBinsCtx[k];
79
478k
  }
80
1.29k
  return count;
81
1.29k
}
82
83
84
85
BinEncoderBase::BinEncoderBase( const BinProbModel* dummy )
86
5.19k
  : BinEncIf          ( dummy )
87
5.19k
  , m_Bitstream       ( 0 )
88
5.19k
  , m_Low             ( 0 )
89
5.19k
  , m_Range           ( 0 )
90
5.19k
  , m_bufferedByte    ( 0 )
91
5.19k
  , m_numBufferedBytes( 0 )
92
5.19k
  , m_bitsLeft        ( 0 )
93
5.19k
{}
94
95
void BinEncoderBase::init( OutputBitstream* bitstream )
96
4.05k
{
97
4.05k
  m_Bitstream = bitstream;
98
4.05k
}
99
100
void BinEncoderBase::uninit()
101
0
{
102
0
  m_Bitstream = 0;
103
0
}
104
105
void BinEncoderBase::start()
106
1.29k
{
107
1.29k
  m_Low               = 0;
108
1.29k
  m_Range             = 510;
109
1.29k
  m_bufferedByte      = 0xff;
110
1.29k
  m_numBufferedBytes  = 0;
111
1.29k
  m_bitsLeft          = 23;
112
1.29k
  BinCounter::reset();
113
1.29k
  m_BinStore. reset();
114
1.29k
}
115
116
void BinEncoderBase::finish()
117
1.29k
{
118
1.29k
  if( m_Low >> ( 32 - m_bitsLeft ) )
119
10
  {
120
10
    m_Bitstream->write( m_bufferedByte + 1, 8 );
121
11
    while( m_numBufferedBytes > 1 )
122
1
    {
123
1
      m_Bitstream->write( 0x00, 8 );
124
1
      m_numBufferedBytes--;
125
1
    }
126
10
    m_Low -= 1 << ( 32 - m_bitsLeft );
127
10
  }
128
1.28k
  else
129
1.28k
  {
130
1.28k
    if( m_numBufferedBytes > 0 )
131
1.28k
    {
132
1.28k
      m_Bitstream->write( m_bufferedByte, 8 );
133
1.28k
    }
134
1.30k
    while( m_numBufferedBytes > 1 )
135
18
    {
136
18
      m_Bitstream->write( 0xff, 8 );
137
18
      m_numBufferedBytes--;
138
18
    }
139
1.28k
  }
140
1.29k
  m_Bitstream->write( m_Low >> 8, 24 - m_bitsLeft );
141
1.29k
}
142
143
void BinEncoderBase::restart()
144
0
{
145
0
  m_Low               = 0;
146
0
  m_Range             = 510;
147
0
  m_bufferedByte      = 0xff;
148
0
  m_numBufferedBytes  = 0;
149
0
  m_bitsLeft          = 23;
150
0
}
151
152
void BinEncoderBase::reset( int qp, int initId )
153
1.29k
{
154
1.29k
  Ctx::init( qp, initId );
155
1.29k
  start();
156
1.29k
}
157
158
void BinEncoderBase::resetBits()
159
0
{
160
0
  m_Low               = 0;
161
0
  m_bufferedByte      = 0xff;
162
0
  m_numBufferedBytes  = 0;
163
0
  m_bitsLeft          = 23;
164
0
  BinCounter::reset();
165
0
}
166
167
void BinEncoderBase::encodeBinEP( unsigned bin )
168
466
{
169
466
  DTRACE( g_trace_ctx, D_CABAC, "%d" "  " "%d" "  EP=%d \n", DTRACE_GET_COUNTER( g_trace_ctx, D_CABAC ), m_Range, bin );
170
171
466
  BinCounter::addEP();
172
466
  m_Low <<= 1;
173
466
  if( bin )
174
18
  {
175
18
    m_Low += m_Range;
176
18
  }
177
466
  m_bitsLeft--;
178
466
  if( m_bitsLeft < 12 )
179
21
  {
180
21
    writeOut();
181
21
  }
182
466
}
183
184
void BinEncoderBase::encodeBinsEP( unsigned bins, unsigned numBins )
185
17.2k
{
186
88.5k
  for(int i = 0; i < numBins; i++)
187
71.3k
  {
188
71.3k
    DTRACE( g_trace_ctx, D_CABAC, "%d" "  " "%d" "  EP=%d \n", DTRACE_GET_COUNTER( g_trace_ctx, D_CABAC ), m_Range, ( bins >> ( numBins - 1 - i ) ) & 1 );
189
71.3k
  }
190
191
17.2k
  BinCounter::addEP( numBins );
192
17.2k
  if( m_Range == 256 )
193
2.00k
  {
194
2.00k
    encodeAlignedBinsEP( bins, numBins );
195
2.00k
    return;
196
2.00k
  }
197
17.6k
  while( numBins > 8 )
198
2.44k
  {
199
2.44k
    numBins          -= 8;
200
2.44k
    unsigned pattern  = bins >> numBins;
201
2.44k
    m_Low           <<= 8;
202
2.44k
    m_Low            += m_Range * pattern;
203
2.44k
    bins             -= pattern << numBins;
204
2.44k
    m_bitsLeft       -= 8;
205
2.44k
    if( m_bitsLeft < 12 )
206
2.44k
    {
207
2.44k
      writeOut();
208
2.44k
    }
209
2.44k
  }
210
15.2k
  m_Low     <<= numBins;
211
15.2k
  m_Low      += m_Range * bins;
212
15.2k
  m_bitsLeft -= numBins;
213
15.2k
  if( m_bitsLeft < 12 )
214
4.75k
  {
215
4.75k
    writeOut();
216
4.75k
  }
217
15.2k
}
218
219
void BinEncoderBase::encodeRemAbsEP(unsigned bins, unsigned goRicePar, unsigned cutoff, int maxLog2TrDynamicRange)
220
2.59k
{
221
2.59k
  const unsigned threshold = cutoff << goRicePar;
222
2.59k
  if (bins < threshold)
223
0
  {
224
0
    const unsigned bitMask = (1 << goRicePar) - 1;
225
0
    const unsigned length = (bins >> goRicePar) + 1;
226
0
    encodeBinsEP((1 << length) - 2, length);
227
0
    encodeBinsEP(bins & bitMask, goRicePar);
228
0
  }
229
2.59k
  else 
230
2.59k
  {
231
2.59k
    const unsigned  maxPrefixLength = 32 - cutoff - maxLog2TrDynamicRange;
232
2.59k
    unsigned        prefixLength = 0;
233
2.59k
    unsigned        codeValue = (bins >> goRicePar) - cutoff;
234
2.59k
    unsigned        suffixLength;
235
2.59k
    if (codeValue >= ((1 << maxPrefixLength) - 1))
236
75
    {
237
75
      prefixLength = maxPrefixLength;
238
75
      suffixLength = maxLog2TrDynamicRange;
239
75
    }
240
2.52k
    else
241
2.52k
    {
242
18.8k
      while (codeValue > ((2 << prefixLength) - 2))
243
16.2k
      {
244
16.2k
        prefixLength++;
245
16.2k
      }
246
2.52k
      suffixLength = prefixLength + goRicePar + 1; //+1 for the separator bit
247
2.52k
    }
248
2.59k
    const unsigned totalPrefixLength = prefixLength + cutoff;
249
2.59k
    const unsigned bitMask = (1 << goRicePar) - 1;
250
2.59k
    const unsigned prefix = (1 << totalPrefixLength) - 1;
251
2.59k
    const unsigned suffix = ((codeValue - ((1 << prefixLength) - 1)) << goRicePar) | (bins & bitMask);
252
2.59k
    encodeBinsEP(prefix, totalPrefixLength); //prefix
253
2.59k
    encodeBinsEP(suffix, suffixLength); //separator, suffix, and rParam bits
254
2.59k
  }
255
2.59k
}
256
257
void BinEncoderBase::encodeBinTrm( unsigned bin )
258
1.29k
{
259
1.29k
  BinCounter::addTrm();
260
1.29k
  m_Range -= 2;
261
1.29k
  if( bin )
262
1.29k
  {
263
1.29k
    m_Low      += m_Range;
264
1.29k
    m_Low     <<= 7;
265
1.29k
    m_Range     = 2 << 7;
266
1.29k
    m_bitsLeft -= 7;
267
1.29k
  }
268
0
  else if( m_Range >= 256 )
269
0
  {
270
0
    return;
271
0
  }
272
0
  else
273
0
  {
274
0
    m_Low     <<= 1;
275
0
    m_Range   <<= 1;
276
0
    m_bitsLeft--;
277
0
  }
278
1.29k
  if( m_bitsLeft < 12 )
279
1.13k
  {
280
1.13k
    writeOut();
281
1.13k
  }
282
1.29k
}
283
284
285
void BinEncoderBase::align()
286
0
{
287
0
  m_Range = 256;
288
0
}
289
290
291
void BinEncoderBase::encodeAlignedBinsEP( unsigned bins, unsigned numBins )
292
2.00k
{
293
2.00k
  unsigned remBins = numBins;
294
5.02k
  while( remBins > 0 )
295
3.01k
  {
296
    //The process of encoding an EP bin is the same as that of coding a normal
297
    //bin where the symbol ranges for 1 and 0 are both half the range:
298
    //
299
    //  low = (low + range/2) << 1       (to encode a 1)
300
    //  low =  low            << 1       (to encode a 0)
301
    //
302
    //  i.e.
303
    //  low = (low + (bin * range/2)) << 1
304
    //
305
    //  which is equivalent to:
306
    //
307
    //  low = (low << 1) + (bin * range)
308
    //
309
    //  this can be generalised for multiple bins, producing the following expression:
310
    //
311
3.01k
    unsigned binsToCode = std::min<unsigned>( remBins, 8); //code bytes if able to take advantage of the system's byte-write function
312
3.01k
    unsigned binMask    = ( 1 << binsToCode ) - 1;
313
3.01k
    unsigned newBins    = ( bins >> ( remBins - binsToCode ) ) & binMask;
314
3.01k
    m_Low               = ( m_Low << binsToCode ) + ( newBins << 8 ); //range is known to be 256
315
3.01k
    remBins            -= binsToCode;
316
3.01k
    m_bitsLeft         -= binsToCode;
317
3.01k
    if( m_bitsLeft < 12 )
318
1.90k
    {
319
1.90k
      writeOut();
320
1.90k
    }
321
3.01k
  }
322
2.00k
}
323
324
void BinEncoderBase::writeOut()
325
30.8k
{
326
30.8k
  unsigned leadByte = m_Low >> ( 24 - m_bitsLeft );
327
30.8k
  m_bitsLeft       += 8;
328
30.8k
  m_Low            &= 0xffffffffu >> m_bitsLeft;
329
30.8k
  if( leadByte == 0xff )
330
1.89k
  {
331
1.89k
    m_numBufferedBytes++;
332
1.89k
  }
333
28.9k
  else
334
28.9k
  {
335
28.9k
    if( m_numBufferedBytes > 0 )
336
27.6k
    {
337
27.6k
      unsigned carry  = leadByte >> 8;
338
27.6k
      unsigned byte   = m_bufferedByte + carry;
339
27.6k
      m_bufferedByte  = leadByte & 0xff;
340
27.6k
      m_Bitstream->write( byte, 8 );
341
27.6k
      byte            = ( 0xff + carry ) & 0xff;
342
29.5k
      while( m_numBufferedBytes > 1 )
343
1.87k
      {
344
1.87k
        m_Bitstream->write( byte, 8 );
345
1.87k
        m_numBufferedBytes--;
346
1.87k
      }
347
27.6k
    }
348
1.29k
    else
349
1.29k
    {
350
1.29k
      m_numBufferedBytes  = 1;
351
1.29k
      m_bufferedByte      = leadByte;
352
1.29k
    }
353
28.9k
  }
354
30.8k
}
355
356
357
358
BinEncoder::BinEncoder()
359
5.19k
  : BinEncoderBase( static_cast<const BinProbModel*>    ( nullptr ) )
360
5.19k
  , m_Ctx         ( static_cast<CtxStore&>( *this   ) )
361
5.19k
{}
362
363
void BinEncoder::encodeBin( unsigned bin, unsigned ctxId )
364
338k
{
365
338k
  BinCounter::addCtx( ctxId );
366
338k
  BinProbModel& rcProbModel = m_Ctx[ctxId];
367
338k
  uint32_t      LPS         = rcProbModel.getLPS( m_Range );
368
369
//  DTRACE( g_trace_ctx, D_CABAC, "%d" " %d " "%d" "  " "[%d:%d]" "  " "%2d(MPS=%d)"  "  " "  -  " "%d" "\n", DTRACE_GET_COUNTER( g_trace_ctx, D_CABAC ), ctxId, m_Range, m_Range - LPS, LPS, ( unsigned int ) ( rcProbModel.state() ), bin == rcProbModel.mps(), bin );
370
338k
  DTRACE( g_trace_ctx, D_CABAC, " %d " "%d" "  " "[%d:%d]" "  " "%2d(MPS=%d)"  "  " "  -  " "%d" "\n", DTRACE_GET_COUNTER( g_trace_ctx, D_CABAC ), m_Range, m_Range - LPS, LPS, (unsigned int)( rcProbModel.state() ), bin == rcProbModel.mps(), bin );
371
372
338k
  m_Range   -=  LPS;
373
338k
  if( bin != rcProbModel.mps() )
374
43.8k
  {
375
43.8k
    int numBits   = rcProbModel.getRenormBitsLPS( LPS );
376
43.8k
    m_bitsLeft   -= numBits;
377
43.8k
    m_Low        += m_Range;
378
43.8k
    m_Low         = m_Low << numBits;
379
43.8k
    m_Range       = LPS   << numBits;
380
43.8k
    if( m_bitsLeft < 12 )
381
9.95k
    {
382
9.95k
      writeOut();
383
9.95k
    }
384
43.8k
  }
385
294k
  else
386
294k
  {
387
294k
    if( m_Range < 256 )
388
91.3k
    {
389
      //int numBits   = rcProbModel.getRenormBitsRange();
390
91.3k
      int numBits   = 1;
391
91.3k
      m_bitsLeft   -= numBits;
392
91.3k
      m_Low       <<= numBits;
393
91.3k
      m_Range     <<= numBits;
394
91.3k
      if( m_bitsLeft < 12 )
395
10.6k
      {
396
10.6k
        writeOut();
397
10.6k
      }
398
91.3k
    }
399
294k
  }
400
338k
  rcProbModel.update( bin );
401
338k
  BinEncoderBase::m_BinStore.addBin( bin, ctxId );
402
338k
}
403
404
BinEncIf* BinEncoder::getTestBinEncoder() const
405
0
{
406
0
  BinEncIf* testBinEncoder = 0;
407
0
  if( m_BinStore.inUse() )
408
0
  {
409
0
    testBinEncoder = new BinEncoder();
410
0
  }
411
0
  return testBinEncoder;
412
0
}
413
414
415
416
417
418
BitEstimatorBase::BitEstimatorBase( const BinProbModel* dummy )
419
32.3k
  : BinEncIf      ( dummy )
420
32.3k
{
421
32.3k
  m_EstFracBits = 0;
422
32.3k
}
423
424
void BitEstimatorBase::encodeRemAbsEP(unsigned bins, unsigned goRicePar, unsigned cutoff, int maxLog2TrDynamicRange)
425
5.51M
{
426
5.51M
  const unsigned threshold = cutoff << goRicePar;
427
5.51M
  if (bins < threshold)
428
2.89M
  {
429
2.89M
    m_EstFracBits += BinProbModelBase::estFracBitsEP((bins >> goRicePar) + 1 + goRicePar);
430
2.89M
  }
431
2.61M
  else 
432
2.61M
  {
433
2.61M
    const unsigned  maxPrefixLength = 32 - cutoff - maxLog2TrDynamicRange;
434
2.61M
    unsigned        prefixLength = 0;
435
2.61M
    unsigned        codeValue = (bins >> goRicePar) - cutoff;
436
2.61M
    unsigned        suffixLength;
437
2.61M
    if (codeValue >= ((1 << maxPrefixLength) - 1))
438
450
    {
439
450
      prefixLength = maxPrefixLength;
440
450
      suffixLength = maxLog2TrDynamicRange;
441
450
    }
442
2.61M
    else
443
2.61M
    {
444
10.1M
      while (codeValue > ((2 << prefixLength) - 2))
445
7.50M
      {
446
7.50M
        prefixLength++;
447
7.50M
      }
448
2.61M
      suffixLength = prefixLength + goRicePar + 1; //+1 for the separator bit
449
2.61M
    }
450
2.61M
    m_EstFracBits += BinProbModelBase::estFracBitsEP(cutoff + prefixLength + suffixLength);
451
2.61M
  }
452
5.51M
}
453
454
void BitEstimatorBase::align()
455
0
{
456
0
  static const uint64_t add   = BinProbModelBase::estFracBitsEP() - 1;
457
0
  static const uint64_t mask  = ~add;
458
0
  m_EstFracBits += add;
459
0
  m_EstFracBits &= mask;
460
0
}
461
462
463
BitEstimator::BitEstimator()
464
32.3k
  : BitEstimatorBase  ( static_cast<const BinProbModel*>    ( nullptr) )
465
32.3k
  , m_Ctx             ( static_cast<CtxStore&>              ( *this  ) )
466
32.3k
{}
467
468
} // namespace vvenc
469
470
//! \}
471