You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

zstd_compress_sequences.c 19KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  1. /*
  2. * Copyright (c) 2016-2020, Yann Collet, Facebook, Inc.
  3. * All rights reserved.
  4. *
  5. * This source code is licensed under both the BSD-style license (found in the
  6. * LICENSE file in the root directory of this source tree) and the GPLv2 (found
  7. * in the COPYING file in the root directory of this source tree).
  8. * You may select, at your option, one of the above-listed licenses.
  9. */
  10. /*-*************************************
  11. * Dependencies
  12. ***************************************/
  13. #include "zstd_compress_sequences.h"
  14. /**
  15. * -log2(x / 256) lookup table for x in [0, 256).
  16. * If x == 0: Return 0
  17. * Else: Return floor(-log2(x / 256) * 256)
  18. */
  19. static unsigned const kInverseProbabilityLog256[256] = {
  20. 0, 2048, 1792, 1642, 1536, 1453, 1386, 1329, 1280, 1236, 1197, 1162,
  21. 1130, 1100, 1073, 1047, 1024, 1001, 980, 960, 941, 923, 906, 889,
  22. 874, 859, 844, 830, 817, 804, 791, 779, 768, 756, 745, 734,
  23. 724, 714, 704, 694, 685, 676, 667, 658, 650, 642, 633, 626,
  24. 618, 610, 603, 595, 588, 581, 574, 567, 561, 554, 548, 542,
  25. 535, 529, 523, 517, 512, 506, 500, 495, 489, 484, 478, 473,
  26. 468, 463, 458, 453, 448, 443, 438, 434, 429, 424, 420, 415,
  27. 411, 407, 402, 398, 394, 390, 386, 382, 377, 373, 370, 366,
  28. 362, 358, 354, 350, 347, 343, 339, 336, 332, 329, 325, 322,
  29. 318, 315, 311, 308, 305, 302, 298, 295, 292, 289, 286, 282,
  30. 279, 276, 273, 270, 267, 264, 261, 258, 256, 253, 250, 247,
  31. 244, 241, 239, 236, 233, 230, 228, 225, 222, 220, 217, 215,
  32. 212, 209, 207, 204, 202, 199, 197, 194, 192, 190, 187, 185,
  33. 182, 180, 178, 175, 173, 171, 168, 166, 164, 162, 159, 157,
  34. 155, 153, 151, 149, 146, 144, 142, 140, 138, 136, 134, 132,
  35. 130, 128, 126, 123, 121, 119, 117, 115, 114, 112, 110, 108,
  36. 106, 104, 102, 100, 98, 96, 94, 93, 91, 89, 87, 85,
  37. 83, 82, 80, 78, 76, 74, 73, 71, 69, 67, 66, 64,
  38. 62, 61, 59, 57, 55, 54, 52, 50, 49, 47, 46, 44,
  39. 42, 41, 39, 37, 36, 34, 33, 31, 30, 28, 26, 25,
  40. 23, 22, 20, 19, 17, 16, 14, 13, 11, 10, 8, 7,
  41. 5, 4, 2, 1,
  42. };
  43. static unsigned ZSTD_getFSEMaxSymbolValue(FSE_CTable const* ctable) {
  44. void const* ptr = ctable;
  45. U16 const* u16ptr = (U16 const*)ptr;
  46. U32 const maxSymbolValue = MEM_read16(u16ptr + 1);
  47. return maxSymbolValue;
  48. }
  49. /**
  50. * Returns the cost in bytes of encoding the normalized count header.
  51. * Returns an error if any of the helper functions return an error.
  52. */
  53. static size_t ZSTD_NCountCost(unsigned const* count, unsigned const max,
  54. size_t const nbSeq, unsigned const FSELog)
  55. {
  56. BYTE wksp[FSE_NCOUNTBOUND];
  57. S16 norm[MaxSeq + 1];
  58. const U32 tableLog = FSE_optimalTableLog(FSELog, nbSeq, max);
  59. FORWARD_IF_ERROR(FSE_normalizeCount(norm, tableLog, count, nbSeq, max), "");
  60. return FSE_writeNCount(wksp, sizeof(wksp), norm, max, tableLog);
  61. }
  62. /**
  63. * Returns the cost in bits of encoding the distribution described by count
  64. * using the entropy bound.
  65. */
  66. static size_t ZSTD_entropyCost(unsigned const* count, unsigned const max, size_t const total)
  67. {
  68. unsigned cost = 0;
  69. unsigned s;
  70. for (s = 0; s <= max; ++s) {
  71. unsigned norm = (unsigned)((256 * count[s]) / total);
  72. if (count[s] != 0 && norm == 0)
  73. norm = 1;
  74. assert(count[s] < total);
  75. cost += count[s] * kInverseProbabilityLog256[norm];
  76. }
  77. return cost >> 8;
  78. }
  79. /**
  80. * Returns the cost in bits of encoding the distribution in count using ctable.
  81. * Returns an error if ctable cannot represent all the symbols in count.
  82. */
  83. size_t ZSTD_fseBitCost(
  84. FSE_CTable const* ctable,
  85. unsigned const* count,
  86. unsigned const max)
  87. {
  88. unsigned const kAccuracyLog = 8;
  89. size_t cost = 0;
  90. unsigned s;
  91. FSE_CState_t cstate;
  92. FSE_initCState(&cstate, ctable);
  93. if (ZSTD_getFSEMaxSymbolValue(ctable) < max) {
  94. DEBUGLOG(5, "Repeat FSE_CTable has maxSymbolValue %u < %u",
  95. ZSTD_getFSEMaxSymbolValue(ctable), max);
  96. return ERROR(GENERIC);
  97. }
  98. for (s = 0; s <= max; ++s) {
  99. unsigned const tableLog = cstate.stateLog;
  100. unsigned const badCost = (tableLog + 1) << kAccuracyLog;
  101. unsigned const bitCost = FSE_bitCost(cstate.symbolTT, tableLog, s, kAccuracyLog);
  102. if (count[s] == 0)
  103. continue;
  104. if (bitCost >= badCost) {
  105. DEBUGLOG(5, "Repeat FSE_CTable has Prob[%u] == 0", s);
  106. return ERROR(GENERIC);
  107. }
  108. cost += (size_t)count[s] * bitCost;
  109. }
  110. return cost >> kAccuracyLog;
  111. }
  112. /**
  113. * Returns the cost in bits of encoding the distribution in count using the
  114. * table described by norm. The max symbol support by norm is assumed >= max.
  115. * norm must be valid for every symbol with non-zero probability in count.
  116. */
  117. size_t ZSTD_crossEntropyCost(short const* norm, unsigned accuracyLog,
  118. unsigned const* count, unsigned const max)
  119. {
  120. unsigned const shift = 8 - accuracyLog;
  121. size_t cost = 0;
  122. unsigned s;
  123. assert(accuracyLog <= 8);
  124. for (s = 0; s <= max; ++s) {
  125. unsigned const normAcc = (norm[s] != -1) ? (unsigned)norm[s] : 1;
  126. unsigned const norm256 = normAcc << shift;
  127. assert(norm256 > 0);
  128. assert(norm256 < 256);
  129. cost += count[s] * kInverseProbabilityLog256[norm256];
  130. }
  131. return cost >> 8;
  132. }
  133. symbolEncodingType_e
  134. ZSTD_selectEncodingType(
  135. FSE_repeat* repeatMode, unsigned const* count, unsigned const max,
  136. size_t const mostFrequent, size_t nbSeq, unsigned const FSELog,
  137. FSE_CTable const* prevCTable,
  138. short const* defaultNorm, U32 defaultNormLog,
  139. ZSTD_defaultPolicy_e const isDefaultAllowed,
  140. ZSTD_strategy const strategy)
  141. {
  142. ZSTD_STATIC_ASSERT(ZSTD_defaultDisallowed == 0 && ZSTD_defaultAllowed != 0);
  143. if (mostFrequent == nbSeq) {
  144. *repeatMode = FSE_repeat_none;
  145. if (isDefaultAllowed && nbSeq <= 2) {
  146. /* Prefer set_basic over set_rle when there are 2 or less symbols,
  147. * since RLE uses 1 byte, but set_basic uses 5-6 bits per symbol.
  148. * If basic encoding isn't possible, always choose RLE.
  149. */
  150. DEBUGLOG(5, "Selected set_basic");
  151. return set_basic;
  152. }
  153. DEBUGLOG(5, "Selected set_rle");
  154. return set_rle;
  155. }
  156. if (strategy < ZSTD_lazy) {
  157. if (isDefaultAllowed) {
  158. size_t const staticFse_nbSeq_max = 1000;
  159. size_t const mult = 10 - strategy;
  160. size_t const baseLog = 3;
  161. size_t const dynamicFse_nbSeq_min = (((size_t)1 << defaultNormLog) * mult) >> baseLog; /* 28-36 for offset, 56-72 for lengths */
  162. assert(defaultNormLog >= 5 && defaultNormLog <= 6); /* xx_DEFAULTNORMLOG */
  163. assert(mult <= 9 && mult >= 7);
  164. if ( (*repeatMode == FSE_repeat_valid)
  165. && (nbSeq < staticFse_nbSeq_max) ) {
  166. DEBUGLOG(5, "Selected set_repeat");
  167. return set_repeat;
  168. }
  169. if ( (nbSeq < dynamicFse_nbSeq_min)
  170. || (mostFrequent < (nbSeq >> (defaultNormLog-1))) ) {
  171. DEBUGLOG(5, "Selected set_basic");
  172. /* The format allows default tables to be repeated, but it isn't useful.
  173. * When using simple heuristics to select encoding type, we don't want
  174. * to confuse these tables with dictionaries. When running more careful
  175. * analysis, we don't need to waste time checking both repeating tables
  176. * and default tables.
  177. */
  178. *repeatMode = FSE_repeat_none;
  179. return set_basic;
  180. }
  181. }
  182. } else {
  183. size_t const basicCost = isDefaultAllowed ? ZSTD_crossEntropyCost(defaultNorm, defaultNormLog, count, max) : ERROR(GENERIC);
  184. size_t const repeatCost = *repeatMode != FSE_repeat_none ? ZSTD_fseBitCost(prevCTable, count, max) : ERROR(GENERIC);
  185. size_t const NCountCost = ZSTD_NCountCost(count, max, nbSeq, FSELog);
  186. size_t const compressedCost = (NCountCost << 3) + ZSTD_entropyCost(count, max, nbSeq);
  187. if (isDefaultAllowed) {
  188. assert(!ZSTD_isError(basicCost));
  189. assert(!(*repeatMode == FSE_repeat_valid && ZSTD_isError(repeatCost)));
  190. }
  191. assert(!ZSTD_isError(NCountCost));
  192. assert(compressedCost < ERROR(maxCode));
  193. DEBUGLOG(5, "Estimated bit costs: basic=%u\trepeat=%u\tcompressed=%u",
  194. (unsigned)basicCost, (unsigned)repeatCost, (unsigned)compressedCost);
  195. if (basicCost <= repeatCost && basicCost <= compressedCost) {
  196. DEBUGLOG(5, "Selected set_basic");
  197. assert(isDefaultAllowed);
  198. *repeatMode = FSE_repeat_none;
  199. return set_basic;
  200. }
  201. if (repeatCost <= compressedCost) {
  202. DEBUGLOG(5, "Selected set_repeat");
  203. assert(!ZSTD_isError(repeatCost));
  204. return set_repeat;
  205. }
  206. assert(compressedCost < basicCost && compressedCost < repeatCost);
  207. }
  208. DEBUGLOG(5, "Selected set_compressed");
  209. *repeatMode = FSE_repeat_check;
  210. return set_compressed;
  211. }
  212. size_t
  213. ZSTD_buildCTable(void* dst, size_t dstCapacity,
  214. FSE_CTable* nextCTable, U32 FSELog, symbolEncodingType_e type,
  215. unsigned* count, U32 max,
  216. const BYTE* codeTable, size_t nbSeq,
  217. const S16* defaultNorm, U32 defaultNormLog, U32 defaultMax,
  218. const FSE_CTable* prevCTable, size_t prevCTableSize,
  219. void* entropyWorkspace, size_t entropyWorkspaceSize)
  220. {
  221. BYTE* op = (BYTE*)dst;
  222. const BYTE* const oend = op + dstCapacity;
  223. DEBUGLOG(6, "ZSTD_buildCTable (dstCapacity=%u)", (unsigned)dstCapacity);
  224. switch (type) {
  225. case set_rle:
  226. FORWARD_IF_ERROR(FSE_buildCTable_rle(nextCTable, (BYTE)max), "");
  227. RETURN_ERROR_IF(dstCapacity==0, dstSize_tooSmall, "not enough space");
  228. *op = codeTable[0];
  229. return 1;
  230. case set_repeat:
  231. memcpy(nextCTable, prevCTable, prevCTableSize);
  232. return 0;
  233. case set_basic:
  234. FORWARD_IF_ERROR(FSE_buildCTable_wksp(nextCTable, defaultNorm, defaultMax, defaultNormLog, entropyWorkspace, entropyWorkspaceSize), ""); /* note : could be pre-calculated */
  235. return 0;
  236. case set_compressed: {
  237. S16 norm[MaxSeq + 1];
  238. size_t nbSeq_1 = nbSeq;
  239. const U32 tableLog = FSE_optimalTableLog(FSELog, nbSeq, max);
  240. if (count[codeTable[nbSeq-1]] > 1) {
  241. count[codeTable[nbSeq-1]]--;
  242. nbSeq_1--;
  243. }
  244. assert(nbSeq_1 > 1);
  245. FORWARD_IF_ERROR(FSE_normalizeCount(norm, tableLog, count, nbSeq_1, max), "");
  246. { size_t const NCountSize = FSE_writeNCount(op, oend - op, norm, max, tableLog); /* overflow protected */
  247. FORWARD_IF_ERROR(NCountSize, "FSE_writeNCount failed");
  248. FORWARD_IF_ERROR(FSE_buildCTable_wksp(nextCTable, norm, max, tableLog, entropyWorkspace, entropyWorkspaceSize), "");
  249. return NCountSize;
  250. }
  251. }
  252. default: assert(0); RETURN_ERROR(GENERIC, "impossible to reach");
  253. }
  254. }
  255. FORCE_INLINE_TEMPLATE size_t
  256. ZSTD_encodeSequences_body(
  257. void* dst, size_t dstCapacity,
  258. FSE_CTable const* CTable_MatchLength, BYTE const* mlCodeTable,
  259. FSE_CTable const* CTable_OffsetBits, BYTE const* ofCodeTable,
  260. FSE_CTable const* CTable_LitLength, BYTE const* llCodeTable,
  261. seqDef const* sequences, size_t nbSeq, int longOffsets)
  262. {
  263. BIT_CStream_t blockStream;
  264. FSE_CState_t stateMatchLength;
  265. FSE_CState_t stateOffsetBits;
  266. FSE_CState_t stateLitLength;
  267. RETURN_ERROR_IF(
  268. ERR_isError(BIT_initCStream(&blockStream, dst, dstCapacity)),
  269. dstSize_tooSmall, "not enough space remaining");
  270. DEBUGLOG(6, "available space for bitstream : %i (dstCapacity=%u)",
  271. (int)(blockStream.endPtr - blockStream.startPtr),
  272. (unsigned)dstCapacity);
  273. /* first symbols */
  274. FSE_initCState2(&stateMatchLength, CTable_MatchLength, mlCodeTable[nbSeq-1]);
  275. FSE_initCState2(&stateOffsetBits, CTable_OffsetBits, ofCodeTable[nbSeq-1]);
  276. FSE_initCState2(&stateLitLength, CTable_LitLength, llCodeTable[nbSeq-1]);
  277. BIT_addBits(&blockStream, sequences[nbSeq-1].litLength, LL_bits[llCodeTable[nbSeq-1]]);
  278. if (MEM_32bits()) BIT_flushBits(&blockStream);
  279. BIT_addBits(&blockStream, sequences[nbSeq-1].matchLength, ML_bits[mlCodeTable[nbSeq-1]]);
  280. if (MEM_32bits()) BIT_flushBits(&blockStream);
  281. if (longOffsets) {
  282. U32 const ofBits = ofCodeTable[nbSeq-1];
  283. unsigned const extraBits = ofBits - MIN(ofBits, STREAM_ACCUMULATOR_MIN-1);
  284. if (extraBits) {
  285. BIT_addBits(&blockStream, sequences[nbSeq-1].offset, extraBits);
  286. BIT_flushBits(&blockStream);
  287. }
  288. BIT_addBits(&blockStream, sequences[nbSeq-1].offset >> extraBits,
  289. ofBits - extraBits);
  290. } else {
  291. BIT_addBits(&blockStream, sequences[nbSeq-1].offset, ofCodeTable[nbSeq-1]);
  292. }
  293. BIT_flushBits(&blockStream);
  294. { size_t n;
  295. for (n=nbSeq-2 ; n<nbSeq ; n--) { /* intentional underflow */
  296. BYTE const llCode = llCodeTable[n];
  297. BYTE const ofCode = ofCodeTable[n];
  298. BYTE const mlCode = mlCodeTable[n];
  299. U32 const llBits = LL_bits[llCode];
  300. U32 const ofBits = ofCode;
  301. U32 const mlBits = ML_bits[mlCode];
  302. DEBUGLOG(6, "encoding: litlen:%2u - matchlen:%2u - offCode:%7u",
  303. (unsigned)sequences[n].litLength,
  304. (unsigned)sequences[n].matchLength + MINMATCH,
  305. (unsigned)sequences[n].offset);
  306. /* 32b*/ /* 64b*/
  307. /* (7)*/ /* (7)*/
  308. FSE_encodeSymbol(&blockStream, &stateOffsetBits, ofCode); /* 15 */ /* 15 */
  309. FSE_encodeSymbol(&blockStream, &stateMatchLength, mlCode); /* 24 */ /* 24 */
  310. if (MEM_32bits()) BIT_flushBits(&blockStream); /* (7)*/
  311. FSE_encodeSymbol(&blockStream, &stateLitLength, llCode); /* 16 */ /* 33 */
  312. if (MEM_32bits() || (ofBits+mlBits+llBits >= 64-7-(LLFSELog+MLFSELog+OffFSELog)))
  313. BIT_flushBits(&blockStream); /* (7)*/
  314. BIT_addBits(&blockStream, sequences[n].litLength, llBits);
  315. if (MEM_32bits() && ((llBits+mlBits)>24)) BIT_flushBits(&blockStream);
  316. BIT_addBits(&blockStream, sequences[n].matchLength, mlBits);
  317. if (MEM_32bits() || (ofBits+mlBits+llBits > 56)) BIT_flushBits(&blockStream);
  318. if (longOffsets) {
  319. unsigned const extraBits = ofBits - MIN(ofBits, STREAM_ACCUMULATOR_MIN-1);
  320. if (extraBits) {
  321. BIT_addBits(&blockStream, sequences[n].offset, extraBits);
  322. BIT_flushBits(&blockStream); /* (7)*/
  323. }
  324. BIT_addBits(&blockStream, sequences[n].offset >> extraBits,
  325. ofBits - extraBits); /* 31 */
  326. } else {
  327. BIT_addBits(&blockStream, sequences[n].offset, ofBits); /* 31 */
  328. }
  329. BIT_flushBits(&blockStream); /* (7)*/
  330. DEBUGLOG(7, "remaining space : %i", (int)(blockStream.endPtr - blockStream.ptr));
  331. } }
  332. DEBUGLOG(6, "ZSTD_encodeSequences: flushing ML state with %u bits", stateMatchLength.stateLog);
  333. FSE_flushCState(&blockStream, &stateMatchLength);
  334. DEBUGLOG(6, "ZSTD_encodeSequences: flushing Off state with %u bits", stateOffsetBits.stateLog);
  335. FSE_flushCState(&blockStream, &stateOffsetBits);
  336. DEBUGLOG(6, "ZSTD_encodeSequences: flushing LL state with %u bits", stateLitLength.stateLog);
  337. FSE_flushCState(&blockStream, &stateLitLength);
  338. { size_t const streamSize = BIT_closeCStream(&blockStream);
  339. RETURN_ERROR_IF(streamSize==0, dstSize_tooSmall, "not enough space");
  340. return streamSize;
  341. }
  342. }
  343. static size_t
  344. ZSTD_encodeSequences_default(
  345. void* dst, size_t dstCapacity,
  346. FSE_CTable const* CTable_MatchLength, BYTE const* mlCodeTable,
  347. FSE_CTable const* CTable_OffsetBits, BYTE const* ofCodeTable,
  348. FSE_CTable const* CTable_LitLength, BYTE const* llCodeTable,
  349. seqDef const* sequences, size_t nbSeq, int longOffsets)
  350. {
  351. return ZSTD_encodeSequences_body(dst, dstCapacity,
  352. CTable_MatchLength, mlCodeTable,
  353. CTable_OffsetBits, ofCodeTable,
  354. CTable_LitLength, llCodeTable,
  355. sequences, nbSeq, longOffsets);
  356. }
  357. #if DYNAMIC_BMI2
  358. static TARGET_ATTRIBUTE("bmi2") size_t
  359. ZSTD_encodeSequences_bmi2(
  360. void* dst, size_t dstCapacity,
  361. FSE_CTable const* CTable_MatchLength, BYTE const* mlCodeTable,
  362. FSE_CTable const* CTable_OffsetBits, BYTE const* ofCodeTable,
  363. FSE_CTable const* CTable_LitLength, BYTE const* llCodeTable,
  364. seqDef const* sequences, size_t nbSeq, int longOffsets)
  365. {
  366. return ZSTD_encodeSequences_body(dst, dstCapacity,
  367. CTable_MatchLength, mlCodeTable,
  368. CTable_OffsetBits, ofCodeTable,
  369. CTable_LitLength, llCodeTable,
  370. sequences, nbSeq, longOffsets);
  371. }
  372. #endif
  373. size_t ZSTD_encodeSequences(
  374. void* dst, size_t dstCapacity,
  375. FSE_CTable const* CTable_MatchLength, BYTE const* mlCodeTable,
  376. FSE_CTable const* CTable_OffsetBits, BYTE const* ofCodeTable,
  377. FSE_CTable const* CTable_LitLength, BYTE const* llCodeTable,
  378. seqDef const* sequences, size_t nbSeq, int longOffsets, int bmi2)
  379. {
  380. DEBUGLOG(5, "ZSTD_encodeSequences: dstCapacity = %u", (unsigned)dstCapacity);
  381. #if DYNAMIC_BMI2
  382. if (bmi2) {
  383. return ZSTD_encodeSequences_bmi2(dst, dstCapacity,
  384. CTable_MatchLength, mlCodeTable,
  385. CTable_OffsetBits, ofCodeTable,
  386. CTable_LitLength, llCodeTable,
  387. sequences, nbSeq, longOffsets);
  388. }
  389. #endif
  390. (void)bmi2;
  391. return ZSTD_encodeSequences_default(dst, dstCapacity,
  392. CTable_MatchLength, mlCodeTable,
  393. CTable_OffsetBits, ofCodeTable,
  394. CTable_LitLength, llCodeTable,
  395. sequences, nbSeq, longOffsets);
  396. }