blob: 3a4ba4c0145d0ab859c55fe085d7802a0ef547f7 [file] [log] [blame] [view]
Yann Collet5cc18822016-07-03 19:03:13 +02001Zstandard Compression Format
2============================
Yann Collet2fa99042016-07-01 20:55:28 +02003
4### Notices
5
6Copyright (c) 2016 Yann Collet
7
8Permission is granted to copy and distribute this document
9for any purpose and without charge,
10including translations into other languages
11and incorporation into compilations,
12provided that the copyright notice and this notice are preserved,
13and that any substantive changes or deletions from the original
14are clearly marked.
15Distribution of this document is unlimited.
16
17### Version
18
Yann Collete557fd52016-07-17 16:21:37 +0200190.1.2 (15/07/16)
Yann Collet2fa99042016-07-01 20:55:28 +020020
21
22Introduction
23------------
24
25The purpose of this document is to define a lossless compressed data format,
26that is independent of CPU type, operating system,
27file system and character set, suitable for
Yann Collet9ca73362016-07-05 10:53:38 +020028file compression, pipe and streaming compression,
Yann Collet2fa99042016-07-01 20:55:28 +020029using the [Zstandard algorithm](http://www.zstandard.org).
30
31The data can be produced or consumed,
32even for an arbitrarily long sequentially presented input data stream,
33using only an a priori bounded amount of intermediate storage,
34and hence can be used in data communications.
35The format uses the Zstandard compression method,
36and optional [xxHash-64 checksum method](http://www.xxhash.org),
37for detection of data corruption.
38
39The data format defined by this specification
40does not attempt to allow random access to compressed data.
41
42This specification is intended for use by implementers of software
43to compress data into Zstandard format and/or decompress data from Zstandard format.
44The text of the specification assumes a basic background in programming
45at the level of bits and other primitive data representations.
46
47Unless otherwise indicated below,
48a compliant compressor must produce data sets
49that conform to the specifications presented here.
50It doesn’t need to support all options though.
51
52A compliant decompressor must be able to decompress
53at least one working set of parameters
54that conforms to the specifications presented here.
55It may also ignore informative fields, such as checksum.
56Whenever it does not support a parameter defined in the compressed stream,
57it must produce a non-ambiguous error code and associated error message
58explaining which parameter is unsupported.
59
60
61Definitions
62-----------
63A content compressed by Zstandard is transformed into a Zstandard __frame__.
64Multiple frames can be appended into a single file or stream.
65A frame is totally independent, has a defined beginning and end,
66and a set of parameters which tells the decoder how to decompress it.
67
68A frame encapsulates one or multiple __blocks__.
69Each block can be compressed or not,
70and has a guaranteed maximum content size, which depends on frame parameters.
71Unlike frames, each block depends on previous blocks for proper decoding.
72However, each block can be decompressed without waiting for its successor,
73allowing streaming operations.
74
75
76General Structure of Zstandard Frame format
77-------------------------------------------
78
Yann Colletcd25a912016-07-05 11:50:37 +020079| MagicNb | Frame Header | Block | (More blocks) | EndMark |
80|:-------:|:-------------:| ----- | ------------- | ------- |
81| 4 bytes | 2-14 bytes | | | 3 bytes |
Yann Collet2fa99042016-07-01 20:55:28 +020082
83__Magic Number__
84
854 Bytes, Little endian format.
86Value : 0xFD2FB527
87
88__Frame Header__
89
Yann Colletcd25a912016-07-05 11:50:37 +0200902 to 14 Bytes, detailed in [next part](#frame-header).
Yann Collet2fa99042016-07-01 20:55:28 +020091
92__Data Blocks__
93
Yann Colletcd25a912016-07-05 11:50:37 +020094Detailed in [next chapter](#data-blocks).
Yann Collet2fa99042016-07-01 20:55:28 +020095That’s where compressed data is stored.
96
97__EndMark__
98
99The flow of blocks ends when the last block header brings an _end signal_ .
100This last block header may optionally host a __Content Checksum__ .
101
Yann Collet9ca73362016-07-05 10:53:38 +0200102##### __Content Checksum__
Yann Collet2fa99042016-07-01 20:55:28 +0200103
Yann Colletcd25a912016-07-05 11:50:37 +0200104Content Checksum verify that frame content has been regenerated correctly.
Yann Collet2fa99042016-07-01 20:55:28 +0200105The content checksum is the result
106of [xxh64() hash function](https://www.xxHash.com)
107digesting the original (decoded) data as input, and a seed of zero.
108Bits from 11 to 32 (included) are extracted to form a 22 bits checksum
Yann Colletcd25a912016-07-05 11:50:37 +0200109stored into the endmark body.
Yann Collet2fa99042016-07-01 20:55:28 +0200110```
Yann Collet9ca73362016-07-05 10:53:38 +0200111mask22bits = (1<<22)-1;
112contentChecksum = (XXH64(content, size, 0) >> 11) & mask22bits;
Yann Collet2fa99042016-07-01 20:55:28 +0200113```
114Content checksum is only present when its associated flag
115is set in the frame descriptor.
116Its usage is optional.
117
118__Frame Concatenation__
119
120In some circumstances, it may be required to append multiple frames,
121for example in order to add new data to an existing compressed file
122without re-framing it.
123
124In such case, each frame brings its own set of descriptor flags.
125Each frame is considered independent.
126The only relation between frames is their sequential order.
127
128The ability to decode multiple concatenated frames
129within a single stream or file is left outside of this specification.
130As an example, the reference `zstd` command line utility is able
131to decode all concatenated frames in their sequential order,
132delivering the final decompressed result as if it was a single content.
133
134
135Frame Header
136-------------
137
Yann Collet23f05cc2016-07-04 16:13:11 +0200138| FHD | (WD) | (dictID) | (Content Size) |
139| ------- | --------- | --------- |:--------------:|
140| 1 byte | 0-1 byte | 0-4 bytes | 0 - 8 bytes |
Yann Collet2fa99042016-07-01 20:55:28 +0200141
142Frame header has a variable size, which uses a minimum of 2 bytes,
143and up to 14 bytes depending on optional parameters.
144
145__FHD byte__ (Frame Header Descriptor)
146
147The first Header's byte is called the Frame Header Descriptor.
148It tells which other fields are present.
Yann Collet23f05cc2016-07-04 16:13:11 +0200149Decoding this byte is enough to tell the size of Frame Header.
Yann Collet2fa99042016-07-01 20:55:28 +0200150
Yann Collet23f05cc2016-07-04 16:13:11 +0200151| BitNb | 7-6 | 5 | 4 | 3 | 2 | 1-0 |
152| ------- | ------ | ------- | ------ | -------- | -------- | ------ |
153|FieldName| FCSize | Segment | Unused | Reserved | Checksum | dictID |
Yann Collet2fa99042016-07-01 20:55:28 +0200154
155In this table, bit 7 is highest bit, while bit 0 is lowest.
156
157__Frame Content Size flag__
158
159This is a 2-bits flag (`= FHD >> 6`),
160specifying if decompressed data size is provided within the header.
161
162| Value | 0 | 1 | 2 | 3 |
163| ------- | --- | --- | --- | --- |
164|FieldSize| 0-1 | 2 | 4 | 8 |
165
Yann Collet23f05cc2016-07-04 16:13:11 +0200166Value 0 meaning depends on _single segment_ mode :
Yann Collet2fa99042016-07-01 20:55:28 +0200167it either means `0` (size not provided) _if_ the `WD` byte is present,
Yann Collet23f05cc2016-07-04 16:13:11 +0200168or `1` (frame content size <= 255 bytes) otherwise.
Yann Collet2fa99042016-07-01 20:55:28 +0200169
170__Single Segment__
171
172If this flag is set,
173data shall be regenerated within a single continuous memory segment.
Yann Collet23f05cc2016-07-04 16:13:11 +0200174
Yann Collet2fa99042016-07-01 20:55:28 +0200175In which case, `WD` byte __is not present__,
176but `Frame Content Size` field necessarily is.
Yann Collet2fa99042016-07-01 20:55:28 +0200177As a consequence, the decoder must allocate a memory segment
178of size `>= Frame Content Size`.
179
180In order to preserve the decoder from unreasonable memory requirement,
Yann Collet23f05cc2016-07-04 16:13:11 +0200181a decoder can reject a compressed frame
Yann Collet2fa99042016-07-01 20:55:28 +0200182which requests a memory size beyond decoder's authorized range.
183
184For broader compatibility, decoders are recommended to support
Yann Collet23f05cc2016-07-04 16:13:11 +0200185memory sizes of at least 8 MB.
186This is just a recommendation,
Yann Collet9ca73362016-07-05 10:53:38 +0200187each decoder is free to support higher or lower limits,
Yann Collet2fa99042016-07-01 20:55:28 +0200188depending on local limitations.
189
190__Unused bit__
191
Yann Colletf0bc6732016-07-13 17:30:21 +0200192The value of this bit should be set to zero.
193A decoder compliant with this specification version should not interpret it.
194It might be used in a future version,
195to signal a property which is not mandatory to properly decode the frame.
Yann Collet2fa99042016-07-01 20:55:28 +0200196
197__Reserved bit__
198
199This bit is reserved for some future feature.
200Its value _must be zero_.
201A decoder compliant with this specification version must ensure it is not set.
202This bit may be used in a future revision,
203to signal a feature that must be interpreted in order to decode the frame.
204
205__Content checksum flag__
206
207If this flag is set, a content checksum will be present into the EndMark.
Yann Collet9ca73362016-07-05 10:53:38 +0200208The checksum is a 22 bits value extracted from the XXH64() of data,
209and stored into endMark. See [__Content Checksum__](#content-checksum) .
Yann Collet2fa99042016-07-01 20:55:28 +0200210
211__Dictionary ID flag__
212
213This is a 2-bits flag (`= FHD & 3`),
Yann Collet9ca73362016-07-05 10:53:38 +0200214telling if a dictionary ID is provided within the header.
215It also specifies the size of this field.
Yann Collet2fa99042016-07-01 20:55:28 +0200216
217| Value | 0 | 1 | 2 | 3 |
218| ------- | --- | --- | --- | --- |
219|FieldSize| 0 | 1 | 2 | 4 |
220
221__WD byte__ (Window Descriptor)
222
223Provides guarantees on maximum back-reference distance
224that will be present within compressed data.
225This information is useful for decoders to allocate enough memory.
226
Yann Colletcd25a912016-07-05 11:50:37 +0200227`WD` byte is optional. It's not present in `single segment` mode.
228In which case, the maximum back-reference distance is the content size itself,
229which can be any value from 1 to 2^64-1 bytes (16 EB).
230
Yann Collet2fa99042016-07-01 20:55:28 +0200231| BitNb | 7-3 | 0-2 |
232| --------- | -------- | -------- |
233| FieldName | Exponent | Mantissa |
234
235Maximum distance is given by the following formulae :
236```
237windowLog = 10 + Exponent;
238windowBase = 1 << windowLog;
239windowAdd = (windowBase / 8) * Mantissa;
240windowSize = windowBase + windowAdd;
241```
242The minimum window size is 1 KB.
Yann Colletcd25a912016-07-05 11:50:37 +0200243The maximum size is `15*(1<<38)` bytes, which is 1.875 TB.
Yann Collet2fa99042016-07-01 20:55:28 +0200244
245To properly decode compressed data,
246a decoder will need to allocate a buffer of at least `windowSize` bytes.
247
Yann Collet2fa99042016-07-01 20:55:28 +0200248In order to preserve decoder from unreasonable memory requirements,
249a decoder can refuse a compressed frame
250which requests a memory size beyond decoder's authorized range.
251
Yann Colletcd25a912016-07-05 11:50:37 +0200252For improved interoperability,
Yann Collet2fa99042016-07-01 20:55:28 +0200253decoders are recommended to be compatible with window sizes of 8 MB.
254Encoders are recommended to not request more than 8 MB.
255It's merely a recommendation though,
256decoders are free to support larger or lower limits,
257depending on local limitations.
258
Yann Collet23f05cc2016-07-04 16:13:11 +0200259__Dictionary ID__
260
Yann Colletf6ff53c2016-07-15 17:03:38 +0200261This is a variable size field, which contains
262the ID of the dictionary required to properly decode the frame.
263Note that this field is optional. When it's not present,
Yann Collet23f05cc2016-07-04 16:13:11 +0200264it's up to the caller to make sure it uses the correct dictionary.
265
266Field size depends on __Dictionary ID flag__.
2671 byte can represent an ID 0-255.
2682 bytes can represent an ID 0-65535.
Yann Colletcd25a912016-07-05 11:50:37 +02002694 bytes can represent an ID 0-4294967295.
Yann Collet23f05cc2016-07-04 16:13:11 +0200270
271It's allowed to represent a small ID (for example `13`)
Yann Colletcd25a912016-07-05 11:50:37 +0200272with a large 4-bytes dictionary ID, losing some compacity in the process.
Yann Collet23f05cc2016-07-04 16:13:11 +0200273
Yann Colletf6ff53c2016-07-15 17:03:38 +0200274_Reserved ranges :_
275If the frame is going to be distributed in a private environment,
276any dictionary ID can be used.
277However, for public distribution of compressed frames using a dictionary,
278some ranges are reserved for future use :
279- low : 1 - 32767 : reserved
280- high : >= (2^31) : reserved
281
282
Yann Collet2fa99042016-07-01 20:55:28 +0200283__Frame Content Size__
284
285This is the original (uncompressed) size.
286This information is optional, and only present if associated flag is set.
287Content size is provided using 1, 2, 4 or 8 Bytes.
288Format is Little endian.
289
290| Field Size | Range |
291| ---------- | ---------- |
292| 0 | 0 |
293| 1 | 0 - 255 |
294| 2 | 256 - 65791|
295| 4 | 0 - 2^32-1 |
296| 8 | 0 - 2^64-1 |
297
298When field size is 1, 4 or 8 bytes, the value is read directly.
299When field size is 2, _an offset of 256 is added_.
Yann Collet9ca73362016-07-05 10:53:38 +0200300It's allowed to represent a small size (ex: `18`) using any compatible variant.
Yann Collet2fa99042016-07-01 20:55:28 +0200301A size of `0` means `content size is unknown`.
302In which case, the `WD` byte will necessarily be present,
Yann Collet9ca73362016-07-05 10:53:38 +0200303and becomes the only hint to guide memory allocation.
Yann Collet2fa99042016-07-01 20:55:28 +0200304
305In order to preserve decoder from unreasonable memory requirement,
306a decoder can refuse a compressed frame
307which requests a memory size beyond decoder's authorized range.
308
Yann Collet2fa99042016-07-01 20:55:28 +0200309
310Data Blocks
311-----------
312
313| B. Header | data |
314|:---------:| ------ |
315| 3 bytes | |
316
317
318__Block Header__
319
320This field uses 3-bytes, format is __big-endian__.
321
322The 2 highest bits represent the `block type`,
323while the remaining 22 bits represent the (compressed) block size.
324
325There are 4 block types :
326
327| Value | 0 | 1 | 2 | 3 |
328| ---------- | ---------- | --- | --- | ------- |
329| Block Type | Compressed | Raw | RLE | EndMark |
330
Yann Collet9ca73362016-07-05 10:53:38 +0200331- Compressed : this is a [Zstandard compressed block](#compressed-block-format),
332 detailed in another section of this specification.
Yann Collet2fa99042016-07-01 20:55:28 +0200333 "block size" is the compressed size.
334 Decompressed size is unknown,
335 but its maximum possible value is guaranteed (see below)
336- Raw : this is an uncompressed block.
337 "block size" is the number of bytes to read and copy.
338- RLE : this is a single byte, repeated N times.
339 In which case, "block size" is the size to regenerate,
340 while the "compressed" block is just 1 byte (the byte to repeat).
341- EndMark : this is not a block. Signal the end of the frame.
342 The rest of the field may be optionally filled by a checksum
Yann Colletcd25a912016-07-05 11:50:37 +0200343 (see [Content Checksum](#content-checksum)).
Yann Collet2fa99042016-07-01 20:55:28 +0200344
345Block sizes must respect a few rules :
Yann Collet9ca73362016-07-05 10:53:38 +0200346- In compressed mode, compressed size if always strictly `< decompressed size`.
347- Block decompressed size is always <= maximum back-reference distance .
348- Block decompressed size is always <= 128 KB
Yann Collet2fa99042016-07-01 20:55:28 +0200349
350
351__Data__
352
353Where the actual data to decode stands.
354It might be compressed or not, depending on previous field indications.
355A data block is not necessarily "full" :
356since an arbitrary “flush” may happen anytime,
Yann Colletcd25a912016-07-05 11:50:37 +0200357block decompressed content can be any size,
358up to Block Maximum Decompressed Size, which is the smallest of :
359- Maximum back-reference distance
Yann Collet2fa99042016-07-01 20:55:28 +0200360- 128 KB
361
362
363Skippable Frames
364----------------
365
366| Magic Number | Frame Size | User Data |
367|:------------:|:----------:| --------- |
368| 4 bytes | 4 bytes | |
369
370Skippable frames allow the insertion of user-defined data
371into a flow of concatenated frames.
372Its design is pretty straightforward,
373with the sole objective to allow the decoder to quickly skip
374over user-defined data and continue decoding.
375
Yann Colletcd25a912016-07-05 11:50:37 +0200376Skippable frames defined in this specification are compatible with [LZ4] ones.
377
378[LZ4]:http://www.lz4.org
Yann Collet2fa99042016-07-01 20:55:28 +0200379
Yann Collet2fa99042016-07-01 20:55:28 +0200380__Magic Number__ :
381
3824 Bytes, Little endian format.
383Value : 0x184D2A5X, which means any value from 0x184D2A50 to 0x184D2A5F.
384All 16 values are valid to identify a skippable frame.
385
386__Frame Size__ :
387
388This is the size, in bytes, of the following User Data
389(without including the magic number nor the size field itself).
3904 Bytes, Little endian format, unsigned 32-bits.
391This means User Data can’t be bigger than (2^32-1) Bytes.
392
393__User Data__ :
394
395User Data can be anything. Data will just be skipped by the decoder.
396
397
398Compressed block format
399-----------------------
400This specification details the content of a _compressed block_.
Yann Collet00d44ab2016-07-04 01:29:47 +0200401A compressed block has a size, which must be known.
Yann Collet2fa99042016-07-01 20:55:28 +0200402It also has a guaranteed maximum regenerated size,
403in order to properly allocate destination buffer.
Yann Collet9ca73362016-07-05 10:53:38 +0200404See [Data Blocks](#data-blocks) for more details.
Yann Collet2fa99042016-07-01 20:55:28 +0200405
406A compressed block consists of 2 sections :
Yann Colletcd25a912016-07-05 11:50:37 +0200407- [Literals section](#literals-section)
408- [Sequences section](#sequences-section)
Yann Collet2fa99042016-07-01 20:55:28 +0200409
Yann Collet23f05cc2016-07-04 16:13:11 +0200410### Prerequisites
411To decode a compressed block, the following elements are necessary :
Yann Collet698cb632016-07-03 18:49:35 +0200412- Previous decoded blocks, up to a distance of `windowSize`,
Yann Collet9ca73362016-07-05 10:53:38 +0200413 or all previous blocks in "single segment" mode.
Yann Collet698cb632016-07-03 18:49:35 +0200414- List of "recent offsets" from previous compressed block.
Yann Collet00d44ab2016-07-04 01:29:47 +0200415- Decoding tables of previous compressed block for each symbol type
Yann Collet9ca73362016-07-05 10:53:38 +0200416 (literals, litLength, matchLength, offset).
Yann Collet698cb632016-07-03 18:49:35 +0200417
418
Yann Collet00d44ab2016-07-04 01:29:47 +0200419### Literals section
Yann Collet2fa99042016-07-01 20:55:28 +0200420
Yann Colletc40ba712016-07-08 15:39:02 +0200421Literals are compressed using Huffman prefix codes.
Yann Collet2fa99042016-07-01 20:55:28 +0200422During sequence phase, literals will be entangled with match copy operations.
423All literals are regrouped in the first part of the block.
424They can be decoded first, and then copied during sequence operations,
Yann Collet00d44ab2016-07-04 01:29:47 +0200425or they can be decoded on the flow, as needed by sequence commands.
Yann Collet2fa99042016-07-01 20:55:28 +0200426
427| Header | (Tree Description) | Stream1 | (Stream2) | (Stream3) | (Stream4) |
428| ------ | ------------------ | ------- | --------- | --------- | --------- |
429
430Literals can be compressed, or uncompressed.
431When compressed, an optional tree description can be present,
432followed by 1 or 4 streams.
433
Yann Collet00d44ab2016-07-04 01:29:47 +0200434#### Literals section header
Yann Collet2fa99042016-07-01 20:55:28 +0200435
Yann Collet00d44ab2016-07-04 01:29:47 +0200436Header is in charge of describing how literals are packed.
Yann Collet2fa99042016-07-01 20:55:28 +0200437It's a byte-aligned variable-size bitfield, ranging from 1 to 5 bytes,
438using big-endian convention.
439
440| BlockType | sizes format | (compressed size) | regenerated size |
441| --------- | ------------ | ----------------- | ---------------- |
442| 2 bits | 1 - 2 bits | 0 - 18 bits | 5 - 20 bits |
443
444__Block Type__ :
445
446This is a 2-bits field, describing 4 different block types :
447
448| Value | 0 | 1 | 2 | 3 |
449| ---------- | ---------- | ------ | --- | ------- |
450| Block Type | Compressed | Repeat | Raw | RLE |
451
452- Compressed : This is a standard huffman-compressed block,
Yann Colletcd25a912016-07-05 11:50:37 +0200453 starting with a huffman tree description.
454 See details below.
Yann Collet2fa99042016-07-01 20:55:28 +0200455- Repeat Stats : This is a huffman-compressed block,
Yann Colletcd25a912016-07-05 11:50:37 +0200456 using huffman tree _from previous huffman-compressed literals block_.
457 Huffman tree description will be skipped.
Yann Collet2fa99042016-07-01 20:55:28 +0200458- Raw : Literals are stored uncompressed.
459- RLE : Literals consist of a single byte value repeated N times.
460
461__Sizes format__ :
462
463Sizes format are divided into 2 families :
464
465- For compressed block, it requires to decode both the compressed size
466 and the decompressed size. It will also decode the number of streams.
467- For Raw or RLE blocks, it's enough to decode the size to regenerate.
468
469For values spanning several bytes, convention is Big-endian.
470
Yann Collet9ca73362016-07-05 10:53:38 +0200471__Sizes format for Raw or RLE literals block__ :
Yann Collet2fa99042016-07-01 20:55:28 +0200472
473- Value : 0x : Regenerated size uses 5 bits (0-31).
474 Total literal header size is 1 byte.
475 `size = h[0] & 31;`
476- Value : 10 : Regenerated size uses 12 bits (0-4095).
477 Total literal header size is 2 bytes.
478 `size = ((h[0] & 15) << 8) + h[1];`
479- Value : 11 : Regenerated size uses 20 bits (0-1048575).
Yann Colletd916c902016-07-04 00:42:58 +0200480 Total literal header size is 3 bytes.
Yann Collet2fa99042016-07-01 20:55:28 +0200481 `size = ((h[0] & 15) << 16) + (h[1]<<8) + h[2];`
482
483Note : it's allowed to represent a short value (ex : `13`)
484using a long format, accepting the reduced compacity.
485
Yann Collet9ca73362016-07-05 10:53:38 +0200486__Sizes format for Compressed literals block__ :
Yann Collet2fa99042016-07-01 20:55:28 +0200487
488Note : also applicable to "repeat-stats" blocks.
Yann Colletcd25a912016-07-05 11:50:37 +0200489- Value : 00 : 4 streams.
490 Compressed and regenerated sizes use 10 bits (0-1023).
491 Total literal header size is 3 bytes.
492- Value : 01 : _Single stream_.
493 Compressed and regenerated sizes use 10 bits (0-1023).
494 Total literal header size is 3 bytes.
495- Value : 10 : 4 streams.
496 Compressed and regenerated sizes use 14 bits (0-16383).
497 Total literal header size is 4 bytes.
498- Value : 10 : 4 streams.
499 Compressed and regenerated sizes use 18 bits (0-262143).
500 Total literal header size is 5 bytes.
Yann Collet2fa99042016-07-01 20:55:28 +0200501
Yann Collet698cb632016-07-03 18:49:35 +0200502Compressed and regenerated size fields follow big endian convention.
503
504#### Huffman Tree description
505
Yann Colletcd25a912016-07-05 11:50:37 +0200506This section is only present when literals block type is `Compressed` (`0`).
Yann Collet00d44ab2016-07-04 01:29:47 +0200507
Yann Collet9ca73362016-07-05 10:53:38 +0200508Prefix coding represents symbols from an a priori known alphabet
Yann Colletb21e9cb2016-07-15 17:31:13 +0200509by bit sequences (codewords), one codeword for each symbol,
Yann Collet9ca73362016-07-05 10:53:38 +0200510in a manner such that different symbols may be represented
511by bit sequences of different lengths,
512but a parser can always parse an encoded string
513unambiguously symbol-by-symbol.
Yann Collet00d44ab2016-07-04 01:29:47 +0200514
Yann Collet9ca73362016-07-05 10:53:38 +0200515Given an alphabet with known symbol frequencies,
516the Huffman algorithm allows the construction of an optimal prefix code
517using the fewest bits of any possible prefix codes for that alphabet.
Yann Collet00d44ab2016-07-04 01:29:47 +0200518
Yann Collet9ca73362016-07-05 10:53:38 +0200519Prefix code must not exceed a maximum code length.
Yann Collet00d44ab2016-07-04 01:29:47 +0200520More bits improve accuracy but cost more header size,
Yann Collete557fd52016-07-17 16:21:37 +0200521and require more memory or more complex decoding operations.
522This specification limits maximum code length to 11 bits.
Yann Collet00d44ab2016-07-04 01:29:47 +0200523
Yann Collet698cb632016-07-03 18:49:35 +0200524
525##### Representation
526
Yann Collet00d44ab2016-07-04 01:29:47 +0200527All literal values from zero (included) to last present one (excluded)
Yann Collet698cb632016-07-03 18:49:35 +0200528are represented by `weight` values, from 0 to `maxBits`.
529Transformation from `weight` to `nbBits` follows this formulae :
530`nbBits = weight ? maxBits + 1 - weight : 0;` .
531The last symbol's weight is deduced from previously decoded ones,
532by completing to the nearest power of 2.
533This power of 2 gives `maxBits`, the depth of the current tree.
534
535__Example__ :
536Let's presume the following huffman tree must be described :
537
Yann Colletd916c902016-07-04 00:42:58 +0200538| literal | 0 | 1 | 2 | 3 | 4 | 5 |
539| ------- | --- | --- | --- | --- | --- | --- |
540| nbBits | 1 | 2 | 3 | 0 | 4 | 4 |
Yann Collet698cb632016-07-03 18:49:35 +0200541
542The tree depth is 4, since its smallest element uses 4 bits.
543Value `5` will not be listed, nor will values above `5`.
544Values from `0` to `4` will be listed using `weight` instead of `nbBits`.
545Weight formula is : `weight = nbBits ? maxBits + 1 - nbBits : 0;`
546It gives the following serie of weights :
547
Yann Colletd916c902016-07-04 00:42:58 +0200548| weights | 4 | 3 | 2 | 0 | 1 |
549| ------- | --- | --- | --- | --- | --- |
550| literal | 0 | 1 | 2 | 3 | 4 |
Yann Collet698cb632016-07-03 18:49:35 +0200551
552The decoder will do the inverse operation :
Yann Colletd916c902016-07-04 00:42:58 +0200553having collected weights of literals from `0` to `4`,
554it knows the last literal, `5`, is present with a non-zero weight.
Yann Colletcd25a912016-07-05 11:50:37 +0200555The weight of `5` can be deducted by joining to the nearest power of 2.
Yann Collet698cb632016-07-03 18:49:35 +0200556Sum of 2^(weight-1) (excluding 0) is :
Yann Colletd916c902016-07-04 00:42:58 +0200557`8 + 4 + 2 + 0 + 1 = 15`
Yann Collet698cb632016-07-03 18:49:35 +0200558Nearest power of 2 is 16.
559Therefore, `maxBits = 4` and `weight[5] = 1`.
Yann Collet698cb632016-07-03 18:49:35 +0200560
561##### Huffman Tree header
562
Yann Collet9ca73362016-07-05 10:53:38 +0200563This is a single byte value (0-255),
564which tells how to decode the list of weights.
Yann Collet698cb632016-07-03 18:49:35 +0200565
566- if headerByte >= 242 : this is one of 14 pre-defined weight distributions :
Yann Colletcd25a912016-07-05 11:50:37 +0200567
568| value |242|243|244|245|246|247|248|249|250|251|252|253|254|255|
Yann Collete0ce5b02016-07-06 01:50:44 +0200569| -------- |---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Yann Colletcd25a912016-07-05 11:50:37 +0200570| Nb of 1s | 1 | 2 | 3 | 4 | 7 | 8 | 15| 16| 31| 32| 63| 64|127|128|
571|Complement| 1 | 2 | 1 | 4 | 1 | 8 | 1 | 16| 1 | 32| 1 | 64| 1 |128|
572
Yann Collet26f68142016-07-08 10:42:59 +0200573_Note_ : complement is found by using "join to nearest power of 2" rule.
Yann Collet698cb632016-07-03 18:49:35 +0200574
575- if headerByte >= 128 : this is a direct representation,
576 where each weight is written directly as a 4 bits field (0-15).
Yann Colletcd25a912016-07-05 11:50:37 +0200577 The full representation occupies `((nbSymbols+1)/2)` bytes,
Yann Collet698cb632016-07-03 18:49:35 +0200578 meaning it uses a last full byte even if nbSymbols is odd.
Yann Collet26f68142016-07-08 10:42:59 +0200579 `nbSymbols = headerByte - 127;`.
580 Note that maximum nbSymbols is 241-127 = 114.
581 A larger serie must necessarily use FSE compression.
Yann Collet698cb632016-07-03 18:49:35 +0200582
583- if headerByte < 128 :
584 the serie of weights is compressed by FSE.
Yann Collet26f68142016-07-08 10:42:59 +0200585 The length of the FSE-compressed serie is `headerByte` (0-127).
Yann Collet698cb632016-07-03 18:49:35 +0200586
587##### FSE (Finite State Entropy) compression of huffman weights
588
Yann Collet26f68142016-07-08 10:42:59 +0200589The serie of weights is compressed using FSE compression.
Yann Collet698cb632016-07-03 18:49:35 +0200590It's a single bitstream with 2 interleaved states,
Yann Collet26f68142016-07-08 10:42:59 +0200591sharing a single distribution table.
Yann Collet698cb632016-07-03 18:49:35 +0200592
593To decode an FSE bitstream, it is necessary to know its compressed size.
594Compressed size is provided by `headerByte`.
Yann Collet26f68142016-07-08 10:42:59 +0200595It's also necessary to know its maximum decompressed size,
596which is `255`, since literal values span from `0` to `255`,
Yann Colletcd25a912016-07-05 11:50:37 +0200597and last symbol value is not represented.
Yann Collet698cb632016-07-03 18:49:35 +0200598
599An FSE bitstream starts by a header, describing probabilities distribution.
Yann Collet00d44ab2016-07-04 01:29:47 +0200600It will create a Decoding Table.
Yann Collet26f68142016-07-08 10:42:59 +0200601Table must be pre-allocated, which requires to support a maximum accuracy.
602For a list of huffman weights, recommended maximum is 7 bits.
Yann Collet698cb632016-07-03 18:49:35 +0200603
Yann Collet26f68142016-07-08 10:42:59 +0200604FSE header is [described in relevant chapter](#fse-distribution-table--condensed-format),
605and so is [FSE bitstream](#bitstream).
606The main difference is that Huffman header compression uses 2 states,
607which share the same FSE distribution table.
608Bitstream contains only FSE symbols, there are no interleaved "raw bitfields".
609The number of symbols to decode is discovered
610by tracking bitStream overflow condition.
611When both states have overflowed the bitstream, end is reached.
612
Yann Collet698cb632016-07-03 18:49:35 +0200613
614##### Conversion from weights to huffman prefix codes
615
Yann Colletd916c902016-07-04 00:42:58 +0200616All present symbols shall now have a `weight` value.
Yann Colletd916c902016-07-04 00:42:58 +0200617Symbols are sorted by weight.
Yann Colletb21e9cb2016-07-15 17:31:13 +0200618Symbols with a weight of zero are removed.
Yann Colletd916c902016-07-04 00:42:58 +0200619Within same weight, symbols keep natural order.
620Starting from lowest weight,
Yann Colletb21e9cb2016-07-15 17:31:13 +0200621symbols are being allocated to a `range`.
622A `weight` directly represents a `range`,
623following the formulae : `range = weight ? 1 << (weight-1) : 0 ;`
624Similarly, it is possible to transform weights into nbBits :
Yann Colletd916c902016-07-04 00:42:58 +0200625`nbBits = nbBits ? maxBits + 1 - weight : 0;` .
626
627
628__Example__ :
Yann Colletb21e9cb2016-07-15 17:31:13 +0200629Let's presume the following list of weights has been decoded :
Yann Colletd916c902016-07-04 00:42:58 +0200630
631| Literal | 0 | 1 | 2 | 3 | 4 | 5 |
632| ------- | --- | --- | --- | --- | --- | --- |
633| weight | 4 | 3 | 2 | 0 | 1 | 1 |
634
635Sorted by weight and then natural order,
636it gives the following distribution :
637
638| Literal | 3 | 4 | 5 | 2 | 1 | 0 |
639| ------------ | --- | --- | --- | --- | --- | ---- |
640| weight | 0 | 1 | 1 | 2 | 3 | 4 |
641| range | 0 | 1 | 1 | 2 | 4 | 8 |
Yann Colletb21e9cb2016-07-15 17:31:13 +0200642| table entries| N/A | 0 | 1 | 2-3 | 4-7 | 8-15 |
Yann Colletd916c902016-07-04 00:42:58 +0200643| nb bits | 0 | 4 | 4 | 3 | 2 | 1 |
Yann Colletb21e9cb2016-07-15 17:31:13 +0200644| prefix codes | N/A | 0000| 0001| 001 | 01 | 1 |
Yann Colletd916c902016-07-04 00:42:58 +0200645
646
Yann Colletd916c902016-07-04 00:42:58 +0200647#### Literals bitstreams
648
649##### Bitstreams sizes
650
651As seen in a previous paragraph,
652there are 2 flavors of huffman-compressed literals :
653single stream, and 4-streams.
654
6554-streams is useful for CPU with multiple execution units and OoO operations.
656Since each stream can be decoded independently,
657it's possible to decode them up to 4x faster than a single stream,
658presuming the CPU has enough parallelism available.
659
660For single stream, header provides both the compressed and regenerated size.
661For 4-streams though,
662header only provides compressed and regenerated size of all 4 streams combined.
Yann Colletd916c902016-07-04 00:42:58 +0200663In order to properly decode the 4 streams,
664it's necessary to know the compressed and regenerated size of each stream.
665
666Regenerated size is easiest :
667each stream has a size of `(totalSize+3)/4`,
Yann Colletcd25a912016-07-05 11:50:37 +0200668except the last one, which is up to 3 bytes smaller, to reach `totalSize`.
Yann Colletd916c902016-07-04 00:42:58 +0200669
670Compressed size must be provided explicitly : in the 4-streams variant,
Yann Collet00d44ab2016-07-04 01:29:47 +0200671bitstreams are preceded by 3 unsigned Little Endian 16-bits values.
672Each value represents the compressed size of one stream, in order.
Yann Colletd916c902016-07-04 00:42:58 +0200673The last stream size is deducted from total compressed size
674and from already known stream sizes :
675`stream4CSize = totalCSize - 6 - stream1CSize - stream2CSize - stream3CSize;`
676
Yann Collet00d44ab2016-07-04 01:29:47 +0200677##### Bitstreams read and decode
Yann Colletd916c902016-07-04 00:42:58 +0200678
679Each bitstream must be read _backward_,
680that is starting from the end down to the beginning.
681Therefore it's necessary to know the size of each bitstream.
682
683It's also necessary to know exactly which _bit_ is the latest.
684This is detected by a final bit flag :
685the highest bit of latest byte is a final-bit-flag.
686Consequently, a last byte of `0` is not possible.
687And the final-bit-flag itself is not part of the useful bitstream.
688Hence, the last byte contain between 0 and 7 useful bits.
689
690Starting from the end,
691it's possible to read the bitstream in a little-endian fashion,
692keeping track of already used bits.
693
Yann Collet00d44ab2016-07-04 01:29:47 +0200694Reading the last `maxBits` bits,
Yann Colletb21e9cb2016-07-15 17:31:13 +0200695it's then possible to compare extracted value to decoding table,
Yann Colletd916c902016-07-04 00:42:58 +0200696determining the symbol to decode and number of bits to discard.
697
698The process continues up to reading the required number of symbols per stream.
699If a bitstream is not entirely and exactly consumed,
Yann Colletb21e9cb2016-07-15 17:31:13 +0200700hence reaching exactly its beginning position with _all_ bits consumed,
Yann Colletd916c902016-07-04 00:42:58 +0200701the decoding process is considered faulty.
702
Yann Collet698cb632016-07-03 18:49:35 +0200703
Yann Collet00d44ab2016-07-04 01:29:47 +0200704### Sequences section
705
706A compressed block is a succession of _sequences_ .
707A sequence is a literal copy command, followed by a match copy command.
708A literal copy command specifies a length.
709It is the number of bytes to be copied (or extracted) from the literal section.
710A match copy command specifies an offset and a length.
711The offset gives the position to copy from,
Yann Colletb21e9cb2016-07-15 17:31:13 +0200712which can be within a previous block.
Yann Collet00d44ab2016-07-04 01:29:47 +0200713
Yann Colletcd25a912016-07-05 11:50:37 +0200714There are 3 symbol types, `literalLength`, `matchLength` and `offset`,
Yann Collet00d44ab2016-07-04 01:29:47 +0200715which are encoded together, interleaved in a single _bitstream_.
716
Yann Colletcd25a912016-07-05 11:50:37 +0200717Each symbol is a _code_ in its own context,
718which specifies a baseline and a number of bits to add.
Yann Collet00d44ab2016-07-04 01:29:47 +0200719_Codes_ are FSE compressed,
720and interleaved with raw additional bits in the same bitstream.
721
Yann Collet23f05cc2016-07-04 16:13:11 +0200722The Sequences section starts by a header,
723followed by optional Probability tables for each symbol type,
Yann Collet00d44ab2016-07-04 01:29:47 +0200724followed by the bitstream.
725
Yann Colletc40ba712016-07-08 15:39:02 +0200726| Header | (LitLengthTable) | (OffsetTable) | (MatchLengthTable) | bitStream |
727| ------ | ---------------- | ------------- | ------------------ | --------- |
728
Yann Collet23f05cc2016-07-04 16:13:11 +0200729To decode the Sequence section, it's required to know its size.
Yann Colletcd25a912016-07-05 11:50:37 +0200730This size is deducted from `blockSize - literalSectionSize`.
Yann Collet23f05cc2016-07-04 16:13:11 +0200731
732
Yann Collet00d44ab2016-07-04 01:29:47 +0200733#### Sequences section header
734
Yann Collet23f05cc2016-07-04 16:13:11 +0200735Consists in 2 items :
736- Nb of Sequences
737- Flags providing Symbol compression types
738
739__Nb of Sequences__
740
741This is a variable size field, `nbSeqs`, using between 1 and 3 bytes.
742Let's call its first byte `byte0`.
743- `if (byte0 == 0)` : there are no sequences.
744 The sequence section stops there.
745 Regenerated content is defined entirely by literals section.
Yann Colletcd25a912016-07-05 11:50:37 +0200746- `if (byte0 < 128)` : `nbSeqs = byte0;` . Uses 1 byte.
747- `if (byte0 < 255)` : `nbSeqs = ((byte0-128) << 8) + byte1;` . Uses 2 bytes.
748- `if (byte0 == 255)`: `nbSeqs = byte1 + (byte2<<8) + 0x7F00;` . Uses 3 bytes.
Yann Collet23f05cc2016-07-04 16:13:11 +0200749
750__Symbol compression modes__
751
752This is a single byte, defining the compression mode of each symbol type.
753
754| BitNb | 7-6 | 5-4 | 3-2 | 1-0 |
755| ------- | ------ | ------ | ------ | -------- |
756|FieldName| LLtype | OFType | MLType | Reserved |
757
758The last field, `Reserved`, must be all-zeroes.
759
760`LLtype`, `OFType` and `MLType` define the compression mode of
761Literal Lengths, Offsets and Match Lengths respectively.
762
763They follow the same enumeration :
764
765| Value | 0 | 1 | 2 | 3 |
766| ---------------- | ------ | --- | ------ | --- |
767| Compression Mode | predef | RLE | Repeat | FSE |
768
769- "predef" : uses a pre-defined distribution table.
770- "RLE" : it's a single code, repeated `nbSeqs` times.
771- "Repeat" : re-use distribution table from previous compressed block.
772- "FSE" : standard FSE compression.
Yann Colletcd25a912016-07-05 11:50:37 +0200773 A distribution table will be present.
774 It will be described in [next part](#distribution-tables).
Yann Collet23f05cc2016-07-04 16:13:11 +0200775
776#### Symbols decoding
777
778##### Literal Lengths codes
779
780Literal lengths codes are values ranging from `0` to `35` included.
781They define lengths from 0 to 131071 bytes.
782
783| Code | 0-15 |
784| ------ | ---- |
Yann Colletc40ba712016-07-08 15:39:02 +0200785| length | Code |
Yann Colletcd25a912016-07-05 11:50:37 +0200786| nbBits | 0 |
787
Yann Collet23f05cc2016-07-04 16:13:11 +0200788
789| Code | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 |
790| -------- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- |
791| Baseline | 16 | 18 | 20 | 22 | 24 | 28 | 32 | 40 |
792| nb Bits | 1 | 1 | 1 | 1 | 2 | 2 | 3 | 3 |
793
794| Code | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 |
795| -------- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- |
796| Baseline | 48 | 64 | 128 | 256 | 512 | 1024 | 2048 | 4096 |
797| nb Bits | 4 | 6 | 7 | 8 | 9 | 10 | 11 | 12 |
798
799| Code | 32 | 33 | 34 | 35 |
800| -------- | ---- | ---- | ---- | ---- |
801| Baseline | 8192 |16384 |32768 |65536 |
802| nb Bits | 13 | 14 | 15 | 16 |
803
804__Default distribution__
805
Yann Colletcd25a912016-07-05 11:50:37 +0200806When "compression mode" is "predef"",
Yann Collet23f05cc2016-07-04 16:13:11 +0200807a pre-defined distribution is used for FSE compression.
808
Yann Colletc40ba712016-07-08 15:39:02 +0200809Below is its definition. It uses an accuracy of 6 bits (64 states).
Yann Collet23f05cc2016-07-04 16:13:11 +0200810```
811short literalLengths_defaultDistribution[36] =
812 { 4, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1,
813 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 2, 1, 1, 1, 1, 1,
814 -1,-1,-1,-1 };
815```
816
817##### Match Lengths codes
818
819Match lengths codes are values ranging from `0` to `52` included.
820They define lengths from 3 to 131074 bytes.
821
822| Code | 0-31 |
823| ------ | -------- |
Yann Collet23f05cc2016-07-04 16:13:11 +0200824| value | Code + 3 |
Yann Colletcd25a912016-07-05 11:50:37 +0200825| nbBits | 0 |
Yann Collet23f05cc2016-07-04 16:13:11 +0200826
827| Code | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 |
828| -------- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- |
829| Baseline | 35 | 37 | 39 | 41 | 43 | 47 | 51 | 59 |
830| nb Bits | 1 | 1 | 1 | 1 | 2 | 2 | 3 | 3 |
831
832| Code | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 |
833| -------- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- |
834| Baseline | 67 | 83 | 99 | 131 | 258 | 514 | 1026 | 2050 |
835| nb Bits | 4 | 4 | 5 | 7 | 8 | 9 | 10 | 11 |
836
837| Code | 48 | 49 | 50 | 51 | 52 |
838| -------- | ---- | ---- | ---- | ---- | ---- |
839| Baseline | 4098 | 8194 |16486 |32770 |65538 |
840| nb Bits | 12 | 13 | 14 | 15 | 16 |
841
842__Default distribution__
843
Yann Colletc40ba712016-07-08 15:39:02 +0200844When "compression mode" is defined as "predef",
Yann Collet23f05cc2016-07-04 16:13:11 +0200845a pre-defined distribution is used for FSE compression.
846
847Here is its definition. It uses an accuracy of 6 bits (64 states).
848```
849short matchLengths_defaultDistribution[53] =
850 { 1, 4, 3, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1,
851 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
852 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,-1,-1,
853 -1,-1,-1,-1,-1 };
854```
855
856##### Offset codes
857
858Offset codes are values ranging from `0` to `N`,
859with `N` being limited by maximum backreference distance.
860
Yann Colletcd25a912016-07-05 11:50:37 +0200861A decoder is free to limit its maximum `N` supported.
862Recommendation is to support at least up to `22`.
Yann Collet23f05cc2016-07-04 16:13:11 +0200863For information, at the time of this writing.
864the reference decoder supports a maximum `N` value of `28` in 64-bits mode.
865
866An offset code is also the nb of additional bits to read,
867and can be translated into an `OFValue` using the following formulae :
868
869```
870OFValue = (1 << offsetCode) + readNBits(offsetCode);
871if (OFValue > 3) offset = OFValue - 3;
872```
873
874OFValue from 1 to 3 are special : they define "repeat codes",
875which means one of the previous offsets will be repeated.
876They are sorted in recency order, with 1 meaning the most recent one.
Yann Colletcd25a912016-07-05 11:50:37 +0200877See [Repeat offsets](#repeat-offsets) paragraph.
Yann Collet23f05cc2016-07-04 16:13:11 +0200878
879__Default distribution__
880
Yann Colletcd25a912016-07-05 11:50:37 +0200881When "compression mode" is defined as "predef",
Yann Collet23f05cc2016-07-04 16:13:11 +0200882a pre-defined distribution is used for FSE compression.
883
884Here is its definition. It uses an accuracy of 5 bits (32 states),
Yann Colletcd25a912016-07-05 11:50:37 +0200885and supports a maximum `N` of 28, allowing offset values up to 536,870,908 .
Yann Collet23f05cc2016-07-04 16:13:11 +0200886
887If any sequence in the compressed block requires an offset larger than this,
888it's not possible to use the default distribution to represent it.
889
890```
891short offsetCodes_defaultDistribution[53] =
892 { 1, 1, 1, 1, 1, 1, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1,
893 1, 1, 1, 1, 1, 1, 1, 1,-1,-1,-1,-1,-1 };
894```
895
896#### Distribution tables
897
898Following the header, up to 3 distribution tables can be described.
899They are, in order :
900- Literal lengthes
901- Offsets
902- Match Lengthes
903
904The content to decode depends on their respective compression mode :
905- Repeat mode : no content. Re-use distribution from previous compressed block.
906- Predef : no content. Use pre-defined distribution table.
907- RLE : 1 byte. This is the only code to use across the whole compressed block.
908- FSE : A distribution table is present.
909
910##### FSE distribution table : condensed format
911
912An FSE distribution table describes the probabilities of all symbols
913from `0` to the last present one (included)
Yann Collet9ca73362016-07-05 10:53:38 +0200914on a normalized scale of `1 << AccuracyLog` .
Yann Collet23f05cc2016-07-04 16:13:11 +0200915
916It's a bitstream which is read forward, in little-endian fashion.
917It's not necessary to know its exact size,
918since it will be discovered and reported by the decoding process.
919
920The bitstream starts by reporting on which scale it operates.
921`AccuracyLog = low4bits + 5;`
922In theory, it can define a scale from 5 to 20.
923In practice, decoders are allowed to limit the maximum supported `AccuracyLog`.
924Recommended maximum are `9` for literal and match lengthes, and `8` for offsets.
925The reference decoder uses these limits.
926
927Then follow each symbol value, from `0` to last present one.
928The nb of bits used by each field is variable.
929It depends on :
930
931- Remaining probabilities + 1 :
932 __example__ :
933 Presuming an AccuracyLog of 8,
934 and presuming 100 probabilities points have already been distributed,
Yann Colletcd25a912016-07-05 11:50:37 +0200935 the decoder may read any value from `0` to `255 - 100 + 1 == 156` (included).
Yann Collet23f05cc2016-07-04 16:13:11 +0200936 Therefore, it must read `log2sup(156) == 8` bits.
937
938- Value decoded : small values use 1 less bit :
939 __example__ :
940 Presuming values from 0 to 156 (included) are possible,
941 255-156 = 99 values are remaining in an 8-bits field.
942 They are used this way :
943 first 99 values (hence from 0 to 98) use only 7 bits,
944 values from 99 to 156 use 8 bits.
945 This is achieved through this scheme :
946
947 | Value read | Value decoded | nb Bits used |
948 | ---------- | ------------- | ------------ |
949 | 0 - 98 | 0 - 98 | 7 |
950 | 99 - 127 | 99 - 127 | 8 |
951 | 128 - 226 | 0 - 98 | 7 |
952 | 227 - 255 | 128 - 156 | 8 |
953
954Symbols probabilities are read one by one, in order.
955
956Probability is obtained from Value decoded by following formulae :
957`Proba = value - 1;`
958
959It means value `0` becomes negative probability `-1`.
960`-1` is a special probability, which means `less than 1`.
Yann Colletc40ba712016-07-08 15:39:02 +0200961Its effect on distribution table is described in [next paragraph].
Yann Collet23f05cc2016-07-04 16:13:11 +0200962For the purpose of calculating cumulated distribution, it counts as one.
963
Yann Colletc40ba712016-07-08 15:39:02 +0200964[next paragraph]:#fse-decoding--from-normalized-distribution-to-decoding-tables
965
Yann Collet23f05cc2016-07-04 16:13:11 +0200966When a symbol has a probability of `zero`,
967it is followed by a 2-bits repeat flag.
968This repeat flag tells how many probabilities of zeroes follow the current one.
969It provides a number ranging from 0 to 3.
970If it is a 3, another 2-bits repeat flag follows, and so on.
971
Yann Collet9ca73362016-07-05 10:53:38 +0200972When last symbol reaches cumulated total of `1 << AccuracyLog`,
Yann Collet23f05cc2016-07-04 16:13:11 +0200973decoding is complete.
974Then the decoder can tell how many bytes were used in this process,
975and how many symbols are present.
976
977The bitstream consumes a round number of bytes.
978Any remaining bit within the last byte is just unused.
979
Yann Collet9ca73362016-07-05 10:53:38 +0200980If the last symbol makes cumulated total go above `1 << AccuracyLog`,
Yann Collet23f05cc2016-07-04 16:13:11 +0200981distribution is considered corrupted.
982
983##### FSE decoding : from normalized distribution to decoding tables
984
Yann Collet9ca73362016-07-05 10:53:38 +0200985The distribution of normalized probabilities is enough
986to create a unique decoding table.
987
988It follows the following build rule :
989
990The table has a size of `tableSize = 1 << AccuracyLog;`.
991Each cell describes the symbol decoded,
992and instructions to get the next state.
993
994Symbols are scanned in their natural order for `less than 1` probabilities.
995Symbols with this probability are being attributed a single cell,
996starting from the end of the table.
997These symbols define a full state reset, reading `AccuracyLog` bits.
998
999All remaining symbols are sorted in their natural order.
1000Starting from symbol `0` and table position `0`,
1001each symbol gets attributed as many cells as its probability.
1002Cell allocation is spreaded, not linear :
1003each successor position follow this rule :
1004
Yann Colletcd25a912016-07-05 11:50:37 +02001005```
1006position += (tableSize>>1) + (tableSize>>3) + 3;
1007position &= tableSize-1;
1008```
Yann Collet9ca73362016-07-05 10:53:38 +02001009
1010A position is skipped if already occupied,
1011typically by a "less than 1" probability symbol.
1012
1013The result is a list of state values.
1014Each state will decode the current symbol.
1015
1016To get the Number of bits and baseline required for next state,
1017it's first necessary to sort all states in their natural order.
Yann Colletcd25a912016-07-05 11:50:37 +02001018The lower states will need 1 more bit than higher ones.
Yann Collet9ca73362016-07-05 10:53:38 +02001019
1020__Example__ :
1021Presuming a symbol has a probability of 5.
Yann Colletcd25a912016-07-05 11:50:37 +02001022It receives 5 state values. States are sorted in natural order.
Yann Collet9ca73362016-07-05 10:53:38 +02001023
1024Next power of 2 is 8.
1025Space of probabilities is divided into 8 equal parts.
1026Presuming the AccuracyLog is 7, it defines 128 states.
1027Divided by 8, each share is 16 large.
1028
1029In order to reach 8, 8-5=3 lowest states will count "double",
1030taking shares twice larger,
1031requiring one more bit in the process.
1032
1033Numbering starts from higher states using less bits.
1034
1035| state order | 0 | 1 | 2 | 3 | 4 |
1036| ----------- | ----- | ----- | ------ | ---- | ----- |
1037| width | 32 | 32 | 32 | 16 | 16 |
1038| nb Bits | 5 | 5 | 5 | 4 | 4 |
1039| range nb | 2 | 4 | 6 | 0 | 1 |
1040| baseline | 32 | 64 | 96 | 0 | 16 |
1041| range | 32-63 | 64-95 | 96-127 | 0-15 | 16-31 |
1042
1043Next state is determined from current state
1044by reading the required number of bits, and adding the specified baseline.
Yann Collet23f05cc2016-07-04 16:13:11 +02001045
1046
1047#### Bitstream
Yann Collet00d44ab2016-07-04 01:29:47 +02001048
Yann Collet9ca73362016-07-05 10:53:38 +02001049All sequences are stored in a single bitstream, read _backward_.
1050It is therefore necessary to know the bitstream size,
1051which is deducted from compressed block size.
1052
Yann Colletc40ba712016-07-08 15:39:02 +02001053The last useful bit of the stream is followed by an end-bit-flag.
Yann Colletcd25a912016-07-05 11:50:37 +02001054Highest bit of last byte is this flag.
Yann Collet9ca73362016-07-05 10:53:38 +02001055It does not belong to the useful part of the bitstream.
1056Therefore, last byte has 0-7 useful bits.
1057Note that it also means that last byte cannot be `0`.
1058
1059##### Starting states
1060
1061The bitstream starts with initial state values,
1062each using the required number of bits in their respective _accuracy_,
1063decoded previously from their normalized distribution.
1064
1065It starts by `Literal Length State`,
1066followed by `Offset State`,
1067and finally `Match Length State`.
1068
1069Reminder : always keep in mind that all values are read _backward_.
1070
1071##### Decoding a sequence
1072
1073A state gives a code.
1074A code provides a baseline and number of bits to add.
1075See [Symbol Decoding] section for details on each symbol.
1076
1077Decoding starts by reading the nb of bits required to decode offset.
1078It then does the same for match length,
1079and then for literal length.
1080
Yann Colletc40ba712016-07-08 15:39:02 +02001081Offset / matchLength / litLength define a sequence.
1082It starts by inserting the number of literals defined by `litLength`,
1083then continue by copying `matchLength` bytes from `currentPos - offset`.
Yann Collet9ca73362016-07-05 10:53:38 +02001084
1085The next operation is to update states.
1086Using rules pre-calculated in the decoding tables,
1087`Literal Length State` is updated,
1088followed by `Match Length State`,
1089and then `Offset State`.
1090
1091This operation will be repeated `NbSeqs` times.
1092At the end, the bitstream shall be entirely consumed,
1093otherwise bitstream is considered corrupted.
1094
1095[Symbol Decoding]:#symbols-decoding
1096
1097##### Repeat offsets
1098
1099As seen in [Offset Codes], the first 3 values define a repeated offset.
1100They are sorted in recency order, with 1 meaning "most recent one".
1101
1102There is an exception though, when current sequence's literal length is `0`.
1103In which case, 1 would just make previous match longer.
1104Therefore, in such case, 1 means in fact 2, and 2 is impossible.
1105Meaning of 3 is unmodified.
1106
1107Repeat offsets start with the following values : 1, 4 and 8 (in order).
1108
1109Then each block receives its start value from previous compressed block.
1110Note that non-compressed blocks are skipped,
1111they do not contribute to offset history.
1112
1113[Offset Codes]: #offset-codes
1114
1115###### Offset updates rules
1116
1117When the new offset is a normal one,
1118offset history is simply translated by one position,
1119with the new offset taking first spot.
1120
1121- When repeat offset 1 (most recent) is used, history is unmodified.
1122- When repeat offset 2 is used, it's swapped with offset 1.
1123- When repeat offset 3 is used, it takes first spot,
1124 pushing the other ones by one position.
Yann Collet00d44ab2016-07-04 01:29:47 +02001125
Yann Collet2fa99042016-07-01 20:55:28 +02001126
Yann Colletbd106072016-07-08 19:16:57 +02001127Dictionary format
1128-----------------
1129
1130`zstd` is compatible with "pure content" dictionaries, free of any format restriction.
1131But dictionaries created by `zstd --train` follow a format, described here.
1132
1133__Pre-requisites__ : a dictionary has a known length,
1134 defined either by a buffer limit, or a file size.
1135
1136| Header | DictID | Stats | Content |
1137| ------ | ------ | ----- | ------- |
1138
1139__Header__ : 4 bytes ID, value 0xEC30A437, Little Endian format
1140
1141__Dict_ID__ : 4 bytes, stored in Little Endian format.
1142 DictID can be any value, except 0 (which means no DictID).
Yann Collet722e14b2016-07-08 19:22:16 +02001143 It's used by decoders to check if they use the correct dictionary.
Yann Colletf6ff53c2016-07-15 17:03:38 +02001144 _Reserved ranges :_
1145 If the frame is going to be distributed in a private environment,
1146 any dictionary ID can be used.
1147 However, for public distribution of compressed frames,
1148 some ranges are reserved for future use :
Yann Collet6cacd342016-07-15 17:58:13 +02001149
1150 - low range : 1 - 32767 : reserved
1151 - high range : >= (2^31) : reserved
Yann Colletbd106072016-07-08 19:16:57 +02001152
1153__Stats__ : Entropy tables, following the same format as a [compressed blocks].
1154 They are stored in following order :
1155 Huffman tables for literals, FSE table for offset,
Yann Collet722e14b2016-07-08 19:22:16 +02001156 FSE table for matchLenth, and FSE table for litLength.
1157 It's finally followed by 3 offset values, populating recent offsets,
1158 stored in order, 4-bytes little endian each, for a total of 12 bytes.
Yann Colletbd106072016-07-08 19:16:57 +02001159
1160__Content__ : Where the actual dictionary content is.
Yann Collet722e14b2016-07-08 19:22:16 +02001161 Content size depends on Dictionary size.
Yann Colletbd106072016-07-08 19:16:57 +02001162
1163[compressed blocks]: #compressed-block-format
1164
Yann Collet2fa99042016-07-01 20:55:28 +02001165
1166Version changes
1167---------------
Yann Collete557fd52016-07-17 16:21:37 +02001168- 0.1.2 : limit huffman tree depth to 11 bits
1169- 0.1.1 : reserved dictID ranges
1170- 0.1.0 : initial release