blob: 0d27265a1a9c55c7181459b9d54dd987c3c6cfa3 [file] [log] [blame]
Nick Terrellac58c8d2020-03-26 15:19:05 -07001/* ******************************************************************
2 * Common functions of New Generation Entropy library
3 * Copyright (c) 2016-2020, Yann Collet, Facebook, Inc.
4 *
5 * You can contact the author at :
6 * - FSE+HUF source repository : https://github.com/Cyan4973/FiniteStateEntropy
7 * - Public forum : https://groups.google.com/forum/#!forum/lz4c
8 *
9 * This source code is licensed under both the BSD-style license (found in the
10 * LICENSE file in the root directory of this source tree) and the GPLv2 (found
11 * in the COPYING file in the root directory of this source tree).
12 * You may select, at your option, one of the above-listed licenses.
13****************************************************************** */
inikep63ecd742016-05-13 11:27:56 +020014
15/* *************************************
16* Dependencies
17***************************************/
inikep63ecd742016-05-13 11:27:56 +020018#include "mem.h"
Yann Colleta91ca622016-06-05 01:33:55 +020019#include "error_private.h" /* ERR_*, ERROR */
Yann Colletd0e2cd12016-06-05 00:58:01 +020020#define FSE_STATIC_LINKING_ONLY /* FSE_MIN_TABLELOG */
Yann Collet38b75dd2016-07-24 15:35:59 +020021#include "fse.h"
Yann Colleta91ca622016-06-05 01:33:55 +020022#define HUF_STATIC_LINKING_ONLY /* HUF_TABLELOG_ABSOLUTEMAX */
Yann Collet38b75dd2016-07-24 15:35:59 +020023#include "huf.h"
inikep63ecd742016-05-13 11:27:56 +020024
25
Yann Collet1f2c95c2017-03-05 21:07:20 -080026/*=== Version ===*/
Yann Collet45960372017-02-15 12:00:03 -080027unsigned FSE_versionNumber(void) { return FSE_VERSION_NUMBER; }
28
29
Yann Collet1f2c95c2017-03-05 21:07:20 -080030/*=== Error Management ===*/
inikep63ecd742016-05-13 11:27:56 +020031unsigned FSE_isError(size_t code) { return ERR_isError(code); }
inikep63ecd742016-05-13 11:27:56 +020032const char* FSE_getErrorName(size_t code) { return ERR_getErrorName(code); }
33
inikep63ecd742016-05-13 11:27:56 +020034unsigned HUF_isError(size_t code) { return ERR_isError(code); }
inikep63ecd742016-05-13 11:27:56 +020035const char* HUF_getErrorName(size_t code) { return ERR_getErrorName(code); }
36
37
38/*-**************************************************************
39* FSE NCount encoding-decoding
40****************************************************************/
Nick Terrell8f8bd2d2020-08-18 16:57:35 -070041static U32 FSE_ctz(U32 val)
42{
43 assert(val != 0);
44 {
45# if defined(_MSC_VER) /* Visual */
46 unsigned long r=0;
47 return _BitScanForward(&r, val) ? (unsigned)r : 0;
48# elif defined(__GNUC__) && (__GNUC__ >= 3) /* GCC Intrinsic */
49 return __builtin_ctz(val);
50# elif defined(__ICCARM__) /* IAR Intrinsic */
51 return __CTZ(val);
52# else /* Software version */
53 U32 count = 0;
54 while ((val & 1) == 0) {
55 val >>= 1;
56 ++count;
57 }
58 return count;
59# endif
60 }
61}
62
Nick Terrell612e9472020-08-17 13:44:49 -070063FORCE_INLINE_TEMPLATE
64size_t FSE_readNCount_body(short* normalizedCounter, unsigned* maxSVPtr, unsigned* tableLogPtr,
65 const void* headerBuffer, size_t hbSize)
inikep63ecd742016-05-13 11:27:56 +020066{
67 const BYTE* const istart = (const BYTE*) headerBuffer;
68 const BYTE* const iend = istart + hbSize;
69 const BYTE* ip = istart;
70 int nbBits;
71 int remaining;
72 int threshold;
73 U32 bitStream;
74 int bitCount;
75 unsigned charnum = 0;
Nick Terrell6004c112020-08-14 15:28:59 -070076 unsigned const maxSV1 = *maxSVPtr + 1;
inikep63ecd742016-05-13 11:27:56 +020077 int previous0 = 0;
78
Nick Terrell8f8bd2d2020-08-18 16:57:35 -070079 if (hbSize < 8) {
Nick Terrell8def0e52020-08-24 12:24:45 -070080 /* This function only works when hbSize >= 8 */
Nick Terrell8f8bd2d2020-08-18 16:57:35 -070081 char buffer[8] = {0};
Nick Terrellf2d09242018-05-23 14:58:58 -070082 memcpy(buffer, headerBuffer, hbSize);
83 { size_t const countSize = FSE_readNCount(normalizedCounter, maxSVPtr, tableLogPtr,
84 buffer, sizeof(buffer));
85 if (FSE_isError(countSize)) return countSize;
86 if (countSize > hbSize) return ERROR(corruption_detected);
87 return countSize;
88 } }
Nick Terrell8def0e52020-08-24 12:24:45 -070089 assert(hbSize >= 8);
Nick Terrella97e9a62018-05-23 12:16:00 -070090
Yann Colletff773bf2018-06-26 17:24:41 -070091 /* init */
92 memset(normalizedCounter, 0, (*maxSVPtr+1) * sizeof(normalizedCounter[0])); /* all symbols not present in NCount have a frequency of 0 */
inikep63ecd742016-05-13 11:27:56 +020093 bitStream = MEM_readLE32(ip);
94 nbBits = (bitStream & 0xF) + FSE_MIN_TABLELOG; /* extract tableLog */
95 if (nbBits > FSE_TABLELOG_ABSOLUTE_MAX) return ERROR(tableLog_tooLarge);
96 bitStream >>= 4;
97 bitCount = 4;
98 *tableLogPtr = nbBits;
99 remaining = (1<<nbBits)+1;
100 threshold = 1<<nbBits;
101 nbBits++;
102
Nick Terrell6004c112020-08-14 15:28:59 -0700103 for (;;) {
inikep63ecd742016-05-13 11:27:56 +0200104 if (previous0) {
Nick Terrell8def0e52020-08-24 12:24:45 -0700105 /* Count the number of repeats. Each time the
106 * 2-bit repeat code is 0b11 there is another
107 * repeat.
108 * Avoid UB by setting the high bit to 1.
109 */
Nick Terrell8f8bd2d2020-08-18 16:57:35 -0700110 int repeats = FSE_ctz(~bitStream | 0x80000000) >> 1;
Nick Terrell6004c112020-08-14 15:28:59 -0700111 while (repeats >= 12) {
112 charnum += 3 * 12;
Nick Terrell8f8bd2d2020-08-18 16:57:35 -0700113 if (ip <= iend-7) {
Nick Terrell6004c112020-08-14 15:28:59 -0700114 ip += 3;
inikep63ecd742016-05-13 11:27:56 +0200115 bitStream = MEM_readLE32(ip) >> bitCount;
116 } else {
Nick Terrell6004c112020-08-14 15:28:59 -0700117 bitStream >>= 24;
118 bitCount += 24;
119 }
Nick Terrell8f8bd2d2020-08-18 16:57:35 -0700120 repeats = FSE_ctz(~bitStream | 0x80000000) >> 1;
inikep63ecd742016-05-13 11:27:56 +0200121 }
Nick Terrell6004c112020-08-14 15:28:59 -0700122 charnum += 3 * repeats;
123 bitStream >>= 2 * repeats;
124 bitCount += 2 * repeats;
125
Nick Terrell8def0e52020-08-24 12:24:45 -0700126 /* Add the final repeat which isn't 0b11. */
Nick Terrell6004c112020-08-14 15:28:59 -0700127 charnum += bitStream & 3;
inikep63ecd742016-05-13 11:27:56 +0200128 bitCount += 2;
Nick Terrell6004c112020-08-14 15:28:59 -0700129
130 /* This is an error, but break and return an error
131 * at the end, because returning out of a loop makes
132 * it harder for the compiler to optimize.
133 */
134 if (charnum >= maxSV1) break;
135
136 /* We don't need to set the normalized count to 0
137 * because we already memset the whole buffer to 0.
138 */
139
inikep63ecd742016-05-13 11:27:56 +0200140 if ((ip <= iend-7) || (ip + (bitCount>>3) <= iend-4)) {
Nick Terrella97e9a62018-05-23 12:16:00 -0700141 assert((bitCount >> 3) <= 3); /* For first condition to work */
inikep63ecd742016-05-13 11:27:56 +0200142 ip += bitCount>>3;
143 bitCount &= 7;
144 bitStream = MEM_readLE32(ip) >> bitCount;
Yann Collet38b75dd2016-07-24 15:35:59 +0200145 } else {
inikep63ecd742016-05-13 11:27:56 +0200146 bitStream >>= 2;
Nick Terrell6004c112020-08-14 15:28:59 -0700147 }
148 }
149 {
150 int const max = (2*threshold-1) - remaining;
Yann Collet45960372017-02-15 12:00:03 -0800151 int count;
inikep63ecd742016-05-13 11:27:56 +0200152
153 if ((bitStream & (threshold-1)) < (U32)max) {
Yann Collet45960372017-02-15 12:00:03 -0800154 count = bitStream & (threshold-1);
155 bitCount += nbBits-1;
inikep63ecd742016-05-13 11:27:56 +0200156 } else {
Yann Collet45960372017-02-15 12:00:03 -0800157 count = bitStream & (2*threshold-1);
inikep63ecd742016-05-13 11:27:56 +0200158 if (count >= threshold) count -= max;
Yann Collet45960372017-02-15 12:00:03 -0800159 bitCount += nbBits;
inikep63ecd742016-05-13 11:27:56 +0200160 }
161
162 count--; /* extra accuracy */
Nick Terrell6004c112020-08-14 15:28:59 -0700163 /* When it matters (small blocks), this is a
164 * predictable branch, because we don't use -1.
165 */
166 if (count >= 0) {
167 remaining -= count;
168 } else {
169 assert(count == -1);
170 remaining += count;
171 }
Yann Collet45960372017-02-15 12:00:03 -0800172 normalizedCounter[charnum++] = (short)count;
inikep63ecd742016-05-13 11:27:56 +0200173 previous0 = !count;
inikep63ecd742016-05-13 11:27:56 +0200174
Nick Terrell6004c112020-08-14 15:28:59 -0700175 assert(threshold > 1);
176 if (remaining < threshold) {
177 /* This branch can be folded into the
178 * threshold update condition because we
179 * know that threshold > 1.
180 */
181 if (remaining <= 1) break;
182 nbBits = BIT_highbit32(remaining) + 1;
183 threshold = 1 << (nbBits - 1);
184 }
185 if (charnum >= maxSV1) break;
186
187 if (LIKELY((ip <= iend-7) || (ip + (bitCount>>3) <= iend-4))) {
inikep63ecd742016-05-13 11:27:56 +0200188 ip += bitCount>>3;
189 bitCount &= 7;
190 } else {
191 bitCount -= (int)(8 * (iend - 4 - ip));
192 ip = iend - 4;
193 }
194 bitStream = MEM_readLE32(ip) >> (bitCount & 31);
Nick Terrell6004c112020-08-14 15:28:59 -0700195 } }
Yann Collet38b75dd2016-07-24 15:35:59 +0200196 if (remaining != 1) return ERROR(corruption_detected);
Nick Terrell6004c112020-08-14 15:28:59 -0700197 /* Only possible when there are too many zeros. */
198 if (charnum > maxSV1) return ERROR(maxSymbolValue_tooSmall);
Yann Colletcbc5e9d2016-07-24 18:02:04 +0200199 if (bitCount > 32) return ERROR(corruption_detected);
inikep63ecd742016-05-13 11:27:56 +0200200 *maxSVPtr = charnum-1;
201
202 ip += (bitCount+7)>>3;
inikep63ecd742016-05-13 11:27:56 +0200203 return ip-istart;
204}
Yann Colleta91ca622016-06-05 01:33:55 +0200205
Nick Terrell6d2f7502020-08-24 14:44:33 -0700206/* Avoids the FORCE_INLINE of the _body() function. */
Nick Terrell612e9472020-08-17 13:44:49 -0700207static size_t FSE_readNCount_body_default(
208 short* normalizedCounter, unsigned* maxSVPtr, unsigned* tableLogPtr,
209 const void* headerBuffer, size_t hbSize)
210{
211 return FSE_readNCount_body(normalizedCounter, maxSVPtr, tableLogPtr, headerBuffer, hbSize);
212}
213
214#if DYNAMIC_BMI2
215TARGET_ATTRIBUTE("bmi2") static size_t FSE_readNCount_body_bmi2(
216 short* normalizedCounter, unsigned* maxSVPtr, unsigned* tableLogPtr,
217 const void* headerBuffer, size_t hbSize)
218{
219 return FSE_readNCount_body(normalizedCounter, maxSVPtr, tableLogPtr, headerBuffer, hbSize);
220}
221#endif
222
223size_t FSE_readNCount_bmi2(
224 short* normalizedCounter, unsigned* maxSVPtr, unsigned* tableLogPtr,
225 const void* headerBuffer, size_t hbSize, int bmi2)
226{
227#if DYNAMIC_BMI2
228 if (bmi2) {
229 return FSE_readNCount_body_bmi2(normalizedCounter, maxSVPtr, tableLogPtr, headerBuffer, hbSize);
230 }
231#endif
232 (void)bmi2;
233 return FSE_readNCount_body_default(normalizedCounter, maxSVPtr, tableLogPtr, headerBuffer, hbSize);
234}
235
236size_t FSE_readNCount(
237 short* normalizedCounter, unsigned* maxSVPtr, unsigned* tableLogPtr,
238 const void* headerBuffer, size_t hbSize)
239{
240 return FSE_readNCount_bmi2(normalizedCounter, maxSVPtr, tableLogPtr, headerBuffer, hbSize, /* bmi2 */ 0);
241}
242
243
Yann Colleta91ca622016-06-05 01:33:55 +0200244/*! HUF_readStats() :
245 Read compact Huffman tree, saved by HUF_writeCTable().
246 `huffWeight` is destination buffer.
Yann Colletb89af202016-12-01 18:24:59 -0800247 `rankStats` is assumed to be a table of at least HUF_TABLELOG_MAX U32.
Yann Colleta91ca622016-06-05 01:33:55 +0200248 @return : size read from `src` , or an error Code .
Yann Collet38b75dd2016-07-24 15:35:59 +0200249 Note : Needed by HUF_readCTable() and HUF_readDTableX?() .
Yann Colleta91ca622016-06-05 01:33:55 +0200250*/
251size_t HUF_readStats(BYTE* huffWeight, size_t hwSize, U32* rankStats,
252 U32* nbSymbolsPtr, U32* tableLogPtr,
253 const void* src, size_t srcSize)
254{
Nick Terrellba1fd172020-08-16 22:22:33 -0700255 U32 wksp[HUF_READ_STATS_WORKSPACE_SIZE_U32];
Nick Terrell612e9472020-08-17 13:44:49 -0700256 return HUF_readStats_wksp(huffWeight, hwSize, rankStats, nbSymbolsPtr, tableLogPtr, src, srcSize, wksp, sizeof(wksp), /* bmi2 */ 0);
Nick Terrellba1fd172020-08-16 22:22:33 -0700257}
258
Nick Terrell612e9472020-08-17 13:44:49 -0700259FORCE_INLINE_TEMPLATE size_t HUF_readStats_body(BYTE* huffWeight, size_t hwSize, U32* rankStats,
Nick Terrellba1fd172020-08-16 22:22:33 -0700260 U32* nbSymbolsPtr, U32* tableLogPtr,
261 const void* src, size_t srcSize,
Nick Terrell612e9472020-08-17 13:44:49 -0700262 void* workSpace, size_t wkspSize,
263 int bmi2)
Nick Terrellba1fd172020-08-16 22:22:33 -0700264{
Yann Colleta91ca622016-06-05 01:33:55 +0200265 U32 weightTotal;
266 const BYTE* ip = (const BYTE*) src;
Nick Terrellccfcc642016-10-17 11:28:02 -0700267 size_t iSize;
Yann Colleta91ca622016-06-05 01:33:55 +0200268 size_t oSize;
269
Nick Terrellccfcc642016-10-17 11:28:02 -0700270 if (!srcSize) return ERROR(srcSize_wrong);
271 iSize = ip[0];
Yann Collet7ed5e332016-07-24 14:26:11 +0200272 /* memset(huffWeight, 0, hwSize); *//* is not necessary, even though some analyzer complain ... */
Yann Colleta91ca622016-06-05 01:33:55 +0200273
Yann Collet7ed5e332016-07-24 14:26:11 +0200274 if (iSize >= 128) { /* special header */
Yann Collet38b75dd2016-07-24 15:35:59 +0200275 oSize = iSize - 127;
276 iSize = ((oSize+1)/2);
277 if (iSize+1 > srcSize) return ERROR(srcSize_wrong);
278 if (oSize >= hwSize) return ERROR(corruption_detected);
279 ip += 1;
280 { U32 n;
281 for (n=0; n<oSize; n+=2) {
282 huffWeight[n] = ip[n/2] >> 4;
283 huffWeight[n+1] = ip[n/2] & 15;
284 } } }
Yann Colleta91ca622016-06-05 01:33:55 +0200285 else { /* header compressed with FSE (normal case) */
286 if (iSize+1 > srcSize) return ERROR(srcSize_wrong);
Nick Terrell612e9472020-08-17 13:44:49 -0700287 oSize = FSE_decompress_wksp_bmi2(huffWeight, hwSize-1, ip+1, iSize, 6, workSpace, wkspSize, bmi2); /* max (hwSize-1) values decoded, as last one is implied */
Yann Colleta91ca622016-06-05 01:33:55 +0200288 if (FSE_isError(oSize)) return oSize;
289 }
290
291 /* collect weight stats */
Yann Colletb89af202016-12-01 18:24:59 -0800292 memset(rankStats, 0, (HUF_TABLELOG_MAX + 1) * sizeof(U32));
Yann Colleta91ca622016-06-05 01:33:55 +0200293 weightTotal = 0;
294 { U32 n; for (n=0; n<oSize; n++) {
Yann Colletb89af202016-12-01 18:24:59 -0800295 if (huffWeight[n] >= HUF_TABLELOG_MAX) return ERROR(corruption_detected);
Yann Colleta91ca622016-06-05 01:33:55 +0200296 rankStats[huffWeight[n]]++;
297 weightTotal += (1 << huffWeight[n]) >> 1;
298 } }
Nick Terrelld7605292016-10-19 11:19:54 -0700299 if (weightTotal == 0) return ERROR(corruption_detected);
Yann Colleta91ca622016-06-05 01:33:55 +0200300
301 /* get last non-null symbol weight (implied, total must be 2^n) */
302 { U32 const tableLog = BIT_highbit32(weightTotal) + 1;
Yann Colletb89af202016-12-01 18:24:59 -0800303 if (tableLog > HUF_TABLELOG_MAX) return ERROR(corruption_detected);
Yann Colleta91ca622016-06-05 01:33:55 +0200304 *tableLogPtr = tableLog;
305 /* determine last weight */
306 { U32 const total = 1 << tableLog;
307 U32 const rest = total - weightTotal;
308 U32 const verif = 1 << BIT_highbit32(rest);
309 U32 const lastWeight = BIT_highbit32(rest) + 1;
310 if (verif != rest) return ERROR(corruption_detected); /* last value must be a clean power of 2 */
311 huffWeight[oSize] = (BYTE)lastWeight;
312 rankStats[lastWeight]++;
313 } }
314
315 /* check tree construction validity */
316 if ((rankStats[1] < 2) || (rankStats[1] & 1)) return ERROR(corruption_detected); /* by construction : at least 2 elts of rank 1, must be even */
317
318 /* results */
319 *nbSymbolsPtr = (U32)(oSize+1);
320 return iSize+1;
321}
Nick Terrell612e9472020-08-17 13:44:49 -0700322
Nick Terrell6d2f7502020-08-24 14:44:33 -0700323/* Avoids the FORCE_INLINE of the _body() function. */
Nick Terrell612e9472020-08-17 13:44:49 -0700324static size_t HUF_readStats_body_default(BYTE* huffWeight, size_t hwSize, U32* rankStats,
325 U32* nbSymbolsPtr, U32* tableLogPtr,
326 const void* src, size_t srcSize,
327 void* workSpace, size_t wkspSize)
328{
329 return HUF_readStats_body(huffWeight, hwSize, rankStats, nbSymbolsPtr, tableLogPtr, src, srcSize, workSpace, wkspSize, 0);
330}
331
332#if DYNAMIC_BMI2
333static TARGET_ATTRIBUTE("bmi2") size_t HUF_readStats_body_bmi2(BYTE* huffWeight, size_t hwSize, U32* rankStats,
334 U32* nbSymbolsPtr, U32* tableLogPtr,
335 const void* src, size_t srcSize,
336 void* workSpace, size_t wkspSize)
337{
338 return HUF_readStats_body(huffWeight, hwSize, rankStats, nbSymbolsPtr, tableLogPtr, src, srcSize, workSpace, wkspSize, 1);
339}
340#endif
341
342size_t HUF_readStats_wksp(BYTE* huffWeight, size_t hwSize, U32* rankStats,
343 U32* nbSymbolsPtr, U32* tableLogPtr,
344 const void* src, size_t srcSize,
345 void* workSpace, size_t wkspSize,
346 int bmi2)
347{
348#if DYNAMIC_BMI2
349 if (bmi2) {
350 return HUF_readStats_body_bmi2(huffWeight, hwSize, rankStats, nbSymbolsPtr, tableLogPtr, src, srcSize, workSpace, wkspSize);
351 }
352#endif
353 (void)bmi2;
354 return HUF_readStats_body_default(huffWeight, hwSize, rankStats, nbSymbolsPtr, tableLogPtr, src, srcSize, workSpace, wkspSize);
355}