Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
freebsd
GitHub Repository: freebsd/freebsd-src
Path: blob/main/sys/contrib/openzfs/module/zstd/lib/common/fse.h
48774 views
1
// SPDX-License-Identifier: BSD-3-Clause OR GPL-2.0-only
2
/* ******************************************************************
3
* FSE : Finite State Entropy codec
4
* Public Prototypes declaration
5
* Copyright (c) 2013-2020, Yann Collet, Facebook, Inc.
6
*
7
* You can contact the author at :
8
* - Source repository : https://github.com/Cyan4973/FiniteStateEntropy
9
*
10
* This source code is licensed under both the BSD-style license (found in the
11
* LICENSE file in the root directory of this source tree) and the GPLv2 (found
12
* in the COPYING file in the root directory of this source tree).
13
* You may select, at your option, one of the above-listed licenses.
14
****************************************************************** */
15
16
#if defined (__cplusplus)
17
extern "C" {
18
#endif
19
20
#ifndef FSE_H
21
#define FSE_H
22
23
24
/*-*****************************************
25
* Dependencies
26
******************************************/
27
#include <stddef.h> /* size_t, ptrdiff_t */
28
29
30
/*-*****************************************
31
* FSE_PUBLIC_API : control library symbols visibility
32
******************************************/
33
#if defined(FSE_DLL_EXPORT) && (FSE_DLL_EXPORT==1) && defined(__GNUC__) && (__GNUC__ >= 4)
34
# define FSE_PUBLIC_API __attribute__ ((visibility ("default")))
35
#elif defined(FSE_DLL_EXPORT) && (FSE_DLL_EXPORT==1) /* Visual expected */
36
# define FSE_PUBLIC_API __declspec(dllexport)
37
#elif defined(FSE_DLL_IMPORT) && (FSE_DLL_IMPORT==1)
38
# define FSE_PUBLIC_API __declspec(dllimport) /* It isn't required but allows to generate better code, saving a function pointer load from the IAT and an indirect jump.*/
39
#else
40
# define FSE_PUBLIC_API
41
#endif
42
43
/*------ Version ------*/
44
#define FSE_VERSION_MAJOR 0
45
#define FSE_VERSION_MINOR 9
46
#define FSE_VERSION_RELEASE 0
47
48
#define FSE_LIB_VERSION FSE_VERSION_MAJOR.FSE_VERSION_MINOR.FSE_VERSION_RELEASE
49
#define FSE_QUOTE(str) #str
50
#define FSE_EXPAND_AND_QUOTE(str) FSE_QUOTE(str)
51
#define FSE_VERSION_STRING FSE_EXPAND_AND_QUOTE(FSE_LIB_VERSION)
52
53
#define FSE_VERSION_NUMBER (FSE_VERSION_MAJOR *100*100 + FSE_VERSION_MINOR *100 + FSE_VERSION_RELEASE)
54
FSE_PUBLIC_API unsigned FSE_versionNumber(void); /**< library version number; to be used when checking dll version */
55
56
57
/*-****************************************
58
* FSE simple functions
59
******************************************/
60
/*! FSE_compress() :
61
Compress content of buffer 'src', of size 'srcSize', into destination buffer 'dst'.
62
'dst' buffer must be already allocated. Compression runs faster is dstCapacity >= FSE_compressBound(srcSize).
63
@return : size of compressed data (<= dstCapacity).
64
Special values : if return == 0, srcData is not compressible => Nothing is stored within dst !!!
65
if return == 1, srcData is a single byte symbol * srcSize times. Use RLE compression instead.
66
if FSE_isError(return), compression failed (more details using FSE_getErrorName())
67
*/
68
FSE_PUBLIC_API size_t FSE_compress(void* dst, size_t dstCapacity,
69
const void* src, size_t srcSize);
70
71
/*! FSE_decompress():
72
Decompress FSE data from buffer 'cSrc', of size 'cSrcSize',
73
into already allocated destination buffer 'dst', of size 'dstCapacity'.
74
@return : size of regenerated data (<= maxDstSize),
75
or an error code, which can be tested using FSE_isError() .
76
77
** Important ** : FSE_decompress() does not decompress non-compressible nor RLE data !!!
78
Why ? : making this distinction requires a header.
79
Header management is intentionally delegated to the user layer, which can better manage special cases.
80
*/
81
FSE_PUBLIC_API size_t FSE_decompress(void* dst, size_t dstCapacity,
82
const void* cSrc, size_t cSrcSize);
83
84
85
/*-*****************************************
86
* Tool functions
87
******************************************/
88
FSE_PUBLIC_API size_t FSE_compressBound(size_t size); /* maximum compressed size */
89
90
/* Error Management */
91
FSE_PUBLIC_API unsigned FSE_isError(size_t code); /* tells if a return value is an error code */
92
FSE_PUBLIC_API const char* FSE_getErrorName(size_t code); /* provides error code string (useful for debugging) */
93
94
95
/*-*****************************************
96
* FSE advanced functions
97
******************************************/
98
/*! FSE_compress2() :
99
Same as FSE_compress(), but allows the selection of 'maxSymbolValue' and 'tableLog'
100
Both parameters can be defined as '0' to mean : use default value
101
@return : size of compressed data
102
Special values : if return == 0, srcData is not compressible => Nothing is stored within cSrc !!!
103
if return == 1, srcData is a single byte symbol * srcSize times. Use RLE compression.
104
if FSE_isError(return), it's an error code.
105
*/
106
FSE_PUBLIC_API size_t FSE_compress2 (void* dst, size_t dstSize, const void* src, size_t srcSize, unsigned maxSymbolValue, unsigned tableLog);
107
108
109
/*-*****************************************
110
* FSE detailed API
111
******************************************/
112
/*!
113
FSE_compress() does the following:
114
1. count symbol occurrence from source[] into table count[] (see hist.h)
115
2. normalize counters so that sum(count[]) == Power_of_2 (2^tableLog)
116
3. save normalized counters to memory buffer using writeNCount()
117
4. build encoding table 'CTable' from normalized counters
118
5. encode the data stream using encoding table 'CTable'
119
120
FSE_decompress() does the following:
121
1. read normalized counters with readNCount()
122
2. build decoding table 'DTable' from normalized counters
123
3. decode the data stream using decoding table 'DTable'
124
125
The following API allows targeting specific sub-functions for advanced tasks.
126
For example, it's possible to compress several blocks using the same 'CTable',
127
or to save and provide normalized distribution using external method.
128
*/
129
130
/* *** COMPRESSION *** */
131
132
/*! FSE_optimalTableLog():
133
dynamically downsize 'tableLog' when conditions are met.
134
It saves CPU time, by using smaller tables, while preserving or even improving compression ratio.
135
@return : recommended tableLog (necessarily <= 'maxTableLog') */
136
FSE_PUBLIC_API unsigned FSE_optimalTableLog(unsigned maxTableLog, size_t srcSize, unsigned maxSymbolValue);
137
138
/*! FSE_normalizeCount():
139
normalize counts so that sum(count[]) == Power_of_2 (2^tableLog)
140
'normalizedCounter' is a table of short, of minimum size (maxSymbolValue+1).
141
@return : tableLog,
142
or an errorCode, which can be tested using FSE_isError() */
143
FSE_PUBLIC_API size_t FSE_normalizeCount(short* normalizedCounter, unsigned tableLog,
144
const unsigned* count, size_t srcSize, unsigned maxSymbolValue);
145
146
/*! FSE_NCountWriteBound():
147
Provides the maximum possible size of an FSE normalized table, given 'maxSymbolValue' and 'tableLog'.
148
Typically useful for allocation purpose. */
149
FSE_PUBLIC_API size_t FSE_NCountWriteBound(unsigned maxSymbolValue, unsigned tableLog);
150
151
/*! FSE_writeNCount():
152
Compactly save 'normalizedCounter' into 'buffer'.
153
@return : size of the compressed table,
154
or an errorCode, which can be tested using FSE_isError(). */
155
FSE_PUBLIC_API size_t FSE_writeNCount (void* buffer, size_t bufferSize,
156
const short* normalizedCounter,
157
unsigned maxSymbolValue, unsigned tableLog);
158
159
/*! Constructor and Destructor of FSE_CTable.
160
Note that FSE_CTable size depends on 'tableLog' and 'maxSymbolValue' */
161
typedef unsigned FSE_CTable; /* don't allocate that. It's only meant to be more restrictive than void* */
162
FSE_PUBLIC_API FSE_CTable* FSE_createCTable (unsigned maxSymbolValue, unsigned tableLog);
163
FSE_PUBLIC_API void FSE_freeCTable (FSE_CTable* ct);
164
165
/*! FSE_buildCTable():
166
Builds `ct`, which must be already allocated, using FSE_createCTable().
167
@return : 0, or an errorCode, which can be tested using FSE_isError() */
168
FSE_PUBLIC_API size_t FSE_buildCTable(FSE_CTable* ct, const short* normalizedCounter, unsigned maxSymbolValue, unsigned tableLog);
169
170
/*! FSE_compress_usingCTable():
171
Compress `src` using `ct` into `dst` which must be already allocated.
172
@return : size of compressed data (<= `dstCapacity`),
173
or 0 if compressed data could not fit into `dst`,
174
or an errorCode, which can be tested using FSE_isError() */
175
FSE_PUBLIC_API size_t FSE_compress_usingCTable (void* dst, size_t dstCapacity, const void* src, size_t srcSize, const FSE_CTable* ct);
176
177
/*!
178
Tutorial :
179
----------
180
The first step is to count all symbols. FSE_count() does this job very fast.
181
Result will be saved into 'count', a table of unsigned int, which must be already allocated, and have 'maxSymbolValuePtr[0]+1' cells.
182
'src' is a table of bytes of size 'srcSize'. All values within 'src' MUST be <= maxSymbolValuePtr[0]
183
maxSymbolValuePtr[0] will be updated, with its real value (necessarily <= original value)
184
FSE_count() will return the number of occurrence of the most frequent symbol.
185
This can be used to know if there is a single symbol within 'src', and to quickly evaluate its compressibility.
186
If there is an error, the function will return an ErrorCode (which can be tested using FSE_isError()).
187
188
The next step is to normalize the frequencies.
189
FSE_normalizeCount() will ensure that sum of frequencies is == 2 ^'tableLog'.
190
It also guarantees a minimum of 1 to any Symbol with frequency >= 1.
191
You can use 'tableLog'==0 to mean "use default tableLog value".
192
If you are unsure of which tableLog value to use, you can ask FSE_optimalTableLog(),
193
which will provide the optimal valid tableLog given sourceSize, maxSymbolValue, and a user-defined maximum (0 means "default").
194
195
The result of FSE_normalizeCount() will be saved into a table,
196
called 'normalizedCounter', which is a table of signed short.
197
'normalizedCounter' must be already allocated, and have at least 'maxSymbolValue+1' cells.
198
The return value is tableLog if everything proceeded as expected.
199
It is 0 if there is a single symbol within distribution.
200
If there is an error (ex: invalid tableLog value), the function will return an ErrorCode (which can be tested using FSE_isError()).
201
202
'normalizedCounter' can be saved in a compact manner to a memory area using FSE_writeNCount().
203
'buffer' must be already allocated.
204
For guaranteed success, buffer size must be at least FSE_headerBound().
205
The result of the function is the number of bytes written into 'buffer'.
206
If there is an error, the function will return an ErrorCode (which can be tested using FSE_isError(); ex : buffer size too small).
207
208
'normalizedCounter' can then be used to create the compression table 'CTable'.
209
The space required by 'CTable' must be already allocated, using FSE_createCTable().
210
You can then use FSE_buildCTable() to fill 'CTable'.
211
If there is an error, both functions will return an ErrorCode (which can be tested using FSE_isError()).
212
213
'CTable' can then be used to compress 'src', with FSE_compress_usingCTable().
214
Similar to FSE_count(), the convention is that 'src' is assumed to be a table of char of size 'srcSize'
215
The function returns the size of compressed data (without header), necessarily <= `dstCapacity`.
216
If it returns '0', compressed data could not fit into 'dst'.
217
If there is an error, the function will return an ErrorCode (which can be tested using FSE_isError()).
218
*/
219
220
221
/* *** DECOMPRESSION *** */
222
223
/*! FSE_readNCount():
224
Read compactly saved 'normalizedCounter' from 'rBuffer'.
225
@return : size read from 'rBuffer',
226
or an errorCode, which can be tested using FSE_isError().
227
maxSymbolValuePtr[0] and tableLogPtr[0] will also be updated with their respective values */
228
FSE_PUBLIC_API size_t FSE_readNCount (short* normalizedCounter,
229
unsigned* maxSymbolValuePtr, unsigned* tableLogPtr,
230
const void* rBuffer, size_t rBuffSize);
231
232
/*! Constructor and Destructor of FSE_DTable.
233
Note that its size depends on 'tableLog' */
234
typedef unsigned FSE_DTable; /* don't allocate that. It's just a way to be more restrictive than void* */
235
FSE_PUBLIC_API FSE_DTable* FSE_createDTable(unsigned tableLog);
236
FSE_PUBLIC_API void FSE_freeDTable(FSE_DTable* dt);
237
238
/*! FSE_buildDTable():
239
Builds 'dt', which must be already allocated, using FSE_createDTable().
240
return : 0, or an errorCode, which can be tested using FSE_isError() */
241
FSE_PUBLIC_API size_t FSE_buildDTable (FSE_DTable* dt, const short* normalizedCounter, unsigned maxSymbolValue, unsigned tableLog);
242
243
/*! FSE_decompress_usingDTable():
244
Decompress compressed source `cSrc` of size `cSrcSize` using `dt`
245
into `dst` which must be already allocated.
246
@return : size of regenerated data (necessarily <= `dstCapacity`),
247
or an errorCode, which can be tested using FSE_isError() */
248
FSE_PUBLIC_API size_t FSE_decompress_usingDTable(void* dst, size_t dstCapacity, const void* cSrc, size_t cSrcSize, const FSE_DTable* dt);
249
250
/*!
251
Tutorial :
252
----------
253
(Note : these functions only decompress FSE-compressed blocks.
254
If block is uncompressed, use memcpy() instead
255
If block is a single repeated byte, use memset() instead )
256
257
The first step is to obtain the normalized frequencies of symbols.
258
This can be performed by FSE_readNCount() if it was saved using FSE_writeNCount().
259
'normalizedCounter' must be already allocated, and have at least 'maxSymbolValuePtr[0]+1' cells of signed short.
260
In practice, that means it's necessary to know 'maxSymbolValue' beforehand,
261
or size the table to handle worst case situations (typically 256).
262
FSE_readNCount() will provide 'tableLog' and 'maxSymbolValue'.
263
The result of FSE_readNCount() is the number of bytes read from 'rBuffer'.
264
Note that 'rBufferSize' must be at least 4 bytes, even if useful information is less than that.
265
If there is an error, the function will return an error code, which can be tested using FSE_isError().
266
267
The next step is to build the decompression tables 'FSE_DTable' from 'normalizedCounter'.
268
This is performed by the function FSE_buildDTable().
269
The space required by 'FSE_DTable' must be already allocated using FSE_createDTable().
270
If there is an error, the function will return an error code, which can be tested using FSE_isError().
271
272
`FSE_DTable` can then be used to decompress `cSrc`, with FSE_decompress_usingDTable().
273
`cSrcSize` must be strictly correct, otherwise decompression will fail.
274
FSE_decompress_usingDTable() result will tell how many bytes were regenerated (<=`dstCapacity`).
275
If there is an error, the function will return an error code, which can be tested using FSE_isError(). (ex: dst buffer too small)
276
*/
277
278
#endif /* FSE_H */
279
280
#if defined(FSE_STATIC_LINKING_ONLY) && !defined(FSE_H_FSE_STATIC_LINKING_ONLY)
281
#define FSE_H_FSE_STATIC_LINKING_ONLY
282
283
/* *** Dependency *** */
284
#include "bitstream.h"
285
286
287
/* *****************************************
288
* Static allocation
289
*******************************************/
290
/* FSE buffer bounds */
291
#define FSE_NCOUNTBOUND 512
292
#define FSE_BLOCKBOUND(size) (size + (size>>7) + 4 /* fse states */ + sizeof(size_t) /* bitContainer */)
293
#define FSE_COMPRESSBOUND(size) (FSE_NCOUNTBOUND + FSE_BLOCKBOUND(size)) /* Macro version, useful for static allocation */
294
295
/* It is possible to statically allocate FSE CTable/DTable as a table of FSE_CTable/FSE_DTable using below macros */
296
#define FSE_CTABLE_SIZE_U32(maxTableLog, maxSymbolValue) (1 + (1<<(maxTableLog-1)) + ((maxSymbolValue+1)*2))
297
#define FSE_DTABLE_SIZE_U32(maxTableLog) (1 + (1<<maxTableLog))
298
299
/* or use the size to malloc() space directly. Pay attention to alignment restrictions though */
300
#define FSE_CTABLE_SIZE(maxTableLog, maxSymbolValue) (FSE_CTABLE_SIZE_U32(maxTableLog, maxSymbolValue) * sizeof(FSE_CTable))
301
#define FSE_DTABLE_SIZE(maxTableLog) (FSE_DTABLE_SIZE_U32(maxTableLog) * sizeof(FSE_DTable))
302
303
304
/* *****************************************
305
* FSE advanced API
306
***************************************** */
307
308
unsigned FSE_optimalTableLog_internal(unsigned maxTableLog, size_t srcSize, unsigned maxSymbolValue, unsigned minus);
309
/**< same as FSE_optimalTableLog(), which used `minus==2` */
310
311
/* FSE_compress_wksp() :
312
* Same as FSE_compress2(), but using an externally allocated scratch buffer (`workSpace`).
313
* FSE_WKSP_SIZE_U32() provides the minimum size required for `workSpace` as a table of FSE_CTable.
314
*/
315
#define FSE_WKSP_SIZE_U32(maxTableLog, maxSymbolValue) ( FSE_CTABLE_SIZE_U32(maxTableLog, maxSymbolValue) + ((maxTableLog > 12) ? (1 << (maxTableLog - 2)) : 1024) )
316
size_t FSE_compress_wksp (void* dst, size_t dstSize, const void* src, size_t srcSize, unsigned maxSymbolValue, unsigned tableLog, void* workSpace, size_t wkspSize);
317
318
size_t FSE_buildCTable_raw (FSE_CTable* ct, unsigned nbBits);
319
/**< build a fake FSE_CTable, designed for a flat distribution, where each symbol uses nbBits */
320
321
size_t FSE_buildCTable_rle (FSE_CTable* ct, unsigned char symbolValue);
322
/**< build a fake FSE_CTable, designed to compress always the same symbolValue */
323
324
/* FSE_buildCTable_wksp() :
325
* Same as FSE_buildCTable(), but using an externally allocated scratch buffer (`workSpace`).
326
* `wkspSize` must be >= `(1<<tableLog)`.
327
*/
328
size_t FSE_buildCTable_wksp(FSE_CTable* ct, const short* normalizedCounter, unsigned maxSymbolValue, unsigned tableLog, void* workSpace, size_t wkspSize);
329
330
size_t FSE_buildDTable_raw (FSE_DTable* dt, unsigned nbBits);
331
/**< build a fake FSE_DTable, designed to read a flat distribution where each symbol uses nbBits */
332
333
size_t FSE_buildDTable_rle (FSE_DTable* dt, unsigned char symbolValue);
334
/**< build a fake FSE_DTable, designed to always generate the same symbolValue */
335
336
size_t FSE_decompress_wksp(void* dst, size_t dstCapacity, const void* cSrc, size_t cSrcSize, FSE_DTable* workSpace, unsigned maxLog);
337
/**< same as FSE_decompress(), using an externally allocated `workSpace` produced with `FSE_DTABLE_SIZE_U32(maxLog)` */
338
339
typedef enum {
340
FSE_repeat_none, /**< Cannot use the previous table */
341
FSE_repeat_check, /**< Can use the previous table but it must be checked */
342
FSE_repeat_valid /**< Can use the previous table and it is assumed to be valid */
343
} FSE_repeat;
344
345
/* *****************************************
346
* FSE symbol compression API
347
*******************************************/
348
/*!
349
This API consists of small unitary functions, which highly benefit from being inlined.
350
Hence their body are included in next section.
351
*/
352
typedef struct {
353
ptrdiff_t value;
354
const void* stateTable;
355
const void* symbolTT;
356
unsigned stateLog;
357
} FSE_CState_t;
358
359
static void FSE_initCState(FSE_CState_t* CStatePtr, const FSE_CTable* ct);
360
361
static void FSE_encodeSymbol(BIT_CStream_t* bitC, FSE_CState_t* CStatePtr, unsigned symbol);
362
363
static void FSE_flushCState(BIT_CStream_t* bitC, const FSE_CState_t* CStatePtr);
364
365
/**<
366
These functions are inner components of FSE_compress_usingCTable().
367
They allow the creation of custom streams, mixing multiple tables and bit sources.
368
369
A key property to keep in mind is that encoding and decoding are done **in reverse direction**.
370
So the first symbol you will encode is the last you will decode, like a LIFO stack.
371
372
You will need a few variables to track your CStream. They are :
373
374
FSE_CTable ct; // Provided by FSE_buildCTable()
375
BIT_CStream_t bitStream; // bitStream tracking structure
376
FSE_CState_t state; // State tracking structure (can have several)
377
378
379
The first thing to do is to init bitStream and state.
380
size_t errorCode = BIT_initCStream(&bitStream, dstBuffer, maxDstSize);
381
FSE_initCState(&state, ct);
382
383
Note that BIT_initCStream() can produce an error code, so its result should be tested, using FSE_isError();
384
You can then encode your input data, byte after byte.
385
FSE_encodeSymbol() outputs a maximum of 'tableLog' bits at a time.
386
Remember decoding will be done in reverse direction.
387
FSE_encodeByte(&bitStream, &state, symbol);
388
389
At any time, you can also add any bit sequence.
390
Note : maximum allowed nbBits is 25, for compatibility with 32-bits decoders
391
BIT_addBits(&bitStream, bitField, nbBits);
392
393
The above methods don't commit data to memory, they just store it into local register, for speed.
394
Local register size is 64-bits on 64-bits systems, 32-bits on 32-bits systems (size_t).
395
Writing data to memory is a manual operation, performed by the flushBits function.
396
BIT_flushBits(&bitStream);
397
398
Your last FSE encoding operation shall be to flush your last state value(s).
399
FSE_flushState(&bitStream, &state);
400
401
Finally, you must close the bitStream.
402
The function returns the size of CStream in bytes.
403
If data couldn't fit into dstBuffer, it will return a 0 ( == not compressible)
404
If there is an error, it returns an errorCode (which can be tested using FSE_isError()).
405
size_t size = BIT_closeCStream(&bitStream);
406
*/
407
408
409
/* *****************************************
410
* FSE symbol decompression API
411
*******************************************/
412
typedef struct {
413
size_t state;
414
const void* table; /* precise table may vary, depending on U16 */
415
} FSE_DState_t;
416
417
418
static void FSE_initDState(FSE_DState_t* DStatePtr, BIT_DStream_t* bitD, const FSE_DTable* dt);
419
420
static unsigned char FSE_decodeSymbol(FSE_DState_t* DStatePtr, BIT_DStream_t* bitD);
421
422
static unsigned FSE_endOfDState(const FSE_DState_t* DStatePtr);
423
424
/**<
425
Let's now decompose FSE_decompress_usingDTable() into its unitary components.
426
You will decode FSE-encoded symbols from the bitStream,
427
and also any other bitFields you put in, **in reverse order**.
428
429
You will need a few variables to track your bitStream. They are :
430
431
BIT_DStream_t DStream; // Stream context
432
FSE_DState_t DState; // State context. Multiple ones are possible
433
FSE_DTable* DTablePtr; // Decoding table, provided by FSE_buildDTable()
434
435
The first thing to do is to init the bitStream.
436
errorCode = BIT_initDStream(&DStream, srcBuffer, srcSize);
437
438
You should then retrieve your initial state(s)
439
(in reverse flushing order if you have several ones) :
440
errorCode = FSE_initDState(&DState, &DStream, DTablePtr);
441
442
You can then decode your data, symbol after symbol.
443
For information the maximum number of bits read by FSE_decodeSymbol() is 'tableLog'.
444
Keep in mind that symbols are decoded in reverse order, like a LIFO stack (last in, first out).
445
unsigned char symbol = FSE_decodeSymbol(&DState, &DStream);
446
447
You can retrieve any bitfield you eventually stored into the bitStream (in reverse order)
448
Note : maximum allowed nbBits is 25, for 32-bits compatibility
449
size_t bitField = BIT_readBits(&DStream, nbBits);
450
451
All above operations only read from local register (which size depends on size_t).
452
Refueling the register from memory is manually performed by the reload method.
453
endSignal = FSE_reloadDStream(&DStream);
454
455
BIT_reloadDStream() result tells if there is still some more data to read from DStream.
456
BIT_DStream_unfinished : there is still some data left into the DStream.
457
BIT_DStream_endOfBuffer : Dstream reached end of buffer. Its container may no longer be completely filled.
458
BIT_DStream_completed : Dstream reached its exact end, corresponding in general to decompression completed.
459
BIT_DStream_tooFar : Dstream went too far. Decompression result is corrupted.
460
461
When reaching end of buffer (BIT_DStream_endOfBuffer), progress slowly, notably if you decode multiple symbols per loop,
462
to properly detect the exact end of stream.
463
After each decoded symbol, check if DStream is fully consumed using this simple test :
464
BIT_reloadDStream(&DStream) >= BIT_DStream_completed
465
466
When it's done, verify decompression is fully completed, by checking both DStream and the relevant states.
467
Checking if DStream has reached its end is performed by :
468
BIT_endOfDStream(&DStream);
469
Check also the states. There might be some symbols left there, if some high probability ones (>50%) are possible.
470
FSE_endOfDState(&DState);
471
*/
472
473
474
/* *****************************************
475
* FSE unsafe API
476
*******************************************/
477
static unsigned char FSE_decodeSymbolFast(FSE_DState_t* DStatePtr, BIT_DStream_t* bitD);
478
/* faster, but works only if nbBits is always >= 1 (otherwise, result will be corrupted) */
479
480
481
/* *****************************************
482
* Implementation of inlined functions
483
*******************************************/
484
typedef struct {
485
int deltaFindState;
486
U32 deltaNbBits;
487
} FSE_symbolCompressionTransform; /* total 8 bytes */
488
489
MEM_STATIC void FSE_initCState(FSE_CState_t* statePtr, const FSE_CTable* ct)
490
{
491
const void* ptr = ct;
492
const U16* u16ptr = (const U16*) ptr;
493
const U32 tableLog = MEM_read16(ptr);
494
statePtr->value = (ptrdiff_t)1<<tableLog;
495
statePtr->stateTable = u16ptr+2;
496
statePtr->symbolTT = ct + 1 + (tableLog ? (1<<(tableLog-1)) : 1);
497
statePtr->stateLog = tableLog;
498
}
499
500
501
/*! FSE_initCState2() :
502
* Same as FSE_initCState(), but the first symbol to include (which will be the last to be read)
503
* uses the smallest state value possible, saving the cost of this symbol */
504
MEM_STATIC void FSE_initCState2(FSE_CState_t* statePtr, const FSE_CTable* ct, U32 symbol)
505
{
506
FSE_initCState(statePtr, ct);
507
{ const FSE_symbolCompressionTransform symbolTT = ((const FSE_symbolCompressionTransform*)(statePtr->symbolTT))[symbol];
508
const U16* stateTable = (const U16*)(statePtr->stateTable);
509
U32 nbBitsOut = (U32)((symbolTT.deltaNbBits + (1<<15)) >> 16);
510
statePtr->value = (nbBitsOut << 16) - symbolTT.deltaNbBits;
511
statePtr->value = stateTable[(statePtr->value >> nbBitsOut) + symbolTT.deltaFindState];
512
}
513
}
514
515
MEM_STATIC void FSE_encodeSymbol(BIT_CStream_t* bitC, FSE_CState_t* statePtr, unsigned symbol)
516
{
517
FSE_symbolCompressionTransform const symbolTT = ((const FSE_symbolCompressionTransform*)(statePtr->symbolTT))[symbol];
518
const U16* const stateTable = (const U16*)(statePtr->stateTable);
519
U32 const nbBitsOut = (U32)((statePtr->value + symbolTT.deltaNbBits) >> 16);
520
BIT_addBits(bitC, statePtr->value, nbBitsOut);
521
statePtr->value = stateTable[ (statePtr->value >> nbBitsOut) + symbolTT.deltaFindState];
522
}
523
524
MEM_STATIC void FSE_flushCState(BIT_CStream_t* bitC, const FSE_CState_t* statePtr)
525
{
526
BIT_addBits(bitC, statePtr->value, statePtr->stateLog);
527
BIT_flushBits(bitC);
528
}
529
530
531
/* FSE_getMaxNbBits() :
532
* Approximate maximum cost of a symbol, in bits.
533
* Fractional get rounded up (i.e : a symbol with a normalized frequency of 3 gives the same result as a frequency of 2)
534
* note 1 : assume symbolValue is valid (<= maxSymbolValue)
535
* note 2 : if freq[symbolValue]==0, @return a fake cost of tableLog+1 bits */
536
MEM_STATIC U32 FSE_getMaxNbBits(const void* symbolTTPtr, U32 symbolValue)
537
{
538
const FSE_symbolCompressionTransform* symbolTT = (const FSE_symbolCompressionTransform*) symbolTTPtr;
539
return (symbolTT[symbolValue].deltaNbBits + ((1<<16)-1)) >> 16;
540
}
541
542
/* FSE_bitCost() :
543
* Approximate symbol cost, as fractional value, using fixed-point format (accuracyLog fractional bits)
544
* note 1 : assume symbolValue is valid (<= maxSymbolValue)
545
* note 2 : if freq[symbolValue]==0, @return a fake cost of tableLog+1 bits */
546
MEM_STATIC U32 FSE_bitCost(const void* symbolTTPtr, U32 tableLog, U32 symbolValue, U32 accuracyLog)
547
{
548
const FSE_symbolCompressionTransform* symbolTT = (const FSE_symbolCompressionTransform*) symbolTTPtr;
549
U32 const minNbBits = symbolTT[symbolValue].deltaNbBits >> 16;
550
U32 const threshold = (minNbBits+1) << 16;
551
assert(tableLog < 16);
552
assert(accuracyLog < 31-tableLog); /* ensure enough room for renormalization double shift */
553
{ U32 const tableSize = 1 << tableLog;
554
U32 const deltaFromThreshold = threshold - (symbolTT[symbolValue].deltaNbBits + tableSize);
555
U32 const normalizedDeltaFromThreshold = (deltaFromThreshold << accuracyLog) >> tableLog; /* linear interpolation (very approximate) */
556
U32 const bitMultiplier = 1 << accuracyLog;
557
assert(symbolTT[symbolValue].deltaNbBits + tableSize <= threshold);
558
assert(normalizedDeltaFromThreshold <= bitMultiplier);
559
return (minNbBits+1)*bitMultiplier - normalizedDeltaFromThreshold;
560
}
561
}
562
563
564
/* ====== Decompression ====== */
565
566
typedef struct {
567
U16 tableLog;
568
U16 fastMode;
569
} FSE_DTableHeader; /* sizeof U32 */
570
571
typedef struct
572
{
573
unsigned short newState;
574
unsigned char symbol;
575
unsigned char nbBits;
576
} FSE_decode_t; /* size == U32 */
577
578
MEM_STATIC void FSE_initDState(FSE_DState_t* DStatePtr, BIT_DStream_t* bitD, const FSE_DTable* dt)
579
{
580
const void* ptr = dt;
581
const FSE_DTableHeader* const DTableH = (const FSE_DTableHeader*)ptr;
582
DStatePtr->state = BIT_readBits(bitD, DTableH->tableLog);
583
BIT_reloadDStream(bitD);
584
DStatePtr->table = dt + 1;
585
}
586
587
MEM_STATIC BYTE FSE_peekSymbol(const FSE_DState_t* DStatePtr)
588
{
589
FSE_decode_t const DInfo = ((const FSE_decode_t*)(DStatePtr->table))[DStatePtr->state];
590
return DInfo.symbol;
591
}
592
593
MEM_STATIC void FSE_updateState(FSE_DState_t* DStatePtr, BIT_DStream_t* bitD)
594
{
595
FSE_decode_t const DInfo = ((const FSE_decode_t*)(DStatePtr->table))[DStatePtr->state];
596
U32 const nbBits = DInfo.nbBits;
597
size_t const lowBits = BIT_readBits(bitD, nbBits);
598
DStatePtr->state = DInfo.newState + lowBits;
599
}
600
601
MEM_STATIC BYTE FSE_decodeSymbol(FSE_DState_t* DStatePtr, BIT_DStream_t* bitD)
602
{
603
FSE_decode_t const DInfo = ((const FSE_decode_t*)(DStatePtr->table))[DStatePtr->state];
604
U32 const nbBits = DInfo.nbBits;
605
BYTE const symbol = DInfo.symbol;
606
size_t const lowBits = BIT_readBits(bitD, nbBits);
607
608
DStatePtr->state = DInfo.newState + lowBits;
609
return symbol;
610
}
611
612
/*! FSE_decodeSymbolFast() :
613
unsafe, only works if no symbol has a probability > 50% */
614
MEM_STATIC BYTE FSE_decodeSymbolFast(FSE_DState_t* DStatePtr, BIT_DStream_t* bitD)
615
{
616
FSE_decode_t const DInfo = ((const FSE_decode_t*)(DStatePtr->table))[DStatePtr->state];
617
U32 const nbBits = DInfo.nbBits;
618
BYTE const symbol = DInfo.symbol;
619
size_t const lowBits = BIT_readBitsFast(bitD, nbBits);
620
621
DStatePtr->state = DInfo.newState + lowBits;
622
return symbol;
623
}
624
625
MEM_STATIC unsigned FSE_endOfDState(const FSE_DState_t* DStatePtr)
626
{
627
return DStatePtr->state == 0;
628
}
629
630
631
632
#ifndef FSE_COMMONDEFS_ONLY
633
634
/* **************************************************************
635
* Tuning parameters
636
****************************************************************/
637
/*!MEMORY_USAGE :
638
* Memory usage formula : N->2^N Bytes (examples : 10 -> 1KB; 12 -> 4KB ; 16 -> 64KB; 20 -> 1MB; etc.)
639
* Increasing memory usage improves compression ratio
640
* Reduced memory usage can improve speed, due to cache effect
641
* Recommended max value is 14, for 16KB, which nicely fits into Intel x86 L1 cache */
642
#ifndef FSE_MAX_MEMORY_USAGE
643
# define FSE_MAX_MEMORY_USAGE 14
644
#endif
645
#ifndef FSE_DEFAULT_MEMORY_USAGE
646
# define FSE_DEFAULT_MEMORY_USAGE 13
647
#endif
648
649
/*!FSE_MAX_SYMBOL_VALUE :
650
* Maximum symbol value authorized.
651
* Required for proper stack allocation */
652
#ifndef FSE_MAX_SYMBOL_VALUE
653
# define FSE_MAX_SYMBOL_VALUE 255
654
#endif
655
656
/* **************************************************************
657
* template functions type & suffix
658
****************************************************************/
659
#define FSE_FUNCTION_TYPE BYTE
660
#define FSE_FUNCTION_EXTENSION
661
#define FSE_DECODE_TYPE FSE_decode_t
662
663
664
#endif /* !FSE_COMMONDEFS_ONLY */
665
666
667
/* ***************************************************************
668
* Constants
669
*****************************************************************/
670
#define FSE_MAX_TABLELOG (FSE_MAX_MEMORY_USAGE-2)
671
#define FSE_MAX_TABLESIZE (1U<<FSE_MAX_TABLELOG)
672
#define FSE_MAXTABLESIZE_MASK (FSE_MAX_TABLESIZE-1)
673
#define FSE_DEFAULT_TABLELOG (FSE_DEFAULT_MEMORY_USAGE-2)
674
#define FSE_MIN_TABLELOG 5
675
676
#define FSE_TABLELOG_ABSOLUTE_MAX 15
677
#if FSE_MAX_TABLELOG > FSE_TABLELOG_ABSOLUTE_MAX
678
# error "FSE_MAX_TABLELOG > FSE_TABLELOG_ABSOLUTE_MAX is not supported"
679
#endif
680
681
#define FSE_TABLESTEP(tableSize) ((tableSize>>1) + (tableSize>>3) + 3)
682
683
684
#endif /* FSE_STATIC_LINKING_ONLY */
685
686
687
#if defined (__cplusplus)
688
}
689
#endif
690
691