bitstream.h 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  1. /* ******************************************************************
  2. bitstream
  3. Part of FSE library
  4. Copyright (C) 2013-present, Yann Collet.
  5. BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)
  6. Redistribution and use in source and binary forms, with or without
  7. modification, are permitted provided that the following conditions are
  8. met:
  9. * Redistributions of source code must retain the above copyright
  10. notice, this list of conditions and the following disclaimer.
  11. * Redistributions in binary form must reproduce the above
  12. copyright notice, this list of conditions and the following disclaimer
  13. in the documentation and/or other materials provided with the
  14. distribution.
  15. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  16. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  17. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  18. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  19. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  20. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  21. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  22. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  23. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  24. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  25. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. You can contact the author at :
  27. - Source repository : https://github.com/Cyan4973/FiniteStateEntropy
  28. ****************************************************************** */
  29. #ifndef BITSTREAM_H_MODULE
  30. #define BITSTREAM_H_MODULE
  31. #if defined (__cplusplus)
  32. extern "C" {
  33. #endif
  34. /*
  35. * This API consists of small unitary functions, which must be inlined for best performance.
  36. * Since link-time-optimization is not available for all compilers,
  37. * these functions are defined into a .h to be included.
  38. */
  39. /*-****************************************
  40. * Dependencies
  41. ******************************************/
  42. #include "mem.h" /* unaligned access routines */
  43. #include "debug.h" /* assert(), DEBUGLOG(), RAWLOG() */
  44. #include "error_private.h" /* error codes and messages */
  45. /*=========================================
  46. * Target specific
  47. =========================================*/
  48. #if defined(__BMI__) && defined(__GNUC__)
  49. # include <immintrin.h> /* support for bextr (experimental) */
  50. #endif
  51. #define STREAM_ACCUMULATOR_MIN_32 25
  52. #define STREAM_ACCUMULATOR_MIN_64 57
  53. #define STREAM_ACCUMULATOR_MIN ((U32)(MEM_32bits() ? STREAM_ACCUMULATOR_MIN_32 : STREAM_ACCUMULATOR_MIN_64))
  54. /*-******************************************
  55. * bitStream encoding API (write forward)
  56. ********************************************/
  57. /* bitStream can mix input from multiple sources.
  58. * A critical property of these streams is that they encode and decode in **reverse** direction.
  59. * So the first bit sequence you add will be the last to be read, like a LIFO stack.
  60. */
  61. typedef struct {
  62. size_t bitContainer;
  63. unsigned bitPos;
  64. char* startPtr;
  65. char* ptr;
  66. char* endPtr;
  67. } BIT_CStream_t;
  68. MEM_STATIC size_t BIT_initCStream(BIT_CStream_t* bitC, void* dstBuffer, size_t dstCapacity);
  69. MEM_STATIC void BIT_addBits(BIT_CStream_t* bitC, size_t value, unsigned nbBits);
  70. MEM_STATIC void BIT_flushBits(BIT_CStream_t* bitC);
  71. MEM_STATIC size_t BIT_closeCStream(BIT_CStream_t* bitC);
  72. /* Start with initCStream, providing the size of buffer to write into.
  73. * bitStream will never write outside of this buffer.
  74. * `dstCapacity` must be >= sizeof(bitD->bitContainer), otherwise @return will be an error code.
  75. *
  76. * bits are first added to a local register.
  77. * Local register is size_t, hence 64-bits on 64-bits systems, or 32-bits on 32-bits systems.
  78. * Writing data into memory is an explicit operation, performed by the flushBits function.
  79. * Hence keep track how many bits are potentially stored into local register to avoid register overflow.
  80. * After a flushBits, a maximum of 7 bits might still be stored into local register.
  81. *
  82. * Avoid storing elements of more than 24 bits if you want compatibility with 32-bits bitstream readers.
  83. *
  84. * Last operation is to close the bitStream.
  85. * The function returns the final size of CStream in bytes.
  86. * If data couldn't fit into `dstBuffer`, it will return a 0 ( == not storable)
  87. */
  88. /*-********************************************
  89. * bitStream decoding API (read backward)
  90. **********************************************/
  91. typedef struct {
  92. size_t bitContainer;
  93. unsigned bitsConsumed;
  94. const char* ptr;
  95. const char* start;
  96. const char* limitPtr;
  97. } BIT_DStream_t;
  98. typedef enum { BIT_DStream_unfinished = 0,
  99. BIT_DStream_endOfBuffer = 1,
  100. BIT_DStream_completed = 2,
  101. BIT_DStream_overflow = 3 } BIT_DStream_status; /* result of BIT_reloadDStream() */
  102. /* 1,2,4,8 would be better for bitmap combinations, but slows down performance a bit ... :( */
  103. MEM_STATIC size_t BIT_initDStream(BIT_DStream_t* bitD, const void* srcBuffer, size_t srcSize);
  104. MEM_STATIC size_t BIT_readBits(BIT_DStream_t* bitD, unsigned nbBits);
  105. MEM_STATIC BIT_DStream_status BIT_reloadDStream(BIT_DStream_t* bitD);
  106. MEM_STATIC unsigned BIT_endOfDStream(const BIT_DStream_t* bitD);
  107. /* Start by invoking BIT_initDStream().
  108. * A chunk of the bitStream is then stored into a local register.
  109. * Local register size is 64-bits on 64-bits systems, 32-bits on 32-bits systems (size_t).
  110. * You can then retrieve bitFields stored into the local register, **in reverse order**.
  111. * Local register is explicitly reloaded from memory by the BIT_reloadDStream() method.
  112. * A reload guarantee a minimum of ((8*sizeof(bitD->bitContainer))-7) bits when its result is BIT_DStream_unfinished.
  113. * Otherwise, it can be less than that, so proceed accordingly.
  114. * Checking if DStream has reached its end can be performed with BIT_endOfDStream().
  115. */
  116. /*-****************************************
  117. * unsafe API
  118. ******************************************/
  119. MEM_STATIC void BIT_addBitsFast(BIT_CStream_t* bitC, size_t value, unsigned nbBits);
  120. /* faster, but works only if value is "clean", meaning all high bits above nbBits are 0 */
  121. MEM_STATIC void BIT_flushBitsFast(BIT_CStream_t* bitC);
  122. /* unsafe version; does not check buffer overflow */
  123. MEM_STATIC size_t BIT_readBitsFast(BIT_DStream_t* bitD, unsigned nbBits);
  124. /* faster, but works only if nbBits >= 1 */
  125. /*-**************************************************************
  126. * Internal functions
  127. ****************************************************************/
  128. MEM_STATIC unsigned BIT_highbit32 (U32 val)
  129. {
  130. assert(val != 0);
  131. {
  132. # if defined(_MSC_VER) /* Visual */
  133. unsigned long r=0;
  134. _BitScanReverse ( &r, val );
  135. return (unsigned) r;
  136. # elif defined(__GNUC__) && (__GNUC__ >= 3) /* Use GCC Intrinsic */
  137. return 31 - __builtin_clz (val);
  138. # else /* Software version */
  139. static const unsigned DeBruijnClz[32] = { 0, 9, 1, 10, 13, 21, 2, 29,
  140. 11, 14, 16, 18, 22, 25, 3, 30,
  141. 8, 12, 20, 28, 15, 17, 24, 7,
  142. 19, 27, 23, 6, 26, 5, 4, 31 };
  143. U32 v = val;
  144. v |= v >> 1;
  145. v |= v >> 2;
  146. v |= v >> 4;
  147. v |= v >> 8;
  148. v |= v >> 16;
  149. return DeBruijnClz[ (U32) (v * 0x07C4ACDDU) >> 27];
  150. # endif
  151. }
  152. }
  153. /*===== Local Constants =====*/
  154. static const unsigned BIT_mask[] = {
  155. 0, 1, 3, 7, 0xF, 0x1F,
  156. 0x3F, 0x7F, 0xFF, 0x1FF, 0x3FF, 0x7FF,
  157. 0xFFF, 0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF, 0x1FFFF,
  158. 0x3FFFF, 0x7FFFF, 0xFFFFF, 0x1FFFFF, 0x3FFFFF, 0x7FFFFF,
  159. 0xFFFFFF, 0x1FFFFFF, 0x3FFFFFF, 0x7FFFFFF, 0xFFFFFFF, 0x1FFFFFFF,
  160. 0x3FFFFFFF, 0x7FFFFFFF}; /* up to 31 bits */
  161. #define BIT_MASK_SIZE (sizeof(BIT_mask) / sizeof(BIT_mask[0]))
  162. /*-**************************************************************
  163. * bitStream encoding
  164. ****************************************************************/
  165. /*! BIT_initCStream() :
  166. * `dstCapacity` must be > sizeof(size_t)
  167. * @return : 0 if success,
  168. * otherwise an error code (can be tested using ERR_isError()) */
  169. MEM_STATIC size_t BIT_initCStream(BIT_CStream_t* bitC,
  170. void* startPtr, size_t dstCapacity)
  171. {
  172. bitC->bitContainer = 0;
  173. bitC->bitPos = 0;
  174. bitC->startPtr = (char*)startPtr;
  175. bitC->ptr = bitC->startPtr;
  176. bitC->endPtr = bitC->startPtr + dstCapacity - sizeof(bitC->bitContainer);
  177. if (dstCapacity <= sizeof(bitC->bitContainer)) return ERROR(dstSize_tooSmall);
  178. return 0;
  179. }
  180. /*! BIT_addBits() :
  181. * can add up to 31 bits into `bitC`.
  182. * Note : does not check for register overflow ! */
  183. MEM_STATIC void BIT_addBits(BIT_CStream_t* bitC,
  184. size_t value, unsigned nbBits)
  185. {
  186. MEM_STATIC_ASSERT(BIT_MASK_SIZE == 32);
  187. assert(nbBits < BIT_MASK_SIZE);
  188. assert(nbBits + bitC->bitPos < sizeof(bitC->bitContainer) * 8);
  189. bitC->bitContainer |= (value & BIT_mask[nbBits]) << bitC->bitPos;
  190. bitC->bitPos += nbBits;
  191. }
  192. /*! BIT_addBitsFast() :
  193. * works only if `value` is _clean_,
  194. * meaning all high bits above nbBits are 0 */
  195. MEM_STATIC void BIT_addBitsFast(BIT_CStream_t* bitC,
  196. size_t value, unsigned nbBits)
  197. {
  198. assert((value>>nbBits) == 0);
  199. assert(nbBits + bitC->bitPos < sizeof(bitC->bitContainer) * 8);
  200. bitC->bitContainer |= value << bitC->bitPos;
  201. bitC->bitPos += nbBits;
  202. }
  203. /*! BIT_flushBitsFast() :
  204. * assumption : bitContainer has not overflowed
  205. * unsafe version; does not check buffer overflow */
  206. MEM_STATIC void BIT_flushBitsFast(BIT_CStream_t* bitC)
  207. {
  208. size_t const nbBytes = bitC->bitPos >> 3;
  209. assert(bitC->bitPos < sizeof(bitC->bitContainer) * 8);
  210. MEM_writeLEST(bitC->ptr, bitC->bitContainer);
  211. bitC->ptr += nbBytes;
  212. assert(bitC->ptr <= bitC->endPtr);
  213. bitC->bitPos &= 7;
  214. bitC->bitContainer >>= nbBytes*8;
  215. }
  216. /*! BIT_flushBits() :
  217. * assumption : bitContainer has not overflowed
  218. * safe version; check for buffer overflow, and prevents it.
  219. * note : does not signal buffer overflow.
  220. * overflow will be revealed later on using BIT_closeCStream() */
  221. MEM_STATIC void BIT_flushBits(BIT_CStream_t* bitC)
  222. {
  223. size_t const nbBytes = bitC->bitPos >> 3;
  224. assert(bitC->bitPos < sizeof(bitC->bitContainer) * 8);
  225. MEM_writeLEST(bitC->ptr, bitC->bitContainer);
  226. bitC->ptr += nbBytes;
  227. if (bitC->ptr > bitC->endPtr) bitC->ptr = bitC->endPtr;
  228. bitC->bitPos &= 7;
  229. bitC->bitContainer >>= nbBytes*8;
  230. }
  231. /*! BIT_closeCStream() :
  232. * @return : size of CStream, in bytes,
  233. * or 0 if it could not fit into dstBuffer */
  234. MEM_STATIC size_t BIT_closeCStream(BIT_CStream_t* bitC)
  235. {
  236. BIT_addBitsFast(bitC, 1, 1); /* endMark */
  237. BIT_flushBits(bitC);
  238. if (bitC->ptr >= bitC->endPtr) return 0; /* overflow detected */
  239. return (bitC->ptr - bitC->startPtr) + (bitC->bitPos > 0);
  240. }
  241. /*-********************************************************
  242. * bitStream decoding
  243. **********************************************************/
  244. /*! BIT_initDStream() :
  245. * Initialize a BIT_DStream_t.
  246. * `bitD` : a pointer to an already allocated BIT_DStream_t structure.
  247. * `srcSize` must be the *exact* size of the bitStream, in bytes.
  248. * @return : size of stream (== srcSize), or an errorCode if a problem is detected
  249. */
  250. MEM_STATIC size_t BIT_initDStream(BIT_DStream_t* bitD, const void* srcBuffer, size_t srcSize)
  251. {
  252. if (srcSize < 1) { memset(bitD, 0, sizeof(*bitD)); return ERROR(srcSize_wrong); }
  253. bitD->start = (const char*)srcBuffer;
  254. bitD->limitPtr = bitD->start + sizeof(bitD->bitContainer);
  255. if (srcSize >= sizeof(bitD->bitContainer)) { /* normal case */
  256. bitD->ptr = (const char*)srcBuffer + srcSize - sizeof(bitD->bitContainer);
  257. bitD->bitContainer = MEM_readLEST(bitD->ptr);
  258. { BYTE const lastByte = ((const BYTE*)srcBuffer)[srcSize-1];
  259. bitD->bitsConsumed = lastByte ? 8 - BIT_highbit32(lastByte) : 0; /* ensures bitsConsumed is always set */
  260. if (lastByte == 0) return ERROR(GENERIC); /* endMark not present */ }
  261. } else {
  262. bitD->ptr = bitD->start;
  263. bitD->bitContainer = *(const BYTE*)(bitD->start);
  264. switch(srcSize)
  265. {
  266. case 7: bitD->bitContainer += (size_t)(((const BYTE*)(srcBuffer))[6]) << (sizeof(bitD->bitContainer)*8 - 16);
  267. /* fall-through */
  268. case 6: bitD->bitContainer += (size_t)(((const BYTE*)(srcBuffer))[5]) << (sizeof(bitD->bitContainer)*8 - 24);
  269. /* fall-through */
  270. case 5: bitD->bitContainer += (size_t)(((const BYTE*)(srcBuffer))[4]) << (sizeof(bitD->bitContainer)*8 - 32);
  271. /* fall-through */
  272. case 4: bitD->bitContainer += (size_t)(((const BYTE*)(srcBuffer))[3]) << 24;
  273. /* fall-through */
  274. case 3: bitD->bitContainer += (size_t)(((const BYTE*)(srcBuffer))[2]) << 16;
  275. /* fall-through */
  276. case 2: bitD->bitContainer += (size_t)(((const BYTE*)(srcBuffer))[1]) << 8;
  277. /* fall-through */
  278. default: break;
  279. }
  280. { BYTE const lastByte = ((const BYTE*)srcBuffer)[srcSize-1];
  281. bitD->bitsConsumed = lastByte ? 8 - BIT_highbit32(lastByte) : 0;
  282. if (lastByte == 0) return ERROR(corruption_detected); /* endMark not present */
  283. }
  284. bitD->bitsConsumed += (U32)(sizeof(bitD->bitContainer) - srcSize)*8;
  285. }
  286. return srcSize;
  287. }
  288. MEM_STATIC size_t BIT_getUpperBits(size_t bitContainer, U32 const start)
  289. {
  290. return bitContainer >> start;
  291. }
  292. MEM_STATIC size_t BIT_getMiddleBits(size_t bitContainer, U32 const start, U32 const nbBits)
  293. {
  294. #if defined(__BMI__) && defined(__GNUC__) && __GNUC__*1000+__GNUC_MINOR__ >= 4008 /* experimental */
  295. # if defined(__x86_64__)
  296. if (sizeof(bitContainer)==8)
  297. return _bextr_u64(bitContainer, start, nbBits);
  298. else
  299. # endif
  300. return _bextr_u32(bitContainer, start, nbBits);
  301. #else
  302. assert(nbBits < BIT_MASK_SIZE);
  303. return (bitContainer >> start) & BIT_mask[nbBits];
  304. #endif
  305. }
  306. MEM_STATIC size_t BIT_getLowerBits(size_t bitContainer, U32 const nbBits)
  307. {
  308. assert(nbBits < BIT_MASK_SIZE);
  309. return bitContainer & BIT_mask[nbBits];
  310. }
  311. /*! BIT_lookBits() :
  312. * Provides next n bits from local register.
  313. * local register is not modified.
  314. * On 32-bits, maxNbBits==24.
  315. * On 64-bits, maxNbBits==56.
  316. * @return : value extracted */
  317. MEM_STATIC size_t BIT_lookBits(const BIT_DStream_t* bitD, U32 nbBits)
  318. {
  319. #if defined(__BMI__) && defined(__GNUC__) /* experimental; fails if bitD->bitsConsumed + nbBits > sizeof(bitD->bitContainer)*8 */
  320. return BIT_getMiddleBits(bitD->bitContainer, (sizeof(bitD->bitContainer)*8) - bitD->bitsConsumed - nbBits, nbBits);
  321. #else
  322. U32 const regMask = sizeof(bitD->bitContainer)*8 - 1;
  323. return ((bitD->bitContainer << (bitD->bitsConsumed & regMask)) >> 1) >> ((regMask-nbBits) & regMask);
  324. #endif
  325. }
  326. /*! BIT_lookBitsFast() :
  327. * unsafe version; only works if nbBits >= 1 */
  328. MEM_STATIC size_t BIT_lookBitsFast(const BIT_DStream_t* bitD, U32 nbBits)
  329. {
  330. U32 const regMask = sizeof(bitD->bitContainer)*8 - 1;
  331. assert(nbBits >= 1);
  332. return (bitD->bitContainer << (bitD->bitsConsumed & regMask)) >> (((regMask+1)-nbBits) & regMask);
  333. }
  334. MEM_STATIC void BIT_skipBits(BIT_DStream_t* bitD, U32 nbBits)
  335. {
  336. bitD->bitsConsumed += nbBits;
  337. }
  338. /*! BIT_readBits() :
  339. * Read (consume) next n bits from local register and update.
  340. * Pay attention to not read more than nbBits contained into local register.
  341. * @return : extracted value. */
  342. MEM_STATIC size_t BIT_readBits(BIT_DStream_t* bitD, U32 nbBits)
  343. {
  344. size_t const value = BIT_lookBits(bitD, nbBits);
  345. BIT_skipBits(bitD, nbBits);
  346. return value;
  347. }
  348. /*! BIT_readBitsFast() :
  349. * unsafe version; only works only if nbBits >= 1 */
  350. MEM_STATIC size_t BIT_readBitsFast(BIT_DStream_t* bitD, U32 nbBits)
  351. {
  352. size_t const value = BIT_lookBitsFast(bitD, nbBits);
  353. assert(nbBits >= 1);
  354. BIT_skipBits(bitD, nbBits);
  355. return value;
  356. }
  357. /*! BIT_reloadDStream() :
  358. * Refill `bitD` from buffer previously set in BIT_initDStream() .
  359. * This function is safe, it guarantees it will not read beyond src buffer.
  360. * @return : status of `BIT_DStream_t` internal register.
  361. * when status == BIT_DStream_unfinished, internal register is filled with at least 25 or 57 bits */
  362. MEM_STATIC BIT_DStream_status BIT_reloadDStream(BIT_DStream_t* bitD)
  363. {
  364. if (bitD->bitsConsumed > (sizeof(bitD->bitContainer)*8)) /* overflow detected, like end of stream */
  365. return BIT_DStream_overflow;
  366. if (bitD->ptr >= bitD->limitPtr) {
  367. bitD->ptr -= bitD->bitsConsumed >> 3;
  368. bitD->bitsConsumed &= 7;
  369. bitD->bitContainer = MEM_readLEST(bitD->ptr);
  370. return BIT_DStream_unfinished;
  371. }
  372. if (bitD->ptr == bitD->start) {
  373. if (bitD->bitsConsumed < sizeof(bitD->bitContainer)*8) return BIT_DStream_endOfBuffer;
  374. return BIT_DStream_completed;
  375. }
  376. /* start < ptr < limitPtr */
  377. { U32 nbBytes = bitD->bitsConsumed >> 3;
  378. BIT_DStream_status result = BIT_DStream_unfinished;
  379. if (bitD->ptr - nbBytes < bitD->start) {
  380. nbBytes = (U32)(bitD->ptr - bitD->start); /* ptr > start */
  381. result = BIT_DStream_endOfBuffer;
  382. }
  383. bitD->ptr -= nbBytes;
  384. bitD->bitsConsumed -= nbBytes*8;
  385. bitD->bitContainer = MEM_readLEST(bitD->ptr); /* reminder : srcSize > sizeof(bitD->bitContainer), otherwise bitD->ptr == bitD->start */
  386. return result;
  387. }
  388. }
  389. /*! BIT_endOfDStream() :
  390. * @return : 1 if DStream has _exactly_ reached its end (all bits consumed).
  391. */
  392. MEM_STATIC unsigned BIT_endOfDStream(const BIT_DStream_t* DStream)
  393. {
  394. return ((DStream->ptr == DStream->start) && (DStream->bitsConsumed == sizeof(DStream->bitContainer)*8));
  395. }
  396. #if defined (__cplusplus)
  397. }
  398. #endif
  399. #endif /* BITSTREAM_H_MODULE */