blob: b6ace36171fe35f0ef720bc0c847c79821872707 [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
inikepf9c3cce2016-07-25 11:04:56 +02009for any purpose and without charge,
10including translations into other languages
Yann Collet2fa99042016-07-01 20:55:28 +020011and 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 Collet6fa05a22016-07-20 14:58:49 +0200190.2.0 (22/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
inikepf9c3cce2016-07-25 11:04:56 +020061Overall conventions
62-----------
63In this document square brackets i.e. `[` and `]` are used to indicate optional fields or parameters.
64
65
Yann Collet2fa99042016-07-01 20:55:28 +020066Definitions
67-----------
68A content compressed by Zstandard is transformed into a Zstandard __frame__.
69Multiple frames can be appended into a single file or stream.
70A frame is totally independent, has a defined beginning and end,
71and a set of parameters which tells the decoder how to decompress it.
72
73A frame encapsulates one or multiple __blocks__.
74Each block can be compressed or not,
75and has a guaranteed maximum content size, which depends on frame parameters.
76Unlike frames, each block depends on previous blocks for proper decoding.
77However, each block can be decompressed without waiting for its successor,
78allowing streaming operations.
79
80
inikepf9c3cce2016-07-25 11:04:56 +020081Frame Concatenation
82-------------------
Yann Collet2fa99042016-07-01 20:55:28 +020083
84In some circumstances, it may be required to append multiple frames,
85for example in order to add new data to an existing compressed file
86without re-framing it.
87
88In such case, each frame brings its own set of descriptor flags.
89Each frame is considered independent.
90The only relation between frames is their sequential order.
91
92The ability to decode multiple concatenated frames
93within a single stream or file is left outside of this specification.
94As an example, the reference `zstd` command line utility is able
95to decode all concatenated frames in their sequential order,
96delivering the final decompressed result as if it was a single content.
97
98
inikepf9c3cce2016-07-25 11:04:56 +020099General Structure of Zstandard Frame format
100-------------------------------------------
101The structure of a single Zstandard frame is following:
Yann Collet2fa99042016-07-01 20:55:28 +0200102
Yann Colletc991cc12016-07-28 00:55:43 +0200103| `Magic_Number` | `Frame_Header` |`Data_Block`| [More data blocks] | [`Content_Checksum`] |
104|:--------------:|:--------------:|:----------:| ------------------ |:--------------------:|
105| 4 bytes | 2-14 bytes | n bytes | | 0-4 bytes |
Yann Collet2fa99042016-07-01 20:55:28 +0200106
inikepf9c3cce2016-07-25 11:04:56 +0200107__`Magic_Number`__
108
inikep2fc37522016-07-25 12:47:02 +02001094 Bytes, Little-endian format.
inikepf9c3cce2016-07-25 11:04:56 +0200110Value : 0xFD2FB527
111
112__`Frame_Header`__
113
1142 to 14 Bytes, detailed in [next part](#the-structure-of-frame_header).
115
116__`Data_Block`__
117
118Detailed in [next chapter](#the-structure-of-data_block).
119That’s where compressed data is stored.
120
Yann Colletc991cc12016-07-28 00:55:43 +0200121__`Content_Checksum`__
inikepf9c3cce2016-07-25 11:04:56 +0200122
Yann Colletc991cc12016-07-28 00:55:43 +0200123An optional 32-bit checksum, only present if `Content_Checksum_flag` is set.
inikepf9c3cce2016-07-25 11:04:56 +0200124The content checksum is the result
125of [xxh64() hash function](https://www.xxHash.com)
126digesting the original (decoded) data as input, and a seed of zero.
Yann Colletc991cc12016-07-28 00:55:43 +0200127The low 4 bytes of the checksum are stored in little endian format.
inikepf9c3cce2016-07-25 11:04:56 +0200128
129
130The structure of `Frame_Header`
131-------------------------------
132The `Frame_Header` has a variable size, which uses a minimum of 2 bytes,
Yann Collet2fa99042016-07-01 20:55:28 +0200133and up to 14 bytes depending on optional parameters.
inikepf9c3cce2016-07-25 11:04:56 +0200134The structure of `Frame_Header` is following:
Yann Collet2fa99042016-07-01 20:55:28 +0200135
inikepf9c3cce2016-07-25 11:04:56 +0200136| `Frame_Header_Descriptor` | [`Window_Descriptor`] | [`Dictionary_ID`] | [`Frame_Content_Size`] |
137| ------------------------- | --------------------- | ----------------- | ---------------------- |
138| 1 byte | 0-1 byte | 0-4 bytes | 0-8 bytes |
Yann Collet2fa99042016-07-01 20:55:28 +0200139
inikepf9c3cce2016-07-25 11:04:56 +0200140### `Frame_Header_Descriptor`
141
142The first header's byte is called the `Frame_Header_Descriptor`.
Yann Collet2fa99042016-07-01 20:55:28 +0200143It tells which other fields are present.
inikepf9c3cce2016-07-25 11:04:56 +0200144Decoding this byte is enough to tell the size of `Frame_Header`.
Yann Collet2fa99042016-07-01 20:55:28 +0200145
inikepf9c3cce2016-07-25 11:04:56 +0200146| Bit number | Field name |
147| ---------- | ---------- |
148| 7-6 | `Frame_Content_Size_flag` |
149| 5 | `Single_Segment_flag` |
150| 4 | `Unused_bit` |
151| 3 | `Reserved_bit` |
152| 2 | `Content_Checksum_flag` |
153| 1-0 | `Dictionary_ID_flag` |
Yann Collet2fa99042016-07-01 20:55:28 +0200154
155In this table, bit 7 is highest bit, while bit 0 is lowest.
156
inikep49ec6d12016-07-25 12:26:39 +0200157__`Frame_Content_Size_flag`__
158
159This is a 2-bits flag (`= Frame_Header_Descriptor >> 6`),
160specifying if decompressed data size is provided within the header.
Yann Colletc991cc12016-07-28 00:55:43 +0200161The `Flag_Value` can be converted into `Field_Size`,
162which is the number of bytes used by `Frame_Content_Size`
163according to the following table:
inikep49ec6d12016-07-25 12:26:39 +0200164
Yann Colletc991cc12016-07-28 00:55:43 +0200165|`Flag_Value`| 0 | 1 | 2 | 3 |
inikep49ec6d12016-07-25 12:26:39 +0200166| ---------- | --- | --- | --- | --- |
167|`Field_Size`| 0-1 | 2 | 4 | 8 |
168
Yann Colletc991cc12016-07-28 00:55:43 +0200169When `Flag_Value` is `0`, `Field_Size` depends on `Single_Segment_flag` :
170if `Single_Segment_flag` is set, `Field_Size` is 1.
171Otherwise, `Field_Size` is 0 (content size not provided).
inikep49ec6d12016-07-25 12:26:39 +0200172
inikepf9c3cce2016-07-25 11:04:56 +0200173__`Single_Segment_flag`__
Yann Collet2fa99042016-07-01 20:55:28 +0200174
inikep49ec6d12016-07-25 12:26:39 +0200175If this flag is set,
Yann Colletc991cc12016-07-28 00:55:43 +0200176data must be regenerated within a single continuous memory segment.
Yann Collet2fa99042016-07-01 20:55:28 +0200177
Yann Colletc991cc12016-07-28 00:55:43 +0200178In this case, `Frame_Content_Size` is necessarily present,
179but `Window_Descriptor` byte is skipped.
inikep49ec6d12016-07-25 12:26:39 +0200180As a consequence, the decoder must allocate a memory segment
181of size equal or bigger than `Frame_Content_Size`.
Yann Collet2fa99042016-07-01 20:55:28 +0200182
183In order to preserve the decoder from unreasonable memory requirement,
Yann Collet23f05cc2016-07-04 16:13:11 +0200184a decoder can reject a compressed frame
Yann Collet2fa99042016-07-01 20:55:28 +0200185which requests a memory size beyond decoder's authorized range.
186
187For broader compatibility, decoders are recommended to support
Yann Collet23f05cc2016-07-04 16:13:11 +0200188memory sizes of at least 8 MB.
189This is just a recommendation,
Yann Collet9ca73362016-07-05 10:53:38 +0200190each decoder is free to support higher or lower limits,
Yann Collet2fa99042016-07-01 20:55:28 +0200191depending on local limitations.
192
inikepf9c3cce2016-07-25 11:04:56 +0200193__`Unused_bit`__
Yann Collet2fa99042016-07-01 20:55:28 +0200194
Yann Colletf0bc6732016-07-13 17:30:21 +0200195The value of this bit should be set to zero.
Yann Colletc991cc12016-07-28 00:55:43 +0200196A decoder compliant with this specification version shall not interpret it.
Yann Colletf0bc6732016-07-13 17:30:21 +0200197It might be used in a future version,
198to signal a property which is not mandatory to properly decode the frame.
Yann Collet2fa99042016-07-01 20:55:28 +0200199
inikepf9c3cce2016-07-25 11:04:56 +0200200__`Reserved_bit`__
Yann Collet2fa99042016-07-01 20:55:28 +0200201
202This bit is reserved for some future feature.
203Its value _must be zero_.
204A decoder compliant with this specification version must ensure it is not set.
205This bit may be used in a future revision,
Yann Colletc991cc12016-07-28 00:55:43 +0200206to signal a feature that must be interpreted to decode the frame correctly.
Yann Collet2fa99042016-07-01 20:55:28 +0200207
inikepf9c3cce2016-07-25 11:04:56 +0200208__`Content_Checksum_flag`__
Yann Collet2fa99042016-07-01 20:55:28 +0200209
Yann Colletc991cc12016-07-28 00:55:43 +0200210If this flag is set, a 32-bits `Content_Checksum` will be present at frame's end.
211See `Content_Checksum` paragraph.
Yann Collet2fa99042016-07-01 20:55:28 +0200212
inikepf9c3cce2016-07-25 11:04:56 +0200213__`Dictionary_ID_flag`__
Yann Collet2fa99042016-07-01 20:55:28 +0200214
215This is a 2-bits flag (`= FHD & 3`),
Yann Collet9ca73362016-07-05 10:53:38 +0200216telling if a dictionary ID is provided within the header.
217It also specifies the size of this field.
Yann Collet2fa99042016-07-01 20:55:28 +0200218
inikepf9c3cce2016-07-25 11:04:56 +0200219| Value | 0 | 1 | 2 | 3 |
220| -------- | --- | --- | --- | --- |
221|Field size| 0 | 1 | 2 | 4 |
Yann Collet2fa99042016-07-01 20:55:28 +0200222
inikepf9c3cce2016-07-25 11:04:56 +0200223### `Window_Descriptor`
Yann Collet2fa99042016-07-01 20:55:28 +0200224
225Provides guarantees on maximum back-reference distance
Yann Colletc991cc12016-07-28 00:55:43 +0200226that will be used within compressed data.
227This information is important for decoders to allocate enough memory.
Yann Collet2fa99042016-07-01 20:55:28 +0200228
Yann Colletc991cc12016-07-28 00:55:43 +0200229The `Window_Descriptor` byte is optional. It is absent when `Single_Segment_flag` is set.
inikepf9c3cce2016-07-25 11:04:56 +0200230In this case, the maximum back-reference distance is the content size itself,
Yann Colletcd25a912016-07-05 11:50:37 +0200231which can be any value from 1 to 2^64-1 bytes (16 EB).
232
inikepf9c3cce2016-07-25 11:04:56 +0200233| Bit numbers | 7-3 | 0-2 |
234| ----------- | -------- | -------- |
235| Field name | Exponent | Mantissa |
Yann Collet2fa99042016-07-01 20:55:28 +0200236
237Maximum distance is given by the following formulae :
238```
239windowLog = 10 + Exponent;
240windowBase = 1 << windowLog;
241windowAdd = (windowBase / 8) * Mantissa;
242windowSize = windowBase + windowAdd;
243```
244The minimum window size is 1 KB.
Yann Colletcd25a912016-07-05 11:50:37 +0200245The maximum size is `15*(1<<38)` bytes, which is 1.875 TB.
Yann Collet2fa99042016-07-01 20:55:28 +0200246
247To properly decode compressed data,
248a decoder will need to allocate a buffer of at least `windowSize` bytes.
249
Yann Collet2fa99042016-07-01 20:55:28 +0200250In order to preserve decoder from unreasonable memory requirements,
251a decoder can refuse a compressed frame
252which requests a memory size beyond decoder's authorized range.
253
Yann Colletcd25a912016-07-05 11:50:37 +0200254For improved interoperability,
Yann Colletc991cc12016-07-28 00:55:43 +0200255decoders are recommended to be compatible with window sizes of 8 MB,
256and encoders are recommended to not request more than 8 MB.
Yann Collet2fa99042016-07-01 20:55:28 +0200257It's merely a recommendation though,
258decoders are free to support larger or lower limits,
259depending on local limitations.
260
inikepf9c3cce2016-07-25 11:04:56 +0200261### `Dictionary_ID`
Yann Collet23f05cc2016-07-04 16:13:11 +0200262
Yann Colletf6ff53c2016-07-15 17:03:38 +0200263This is a variable size field, which contains
264the ID of the dictionary required to properly decode the frame.
265Note that this field is optional. When it's not present,
Yann Collet23f05cc2016-07-04 16:13:11 +0200266it's up to the caller to make sure it uses the correct dictionary.
267
inikepf9c3cce2016-07-25 11:04:56 +0200268Field size depends on `Dictionary_ID_flag`.
Yann Collet23f05cc2016-07-04 16:13:11 +02002691 byte can represent an ID 0-255.
2702 bytes can represent an ID 0-65535.
Yann Colletcd25a912016-07-05 11:50:37 +02002714 bytes can represent an ID 0-4294967295.
Yann Collet23f05cc2016-07-04 16:13:11 +0200272
273It's allowed to represent a small ID (for example `13`)
Yann Colletcd25a912016-07-05 11:50:37 +0200274with a large 4-bytes dictionary ID, losing some compacity in the process.
Yann Collet23f05cc2016-07-04 16:13:11 +0200275
Yann Colletf6ff53c2016-07-15 17:03:38 +0200276_Reserved ranges :_
277If the frame is going to be distributed in a private environment,
278any dictionary ID can be used.
279However, for public distribution of compressed frames using a dictionary,
inikepf9c3cce2016-07-25 11:04:56 +0200280the following ranges are reserved for future use and should not be used :
281- low range : 1 - 32767
282- high range : >= (2^31)
Yann Colletf6ff53c2016-07-15 17:03:38 +0200283
284
inikepf9c3cce2016-07-25 11:04:56 +0200285### `Frame_Content_Size`
Yann Collet2fa99042016-07-01 20:55:28 +0200286
inikep2fc37522016-07-25 12:47:02 +0200287This is the original (uncompressed) size. This information is optional.
288The `Field_Size` is provided according to value of `Frame_Content_Size_flag`.
289The `Field_Size` can be equal to 0 (not present), 1, 2, 4 or 8 bytes.
290Format is Little-endian.
Yann Collet2fa99042016-07-01 20:55:28 +0200291
inikep2fc37522016-07-25 12:47:02 +0200292| `Field_Size` | Range |
293| ------------ | ---------- |
294| 1 | 0 - 255 |
295| 2 | 256 - 65791|
296| 4 | 0 - 2^32-1 |
297| 8 | 0 - 2^64-1 |
Yann Collet2fa99042016-07-01 20:55:28 +0200298
inikep2fc37522016-07-25 12:47:02 +0200299When `Field_Size` is 1, 4 or 8 bytes, the value is read directly.
300When `Field_Size` is 2, _the offset of 256 is added_.
inikepf9c3cce2016-07-25 11:04:56 +0200301It's allowed to represent a small size (for example `18`) using any compatible variant.
Yann Collet2fa99042016-07-01 20:55:28 +0200302
Yann Collet2fa99042016-07-01 20:55:28 +0200303
inikepf9c3cce2016-07-25 11:04:56 +0200304The structure of `Data_Block`
305-----------------------------
306The structure of `Data_Block` is following:
Yann Collet2fa99042016-07-01 20:55:28 +0200307
Yann Colletc991cc12016-07-28 00:55:43 +0200308| `Last_Block` | `Block_Type` | `Block_Size` | `Block_Content` |
309|:------------:|:------------:|:------------:|:---------------:|
310| 1 bit | 2 bits | 21 bits | n bytes |
311
312The block header uses 3-bytes.
313
314__`Last_Block`__
315
316The lowest bit signals if this block is the last one.
317Frame ends right after this block.
318It may be followed by an optional `Content_Checksum` .
Yann Collet2fa99042016-07-01 20:55:28 +0200319
inikepf9c3cce2016-07-25 11:04:56 +0200320__`Block_Type` and `Block_Size`__
Yann Collet2fa99042016-07-01 20:55:28 +0200321
Yann Colletc991cc12016-07-28 00:55:43 +0200322The next 2 bits represent the `Block_Type`,
323while the remaining 21 bits represent the `Block_Size`.
324Format is __little-endian__.
Yann Collet2fa99042016-07-01 20:55:28 +0200325
326There are 4 block types :
327
inikepf9c3cce2016-07-25 11:04:56 +0200328| Value | 0 | 1 | 2 | 3 |
329| ------------ | ----------- | ----------- | ------------------ | --------- |
Yann Colletc991cc12016-07-28 00:55:43 +0200330| `Block_Type` | `Raw_Block` | `RLE_Block` | `Compressed_Block` | `Reserved`|
Yann Collet2fa99042016-07-01 20:55:28 +0200331
inikepf9c3cce2016-07-25 11:04:56 +0200332- `Raw_Block` - this is an uncompressed block.
333 `Block_Size` is the number of bytes to read and copy.
334- `RLE_Block` - this is a single byte, repeated N times.
335 In which case, `Block_Size` is the size to regenerate,
336 while the "compressed" block is just 1 byte (the byte to repeat).
337- `Compressed_Block` - this is a [Zstandard compressed block](#the-format-of-compressed_block),
Yann Collet9ca73362016-07-05 10:53:38 +0200338 detailed in another section of this specification.
inikepf9c3cce2016-07-25 11:04:56 +0200339 `Block_Size` is the compressed size.
Yann Collet2fa99042016-07-01 20:55:28 +0200340 Decompressed size is unknown,
341 but its maximum possible value is guaranteed (see below)
Yann Colletc991cc12016-07-28 00:55:43 +0200342- `Reserved` - this is not a block.
343 This value cannot be used with current version of this specification.
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
inikepf9c3cce2016-07-25 11:04:56 +0200351__`Block_Content`__
Yann Collet2fa99042016-07-01 20:55:28 +0200352
inikepf9c3cce2016-07-25 11:04:56 +0200353The `Block_Content` is where the actual data to decode stands.
Yann Collet2fa99042016-07-01 20:55:28 +0200354It 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,
inikepf9c3cce2016-07-25 11:04:56 +0200358up to `Block_Maximum_Decompressed_Size`, which is the smallest of :
Yann Colletcd25a912016-07-05 11:50:37 +0200359- Maximum back-reference distance
Yann Collet2fa99042016-07-01 20:55:28 +0200360- 128 KB
361
362
363Skippable Frames
364----------------
365
inikepf9c3cce2016-07-25 11:04:56 +0200366| `Magic_Number` | `Frame_Size` | `User_Data` |
367|:--------------:|:------------:|:-----------:|
368| 4 bytes | 4 bytes | n bytes |
Yann Collet2fa99042016-07-01 20:55:28 +0200369
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
inikepf9c3cce2016-07-25 11:04:56 +0200380__`Magic_Number`__
Yann Collet2fa99042016-07-01 20:55:28 +0200381
inikep2fc37522016-07-25 12:47:02 +02003824 Bytes, Little-endian format.
Yann Collet2fa99042016-07-01 20:55:28 +0200383Value : 0x184D2A5X, which means any value from 0x184D2A50 to 0x184D2A5F.
384All 16 values are valid to identify a skippable frame.
385
inikepf9c3cce2016-07-25 11:04:56 +0200386__`Frame_Size`__
Yann Collet2fa99042016-07-01 20:55:28 +0200387
inikepf9c3cce2016-07-25 11:04:56 +0200388This is the size, in bytes, of the following `User_Data`
Yann Collet2fa99042016-07-01 20:55:28 +0200389(without including the magic number nor the size field itself).
inikep2fc37522016-07-25 12:47:02 +0200390This field is represented using 4 Bytes, Little-endian format, unsigned 32-bits.
inikepf9c3cce2016-07-25 11:04:56 +0200391This means `User_Data` can’t be bigger than (2^32-1) bytes.
Yann Collet2fa99042016-07-01 20:55:28 +0200392
inikepf9c3cce2016-07-25 11:04:56 +0200393__`User_Data`__
Yann Collet2fa99042016-07-01 20:55:28 +0200394
inikepf9c3cce2016-07-25 11:04:56 +0200395The `User_Data` can be anything. Data will just be skipped by the decoder.
Yann Collet2fa99042016-07-01 20:55:28 +0200396
397
inikepf9c3cce2016-07-25 11:04:56 +0200398The format of `Compressed_Block`
399--------------------------------
400The size of `Compressed_Block` must be provided using `Block_Size` field from `Data_Block`.
401The `Compressed_Block` has a guaranteed maximum regenerated size,
Yann Collet2fa99042016-07-01 20:55:28 +0200402in order to properly allocate destination buffer.
inikepf9c3cce2016-07-25 11:04:56 +0200403See [`Data_Block`](#the-structure-of-data_block) for more details.
Yann Collet2fa99042016-07-01 20:55:28 +0200404
405A compressed block consists of 2 sections :
Yann Colletcd25a912016-07-05 11:50:37 +0200406- [Literals section](#literals-section)
407- [Sequences section](#sequences-section)
Yann Collet2fa99042016-07-01 20:55:28 +0200408
Yann Collet23f05cc2016-07-04 16:13:11 +0200409### Prerequisites
410To decode a compressed block, the following elements are necessary :
Yann Collet698cb632016-07-03 18:49:35 +0200411- Previous decoded blocks, up to a distance of `windowSize`,
inikepf9c3cce2016-07-25 11:04:56 +0200412 or all previous blocks when `Single_Segment_flag` is set.
Yann Collet698cb632016-07-03 18:49:35 +0200413- List of "recent offsets" from previous compressed block.
Yann Collet00d44ab2016-07-04 01:29:47 +0200414- Decoding tables of previous compressed block for each symbol type
Yann Collet9ca73362016-07-05 10:53:38 +0200415 (literals, litLength, matchLength, offset).
Yann Collet698cb632016-07-03 18:49:35 +0200416
417
Yann Collet00d44ab2016-07-04 01:29:47 +0200418### Literals section
Yann Collet2fa99042016-07-01 20:55:28 +0200419
Yann Collet2fa99042016-07-01 20:55:28 +0200420During sequence phase, literals will be entangled with match copy operations.
421All literals are regrouped in the first part of the block.
422They can be decoded first, and then copied during sequence operations,
Yann Collet00d44ab2016-07-04 01:29:47 +0200423or they can be decoded on the flow, as needed by sequence commands.
Yann Collet2fa99042016-07-01 20:55:28 +0200424
inikepf9c3cce2016-07-25 11:04:56 +0200425| Literals section header | [Huffman Tree Description] | Stream1 | [Stream2] | [Stream3] | [Stream4] |
426| ----------------------- | -------------------------- | ------- | --------- | --------- | --------- |
Yann Collet2fa99042016-07-01 20:55:28 +0200427
inikepf9c3cce2016-07-25 11:04:56 +0200428Literals can be stored uncompressed or compressed using Huffman prefix codes.
Yann Collet2fa99042016-07-01 20:55:28 +0200429When compressed, an optional tree description can be present,
430followed by 1 or 4 streams.
431
inikepf9c3cce2016-07-25 11:04:56 +0200432
Yann Collet00d44ab2016-07-04 01:29:47 +0200433#### Literals section header
Yann Collet2fa99042016-07-01 20:55:28 +0200434
Yann Collet00d44ab2016-07-04 01:29:47 +0200435Header is in charge of describing how literals are packed.
Yann Collet2fa99042016-07-01 20:55:28 +0200436It's a byte-aligned variable-size bitfield, ranging from 1 to 5 bytes,
Yann Collet198e6aa2016-07-20 20:12:24 +0200437using little-endian convention.
Yann Collet2fa99042016-07-01 20:55:28 +0200438
inikepf9c3cce2016-07-25 11:04:56 +0200439| Literals Block Type | sizes format | regenerated size | [compressed size] |
440| ------------------- | ------------ | ---------------- | ----------------- |
441| 2 bits | 1 - 2 bits | 5 - 20 bits | 0 - 18 bits |
Yann Collet198e6aa2016-07-20 20:12:24 +0200442
443In this representation, bits on the left are smallest bits.
Yann Collet2fa99042016-07-01 20:55:28 +0200444
inikepf9c3cce2016-07-25 11:04:56 +0200445__Literals Block Type__ :
Yann Collet2fa99042016-07-01 20:55:28 +0200446
Yann Collet198e6aa2016-07-20 20:12:24 +0200447This field uses 2 lowest bits of first byte, describing 4 different block types :
Yann Collet2fa99042016-07-01 20:55:28 +0200448
inikepf9c3cce2016-07-25 11:04:56 +0200449| Value | 0 | 1 | 2 | 3 |
450| ------------------- | --- | --- | ---------- | ----------- |
451| Literals Block Type | Raw | RLE | Compressed | RepeatStats |
Yann Collet2fa99042016-07-01 20:55:28 +0200452
inikepf9c3cce2016-07-25 11:04:56 +0200453- Raw literals block - Literals are stored uncompressed.
454- RLE literals block - Literals consist of a single byte value repeated N times.
inikep586a0552016-08-03 16:16:38 +0200455- Compressed literals block - This is a standard Huffman-compressed block,
456 starting with a Huffman tree description.
Yann Colletcd25a912016-07-05 11:50:37 +0200457 See details below.
inikep586a0552016-08-03 16:16:38 +0200458- Repeat Stats literals block - This is a Huffman-compressed block,
459 using Huffman tree _from previous Huffman-compressed literals block_.
Yann Colletcd25a912016-07-05 11:50:37 +0200460 Huffman tree description will be skipped.
Yann Collet2fa99042016-07-01 20:55:28 +0200461
462__Sizes format__ :
463
464Sizes format are divided into 2 families :
465
466- For compressed block, it requires to decode both the compressed size
467 and the decompressed size. It will also decode the number of streams.
468- For Raw or RLE blocks, it's enough to decode the size to regenerate.
469
Yann Collet198e6aa2016-07-20 20:12:24 +0200470For values spanning several bytes, convention is Little-endian.
Yann Collet2fa99042016-07-01 20:55:28 +0200471
Yann Collet198e6aa2016-07-20 20:12:24 +0200472__Sizes format for Raw and RLE literals block__ :
Yann Collet2fa99042016-07-01 20:55:28 +0200473
Yann Collet198e6aa2016-07-20 20:12:24 +0200474- Value : x0 : Regenerated size uses 5 bits (0-31).
Yann Collet2fa99042016-07-01 20:55:28 +0200475 Total literal header size is 1 byte.
Yann Collet198e6aa2016-07-20 20:12:24 +0200476 `size = h[0]>>3;`
477- Value : 01 : Regenerated size uses 12 bits (0-4095).
Yann Collet2fa99042016-07-01 20:55:28 +0200478 Total literal header size is 2 bytes.
Yann Collet198e6aa2016-07-20 20:12:24 +0200479 `size = (h[0]>>4) + (h[1]<<4);`
Yann Collet2fa99042016-07-01 20:55:28 +0200480- Value : 11 : Regenerated size uses 20 bits (0-1048575).
Yann Colletd916c902016-07-04 00:42:58 +0200481 Total literal header size is 3 bytes.
Yann Collet198e6aa2016-07-20 20:12:24 +0200482 `size = (h[0]>>4) + (h[1]<<4) + (h[2]<<12);`
Yann Collet2fa99042016-07-01 20:55:28 +0200483
484Note : it's allowed to represent a short value (ex : `13`)
485using a long format, accepting the reduced compacity.
486
inikepf9c3cce2016-07-25 11:04:56 +0200487__Sizes format for Compressed literals block and Repeat Stats literals block__ :
Yann Collet2fa99042016-07-01 20:55:28 +0200488
Yann Colletc2e1a682016-07-22 17:30:52 +0200489- Value : 00 : _Single stream_.
Yann Colletcd25a912016-07-05 11:50:37 +0200490 Compressed and regenerated sizes use 10 bits (0-1023).
491 Total literal header size is 3 bytes.
Yann Colletc2e1a682016-07-22 17:30:52 +0200492- Value : 01 : 4 streams.
Yann Colletcd25a912016-07-05 11:50:37 +0200493 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.
Yann Colletd9cc4422016-07-22 19:15:27 +0200498- Value : 11 : 4 streams.
Yann Colletcd25a912016-07-05 11:50:37 +0200499 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
inikepf9c3cce2016-07-25 11:04:56 +0200502Compressed and regenerated size fields follow little-endian convention.
Yann Collet698cb632016-07-03 18:49:35 +0200503
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__ :
inikep586a0552016-08-03 16:16:38 +0200536Let's presume the following Huffman tree must be described :
Yann Collet698cb632016-07-03 18:49:35 +0200537
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
Yann Collet698cb632016-07-03 18:49:35 +0200566- if headerByte >= 128 : this is a direct representation,
567 where each weight is written directly as a 4 bits field (0-15).
Yann Colletcd25a912016-07-05 11:50:37 +0200568 The full representation occupies `((nbSymbols+1)/2)` bytes,
Yann Collet698cb632016-07-03 18:49:35 +0200569 meaning it uses a last full byte even if nbSymbols is odd.
Yann Collet26f68142016-07-08 10:42:59 +0200570 `nbSymbols = headerByte - 127;`.
Yann Collet38b75dd2016-07-24 15:35:59 +0200571 Note that maximum nbSymbols is 255-127 = 128.
Yann Collet26f68142016-07-08 10:42:59 +0200572 A larger serie must necessarily use FSE compression.
Yann Collet698cb632016-07-03 18:49:35 +0200573
574- if headerByte < 128 :
575 the serie of weights is compressed by FSE.
Yann Collet26f68142016-07-08 10:42:59 +0200576 The length of the FSE-compressed serie is `headerByte` (0-127).
Yann Collet698cb632016-07-03 18:49:35 +0200577
inikep586a0552016-08-03 16:16:38 +0200578##### FSE (Finite State Entropy) compression of Huffman weights
Yann Collet698cb632016-07-03 18:49:35 +0200579
Yann Collet26f68142016-07-08 10:42:59 +0200580The serie of weights is compressed using FSE compression.
Yann Collet698cb632016-07-03 18:49:35 +0200581It's a single bitstream with 2 interleaved states,
Yann Collet26f68142016-07-08 10:42:59 +0200582sharing a single distribution table.
Yann Collet698cb632016-07-03 18:49:35 +0200583
584To decode an FSE bitstream, it is necessary to know its compressed size.
585Compressed size is provided by `headerByte`.
Yann Collet38b75dd2016-07-24 15:35:59 +0200586It's also necessary to know its _maximum possible_ decompressed size,
Yann Collet26f68142016-07-08 10:42:59 +0200587which is `255`, since literal values span from `0` to `255`,
Yann Colletcd25a912016-07-05 11:50:37 +0200588and last symbol value is not represented.
Yann Collet698cb632016-07-03 18:49:35 +0200589
590An FSE bitstream starts by a header, describing probabilities distribution.
Yann Collet00d44ab2016-07-04 01:29:47 +0200591It will create a Decoding Table.
Yann Collet26f68142016-07-08 10:42:59 +0200592Table must be pre-allocated, which requires to support a maximum accuracy.
inikep586a0552016-08-03 16:16:38 +0200593For a list of Huffman weights, maximum accuracy is 7 bits.
Yann Collet698cb632016-07-03 18:49:35 +0200594
Yann Collet26f68142016-07-08 10:42:59 +0200595FSE header is [described in relevant chapter](#fse-distribution-table--condensed-format),
596and so is [FSE bitstream](#bitstream).
597The main difference is that Huffman header compression uses 2 states,
598which share the same FSE distribution table.
Yann Collet38b75dd2016-07-24 15:35:59 +0200599Bitstream contains only FSE symbols (no interleaved "raw bitfields").
Yann Collet26f68142016-07-08 10:42:59 +0200600The number of symbols to decode is discovered
601by tracking bitStream overflow condition.
602When both states have overflowed the bitstream, end is reached.
603
Yann Collet698cb632016-07-03 18:49:35 +0200604
inikep586a0552016-08-03 16:16:38 +0200605##### Conversion from weights to Huffman prefix codes
Yann Collet698cb632016-07-03 18:49:35 +0200606
Yann Colletd916c902016-07-04 00:42:58 +0200607All present symbols shall now have a `weight` value.
Yann Collet38b75dd2016-07-24 15:35:59 +0200608It is possible to transform weights into nbBits, using this formula :
Yann Colletd916c902016-07-04 00:42:58 +0200609`nbBits = nbBits ? maxBits + 1 - weight : 0;` .
610
Yann Collet38b75dd2016-07-24 15:35:59 +0200611Symbols are sorted by weight. Within same weight, symbols keep natural order.
612Symbols with a weight of zero are removed.
613Then, starting from lowest weight, prefix codes are distributed in order.
Yann Colletd916c902016-07-04 00:42:58 +0200614
615__Example__ :
Yann Colletb21e9cb2016-07-15 17:31:13 +0200616Let's presume the following list of weights has been decoded :
Yann Colletd916c902016-07-04 00:42:58 +0200617
618| Literal | 0 | 1 | 2 | 3 | 4 | 5 |
619| ------- | --- | --- | --- | --- | --- | --- |
620| weight | 4 | 3 | 2 | 0 | 1 | 1 |
621
622Sorted by weight and then natural order,
623it gives the following distribution :
624
625| Literal | 3 | 4 | 5 | 2 | 1 | 0 |
626| ------------ | --- | --- | --- | --- | --- | ---- |
627| weight | 0 | 1 | 1 | 2 | 3 | 4 |
Yann Colletd916c902016-07-04 00:42:58 +0200628| nb bits | 0 | 4 | 4 | 3 | 2 | 1 |
Yann Colletb21e9cb2016-07-15 17:31:13 +0200629| prefix codes | N/A | 0000| 0001| 001 | 01 | 1 |
Yann Colletd916c902016-07-04 00:42:58 +0200630
631
Yann Colletd916c902016-07-04 00:42:58 +0200632#### Literals bitstreams
633
634##### Bitstreams sizes
635
636As seen in a previous paragraph,
inikep586a0552016-08-03 16:16:38 +0200637there are 2 flavors of Huffman-compressed literals :
Yann Colletd916c902016-07-04 00:42:58 +0200638single stream, and 4-streams.
639
6404-streams is useful for CPU with multiple execution units and OoO operations.
641Since each stream can be decoded independently,
642it's possible to decode them up to 4x faster than a single stream,
643presuming the CPU has enough parallelism available.
644
645For single stream, header provides both the compressed and regenerated size.
646For 4-streams though,
647header only provides compressed and regenerated size of all 4 streams combined.
Yann Colletd916c902016-07-04 00:42:58 +0200648In order to properly decode the 4 streams,
649it's necessary to know the compressed and regenerated size of each stream.
650
Yann Collet38b75dd2016-07-24 15:35:59 +0200651Regenerated size of each stream can be calculated by `(totalSize+3)/4`,
652except for last one, which can be up to 3 bytes smaller, to reach `totalSize`.
Yann Colletd916c902016-07-04 00:42:58 +0200653
Yann Collet38b75dd2016-07-24 15:35:59 +0200654Compressed size is provided explicitly : in the 4-streams variant,
inikep2fc37522016-07-25 12:47:02 +0200655bitstreams are preceded by 3 unsigned Little-Endian 16-bits values.
Yann Collet00d44ab2016-07-04 01:29:47 +0200656Each value represents the compressed size of one stream, in order.
Yann Colletd916c902016-07-04 00:42:58 +0200657The last stream size is deducted from total compressed size
Yann Collet38b75dd2016-07-24 15:35:59 +0200658and from previously decoded stream sizes :
Yann Colletd916c902016-07-04 00:42:58 +0200659`stream4CSize = totalCSize - 6 - stream1CSize - stream2CSize - stream3CSize;`
660
Yann Collet00d44ab2016-07-04 01:29:47 +0200661##### Bitstreams read and decode
Yann Colletd916c902016-07-04 00:42:58 +0200662
663Each bitstream must be read _backward_,
664that is starting from the end down to the beginning.
665Therefore it's necessary to know the size of each bitstream.
666
667It's also necessary to know exactly which _bit_ is the latest.
668This is detected by a final bit flag :
669the highest bit of latest byte is a final-bit-flag.
670Consequently, a last byte of `0` is not possible.
671And the final-bit-flag itself is not part of the useful bitstream.
Yann Collet38b75dd2016-07-24 15:35:59 +0200672Hence, the last byte contains between 0 and 7 useful bits.
Yann Colletd916c902016-07-04 00:42:58 +0200673
674Starting from the end,
675it's possible to read the bitstream in a little-endian fashion,
676keeping track of already used bits.
677
Yann Collet00d44ab2016-07-04 01:29:47 +0200678Reading the last `maxBits` bits,
Yann Colletb21e9cb2016-07-15 17:31:13 +0200679it's then possible to compare extracted value to decoding table,
Yann Colletd916c902016-07-04 00:42:58 +0200680determining the symbol to decode and number of bits to discard.
681
682The process continues up to reading the required number of symbols per stream.
683If a bitstream is not entirely and exactly consumed,
Yann Colletb21e9cb2016-07-15 17:31:13 +0200684hence reaching exactly its beginning position with _all_ bits consumed,
Yann Colletd916c902016-07-04 00:42:58 +0200685the decoding process is considered faulty.
686
Yann Collet698cb632016-07-03 18:49:35 +0200687
Yann Collet00d44ab2016-07-04 01:29:47 +0200688### Sequences section
689
690A compressed block is a succession of _sequences_ .
691A sequence is a literal copy command, followed by a match copy command.
692A literal copy command specifies a length.
693It is the number of bytes to be copied (or extracted) from the literal section.
694A match copy command specifies an offset and a length.
695The offset gives the position to copy from,
Yann Colletb21e9cb2016-07-15 17:31:13 +0200696which can be within a previous block.
Yann Collet00d44ab2016-07-04 01:29:47 +0200697
Yann Colletcd25a912016-07-05 11:50:37 +0200698There are 3 symbol types, `literalLength`, `matchLength` and `offset`,
Yann Collet00d44ab2016-07-04 01:29:47 +0200699which are encoded together, interleaved in a single _bitstream_.
700
Yann Colletcd25a912016-07-05 11:50:37 +0200701Each symbol is a _code_ in its own context,
702which specifies a baseline and a number of bits to add.
Yann Collet00d44ab2016-07-04 01:29:47 +0200703_Codes_ are FSE compressed,
704and interleaved with raw additional bits in the same bitstream.
705
Yann Collet23f05cc2016-07-04 16:13:11 +0200706The Sequences section starts by a header,
707followed by optional Probability tables for each symbol type,
Yann Collet00d44ab2016-07-04 01:29:47 +0200708followed by the bitstream.
709
Yann Collet6fa05a22016-07-20 14:58:49 +0200710| Header | [LitLengthTable] | [OffsetTable] | [MatchLengthTable] | bitStream |
Yann Colletc40ba712016-07-08 15:39:02 +0200711| ------ | ---------------- | ------------- | ------------------ | --------- |
712
Yann Collet23f05cc2016-07-04 16:13:11 +0200713To decode the Sequence section, it's required to know its size.
Yann Colletcd25a912016-07-05 11:50:37 +0200714This size is deducted from `blockSize - literalSectionSize`.
Yann Collet23f05cc2016-07-04 16:13:11 +0200715
716
Yann Collet00d44ab2016-07-04 01:29:47 +0200717#### Sequences section header
718
Yann Collet23f05cc2016-07-04 16:13:11 +0200719Consists in 2 items :
720- Nb of Sequences
721- Flags providing Symbol compression types
722
723__Nb of Sequences__
724
725This is a variable size field, `nbSeqs`, using between 1 and 3 bytes.
726Let's call its first byte `byte0`.
727- `if (byte0 == 0)` : there are no sequences.
728 The sequence section stops there.
729 Regenerated content is defined entirely by literals section.
Yann Colletcd25a912016-07-05 11:50:37 +0200730- `if (byte0 < 128)` : `nbSeqs = byte0;` . Uses 1 byte.
731- `if (byte0 < 255)` : `nbSeqs = ((byte0-128) << 8) + byte1;` . Uses 2 bytes.
732- `if (byte0 == 255)`: `nbSeqs = byte1 + (byte2<<8) + 0x7F00;` . Uses 3 bytes.
Yann Collet23f05cc2016-07-04 16:13:11 +0200733
Yann Collet10b9c132016-07-24 01:21:53 +0200734__Symbol encoding modes__
Yann Collet23f05cc2016-07-04 16:13:11 +0200735
736This is a single byte, defining the compression mode of each symbol type.
737
738| BitNb | 7-6 | 5-4 | 3-2 | 1-0 |
739| ------- | ------ | ------ | ------ | -------- |
Yann Collet10b9c132016-07-24 01:21:53 +0200740|FieldName| LLType | OFType | MLType | Reserved |
Yann Collet23f05cc2016-07-04 16:13:11 +0200741
742The last field, `Reserved`, must be all-zeroes.
743
Yann Collet10b9c132016-07-24 01:21:53 +0200744`LLType`, `OFType` and `MLType` define the compression mode of
Yann Collet23f05cc2016-07-04 16:13:11 +0200745Literal Lengths, Offsets and Match Lengths respectively.
746
747They follow the same enumeration :
748
Yann Colletf8e7b532016-07-23 16:31:49 +0200749| Value | 0 | 1 | 2 | 3 |
750| ---------------- | ------ | --- | ---------- | ------ |
751| Compression Mode | predef | RLE | Compressed | Repeat |
Yann Collet23f05cc2016-07-04 16:13:11 +0200752
753- "predef" : uses a pre-defined distribution table.
754- "RLE" : it's a single code, repeated `nbSeqs` times.
755- "Repeat" : re-use distribution table from previous compressed block.
Yann Colletf8e7b532016-07-23 16:31:49 +0200756- "Compressed" : standard FSE compression.
Yann Colletcd25a912016-07-05 11:50:37 +0200757 A distribution table will be present.
758 It will be described in [next part](#distribution-tables).
Yann Collet23f05cc2016-07-04 16:13:11 +0200759
760#### Symbols decoding
761
762##### Literal Lengths codes
763
764Literal lengths codes are values ranging from `0` to `35` included.
765They define lengths from 0 to 131071 bytes.
766
767| Code | 0-15 |
768| ------ | ---- |
Yann Colletc40ba712016-07-08 15:39:02 +0200769| length | Code |
Yann Colletcd25a912016-07-05 11:50:37 +0200770| nbBits | 0 |
771
Yann Collet23f05cc2016-07-04 16:13:11 +0200772
773| Code | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 |
774| -------- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- |
775| Baseline | 16 | 18 | 20 | 22 | 24 | 28 | 32 | 40 |
776| nb Bits | 1 | 1 | 1 | 1 | 2 | 2 | 3 | 3 |
777
778| Code | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 |
779| -------- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- |
780| Baseline | 48 | 64 | 128 | 256 | 512 | 1024 | 2048 | 4096 |
781| nb Bits | 4 | 6 | 7 | 8 | 9 | 10 | 11 | 12 |
782
783| Code | 32 | 33 | 34 | 35 |
784| -------- | ---- | ---- | ---- | ---- |
785| Baseline | 8192 |16384 |32768 |65536 |
786| nb Bits | 13 | 14 | 15 | 16 |
787
788__Default distribution__
789
Yann Colletcd25a912016-07-05 11:50:37 +0200790When "compression mode" is "predef"",
Yann Collet23f05cc2016-07-04 16:13:11 +0200791a pre-defined distribution is used for FSE compression.
792
Yann Colletc40ba712016-07-08 15:39:02 +0200793Below is its definition. It uses an accuracy of 6 bits (64 states).
Yann Collet23f05cc2016-07-04 16:13:11 +0200794```
795short literalLengths_defaultDistribution[36] =
796 { 4, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1,
797 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 2, 1, 1, 1, 1, 1,
798 -1,-1,-1,-1 };
799```
800
801##### Match Lengths codes
802
803Match lengths codes are values ranging from `0` to `52` included.
804They define lengths from 3 to 131074 bytes.
805
806| Code | 0-31 |
807| ------ | -------- |
Yann Collet23f05cc2016-07-04 16:13:11 +0200808| value | Code + 3 |
Yann Colletcd25a912016-07-05 11:50:37 +0200809| nbBits | 0 |
Yann Collet23f05cc2016-07-04 16:13:11 +0200810
811| Code | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 |
812| -------- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- |
813| Baseline | 35 | 37 | 39 | 41 | 43 | 47 | 51 | 59 |
814| nb Bits | 1 | 1 | 1 | 1 | 2 | 2 | 3 | 3 |
815
816| Code | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 |
817| -------- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- |
818| Baseline | 67 | 83 | 99 | 131 | 258 | 514 | 1026 | 2050 |
819| nb Bits | 4 | 4 | 5 | 7 | 8 | 9 | 10 | 11 |
820
821| Code | 48 | 49 | 50 | 51 | 52 |
822| -------- | ---- | ---- | ---- | ---- | ---- |
823| Baseline | 4098 | 8194 |16486 |32770 |65538 |
824| nb Bits | 12 | 13 | 14 | 15 | 16 |
825
826__Default distribution__
827
Yann Colletc40ba712016-07-08 15:39:02 +0200828When "compression mode" is defined as "predef",
Yann Collet23f05cc2016-07-04 16:13:11 +0200829a pre-defined distribution is used for FSE compression.
830
831Here is its definition. It uses an accuracy of 6 bits (64 states).
832```
833short matchLengths_defaultDistribution[53] =
834 { 1, 4, 3, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1,
835 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
836 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,-1,-1,
837 -1,-1,-1,-1,-1 };
838```
839
840##### Offset codes
841
842Offset codes are values ranging from `0` to `N`,
843with `N` being limited by maximum backreference distance.
844
Yann Colletcd25a912016-07-05 11:50:37 +0200845A decoder is free to limit its maximum `N` supported.
846Recommendation is to support at least up to `22`.
Yann Collet23f05cc2016-07-04 16:13:11 +0200847For information, at the time of this writing.
848the reference decoder supports a maximum `N` value of `28` in 64-bits mode.
849
850An offset code is also the nb of additional bits to read,
851and can be translated into an `OFValue` using the following formulae :
852
853```
854OFValue = (1 << offsetCode) + readNBits(offsetCode);
855if (OFValue > 3) offset = OFValue - 3;
856```
857
858OFValue from 1 to 3 are special : they define "repeat codes",
859which means one of the previous offsets will be repeated.
860They are sorted in recency order, with 1 meaning the most recent one.
Yann Colletcd25a912016-07-05 11:50:37 +0200861See [Repeat offsets](#repeat-offsets) paragraph.
Yann Collet23f05cc2016-07-04 16:13:11 +0200862
863__Default distribution__
864
Yann Colletcd25a912016-07-05 11:50:37 +0200865When "compression mode" is defined as "predef",
Yann Collet23f05cc2016-07-04 16:13:11 +0200866a pre-defined distribution is used for FSE compression.
867
868Here is its definition. It uses an accuracy of 5 bits (32 states),
Yann Colletcd25a912016-07-05 11:50:37 +0200869and supports a maximum `N` of 28, allowing offset values up to 536,870,908 .
Yann Collet23f05cc2016-07-04 16:13:11 +0200870
871If any sequence in the compressed block requires an offset larger than this,
872it's not possible to use the default distribution to represent it.
873
874```
875short offsetCodes_defaultDistribution[53] =
876 { 1, 1, 1, 1, 1, 1, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1,
877 1, 1, 1, 1, 1, 1, 1, 1,-1,-1,-1,-1,-1 };
878```
879
880#### Distribution tables
881
882Following the header, up to 3 distribution tables can be described.
Yann Collet10b9c132016-07-24 01:21:53 +0200883When present, they are in this order :
Yann Collet23f05cc2016-07-04 16:13:11 +0200884- Literal lengthes
885- Offsets
886- Match Lengthes
887
Yann Collet10b9c132016-07-24 01:21:53 +0200888The content to decode depends on their respective encoding mode :
Yann Collet23f05cc2016-07-04 16:13:11 +0200889- Predef : no content. Use pre-defined distribution table.
890- RLE : 1 byte. This is the only code to use across the whole compressed block.
891- FSE : A distribution table is present.
Yann Collet10b9c132016-07-24 01:21:53 +0200892- Repeat mode : no content. Re-use distribution from previous compressed block.
Yann Collet23f05cc2016-07-04 16:13:11 +0200893
894##### FSE distribution table : condensed format
895
896An FSE distribution table describes the probabilities of all symbols
897from `0` to the last present one (included)
Yann Collet9ca73362016-07-05 10:53:38 +0200898on a normalized scale of `1 << AccuracyLog` .
Yann Collet23f05cc2016-07-04 16:13:11 +0200899
900It's a bitstream which is read forward, in little-endian fashion.
901It's not necessary to know its exact size,
902since it will be discovered and reported by the decoding process.
903
904The bitstream starts by reporting on which scale it operates.
905`AccuracyLog = low4bits + 5;`
Yann Collet9d6e9492016-07-22 19:32:07 +0200906Note that maximum `AccuracyLog` for literal and match lengthes is `9`,
907and for offsets it is `8`. Higher values are considered errors.
Yann Collet23f05cc2016-07-04 16:13:11 +0200908
909Then follow each symbol value, from `0` to last present one.
910The nb of bits used by each field is variable.
911It depends on :
912
913- Remaining probabilities + 1 :
914 __example__ :
915 Presuming an AccuracyLog of 8,
916 and presuming 100 probabilities points have already been distributed,
Yann Colletcd25a912016-07-05 11:50:37 +0200917 the decoder may read any value from `0` to `255 - 100 + 1 == 156` (included).
Yann Collet23f05cc2016-07-04 16:13:11 +0200918 Therefore, it must read `log2sup(156) == 8` bits.
919
920- Value decoded : small values use 1 less bit :
921 __example__ :
922 Presuming values from 0 to 156 (included) are possible,
923 255-156 = 99 values are remaining in an 8-bits field.
924 They are used this way :
925 first 99 values (hence from 0 to 98) use only 7 bits,
926 values from 99 to 156 use 8 bits.
927 This is achieved through this scheme :
928
929 | Value read | Value decoded | nb Bits used |
930 | ---------- | ------------- | ------------ |
931 | 0 - 98 | 0 - 98 | 7 |
932 | 99 - 127 | 99 - 127 | 8 |
933 | 128 - 226 | 0 - 98 | 7 |
934 | 227 - 255 | 128 - 156 | 8 |
935
936Symbols probabilities are read one by one, in order.
937
938Probability is obtained from Value decoded by following formulae :
939`Proba = value - 1;`
940
941It means value `0` becomes negative probability `-1`.
942`-1` is a special probability, which means `less than 1`.
Yann Colletc40ba712016-07-08 15:39:02 +0200943Its effect on distribution table is described in [next paragraph].
Yann Collet23f05cc2016-07-04 16:13:11 +0200944For the purpose of calculating cumulated distribution, it counts as one.
945
Yann Colletc40ba712016-07-08 15:39:02 +0200946[next paragraph]:#fse-decoding--from-normalized-distribution-to-decoding-tables
947
Yann Collet23f05cc2016-07-04 16:13:11 +0200948When a symbol has a probability of `zero`,
949it is followed by a 2-bits repeat flag.
950This repeat flag tells how many probabilities of zeroes follow the current one.
951It provides a number ranging from 0 to 3.
952If it is a 3, another 2-bits repeat flag follows, and so on.
953
Yann Collet9ca73362016-07-05 10:53:38 +0200954When last symbol reaches cumulated total of `1 << AccuracyLog`,
Yann Collet23f05cc2016-07-04 16:13:11 +0200955decoding is complete.
Yann Collet9ca73362016-07-05 10:53:38 +0200956If the last symbol makes cumulated total go above `1 << AccuracyLog`,
Yann Collet23f05cc2016-07-04 16:13:11 +0200957distribution is considered corrupted.
958
Yann Collet10b9c132016-07-24 01:21:53 +0200959Then the decoder can tell how many bytes were used in this process,
960and how many symbols are present.
961The bitstream consumes a round number of bytes.
962Any remaining bit within the last byte is just unused.
963
Yann Collet23f05cc2016-07-04 16:13:11 +0200964##### FSE decoding : from normalized distribution to decoding tables
965
Yann Collet9ca73362016-07-05 10:53:38 +0200966The distribution of normalized probabilities is enough
967to create a unique decoding table.
968
969It follows the following build rule :
970
971The table has a size of `tableSize = 1 << AccuracyLog;`.
972Each cell describes the symbol decoded,
973and instructions to get the next state.
974
975Symbols are scanned in their natural order for `less than 1` probabilities.
976Symbols with this probability are being attributed a single cell,
977starting from the end of the table.
978These symbols define a full state reset, reading `AccuracyLog` bits.
979
980All remaining symbols are sorted in their natural order.
981Starting from symbol `0` and table position `0`,
982each symbol gets attributed as many cells as its probability.
983Cell allocation is spreaded, not linear :
984each successor position follow this rule :
985
Yann Colletcd25a912016-07-05 11:50:37 +0200986```
987position += (tableSize>>1) + (tableSize>>3) + 3;
988position &= tableSize-1;
989```
Yann Collet9ca73362016-07-05 10:53:38 +0200990
991A position is skipped if already occupied,
992typically by a "less than 1" probability symbol.
993
994The result is a list of state values.
995Each state will decode the current symbol.
996
997To get the Number of bits and baseline required for next state,
998it's first necessary to sort all states in their natural order.
Yann Colletcd25a912016-07-05 11:50:37 +0200999The lower states will need 1 more bit than higher ones.
Yann Collet9ca73362016-07-05 10:53:38 +02001000
1001__Example__ :
1002Presuming a symbol has a probability of 5.
Yann Colletcd25a912016-07-05 11:50:37 +02001003It receives 5 state values. States are sorted in natural order.
Yann Collet9ca73362016-07-05 10:53:38 +02001004
1005Next power of 2 is 8.
1006Space of probabilities is divided into 8 equal parts.
1007Presuming the AccuracyLog is 7, it defines 128 states.
1008Divided by 8, each share is 16 large.
1009
1010In order to reach 8, 8-5=3 lowest states will count "double",
1011taking shares twice larger,
1012requiring one more bit in the process.
1013
1014Numbering starts from higher states using less bits.
1015
1016| state order | 0 | 1 | 2 | 3 | 4 |
1017| ----------- | ----- | ----- | ------ | ---- | ----- |
1018| width | 32 | 32 | 32 | 16 | 16 |
1019| nb Bits | 5 | 5 | 5 | 4 | 4 |
1020| range nb | 2 | 4 | 6 | 0 | 1 |
1021| baseline | 32 | 64 | 96 | 0 | 16 |
1022| range | 32-63 | 64-95 | 96-127 | 0-15 | 16-31 |
1023
1024Next state is determined from current state
1025by reading the required number of bits, and adding the specified baseline.
Yann Collet23f05cc2016-07-04 16:13:11 +02001026
1027
1028#### Bitstream
Yann Collet00d44ab2016-07-04 01:29:47 +02001029
Yann Collet9ca73362016-07-05 10:53:38 +02001030All sequences are stored in a single bitstream, read _backward_.
1031It is therefore necessary to know the bitstream size,
1032which is deducted from compressed block size.
1033
Yann Colletc40ba712016-07-08 15:39:02 +02001034The last useful bit of the stream is followed by an end-bit-flag.
Yann Colletcd25a912016-07-05 11:50:37 +02001035Highest bit of last byte is this flag.
Yann Collet9ca73362016-07-05 10:53:38 +02001036It does not belong to the useful part of the bitstream.
1037Therefore, last byte has 0-7 useful bits.
1038Note that it also means that last byte cannot be `0`.
1039
1040##### Starting states
1041
1042The bitstream starts with initial state values,
1043each using the required number of bits in their respective _accuracy_,
1044decoded previously from their normalized distribution.
1045
1046It starts by `Literal Length State`,
1047followed by `Offset State`,
1048and finally `Match Length State`.
1049
1050Reminder : always keep in mind that all values are read _backward_.
1051
1052##### Decoding a sequence
1053
1054A state gives a code.
1055A code provides a baseline and number of bits to add.
1056See [Symbol Decoding] section for details on each symbol.
1057
1058Decoding starts by reading the nb of bits required to decode offset.
1059It then does the same for match length,
1060and then for literal length.
1061
Yann Colletc40ba712016-07-08 15:39:02 +02001062Offset / matchLength / litLength define a sequence.
1063It starts by inserting the number of literals defined by `litLength`,
1064then continue by copying `matchLength` bytes from `currentPos - offset`.
Yann Collet9ca73362016-07-05 10:53:38 +02001065
1066The next operation is to update states.
1067Using rules pre-calculated in the decoding tables,
1068`Literal Length State` is updated,
1069followed by `Match Length State`,
1070and then `Offset State`.
1071
1072This operation will be repeated `NbSeqs` times.
1073At the end, the bitstream shall be entirely consumed,
1074otherwise bitstream is considered corrupted.
1075
1076[Symbol Decoding]:#symbols-decoding
1077
1078##### Repeat offsets
1079
1080As seen in [Offset Codes], the first 3 values define a repeated offset.
1081They are sorted in recency order, with 1 meaning "most recent one".
1082
1083There is an exception though, when current sequence's literal length is `0`.
Yann Collet917fe182016-07-31 04:01:57 +02001084In which case, repcodes are "pushed by one",
1085so 1 becomes 2, 2 becomes 3,
1086and 3 becomes "offset_1 - 1_byte".
Yann Collet9ca73362016-07-05 10:53:38 +02001087
Yann Collet917fe182016-07-31 04:01:57 +02001088On first block, offset history is populated by the following values : 1, 4 and 8 (in order).
Yann Collet9ca73362016-07-05 10:53:38 +02001089
1090Then each block receives its start value from previous compressed block.
1091Note that non-compressed blocks are skipped,
1092they do not contribute to offset history.
1093
1094[Offset Codes]: #offset-codes
1095
1096###### Offset updates rules
1097
Yann Collet917fe182016-07-31 04:01:57 +02001098New offset take the lead in offset history,
1099up to its previous place if it was already present.
Yann Collet9ca73362016-07-05 10:53:38 +02001100
Yann Collet917fe182016-07-31 04:01:57 +02001101It means that when repeat offset 1 (most recent) is used, history is unmodified.
1102When repeat offset 2 is used, it's swapped with offset 1.
Yann Collet00d44ab2016-07-04 01:29:47 +02001103
Yann Collet2fa99042016-07-01 20:55:28 +02001104
Yann Colletbd106072016-07-08 19:16:57 +02001105Dictionary format
1106-----------------
1107
1108`zstd` is compatible with "pure content" dictionaries, free of any format restriction.
1109But dictionaries created by `zstd --train` follow a format, described here.
1110
1111__Pre-requisites__ : a dictionary has a known length,
1112 defined either by a buffer limit, or a file size.
1113
1114| Header | DictID | Stats | Content |
1115| ------ | ------ | ----- | ------- |
1116
inikep2fc37522016-07-25 12:47:02 +02001117__Header__ : 4 bytes ID, value 0xEC30A437, Little-Endian format
Yann Colletbd106072016-07-08 19:16:57 +02001118
inikep2fc37522016-07-25 12:47:02 +02001119__Dict_ID__ : 4 bytes, stored in Little-Endian format.
Yann Colletbd106072016-07-08 19:16:57 +02001120 DictID can be any value, except 0 (which means no DictID).
Yann Collet722e14b2016-07-08 19:22:16 +02001121 It's used by decoders to check if they use the correct dictionary.
Yann Colletf6ff53c2016-07-15 17:03:38 +02001122 _Reserved ranges :_
1123 If the frame is going to be distributed in a private environment,
1124 any dictionary ID can be used.
1125 However, for public distribution of compressed frames,
1126 some ranges are reserved for future use :
Yann Collet6cacd342016-07-15 17:58:13 +02001127
1128 - low range : 1 - 32767 : reserved
1129 - high range : >= (2^31) : reserved
Yann Colletbd106072016-07-08 19:16:57 +02001130
1131__Stats__ : Entropy tables, following the same format as a [compressed blocks].
1132 They are stored in following order :
1133 Huffman tables for literals, FSE table for offset,
Yann Collet722e14b2016-07-08 19:22:16 +02001134 FSE table for matchLenth, and FSE table for litLength.
1135 It's finally followed by 3 offset values, populating recent offsets,
inikep2fc37522016-07-25 12:47:02 +02001136 stored in order, 4-bytes little-endian each, for a total of 12 bytes.
Yann Colletbd106072016-07-08 19:16:57 +02001137
1138__Content__ : Where the actual dictionary content is.
Yann Collet722e14b2016-07-08 19:22:16 +02001139 Content size depends on Dictionary size.
Yann Colletbd106072016-07-08 19:16:57 +02001140
inikepf9c3cce2016-07-25 11:04:56 +02001141[compressed blocks]: #the-format-of-compressed_block
Yann Colletbd106072016-07-08 19:16:57 +02001142
Yann Collet2fa99042016-07-01 20:55:28 +02001143
1144Version changes
1145---------------
Yann Collet6fa05a22016-07-20 14:58:49 +02001146- 0.2.0 : numerous format adjustments for zstd v0.8
inikep586a0552016-08-03 16:16:38 +02001147- 0.1.2 : limit Huffman tree depth to 11 bits
Yann Collete557fd52016-07-17 16:21:37 +02001148- 0.1.1 : reserved dictID ranges
1149- 0.1.0 : initial release