Next: , Up: (dir)

Lzlib Manual

This manual is for Lzlib (version 1.6, 27 August 2014).


Copyright © 2009-2014 Antonio Diaz Diaz.

This manual is free documentation: you have unlimited permission to copy, distribute and modify it.


Next: , Previous: Top, Up: Top

1 Introduction

Lzlib is a data compression library providing in-memory LZMA compression and decompression functions, including integrity checking of the decompressed data. The compressed data format used by the library is the lzip format. Lzlib is written in C.

The lzip file format is designed for long-term data archiving, taking into account both data integrity and decoder availability:

A nice feature of the lzip format is that a corrupt byte is easier to repair the nearer it is from the beginning of the file. Therefore, with the help of lziprecover, losing an entire archive just because of a corrupt byte near the beginning is a thing of the past.

The functions and variables forming the interface of the compression library are declared in the file 'lzlib.h'. Usage examples of the library are given in the files 'main.c' and 'bbexample.c' from the source distribution.

Compression/decompression is done by repeatedly calling a couple of read/write functions until all the data has been processed by the library. This interface is safer and less error prone than the traditional zlib interface.

Compression/decompression is done when the read function is called. This means the value returned by the position functions will not be updated until some data is read, even if you write a lot of data. If you want the data to be compressed in advance, just call the read function with a size equal to 0.

Lzlib will correctly decompress a data stream which is the concatenation of two or more compressed data streams. The result is the concatenation of the corresponding decompressed data streams. Integrity testing of concatenated compressed data streams is also supported.

All the library functions are thread safe. The library does not install any signal handler. The decoder checks the consistency of the compressed data, so the library should never crash even in case of corrupted input.

There is no such thing as a "LZMA algorithm"; it is more like a "LZMA coding scheme". For example, the option '-0' of lzip uses the scheme in almost the simplest way possible; issuing the longest match it can find, or a literal byte if it can't find a match. Inversely, a much more elaborated way of finding coding sequences of minimum price than the one currently used by lzip could be developed, and the resulting sequence could also be coded using the LZMA coding scheme.

Lzip currently implements two variants of the LZMA algorithm; fast (used by option -0) and normal (used by all other compression levels). Lzlib just implements the "normal" variant.

The high compression of LZMA comes from combining two basic, well-proven compression ideas: sliding dictionaries (LZ77/78) and markov models (the thing used by every compression algorithm that uses a range encoder or similar order-0 entropy coder as its last stage) with segregation of contexts according to what the bits are used for.

The ideas embodied in lzlib are due to (at least) the following people: Abraham Lempel and Jacob Ziv (for the LZ algorithm), Andrey Markov (for the definition of Markov chains), G.N.N. Martin (for the definition of range encoding), Igor Pavlov (for putting all the above together in LZMA), and Julian Seward (for bzip2's CLI).


Next: , Previous: Introduction, Up: Top

2 Library version

-- Function: const char * LZ_version ( void )

Returns the library version as a string.

-- Constant: const char * LZ_version_string

This constant is defined in the header file 'lzlib.h'.

The application should compare LZ_version and LZ_version_string for consistency. If the first character differs, the library code actually used may be incompatible with the 'lzlib.h' header file used by the application.

     if( LZ_version()[0] != LZ_version_string[0] )
       error( "bad library version" );


Next: , Previous: Library version, Up: Top

3 Buffering

Lzlib internal functions need access to a memory chunk at least as large as the dictionary size (sliding window). For efficiency reasons, the input buffer for compression is twice as large as the dictionary size. Finally, for safety reasons, lzlib uses two more internal buffers.

These are the four buffers used by lzlib, and their guaranteed minimum sizes:


Next: , Previous: Buffering, Up: Top

4 Parameter limits

These functions provide minimum and maximum values for some parameters. Current values are shown in square brackets.

-- Function: int LZ_min_dictionary_bits ( void )

Returns the base 2 logarithm of the smallest valid dictionary size [12].

-- Function: int LZ_min_dictionary_size ( void )

Returns the smallest valid dictionary size [4 KiB].

-- Function: int LZ_max_dictionary_bits ( void )

Returns the base 2 logarithm of the largest valid dictionary size [29].

-- Function: int LZ_max_dictionary_size ( void )

Returns the largest valid dictionary size [512 MiB].

-- Function: int LZ_min_match_len_limit ( void )

Returns the smallest valid match length limit [5].

-- Function: int LZ_max_match_len_limit ( void )

Returns the largest valid match length limit [273].


Next: , Previous: Parameter limits, Up: Top

5 Compression functions

These are the functions used to compress data. In case of error, all of them return -1 or 0, for signed and unsigned return values respectively, except 'LZ_compress_open' whose return value must be verified by calling 'LZ_compress_errno' before using it.

-- Function: struct LZ_Encoder * LZ_compress_open ( const int dictionary_size, const int match_len_limit, const unsigned long long member_size )

Initializes the internal stream state for compression and returns a pointer that can only be used as the encoder argument for the other LZ_compress functions, or a null pointer if the encoder could not be allocated.

The returned pointer must be verified by calling 'LZ_compress_errno' before using it. If 'LZ_compress_errno' does not return 'LZ_ok', the returned pointer must not be used and should be freed with 'LZ_compress_close' to avoid memory leaks.

dictionary_size sets the dictionary size to be used, in bytes. Valid values range from 4 KiB to 512 MiB. Note that dictionary sizes are quantized. If the specified size does not match one of the valid sizes, it will be rounded upwards by adding up to (dictionary_size / 16) to it.

match_len_limit sets the match length limit in bytes. Valid values range from 5 to 273. Larger values usually give better compression ratios but longer compression times.

member_size sets the member size limit in bytes. Minimum member size limit is 100 kB. Small member size may degrade compression ratio, so use it only when needed. To produce a single-member data stream, give member_size a value larger than the amount of data to be produced, for example INT64_MAX.

-- Function: int LZ_compress_close ( struct LZ_Encoder * const encoder )

Frees all dynamically allocated data structures for this stream. This function discards any unprocessed input and does not flush any pending output. After a call to 'LZ_compress_close', encoder can no more be used as an argument to any LZ_compress function.

-- Function: int LZ_compress_finish ( struct LZ_Encoder * const encoder )

Use this function to tell 'lzlib' that all the data for this member has already been written (with the 'LZ_compress_write' function). After all the produced compressed data has been read with 'LZ_compress_read' and 'LZ_compress_member_finished' returns 1, a new member can be started with 'LZ_compress_restart_member'.

-- Function: int LZ_compress_restart_member ( struct LZ_Encoder * const encoder, const unsigned long long member_size )

Use this function to start a new member, in a multi-member data stream. Call this function only after 'LZ_compress_member_finished' indicates that the current member has been fully read (with the 'LZ_compress_read' function).

-- Function: int LZ_compress_sync_flush ( struct LZ_Encoder * const encoder )

Use this function to make available to 'LZ_compress_read' all the data already written with the 'LZ_compress_write' function. First call 'LZ_compress_read' until it returns 0. Then call 'LZ_compress_sync_flush'. Finally, call 'LZ_compress_read' again to read the remaining data.

Repeated use of 'LZ_compress_sync_flush' may degrade compression ratio, so use it only when needed.

-- Function: int LZ_compress_read ( struct LZ_Encoder * const encoder, uint8_t * const buffer, const int size )

The 'LZ_compress_read' function reads up to size bytes from the stream pointed to by encoder, storing the results in buffer.

The return value is the number of bytes actually read. This might be less than size; for example, if there aren't that many bytes left in the stream or if more bytes have to be yet written with the 'LZ_compress_write' function. Note that reading less than size bytes is not an error.

-- Function: int LZ_compress_write ( struct LZ_Encoder * const encoder, uint8_t * const buffer, const int size )

The 'LZ_compress_write' function writes up to size bytes from buffer to the stream pointed to by encoder.

The return value is the number of bytes actually written. This might be less than size. Note that writing less than size bytes is not an error.

-- Function: int LZ_compress_write_size ( struct LZ_Encoder * const encoder )

The 'LZ_compress_write_size' function returns the maximum number of bytes that can be immediately written through the 'LZ_compress_write' function.

It is guaranteed that an immediate call to 'LZ_compress_write' will accept a size up to the returned number of bytes.

-- Function: enum LZ_Errno LZ_compress_errno ( struct LZ_Encoder * const encoder )

Returns the current error code for encoder (see Error codes).

-- Function: int LZ_compress_finished ( struct LZ_Encoder * const encoder )

Returns 1 if all the data has been read and 'LZ_compress_close' can be safely called. Otherwise it returns 0.

-- Function: int LZ_compress_member_finished ( struct LZ_Encoder * const encoder )

Returns 1 if the current member, in a multi-member data stream, has been fully read and 'LZ_compress_restart_member' can be safely called. Otherwise it returns 0.

-- Function: unsigned long long LZ_compress_data_position ( struct LZ_Encoder * const encoder )

Returns the number of input bytes already compressed in the current member.

-- Function: unsigned long long LZ_compress_member_position ( struct LZ_Encoder * const encoder )

Returns the number of compressed bytes already produced, but perhaps not yet read, in the current member.

-- Function: unsigned long long LZ_compress_total_in_size ( struct LZ_Encoder * const encoder )

Returns the total number of input bytes already compressed.

-- Function: unsigned long long LZ_compress_total_out_size ( struct LZ_Encoder * const encoder )

Returns the total number of compressed bytes already produced, but perhaps not yet read.


Next: , Previous: Compression functions, Up: Top

6 Decompression functions

These are the functions used to decompress data. In case of error, all of them return -1 or 0, for signed and unsigned return values respectively, except 'LZ_decompress_open' whose return value must be verified by calling 'LZ_decompress_errno' before using it.

-- Function: struct LZ_Decoder * LZ_decompress_open ( void )

Initializes the internal stream state for decompression and returns a pointer that can only be used as the decoder argument for the other LZ_decompress functions, or a null pointer if the decoder could not be allocated.

The returned pointer must be verified by calling 'LZ_decompress_errno' before using it. If 'LZ_decompress_errno' does not return 'LZ_ok', the returned pointer must not be used and should be freed with 'LZ_decompress_close' to avoid memory leaks.

-- Function: int LZ_decompress_close ( struct LZ_Decoder * const decoder )

Frees all dynamically allocated data structures for this stream. This function discards any unprocessed input and does not flush any pending output. After a call to 'LZ_decompress_close', decoder can no more be used as an argument to any LZ_decompress function.

-- Function: int LZ_decompress_finish ( struct LZ_Decoder * const decoder )

Use this function to tell 'lzlib' that all the data for this stream has already been written (with the 'LZ_decompress_write' function).

-- Function: int LZ_decompress_reset ( struct LZ_Decoder * const decoder )

Resets the internal state of decoder as it was just after opening it with the 'LZ_decompress_open' function. Data stored in the internal buffers is discarded. Position counters are set to 0.

-- Function: int LZ_decompress_sync_to_member ( struct LZ_Decoder * const decoder )

Resets the error state of decoder and enters a search state that lasts until a new member header (or the end of the stream) is found. After a successful call to 'LZ_decompress_sync_to_member', data written with 'LZ_decompress_write' will be consumed and 'LZ_decompress_read' will return 0 until a header is found.

This function is useful to discard any data preceding the first member, or to discard the rest of the current member, for example in case of a data error. If the decoder is already at the beginning of a member, this function does nothing.

-- Function: int LZ_decompress_read ( struct LZ_Decoder * const decoder, uint8_t * const buffer, const int size )

The 'LZ_decompress_read' function reads up to size bytes from the stream pointed to by decoder, storing the results in buffer.

The return value is the number of bytes actually read. This might be less than size; for example, if there aren't that many bytes left in the stream or if more bytes have to be yet written with the 'LZ_decompress_write' function. Note that reading less than size bytes is not an error.

-- Function: int LZ_decompress_write ( struct LZ_Decoder * const decoder, uint8_t * const buffer, const int size )

The 'LZ_decompress_write' function writes up to size bytes from buffer to the stream pointed to by decoder.

The return value is the number of bytes actually written. This might be less than size. Note that writing less than size bytes is not an error.

-- Function: int LZ_decompress_write_size ( struct LZ_Decoder * const decoder )

The 'LZ_decompress_write_size' function returns the maximum number of bytes that can be immediately written through the 'LZ_decompress_write' function.

It is guaranteed that an immediate call to 'LZ_decompress_write' will accept a size up to the returned number of bytes.

-- Function: enum LZ_Errno LZ_decompress_errno ( struct LZ_Decoder * const decoder )

Returns the current error code for decoder (see Error codes).

-- Function: int LZ_decompress_finished ( struct LZ_Decoder * const decoder )

Returns 1 if all the data has been read and 'LZ_decompress_close' can be safely called. Otherwise it returns 0.

-- Function: int LZ_decompress_member_finished ( struct LZ_Decoder * const decoder )

Returns 1 if the previous call to 'LZ_decompress_read' finished reading the current member, indicating that final values for member are available through 'LZ_decompress_data_crc', 'LZ_decompress_data_position', and 'LZ_decompress_member_position'. Otherwise it returns 0.

-- Function: int LZ_decompress_member_version ( struct LZ_Decoder * const decoder )

Returns the version of current member from member header.

-- Function: int LZ_decompress_dictionary_size ( struct LZ_Decoder * const decoder )

Returns the dictionary size of current member from member header.

-- Function: unsigned LZ_decompress_data_crc ( struct LZ_Decoder * const decoder )

Returns the 32 bit Cyclic Redundancy Check of the data decompressed from the current member. The returned value is valid only when 'LZ_decompress_member_finished' returns 1.

-- Function: unsigned long long LZ_decompress_data_position ( struct LZ_Decoder * const decoder )

Returns the number of decompressed bytes already produced, but perhaps not yet read, in the current member.

-- Function: unsigned long long LZ_decompress_member_position ( struct LZ_Decoder * const decoder )

Returns the number of input bytes already decompressed in the current member.

-- Function: unsigned long long LZ_decompress_total_in_size ( struct LZ_Decoder * const decoder )

Returns the total number of input bytes already decompressed.

-- Function: unsigned long long LZ_decompress_total_out_size ( struct LZ_Decoder * const decoder )

Returns the total number of decompressed bytes already produced, but perhaps not yet read.


Next: , Previous: Decompression functions, Up: Top

7 Error codes

Most library functions return -1 to indicate that they have failed. But this return value only tells you that an error has occurred. To find out what kind of error it was, you need to verify the error code by calling 'LZ_(de)compress_errno'.

Library functions do not change the value returned by 'LZ_(de)compress_errno' when they succeed; thus, the value returned by 'LZ_(de)compress_errno' after a successful call is not necessarily LZ_ok, and you should not use 'LZ_(de)compress_errno' to determine whether a call failed. If the call failed, then you can examine 'LZ_(de)compress_errno'.

The error codes are defined in the header file 'lzlib.h'.

-- Constant: enum LZ_Errno LZ_ok

The value of this constant is 0 and is used to indicate that there is no error.

-- Constant: enum LZ_Errno LZ_bad_argument

At least one of the arguments passed to the library function was invalid.

-- Constant: enum LZ_Errno LZ_mem_error

No memory available. The system cannot allocate more virtual memory because its capacity is full.

-- Constant: enum LZ_Errno LZ_sequence_error

A library function was called in the wrong order. For example 'LZ_compress_restart_member' was called before 'LZ_compress_member_finished' indicates that the current member is finished.

-- Constant: enum LZ_Errno LZ_header_error

Reading of member header failed. If this happens at the end of the data stream it may indicate trailing garbage.

-- Constant: enum LZ_Errno LZ_unexpected_eof

The end of the data stream was reached in the middle of a member.

-- Constant: enum LZ_Errno LZ_data_error

The data stream is corrupt.

-- Constant: enum LZ_Errno LZ_library_error

A bug was detected in the library. Please, report it (see Problems).


Next: , Previous: Error codes, Up: Top

8 Error messages

-- Function: const char * LZ_strerror ( const enum LZ_Errno lz_errno )

Returns the standard error message for a given error code. The messages are fairly short; there are no multi-line messages or embedded newlines. This function makes it easy for your program to report informative error messages about the failure of a library call.

The value of lz_errno normally comes from a call to 'LZ_(de)compress_errno'.


Next: , Previous: Error messages, Up: Top

9 Data format

Perfection is reached, not when there is no longer anything to add, but when there is no longer anything to take away.
-- Antoine de Saint-Exupery


In the diagram below, a box like this:
+---+
|   | <-- the vertical bars might be missing
+---+

represents one byte; a box like this:

+==============+
|              |
+==============+

represents a variable number of bytes.


A lzip data stream consists of a series of "members" (compressed data sets). The members simply appear one after another in the data stream, with no additional information before, between, or after them.

Each member has the following structure:

+--+--+--+--+----+----+=============+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| ID string | VN | DS | Lzma stream | CRC32 |   Data size   |  Member size  |
+--+--+--+--+----+----+=============+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+

All multibyte values are stored in little endian order.

'ID string'
A four byte string, identifying the lzip format, with the value "LZIP" (0x4C, 0x5A, 0x49, 0x50).
'VN (version number, 1 byte)'
Just in case something needs to be modified in the future. 1 for now.
'DS (coded dictionary size, 1 byte)'
Lzip divides the distance between any two powers of 2 into 8 equally spaced intervals, named "wedges". The dictionary size is calculated by taking a power of 2 (the base size) and substracting from it a number of wedges between 0 and 7. The size of a wedge is (base_size / 16).
Bits 4-0 contain the base 2 logarithm of the base size (12 to 29).
Bits 7-5 contain the number of wedges (0 to 7) to substract from the base size to obtain the dictionary size.
Example: 0xD3 = 2^19 - 6 * 2^15 = 512 KiB - 6 * 32 KiB = 320 KiB
Valid values for dictionary size range from 4 KiB to 512 MiB.
'Lzma stream'
The lzma stream, finished by an end of stream marker. Uses default values for encoder properties. See the lzip manual for a full description.
Lzip only uses the LZMA marker '2' ("End Of Stream" marker). Lzlib also uses the LZMA marker '3' ("Sync Flush" marker).
'CRC32 (4 bytes)'
CRC of the uncompressed original data.
'Data size (8 bytes)'
Size of the uncompressed original data.
'Member size (8 bytes)'
Total size of the member, including header and trailer. This field acts as a distributed index, allows the verification of stream integrity, and facilitates safe recovery of undamaged members from multi-member files.


Next: , Previous: Data format, Up: Top

10 A small tutorial with examples

This chapter shows the order in which the library functions should be called depending on what kind of data stream you want to compress or decompress. See the file 'bbexample.c' in the source distribution for an example of how buffer-to-buffer compression/decompression can be implemented using lzlib.

Note that lzlib's interface is symmetrical. That is, the code for normal compression and decompression is identical except because one calls LZ_compress* functions while the other calls LZ_decompress* functions.


Example 1: Normal compression (member_size > total output).
     1) LZ_compress_open
     2) LZ_compress_write
     3) LZ_compress_read
     4) go back to step 2 until all input data has been written
     5) LZ_compress_finish
     6) LZ_compress_read
     7) go back to step 6 until LZ_compress_finished returns 1
     8) LZ_compress_close

Example 2: Normal compression using LZ_compress_write_size.
     1) LZ_compress_open
     2) go to step 5 if LZ_compress_write_size returns 0
     3) LZ_compress_write
     4) if no more data to write, call LZ_compress_finish
     5) LZ_compress_read
     6) go back to step 2 until LZ_compress_finished returns 1
     7) LZ_compress_close

Example 3: Decompression.
     1) LZ_decompress_open
     2) LZ_decompress_write
     3) LZ_decompress_read
     4) go back to step 2 until all input data has been written
     5) LZ_decompress_finish
     6) LZ_decompress_read
     7) go back to step 6 until LZ_decompress_finished returns 1
     8) LZ_decompress_close

Example 4: Decompression using LZ_decompress_write_size.
     1) LZ_decompress_open
     2) go to step 5 if LZ_decompress_write_size returns 0
     3) LZ_decompress_write
     4) if no more data to write, call LZ_decompress_finish
     5) LZ_decompress_read
     5a) optionally, if LZ_decompress_member_finished returns 1, read
         final values for member with LZ_decompress_data_crc, etc.
     6) go back to step 2 until LZ_decompress_finished returns 1
     7) LZ_decompress_close

Example 5: Multi-member compression (member_size < total output).
      1) LZ_compress_open
      2) go to step 5 if LZ_compress_write_size returns 0
      3) LZ_compress_write
      4) if no more data to write, call LZ_compress_finish
      5) LZ_compress_read
      6) go back to step 2 until LZ_compress_member_finished returns 1
      7) go to step 10 if LZ_compress_finished() returns 1
      8) LZ_compress_restart_member
      9) go back to step 2
     10) LZ_compress_close

Example 6: Multi-member compression (user-restarted members).
      1) LZ_compress_open
      2) LZ_compress_write
      3) LZ_compress_read
      4) go back to step 2 until member termination is desired
      5) LZ_compress_finish
      6) LZ_compress_read
      7) go back to step 6 until LZ_compress_member_finished returns 1
      8) verify that LZ_compress_finished returns 1
      9) go to step 12 if all input data has been written
     10) LZ_compress_restart_member
     11) go back to step 2
     12) LZ_compress_close

Example 7: Decompression with automatic removal of leading garbage.
     1) LZ_decompress_open
     2) LZ_decompress_sync_to_member
     3) go to step 6 if LZ_decompress_write_size returns 0
     4) LZ_decompress_write
     5) if no more data to write, call LZ_decompress_finish
     6) LZ_decompress_read
     7) go back to step 3 until LZ_decompress_finished returns 1
     8) LZ_decompress_close

Example 8: Streamed decompression with automatic resynchronization to next member in case of data error.
     1) LZ_decompress_open
     2) go to step 5 if LZ_decompress_write_size returns 0
     3) LZ_decompress_write
     4) if no more data to write, call LZ_decompress_finish
     5) if LZ_decompress_read produces LZ_header_error or LZ_data_error,
        call LZ_decompress_sync_to_member
     6) go back to step 2 until LZ_decompress_finished returns 1
     7) LZ_decompress_close


Next: , Previous: Examples, Up: Top

11 Reporting bugs

There are probably bugs in Lzlib. There are certainly errors and omissions in this manual. If you report them, they will get fixed. If you don't, no one will ever know about them and they will remain unfixed for all eternity, if not longer.

If you find a bug in Lzlib, please send electronic mail to lzip-bug@nongnu.org. Include the version number, which you can find by running 'minilzip --version' or in 'LZ_version_string' from 'lzlib.h'.


Previous: Problems, Up: Top

Concept index