1 <?xml version="1.0"?> <!-- -*- sgml -*- -->
2 <!DOCTYPE book PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN"
3 "http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"[
5 <!-- various strings, dates etc. common to all docs -->
6 <!ENTITY % common-ents SYSTEM "entities.xml"> %common-ents;
9 <book lang="en" id="userman" xreflabel="bzip2 Manual">
12 <title>bzip2 and libbzip2, version 1.0.5</title>
13 <subtitle>A program and library for data compression</subtitle>
15 <year>&bz-lifespan;</year>
16 <holder>Julian Seward</holder>
18 <releaseinfo>Version &bz-version; of &bz-date;</releaseinfo>
22 <firstname>Julian</firstname>
23 <surname>Seward</surname>
25 <orgname>&bz-url;</orgname>
32 <para>This program, <computeroutput>bzip2</computeroutput>, the
33 associated library <computeroutput>libbzip2</computeroutput>, and
34 all documentation, are copyright © &bz-lifespan; Julian Seward.
35 All rights reserved.</para>
37 <para>Redistribution and use in source and binary forms, with
38 or without modification, are permitted provided that the
39 following conditions are met:</para>
41 <itemizedlist mark='bullet'>
43 <listitem><para>Redistributions of source code must retain the
44 above copyright notice, this list of conditions and the
45 following disclaimer.</para></listitem>
47 <listitem><para>The origin of this software must not be
48 misrepresented; you must not claim that you wrote the original
49 software. If you use this software in a product, an
50 acknowledgment in the product documentation would be
51 appreciated but is not required.</para></listitem>
53 <listitem><para>Altered source versions must be plainly marked
54 as such, and must not be misrepresented as being the original
55 software.</para></listitem>
57 <listitem><para>The name of the author may not be used to
58 endorse or promote products derived from this software without
59 specific prior written permission.</para></listitem>
63 <para>THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY
64 EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
65 THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
66 PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
67 AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
68 EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
69 TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
70 DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
71 ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
72 LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
73 IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
74 THE POSSIBILITY OF SUCH DAMAGE.</para>
76 <para>PATENTS: To the best of my knowledge,
77 <computeroutput>bzip2</computeroutput> and
78 <computeroutput>libbzip2</computeroutput> do not use any patented
79 algorithms. However, I do not have the resources to carry
80 out a patent search. Therefore I cannot give any guarantee of
90 <chapter id="intro" xreflabel="Introduction">
91 <title>Introduction</title>
93 <para><computeroutput>bzip2</computeroutput> compresses files
94 using the Burrows-Wheeler block-sorting text compression
95 algorithm, and Huffman coding. Compression is generally
96 considerably better than that achieved by more conventional
97 LZ77/LZ78-based compressors, and approaches the performance of
98 the PPM family of statistical compressors.</para>
100 <para><computeroutput>bzip2</computeroutput> is built on top of
101 <computeroutput>libbzip2</computeroutput>, a flexible library for
102 handling compressed data in the
103 <computeroutput>bzip2</computeroutput> format. This manual
104 describes both how to use the program and how to work with the
105 library interface. Most of the manual is devoted to this
106 library, not the program, which is good news if your interest is
107 only in the program.</para>
109 <itemizedlist mark='bullet'>
111 <listitem><para><xref linkend="using"/> describes how to use
112 <computeroutput>bzip2</computeroutput>; this is the only part
113 you need to read if you just want to know how to operate the
114 program.</para></listitem>
116 <listitem><para><xref linkend="libprog"/> describes the
117 programming interfaces in detail, and</para></listitem>
119 <listitem><para><xref linkend="misc"/> records some
120 miscellaneous notes which I thought ought to be recorded
121 somewhere.</para></listitem>
128 <chapter id="using" xreflabel="How to use bzip2">
129 <title>How to use bzip2</title>
131 <para>This chapter contains a copy of the
132 <computeroutput>bzip2</computeroutput> man page, and nothing
135 <sect1 id="name" xreflabel="NAME">
138 <itemizedlist mark='bullet'>
140 <listitem><para><computeroutput>bzip2</computeroutput>,
141 <computeroutput>bunzip2</computeroutput> - a block-sorting file
142 compressor, v1.0.4</para></listitem>
144 <listitem><para><computeroutput>bzcat</computeroutput> -
145 decompresses files to stdout</para></listitem>
147 <listitem><para><computeroutput>bzip2recover</computeroutput> -
148 recovers data from damaged bzip2 files</para></listitem>
155 <sect1 id="synopsis" xreflabel="SYNOPSIS">
156 <title>SYNOPSIS</title>
158 <itemizedlist mark='bullet'>
160 <listitem><para><computeroutput>bzip2</computeroutput> [
161 -cdfkqstvzVL123456789 ] [ filenames ... ]</para></listitem>
163 <listitem><para><computeroutput>bzip2</computeroutput> [
164 -h | --help ]</para></listitem>
166 <listitem><para><computeroutput>bunzip2</computeroutput> [
167 -fkvsVL ] [ filenames ... ]</para></listitem>
169 <listitem><para><computeroutput>bunzip2</computeroutput> [
170 -h | --help ]</para></listitem>
172 <listitem><para><computeroutput>bzcat</computeroutput> [ -s ] [
173 filenames ... ]</para></listitem>
175 <listitem><para><computeroutput>bzcat</computeroutput> [
176 -h | --help ]</para></listitem>
178 <listitem><para><computeroutput>bzip2recover</computeroutput>
179 filename</para></listitem>
186 <sect1 id="description" xreflabel="DESCRIPTION">
187 <title>DESCRIPTION</title>
189 <para><computeroutput>bzip2</computeroutput> compresses files
190 using the Burrows-Wheeler block sorting text compression
191 algorithm, and Huffman coding. Compression is generally
192 considerably better than that achieved by more conventional
193 LZ77/LZ78-based compressors, and approaches the performance of
194 the PPM family of statistical compressors.</para>
196 <para>The command-line options are deliberately very similar to
197 those of GNU <computeroutput>gzip</computeroutput>, but they are
198 not identical.</para>
200 <para><computeroutput>bzip2</computeroutput> expects a list of
201 file names to accompany the command-line flags. Each file is
202 replaced by a compressed version of itself, with the name
203 <computeroutput>original_name.bz2</computeroutput>. Each
204 compressed file has the same modification date, permissions, and,
205 when possible, ownership as the corresponding original, so that
206 these properties can be correctly restored at decompression time.
207 File name handling is naive in the sense that there is no
208 mechanism for preserving original file names, permissions,
209 ownerships or dates in filesystems which lack these concepts, or
210 have serious file name length restrictions, such as
213 <para><computeroutput>bzip2</computeroutput> and
214 <computeroutput>bunzip2</computeroutput> will by default not
215 overwrite existing files. If you want this to happen, specify
216 the <computeroutput>-f</computeroutput> flag.</para>
218 <para>If no file names are specified,
219 <computeroutput>bzip2</computeroutput> compresses from standard
220 input to standard output. In this case,
221 <computeroutput>bzip2</computeroutput> will decline to write
222 compressed output to a terminal, as this would be entirely
223 incomprehensible and therefore pointless.</para>
225 <para><computeroutput>bunzip2</computeroutput> (or
226 <computeroutput>bzip2 -d</computeroutput>) decompresses all
227 specified files. Files which were not created by
228 <computeroutput>bzip2</computeroutput> will be detected and
229 ignored, and a warning issued.
230 <computeroutput>bzip2</computeroutput> attempts to guess the
231 filename for the decompressed file from that of the compressed
232 file as follows:</para>
234 <itemizedlist mark='bullet'>
236 <listitem><para><computeroutput>filename.bz2 </computeroutput>
238 <computeroutput>filename</computeroutput></para></listitem>
240 <listitem><para><computeroutput>filename.bz </computeroutput>
242 <computeroutput>filename</computeroutput></para></listitem>
244 <listitem><para><computeroutput>filename.tbz2</computeroutput>
246 <computeroutput>filename.tar</computeroutput></para></listitem>
248 <listitem><para><computeroutput>filename.tbz </computeroutput>
250 <computeroutput>filename.tar</computeroutput></para></listitem>
252 <listitem><para><computeroutput>anyothername </computeroutput>
254 <computeroutput>anyothername.out</computeroutput></para></listitem>
258 <para>If the file does not end in one of the recognised endings,
259 <computeroutput>.bz2</computeroutput>,
260 <computeroutput>.bz</computeroutput>,
261 <computeroutput>.tbz2</computeroutput> or
262 <computeroutput>.tbz</computeroutput>,
263 <computeroutput>bzip2</computeroutput> complains that it cannot
264 guess the name of the original file, and uses the original name
265 with <computeroutput>.out</computeroutput> appended.</para>
267 <para>As with compression, supplying no filenames causes
268 decompression from standard input to standard output.</para>
270 <para><computeroutput>bunzip2</computeroutput> will correctly
271 decompress a file which is the concatenation of two or more
272 compressed files. The result is the concatenation of the
273 corresponding uncompressed files. Integrity testing
274 (<computeroutput>-t</computeroutput>) of concatenated compressed
275 files is also supported.</para>
277 <para>You can also compress or decompress files to the standard
278 output by giving the <computeroutput>-c</computeroutput> flag.
279 Multiple files may be compressed and decompressed like this. The
280 resulting outputs are fed sequentially to stdout. Compression of
281 multiple files in this manner generates a stream containing
282 multiple compressed file representations. Such a stream can be
283 decompressed correctly only by
284 <computeroutput>bzip2</computeroutput> version 0.9.0 or later.
285 Earlier versions of <computeroutput>bzip2</computeroutput> will
286 stop after decompressing the first file in the stream.</para>
288 <para><computeroutput>bzcat</computeroutput> (or
289 <computeroutput>bzip2 -dc</computeroutput>) decompresses all
290 specified files to the standard output.</para>
292 <para><computeroutput>bzip2</computeroutput> will read arguments
293 from the environment variables
294 <computeroutput>BZIP2</computeroutput> and
295 <computeroutput>BZIP</computeroutput>, in that order, and will
296 process them before any arguments read from the command line.
297 This gives a convenient way to supply default arguments.</para>
299 <para>Compression is always performed, even if the compressed
300 file is slightly larger than the original. Files of less than
301 about one hundred bytes tend to get larger, since the compression
302 mechanism has a constant overhead in the region of 50 bytes.
303 Random data (including the output of most file compressors) is
304 coded at about 8.05 bits per byte, giving an expansion of around
307 <para>As a self-check for your protection,
308 <computeroutput>bzip2</computeroutput> uses 32-bit CRCs to make
309 sure that the decompressed version of a file is identical to the
310 original. This guards against corruption of the compressed data,
311 and against undetected bugs in
312 <computeroutput>bzip2</computeroutput> (hopefully very unlikely).
313 The chances of data corruption going undetected is microscopic,
314 about one chance in four billion for each file processed. Be
315 aware, though, that the check occurs upon decompression, so it
316 can only tell you that something is wrong. It can't help you
317 recover the original uncompressed data. You can use
318 <computeroutput>bzip2recover</computeroutput> to try to recover
319 data from damaged files.</para>
321 <para>Return values: 0 for a normal exit, 1 for environmental
322 problems (file not found, invalid flags, I/O errors, etc.), 2
323 to indicate a corrupt compressed file, 3 for an internal
324 consistency error (eg, bug) which caused
325 <computeroutput>bzip2</computeroutput> to panic.</para>
330 <sect1 id="options" xreflabel="OPTIONS">
331 <title>OPTIONS</title>
336 <term><computeroutput>-c --stdout</computeroutput></term>
337 <listitem><para>Compress or decompress to standard
338 output.</para></listitem>
342 <term><computeroutput>-d --decompress</computeroutput></term>
343 <listitem><para>Force decompression.
344 <computeroutput>bzip2</computeroutput>,
345 <computeroutput>bunzip2</computeroutput> and
346 <computeroutput>bzcat</computeroutput> are really the same
347 program, and the decision about what actions to take is done on
348 the basis of which name is used. This flag overrides that
349 mechanism, and forces bzip2 to decompress.</para></listitem>
353 <term><computeroutput>-z --compress</computeroutput></term>
354 <listitem><para>The complement to
355 <computeroutput>-d</computeroutput>: forces compression,
356 regardless of the invokation name.</para></listitem>
360 <term><computeroutput>-t --test</computeroutput></term>
361 <listitem><para>Check integrity of the specified file(s), but
362 don't decompress them. This really performs a trial
363 decompression and throws away the result.</para></listitem>
367 <term><computeroutput>-f --force</computeroutput></term>
368 <listitem><para>Force overwrite of output files. Normally,
369 <computeroutput>bzip2</computeroutput> will not overwrite
370 existing output files. Also forces
371 <computeroutput>bzip2</computeroutput> to break hard links to
372 files, which it otherwise wouldn't do.</para>
373 <para><computeroutput>bzip2</computeroutput> normally declines
374 to decompress files which don't have the correct magic header
375 bytes. If forced (<computeroutput>-f</computeroutput>),
376 however, it will pass such files through unmodified. This is
377 how GNU <computeroutput>gzip</computeroutput> behaves.</para>
382 <term><computeroutput>-k --keep</computeroutput></term>
383 <listitem><para>Keep (don't delete) input files during
384 compression or decompression.</para></listitem>
388 <term><computeroutput>-s --small</computeroutput></term>
389 <listitem><para>Reduce memory usage, for compression,
390 decompression and testing. Files are decompressed and tested
391 using a modified algorithm which only requires 2.5 bytes per
392 block byte. This means any file can be decompressed in 2300k
393 of memory, albeit at about half the normal speed.</para>
394 <para>During compression, <computeroutput>-s</computeroutput>
395 selects a block size of 200k, which limits memory use to around
396 the same figure, at the expense of your compression ratio. In
397 short, if your machine is low on memory (8 megabytes or less),
398 use <computeroutput>-s</computeroutput> for everything. See
399 <xref linkend="memory-management"/> below.</para></listitem>
403 <term><computeroutput>-q --quiet</computeroutput></term>
404 <listitem><para>Suppress non-essential warning messages.
405 Messages pertaining to I/O errors and other critical events
406 will not be suppressed.</para></listitem>
409 <varlistentry><term><computeroutput>-h --help</computeroutput></term>
410 <listitem><para>Print a help message and exit.</para></listitem>
414 <term><computeroutput>-v --verbose</computeroutput></term>
415 <listitem><para>Verbose mode -- show the compression ratio for
416 each file processed. Further
417 <computeroutput>-v</computeroutput>'s increase the verbosity
418 level, spewing out lots of information which is primarily of
419 interest for diagnostic purposes.</para></listitem>
423 <term><computeroutput>-L --license -V --version</computeroutput></term>
424 <listitem><para>Display the software version, license terms and
425 conditions.</para></listitem>
429 <term><computeroutput>-1</computeroutput> (or
430 <computeroutput>--fast</computeroutput>) to
431 <computeroutput>-9</computeroutput> (or
432 <computeroutput>-best</computeroutput>)</term>
433 <listitem><para>Set the block size to 100 k, 200 k ... 900 k
434 when compressing. Has no effect when decompressing. See <xref
435 linkend="memory-management" /> below. The
436 <computeroutput>--fast</computeroutput> and
437 <computeroutput>--best</computeroutput> aliases are primarily
438 for GNU <computeroutput>gzip</computeroutput> compatibility.
439 In particular, <computeroutput>--fast</computeroutput> doesn't
440 make things significantly faster. And
441 <computeroutput>--best</computeroutput> merely selects the
442 default behaviour.</para></listitem>
446 <term><computeroutput>--</computeroutput></term>
447 <listitem><para>Treats all subsequent arguments as file names,
448 even if they start with a dash. This is so you can handle
449 files with names beginning with a dash, for example:
450 <computeroutput>bzip2 --
451 -myfilename</computeroutput>.</para></listitem>
455 <term><computeroutput>--repetitive-fast</computeroutput></term>
456 <term><computeroutput>--repetitive-best</computeroutput></term>
457 <listitem><para>These flags are redundant in versions 0.9.5 and
458 above. They provided some coarse control over the behaviour of
459 the sorting algorithm in earlier versions, which was sometimes
460 useful. 0.9.5 and above have an improved algorithm which
461 renders these flags irrelevant.</para></listitem>
469 <sect1 id="memory-management" xreflabel="MEMORY MANAGEMENT">
470 <title>MEMORY MANAGEMENT</title>
472 <para><computeroutput>bzip2</computeroutput> compresses large
473 files in blocks. The block size affects both the compression
474 ratio achieved, and the amount of memory needed for compression
475 and decompression. The flags <computeroutput>-1</computeroutput>
476 through <computeroutput>-9</computeroutput> specify the block
477 size to be 100,000 bytes through 900,000 bytes (the default)
478 respectively. At decompression time, the block size used for
479 compression is read from the header of the compressed file, and
480 <computeroutput>bunzip2</computeroutput> then allocates itself
481 just enough memory to decompress the file. Since block sizes are
482 stored in compressed files, it follows that the flags
483 <computeroutput>-1</computeroutput> to
484 <computeroutput>-9</computeroutput> are irrelevant to and so
485 ignored during decompression.</para>
487 <para>Compression and decompression requirements, in bytes, can be
490 Compression: 400k + ( 8 x block size )
492 Decompression: 100k + ( 4 x block size ), or
493 100k + ( 2.5 x block size )
496 <para>Larger block sizes give rapidly diminishing marginal
497 returns. Most of the compression comes from the first two or
498 three hundred k of block size, a fact worth bearing in mind when
499 using <computeroutput>bzip2</computeroutput> on small machines.
500 It is also important to appreciate that the decompression memory
501 requirement is set at compression time by the choice of block
504 <para>For files compressed with the default 900k block size,
505 <computeroutput>bunzip2</computeroutput> will require about 3700
506 kbytes to decompress. To support decompression of any file on a
507 4 megabyte machine, <computeroutput>bunzip2</computeroutput> has
508 an option to decompress using approximately half this amount of
509 memory, about 2300 kbytes. Decompression speed is also halved,
510 so you should use this option only where necessary. The relevant
511 flag is <computeroutput>-s</computeroutput>.</para>
513 <para>In general, try and use the largest block size memory
514 constraints allow, since that maximises the compression achieved.
515 Compression and decompression speed are virtually unaffected by
518 <para>Another significant point applies to files which fit in a
519 single block -- that means most files you'd encounter using a
520 large block size. The amount of real memory touched is
521 proportional to the size of the file, since the file is smaller
522 than a block. For example, compressing a file 20,000 bytes long
523 with the flag <computeroutput>-9</computeroutput> will cause the
524 compressor to allocate around 7600k of memory, but only touch
525 400k + 20000 * 8 = 560 kbytes of it. Similarly, the decompressor
526 will allocate 3700k but only touch 100k + 20000 * 4 = 180
529 <para>Here is a table which summarises the maximum memory usage
530 for different block sizes. Also recorded is the total compressed
531 size for 14 files of the Calgary Text Compression Corpus
532 totalling 3,141,622 bytes. This column gives some feel for how
533 compression varies with block size. These figures tend to
534 understate the advantage of larger block sizes for larger files,
535 since the Corpus is dominated by smaller files.</para>
538 Compress Decompress Decompress Corpus
539 Flag usage usage -s usage Size
541 -1 1200k 500k 350k 914704
542 -2 2000k 900k 600k 877703
543 -3 2800k 1300k 850k 860338
544 -4 3600k 1700k 1100k 846899
545 -5 4400k 2100k 1350k 845160
546 -6 5200k 2500k 1600k 838626
547 -7 6100k 2900k 1850k 834096
548 -8 6800k 3300k 2100k 828642
549 -9 7600k 3700k 2350k 828642
555 <sect1 id="recovering" xreflabel="RECOVERING DATA FROM DAMAGED FILES">
556 <title>RECOVERING DATA FROM DAMAGED FILES</title>
558 <para><computeroutput>bzip2</computeroutput> compresses files in
559 blocks, usually 900kbytes long. Each block is handled
560 independently. If a media or transmission error causes a
561 multi-block <computeroutput>.bz2</computeroutput> file to become
562 damaged, it may be possible to recover data from the undamaged
563 blocks in the file.</para>
565 <para>The compressed representation of each block is delimited by
566 a 48-bit pattern, which makes it possible to find the block
567 boundaries with reasonable certainty. Each block also carries
568 its own 32-bit CRC, so damaged blocks can be distinguished from
569 undamaged ones.</para>
571 <para><computeroutput>bzip2recover</computeroutput> is a simple
572 program whose purpose is to search for blocks in
573 <computeroutput>.bz2</computeroutput> files, and write each block
574 out into its own <computeroutput>.bz2</computeroutput> file. You
575 can then use <computeroutput>bzip2 -t</computeroutput> to test
576 the integrity of the resulting files, and decompress those which
577 are undamaged.</para>
579 <para><computeroutput>bzip2recover</computeroutput> takes a
580 single argument, the name of the damaged file, and writes a
581 number of files <computeroutput>rec0001file.bz2</computeroutput>,
582 <computeroutput>rec0002file.bz2</computeroutput>, etc, containing
583 the extracted blocks. The output filenames are designed so that
584 the use of wildcards in subsequent processing -- for example,
585 <computeroutput>bzip2 -dc rec*file.bz2 >
586 recovered_data</computeroutput> -- lists the files in the correct
589 <para><computeroutput>bzip2recover</computeroutput> should be of
590 most use dealing with large <computeroutput>.bz2</computeroutput>
591 files, as these will contain many blocks. It is clearly futile
592 to use it on damaged single-block files, since a damaged block
593 cannot be recovered. If you wish to minimise any potential data
594 loss through media or transmission errors, you might consider
595 compressing with a smaller block size.</para>
600 <sect1 id="performance" xreflabel="PERFORMANCE NOTES">
601 <title>PERFORMANCE NOTES</title>
603 <para>The sorting phase of compression gathers together similar
604 strings in the file. Because of this, files containing very long
605 runs of repeated symbols, like "aabaabaabaab ..." (repeated
606 several hundred times) may compress more slowly than normal.
607 Versions 0.9.5 and above fare much better than previous versions
608 in this respect. The ratio between worst-case and average-case
609 compression time is in the region of 10:1. For previous
610 versions, this figure was more like 100:1. You can use the
611 <computeroutput>-vvvv</computeroutput> option to monitor progress
612 in great detail, if you want.</para>
614 <para>Decompression speed is unaffected by these
617 <para><computeroutput>bzip2</computeroutput> usually allocates
618 several megabytes of memory to operate in, and then charges all
619 over it in a fairly random fashion. This means that performance,
620 both for compressing and decompressing, is largely determined by
621 the speed at which your machine can service cache misses.
622 Because of this, small changes to the code to reduce the miss
623 rate have been observed to give disproportionately large
624 performance improvements. I imagine
625 <computeroutput>bzip2</computeroutput> will perform best on
626 machines with very large caches.</para>
632 <sect1 id="caveats" xreflabel="CAVEATS">
633 <title>CAVEATS</title>
635 <para>I/O error messages are not as helpful as they could be.
636 <computeroutput>bzip2</computeroutput> tries hard to detect I/O
637 errors and exit cleanly, but the details of what the problem is
638 sometimes seem rather misleading.</para>
640 <para>This manual page pertains to version &bz-version; of
641 <computeroutput>bzip2</computeroutput>. Compressed data created by
642 this version is entirely forwards and backwards compatible with the
643 previous public releases, versions 0.1pl2, 0.9.0 and 0.9.5, 1.0.0,
644 1.0.1, 1.0.2 and 1.0.3, but with the following exception: 0.9.0 and
645 above can correctly decompress multiple concatenated compressed files.
646 0.1pl2 cannot do this; it will stop after decompressing just the first
647 file in the stream.</para>
649 <para><computeroutput>bzip2recover</computeroutput> versions
650 prior to 1.0.2 used 32-bit integers to represent bit positions in
651 compressed files, so it could not handle compressed files more
652 than 512 megabytes long. Versions 1.0.2 and above use 64-bit ints
653 on some platforms which support them (GNU supported targets, and
654 Windows). To establish whether or not
655 <computeroutput>bzip2recover</computeroutput> was built with such
656 a limitation, run it without arguments. In any event you can
657 build yourself an unlimited version if you can recompile it with
658 <computeroutput>MaybeUInt64</computeroutput> set to be an
659 unsigned 64-bit integer.</para>
665 <sect1 id="author" xreflabel="AUTHOR">
666 <title>AUTHOR</title>
669 <computeroutput>&bz-email;</computeroutput></para>
671 <para>The ideas embodied in
672 <computeroutput>bzip2</computeroutput> are due to (at least) the
673 following people: Michael Burrows and David Wheeler (for the
674 block sorting transformation), David Wheeler (again, for the
675 Huffman coder), Peter Fenwick (for the structured coding model in
676 the original <computeroutput>bzip</computeroutput>, and many
677 refinements), and Alistair Moffat, Radford Neal and Ian Witten
678 (for the arithmetic coder in the original
679 <computeroutput>bzip</computeroutput>). I am much indebted for
680 their help, support and advice. See the manual in the source
681 distribution for pointers to sources of documentation. Christian
682 von Roques encouraged me to look for faster sorting algorithms,
683 so as to speed up compression. Bela Lubkin encouraged me to
684 improve the worst-case compression performance.
685 Donna Robinson XMLised the documentation.
687 patches, helped with portability problems, lent machines, gave
688 advice and were generally helpful.</para>
696 <chapter id="libprog" xreflabel="Programming with libbzip2">
698 Programming with <computeroutput>libbzip2</computeroutput>
701 <para>This chapter describes the programming interface to
702 <computeroutput>libbzip2</computeroutput>.</para>
704 <para>For general background information, particularly about
705 memory use and performance aspects, you'd be well advised to read
706 <xref linkend="using"/> as well.</para>
709 <sect1 id="top-level" xreflabel="Top-level structure">
710 <title>Top-level structure</title>
712 <para><computeroutput>libbzip2</computeroutput> is a flexible
713 library for compressing and decompressing data in the
714 <computeroutput>bzip2</computeroutput> data format. Although
715 packaged as a single entity, it helps to regard the library as
716 three separate parts: the low level interface, and the high level
717 interface, and some utility functions.</para>
719 <para>The structure of
720 <computeroutput>libbzip2</computeroutput>'s interfaces is similar
721 to that of Jean-loup Gailly's and Mark Adler's excellent
722 <computeroutput>zlib</computeroutput> library.</para>
724 <para>All externally visible symbols have names beginning
725 <computeroutput>BZ2_</computeroutput>. This is new in version
726 1.0. The intention is to minimise pollution of the namespaces of
727 library clients.</para>
729 <para>To use any part of the library, you need to
730 <computeroutput>#include <bzlib.h></computeroutput>
731 into your sources.</para>
735 <sect2 id="ll-summary" xreflabel="Low-level summary">
736 <title>Low-level summary</title>
738 <para>This interface provides services for compressing and
739 decompressing data in memory. There's no provision for dealing
740 with files, streams or any other I/O mechanisms, just straight
741 memory-to-memory work. In fact, this part of the library can be
742 compiled without inclusion of
743 <computeroutput>stdio.h</computeroutput>, which may be helpful
744 for embedded applications.</para>
746 <para>The low-level part of the library has no global variables
747 and is therefore thread-safe.</para>
749 <para>Six routines make up the low level interface:
750 <computeroutput>BZ2_bzCompressInit</computeroutput>,
751 <computeroutput>BZ2_bzCompress</computeroutput>, and
752 <computeroutput>BZ2_bzCompressEnd</computeroutput> for
753 compression, and a corresponding trio
754 <computeroutput>BZ2_bzDecompressInit</computeroutput>,
755 <computeroutput>BZ2_bzDecompress</computeroutput> and
756 <computeroutput>BZ2_bzDecompressEnd</computeroutput> for
757 decompression. The <computeroutput>*Init</computeroutput>
758 functions allocate memory for compression/decompression and do
759 other initialisations, whilst the
760 <computeroutput>*End</computeroutput> functions close down
761 operations and release memory.</para>
763 <para>The real work is done by
764 <computeroutput>BZ2_bzCompress</computeroutput> and
765 <computeroutput>BZ2_bzDecompress</computeroutput>. These
766 compress and decompress data from a user-supplied input buffer to
767 a user-supplied output buffer. These buffers can be any size;
768 arbitrary quantities of data are handled by making repeated calls
769 to these functions. This is a flexible mechanism allowing a
770 consumer-pull style of activity, or producer-push, or a mixture
776 <sect2 id="hl-summary" xreflabel="High-level summary">
777 <title>High-level summary</title>
779 <para>This interface provides some handy wrappers around the
780 low-level interface to facilitate reading and writing
781 <computeroutput>bzip2</computeroutput> format files
782 (<computeroutput>.bz2</computeroutput> files). The routines
783 provide hooks to facilitate reading files in which the
784 <computeroutput>bzip2</computeroutput> data stream is embedded
785 within some larger-scale file structure, or where there are
786 multiple <computeroutput>bzip2</computeroutput> data streams
787 concatenated end-to-end.</para>
789 <para>For reading files,
790 <computeroutput>BZ2_bzReadOpen</computeroutput>,
791 <computeroutput>BZ2_bzRead</computeroutput>,
792 <computeroutput>BZ2_bzReadClose</computeroutput> and
793 <computeroutput>BZ2_bzReadGetUnused</computeroutput> are
794 supplied. For writing files,
795 <computeroutput>BZ2_bzWriteOpen</computeroutput>,
796 <computeroutput>BZ2_bzWrite</computeroutput> and
797 <computeroutput>BZ2_bzWriteFinish</computeroutput> are
800 <para>As with the low-level library, no global variables are used
801 so the library is per se thread-safe. However, if I/O errors
802 occur whilst reading or writing the underlying compressed files,
803 you may have to consult <computeroutput>errno</computeroutput> to
804 determine the cause of the error. In that case, you'd need a C
805 library which correctly supports
806 <computeroutput>errno</computeroutput> in a multithreaded
809 <para>To make the library a little simpler and more portable,
810 <computeroutput>BZ2_bzReadOpen</computeroutput> and
811 <computeroutput>BZ2_bzWriteOpen</computeroutput> require you to
812 pass them file handles (<computeroutput>FILE*</computeroutput>s)
813 which have previously been opened for reading or writing
814 respectively. That avoids portability problems associated with
815 file operations and file attributes, whilst not being much of an
816 imposition on the programmer.</para>
821 <sect2 id="util-fns-summary" xreflabel="Utility functions summary">
822 <title>Utility functions summary</title>
824 <para>For very simple needs,
825 <computeroutput>BZ2_bzBuffToBuffCompress</computeroutput> and
826 <computeroutput>BZ2_bzBuffToBuffDecompress</computeroutput> are
827 provided. These compress data in memory from one buffer to
828 another buffer in a single function call. You should assess
829 whether these functions fulfill your memory-to-memory
830 compression/decompression requirements before investing effort in
831 understanding the more general but more complex low-level
834 <para>Yoshioka Tsuneo
835 (<computeroutput>tsuneo@rr.iij4u.or.jp</computeroutput>) has
836 contributed some functions to give better
837 <computeroutput>zlib</computeroutput> compatibility. These
838 functions are <computeroutput>BZ2_bzopen</computeroutput>,
839 <computeroutput>BZ2_bzread</computeroutput>,
840 <computeroutput>BZ2_bzwrite</computeroutput>,
841 <computeroutput>BZ2_bzflush</computeroutput>,
842 <computeroutput>BZ2_bzclose</computeroutput>,
843 <computeroutput>BZ2_bzerror</computeroutput> and
844 <computeroutput>BZ2_bzlibVersion</computeroutput>. You may find
845 these functions more convenient for simple file reading and
846 writing, than those in the high-level interface. These functions
847 are not (yet) officially part of the library, and are minimally
848 documented here. If they break, you get to keep all the pieces.
849 I hope to document them properly when time permits.</para>
851 <para>Yoshioka also contributed modifications to allow the
852 library to be built as a Windows DLL.</para>
859 <sect1 id="err-handling" xreflabel="Error handling">
860 <title>Error handling</title>
862 <para>The library is designed to recover cleanly in all
863 situations, including the worst-case situation of decompressing
864 random data. I'm not 100% sure that it can always do this, so
865 you might want to add a signal handler to catch segmentation
866 violations during decompression if you are feeling especially
867 paranoid. I would be interested in hearing more about the
868 robustness of the library to corrupted compressed data.</para>
870 <para>Version 1.0.3 more robust in this respect than any
871 previous version. Investigations with Valgrind (a tool for detecting
872 problems with memory management) indicate
873 that, at least for the few files I tested, all single-bit errors
874 in the decompressed data are caught properly, with no
875 segmentation faults, no uses of uninitialised data, no out of
876 range reads or writes, and no infinite looping in the decompressor.
877 So it's certainly pretty robust, although
878 I wouldn't claim it to be totally bombproof.</para>
880 <para>The file <computeroutput>bzlib.h</computeroutput> contains
881 all definitions needed to use the library. In particular, you
882 should definitely not include
883 <computeroutput>bzlib_private.h</computeroutput>.</para>
885 <para>In <computeroutput>bzlib.h</computeroutput>, the various
886 return values are defined. The following list is not intended as
887 an exhaustive description of the circumstances in which a given
888 value may be returned -- those descriptions are given later.
889 Rather, it is intended to convey the rough meaning of each return
890 value. The first five actions are normal and not intended to
891 denote an error situation.</para>
896 <term><computeroutput>BZ_OK</computeroutput></term>
897 <listitem><para>The requested action was completed
898 successfully.</para></listitem>
902 <term><computeroutput>BZ_RUN_OK, BZ_FLUSH_OK,
903 BZ_FINISH_OK</computeroutput></term>
905 <computeroutput>BZ2_bzCompress</computeroutput>, the requested
906 flush/finish/nothing-special action was completed
907 successfully.</para></listitem>
911 <term><computeroutput>BZ_STREAM_END</computeroutput></term>
912 <listitem><para>Compression of data was completed, or the
913 logical stream end was detected during
914 decompression.</para></listitem>
919 <para>The following return values indicate an error of some
925 <term><computeroutput>BZ_CONFIG_ERROR</computeroutput></term>
926 <listitem><para>Indicates that the library has been improperly
927 compiled on your platform -- a major configuration error.
928 Specifically, it means that
929 <computeroutput>sizeof(char)</computeroutput>,
930 <computeroutput>sizeof(short)</computeroutput> and
931 <computeroutput>sizeof(int)</computeroutput> are not 1, 2 and
932 4 respectively, as they should be. Note that the library
933 should still work properly on 64-bit platforms which follow
934 the LP64 programming model -- that is, where
935 <computeroutput>sizeof(long)</computeroutput> and
936 <computeroutput>sizeof(void*)</computeroutput> are 8. Under
937 LP64, <computeroutput>sizeof(int)</computeroutput> is still 4,
938 so <computeroutput>libbzip2</computeroutput>, which doesn't
939 use the <computeroutput>long</computeroutput> type, is
940 OK.</para></listitem>
944 <term><computeroutput>BZ_SEQUENCE_ERROR</computeroutput></term>
945 <listitem><para>When using the library, it is important to call
946 the functions in the correct sequence and with data structures
947 (buffers etc) in the correct states.
948 <computeroutput>libbzip2</computeroutput> checks as much as it
949 can to ensure this is happening, and returns
950 <computeroutput>BZ_SEQUENCE_ERROR</computeroutput> if not.
951 Code which complies precisely with the function semantics, as
952 detailed below, should never receive this value; such an event
953 denotes buggy code which you should
954 investigate.</para></listitem>
958 <term><computeroutput>BZ_PARAM_ERROR</computeroutput></term>
959 <listitem><para>Returned when a parameter to a function call is
960 out of range or otherwise manifestly incorrect. As with
961 <computeroutput>BZ_SEQUENCE_ERROR</computeroutput>, this
962 denotes a bug in the client code. The distinction between
963 <computeroutput>BZ_PARAM_ERROR</computeroutput> and
964 <computeroutput>BZ_SEQUENCE_ERROR</computeroutput> is a bit
965 hazy, but still worth making.</para></listitem>
969 <term><computeroutput>BZ_MEM_ERROR</computeroutput></term>
970 <listitem><para>Returned when a request to allocate memory
971 failed. Note that the quantity of memory needed to decompress
972 a stream cannot be determined until the stream's header has
974 <computeroutput>BZ2_bzDecompress</computeroutput> and
975 <computeroutput>BZ2_bzRead</computeroutput> may return
976 <computeroutput>BZ_MEM_ERROR</computeroutput> even though some
977 of the compressed data has been read. The same is not true
978 for compression; once
979 <computeroutput>BZ2_bzCompressInit</computeroutput> or
980 <computeroutput>BZ2_bzWriteOpen</computeroutput> have
981 successfully completed,
982 <computeroutput>BZ_MEM_ERROR</computeroutput> cannot
983 occur.</para></listitem>
987 <term><computeroutput>BZ_DATA_ERROR</computeroutput></term>
988 <listitem><para>Returned when a data integrity error is
989 detected during decompression. Most importantly, this means
990 when stored and computed CRCs for the data do not match. This
991 value is also returned upon detection of any other anomaly in
992 the compressed data.</para></listitem>
996 <term><computeroutput>BZ_DATA_ERROR_MAGIC</computeroutput></term>
997 <listitem><para>As a special case of
998 <computeroutput>BZ_DATA_ERROR</computeroutput>, it is
999 sometimes useful to know when the compressed stream does not
1000 start with the correct magic bytes (<computeroutput>'B' 'Z'
1001 'h'</computeroutput>).</para></listitem>
1005 <term><computeroutput>BZ_IO_ERROR</computeroutput></term>
1006 <listitem><para>Returned by
1007 <computeroutput>BZ2_bzRead</computeroutput> and
1008 <computeroutput>BZ2_bzWrite</computeroutput> when there is an
1009 error reading or writing in the compressed file, and by
1010 <computeroutput>BZ2_bzReadOpen</computeroutput> and
1011 <computeroutput>BZ2_bzWriteOpen</computeroutput> for attempts
1012 to use a file for which the error indicator (viz,
1013 <computeroutput>ferror(f)</computeroutput>) is set. On
1014 receipt of <computeroutput>BZ_IO_ERROR</computeroutput>, the
1015 caller should consult <computeroutput>errno</computeroutput>
1016 and/or <computeroutput>perror</computeroutput> to acquire
1017 operating-system specific information about the
1018 problem.</para></listitem>
1022 <term><computeroutput>BZ_UNEXPECTED_EOF</computeroutput></term>
1023 <listitem><para>Returned by
1024 <computeroutput>BZ2_bzRead</computeroutput> when the
1025 compressed file finishes before the logical end of stream is
1026 detected.</para></listitem>
1030 <term><computeroutput>BZ_OUTBUFF_FULL</computeroutput></term>
1031 <listitem><para>Returned by
1032 <computeroutput>BZ2_bzBuffToBuffCompress</computeroutput> and
1033 <computeroutput>BZ2_bzBuffToBuffDecompress</computeroutput> to
1034 indicate that the output data will not fit into the output
1035 buffer provided.</para></listitem>
1044 <sect1 id="low-level" xreflabel=">Low-level interface">
1045 <title>Low-level interface</title>
1048 <sect2 id="bzcompress-init" xreflabel="BZ2_bzCompressInit">
1049 <title><computeroutput>BZ2_bzCompressInit</computeroutput></title>
1054 unsigned int avail_in;
1055 unsigned int total_in_lo32;
1056 unsigned int total_in_hi32;
1059 unsigned int avail_out;
1060 unsigned int total_out_lo32;
1061 unsigned int total_out_hi32;
1065 void *(*bzalloc)(void *,int,int);
1066 void (*bzfree)(void *,void *);
1070 int BZ2_bzCompressInit ( bz_stream *strm,
1076 <para>Prepares for compression. The
1077 <computeroutput>bz_stream</computeroutput> structure holds all
1078 data pertaining to the compression activity. A
1079 <computeroutput>bz_stream</computeroutput> structure should be
1080 allocated and initialised prior to the call. The fields of
1081 <computeroutput>bz_stream</computeroutput> comprise the entirety
1082 of the user-visible data. <computeroutput>state</computeroutput>
1083 is a pointer to the private data structures required for
1086 <para>Custom memory allocators are supported, via fields
1087 <computeroutput>bzalloc</computeroutput>,
1088 <computeroutput>bzfree</computeroutput>, and
1089 <computeroutput>opaque</computeroutput>. The value
1090 <computeroutput>opaque</computeroutput> is passed to as the first
1091 argument to all calls to <computeroutput>bzalloc</computeroutput>
1092 and <computeroutput>bzfree</computeroutput>, but is otherwise
1093 ignored by the library. The call <computeroutput>bzalloc (
1094 opaque, n, m )</computeroutput> is expected to return a pointer
1095 <computeroutput>p</computeroutput> to <computeroutput>n *
1096 m</computeroutput> bytes of memory, and <computeroutput>bzfree (
1097 opaque, p )</computeroutput> should free that memory.</para>
1099 <para>If you don't want to use a custom memory allocator, set
1100 <computeroutput>bzalloc</computeroutput>,
1101 <computeroutput>bzfree</computeroutput> and
1102 <computeroutput>opaque</computeroutput> to
1103 <computeroutput>NULL</computeroutput>, and the library will then
1104 use the standard <computeroutput>malloc</computeroutput> /
1105 <computeroutput>free</computeroutput> routines.</para>
1107 <para>Before calling
1108 <computeroutput>BZ2_bzCompressInit</computeroutput>, fields
1109 <computeroutput>bzalloc</computeroutput>,
1110 <computeroutput>bzfree</computeroutput> and
1111 <computeroutput>opaque</computeroutput> should be filled
1112 appropriately, as just described. Upon return, the internal
1113 state will have been allocated and initialised, and
1114 <computeroutput>total_in_lo32</computeroutput>,
1115 <computeroutput>total_in_hi32</computeroutput>,
1116 <computeroutput>total_out_lo32</computeroutput> and
1117 <computeroutput>total_out_hi32</computeroutput> will have been
1118 set to zero. These four fields are used by the library to inform
1119 the caller of the total amount of data passed into and out of the
1120 library, respectively. You should not try to change them. As of
1121 version 1.0, 64-bit counts are maintained, even on 32-bit
1122 platforms, using the <computeroutput>_hi32</computeroutput>
1123 fields to store the upper 32 bits of the count. So, for example,
1124 the total amount of data in is <computeroutput>(total_in_hi32
1125 << 32) + total_in_lo32</computeroutput>.</para>
1127 <para>Parameter <computeroutput>blockSize100k</computeroutput>
1128 specifies the block size to be used for compression. It should
1129 be a value between 1 and 9 inclusive, and the actual block size
1130 used is 100000 x this figure. 9 gives the best compression but
1131 takes most memory.</para>
1133 <para>Parameter <computeroutput>verbosity</computeroutput> should
1134 be set to a number between 0 and 4 inclusive. 0 is silent, and
1135 greater numbers give increasingly verbose monitoring/debugging
1136 output. If the library has been compiled with
1137 <computeroutput>-DBZ_NO_STDIO</computeroutput>, no such output
1138 will appear for any verbosity setting.</para>
1140 <para>Parameter <computeroutput>workFactor</computeroutput>
1141 controls how the compression phase behaves when presented with
1142 worst case, highly repetitive, input data. If compression runs
1143 into difficulties caused by repetitive data, the library switches
1144 from the standard sorting algorithm to a fallback algorithm. The
1145 fallback is slower than the standard algorithm by perhaps a
1146 factor of three, but always behaves reasonably, no matter how bad
1149 <para>Lower values of <computeroutput>workFactor</computeroutput>
1150 reduce the amount of effort the standard algorithm will expend
1151 before resorting to the fallback. You should set this parameter
1152 carefully; too low, and many inputs will be handled by the
1153 fallback algorithm and so compress rather slowly, too high, and
1154 your average-to-worst case compression times can become very
1155 large. The default value of 30 gives reasonable behaviour over a
1156 wide range of circumstances.</para>
1158 <para>Allowable values range from 0 to 250 inclusive. 0 is a
1159 special case, equivalent to using the default value of 30.</para>
1161 <para>Note that the compressed output generated is the same
1162 regardless of whether or not the fallback algorithm is
1165 <para>Be aware also that this parameter may disappear entirely in
1166 future versions of the library. In principle it should be
1167 possible to devise a good way to automatically choose which
1168 algorithm to use. Such a mechanism would render the parameter
1171 <para>Possible return values:</para>
1175 if the library has been mis-compiled
1178 or blockSize < 1 or blockSize > 9
1179 or verbosity < 0 or verbosity > 4
1180 or workFactor < 0 or workFactor > 250
1182 if not enough memory is available
1187 <para>Allowable next actions:</para>
1191 if BZ_OK is returned
1192 no specific action needed in case of error
1198 <sect2 id="bzCompress" xreflabel="BZ2_bzCompress">
1199 <title><computeroutput>BZ2_bzCompress</computeroutput></title>
1202 int BZ2_bzCompress ( bz_stream *strm, int action );
1205 <para>Provides more input and/or output buffer space for the
1206 library. The caller maintains input and output buffers, and
1207 calls <computeroutput>BZ2_bzCompress</computeroutput> to transfer
1208 data between them.</para>
1210 <para>Before each call to
1211 <computeroutput>BZ2_bzCompress</computeroutput>,
1212 <computeroutput>next_in</computeroutput> should point at the data
1213 to be compressed, and <computeroutput>avail_in</computeroutput>
1214 should indicate how many bytes the library may read.
1215 <computeroutput>BZ2_bzCompress</computeroutput> updates
1216 <computeroutput>next_in</computeroutput>,
1217 <computeroutput>avail_in</computeroutput> and
1218 <computeroutput>total_in</computeroutput> to reflect the number
1219 of bytes it has read.</para>
1221 <para>Similarly, <computeroutput>next_out</computeroutput> should
1222 point to a buffer in which the compressed data is to be placed,
1223 with <computeroutput>avail_out</computeroutput> indicating how
1224 much output space is available.
1225 <computeroutput>BZ2_bzCompress</computeroutput> updates
1226 <computeroutput>next_out</computeroutput>,
1227 <computeroutput>avail_out</computeroutput> and
1228 <computeroutput>total_out</computeroutput> to reflect the number
1229 of bytes output.</para>
1231 <para>You may provide and remove as little or as much data as you
1232 like on each call of
1233 <computeroutput>BZ2_bzCompress</computeroutput>. In the limit,
1234 it is acceptable to supply and remove data one byte at a time,
1235 although this would be terribly inefficient. You should always
1236 ensure that at least one byte of output space is available at
1239 <para>A second purpose of
1240 <computeroutput>BZ2_bzCompress</computeroutput> is to request a
1241 change of mode of the compressed stream.</para>
1243 <para>Conceptually, a compressed stream can be in one of four
1244 states: IDLE, RUNNING, FLUSHING and FINISHING. Before
1246 (<computeroutput>BZ2_bzCompressInit</computeroutput>) and after
1247 termination (<computeroutput>BZ2_bzCompressEnd</computeroutput>),
1248 a stream is regarded as IDLE.</para>
1250 <para>Upon initialisation
1251 (<computeroutput>BZ2_bzCompressInit</computeroutput>), the stream
1252 is placed in the RUNNING state. Subsequent calls to
1253 <computeroutput>BZ2_bzCompress</computeroutput> should pass
1254 <computeroutput>BZ_RUN</computeroutput> as the requested action;
1255 other actions are illegal and will result in
1256 <computeroutput>BZ_SEQUENCE_ERROR</computeroutput>.</para>
1258 <para>At some point, the calling program will have provided all
1259 the input data it wants to. It will then want to finish up -- in
1260 effect, asking the library to process any data it might have
1261 buffered internally. In this state,
1262 <computeroutput>BZ2_bzCompress</computeroutput> will no longer
1263 attempt to read data from
1264 <computeroutput>next_in</computeroutput>, but it will want to
1265 write data to <computeroutput>next_out</computeroutput>. Because
1266 the output buffer supplied by the user can be arbitrarily small,
1267 the finishing-up operation cannot necessarily be done with a
1269 <computeroutput>BZ2_bzCompress</computeroutput>.</para>
1271 <para>Instead, the calling program passes
1272 <computeroutput>BZ_FINISH</computeroutput> as an action to
1273 <computeroutput>BZ2_bzCompress</computeroutput>. This changes
1274 the stream's state to FINISHING. Any remaining input (ie,
1275 <computeroutput>next_in[0 .. avail_in-1]</computeroutput>) is
1276 compressed and transferred to the output buffer. To do this,
1277 <computeroutput>BZ2_bzCompress</computeroutput> must be called
1278 repeatedly until all the output has been consumed. At that
1279 point, <computeroutput>BZ2_bzCompress</computeroutput> returns
1280 <computeroutput>BZ_STREAM_END</computeroutput>, and the stream's
1281 state is set back to IDLE.
1282 <computeroutput>BZ2_bzCompressEnd</computeroutput> should then be
1285 <para>Just to make sure the calling program does not cheat, the
1286 library makes a note of <computeroutput>avail_in</computeroutput>
1287 at the time of the first call to
1288 <computeroutput>BZ2_bzCompress</computeroutput> which has
1289 <computeroutput>BZ_FINISH</computeroutput> as an action (ie, at
1290 the time the program has announced its intention to not supply
1291 any more input). By comparing this value with that of
1292 <computeroutput>avail_in</computeroutput> over subsequent calls
1293 to <computeroutput>BZ2_bzCompress</computeroutput>, the library
1294 can detect any attempts to slip in more data to compress. Any
1295 calls for which this is detected will return
1296 <computeroutput>BZ_SEQUENCE_ERROR</computeroutput>. This
1297 indicates a programming mistake which should be corrected.</para>
1299 <para>Instead of asking to finish, the calling program may ask
1300 <computeroutput>BZ2_bzCompress</computeroutput> to take all the
1301 remaining input, compress it and terminate the current
1302 (Burrows-Wheeler) compression block. This could be useful for
1303 error control purposes. The mechanism is analogous to that for
1304 finishing: call <computeroutput>BZ2_bzCompress</computeroutput>
1305 with an action of <computeroutput>BZ_FLUSH</computeroutput>,
1306 remove output data, and persist with the
1307 <computeroutput>BZ_FLUSH</computeroutput> action until the value
1308 <computeroutput>BZ_RUN</computeroutput> is returned. As with
1309 finishing, <computeroutput>BZ2_bzCompress</computeroutput>
1310 detects any attempt to provide more input data once the flush has
1313 <para>Once the flush is complete, the stream returns to the
1314 normal RUNNING state.</para>
1316 <para>This all sounds pretty complex, but isn't really. Here's a
1317 table which shows which actions are allowable in each state, what
1318 action will be taken, what the next state is, and what the
1319 non-error return values are. Note that you can't explicitly ask
1320 what state the stream is in, but nor do you need to -- it can be
1321 inferred from the values returned by
1322 <computeroutput>BZ2_bzCompress</computeroutput>.</para>
1326 Illegal. IDLE state only exists after BZ2_bzCompressEnd or
1327 before BZ2_bzCompressInit.
1328 Return value = BZ_SEQUENCE_ERROR
1331 Compress from next_in to next_out as much as possible.
1332 Next state = RUNNING
1333 Return value = BZ_RUN_OK
1336 Remember current value of next_in. Compress from next_in
1337 to next_out as much as possible, but do not accept any more input.
1338 Next state = FLUSHING
1339 Return value = BZ_FLUSH_OK
1342 Remember current value of next_in. Compress from next_in
1343 to next_out as much as possible, but do not accept any more input.
1344 Next state = FINISHING
1345 Return value = BZ_FINISH_OK
1348 Compress from next_in to next_out as much as possible,
1349 but do not accept any more input.
1350 If all the existing input has been used up and all compressed
1351 output has been removed
1352 Next state = RUNNING; Return value = BZ_RUN_OK
1354 Next state = FLUSHING; Return value = BZ_FLUSH_OK
1358 Return value = BZ_SEQUENCE_ERROR
1361 Compress from next_in to next_out as much as possible,
1362 but to not accept any more input.
1363 If all the existing input has been used up and all compressed
1364 output has been removed
1365 Next state = IDLE; Return value = BZ_STREAM_END
1367 Next state = FINISHING; Return value = BZ_FINISH_OK
1371 Return value = BZ_SEQUENCE_ERROR
1375 <para>That still looks complicated? Well, fair enough. The
1376 usual sequence of calls for compressing a load of data is:</para>
1380 <listitem><para>Get started with
1381 <computeroutput>BZ2_bzCompressInit</computeroutput>.</para></listitem>
1383 <listitem><para>Shovel data in and shlurp out its compressed form
1384 using zero or more calls of
1385 <computeroutput>BZ2_bzCompress</computeroutput> with action =
1386 <computeroutput>BZ_RUN</computeroutput>.</para></listitem>
1388 <listitem><para>Finish up. Repeatedly call
1389 <computeroutput>BZ2_bzCompress</computeroutput> with action =
1390 <computeroutput>BZ_FINISH</computeroutput>, copying out the
1391 compressed output, until
1392 <computeroutput>BZ_STREAM_END</computeroutput> is
1393 returned.</para></listitem> <listitem><para>Close up and go home. Call
1394 <computeroutput>BZ2_bzCompressEnd</computeroutput>.</para></listitem>
1398 <para>If the data you want to compress fits into your input
1399 buffer all at once, you can skip the calls of
1400 <computeroutput>BZ2_bzCompress ( ..., BZ_RUN )</computeroutput>
1401 and just do the <computeroutput>BZ2_bzCompress ( ..., BZ_FINISH
1402 )</computeroutput> calls.</para>
1404 <para>All required memory is allocated by
1405 <computeroutput>BZ2_bzCompressInit</computeroutput>. The
1406 compression library can accept any data at all (obviously). So
1407 you shouldn't get any error return values from the
1408 <computeroutput>BZ2_bzCompress</computeroutput> calls. If you
1410 <computeroutput>BZ_SEQUENCE_ERROR</computeroutput>, and indicate
1411 a bug in your programming.</para>
1413 <para>Trivial other possible return values:</para>
1417 if strm is NULL, or strm->s is NULL
1423 <sect2 id="bzCompress-end" xreflabel="BZ2_bzCompressEnd">
1424 <title><computeroutput>BZ2_bzCompressEnd</computeroutput></title>
1427 int BZ2_bzCompressEnd ( bz_stream *strm );
1430 <para>Releases all memory associated with a compression
1433 <para>Possible return values:</para>
1436 BZ_PARAM_ERROR if strm is NULL or strm->s is NULL
1443 <sect2 id="bzDecompress-init" xreflabel="BZ2_bzDecompressInit">
1444 <title><computeroutput>BZ2_bzDecompressInit</computeroutput></title>
1447 int BZ2_bzDecompressInit ( bz_stream *strm, int verbosity, int small );
1450 <para>Prepares for decompression. As with
1451 <computeroutput>BZ2_bzCompressInit</computeroutput>, a
1452 <computeroutput>bz_stream</computeroutput> record should be
1453 allocated and initialised before the call. Fields
1454 <computeroutput>bzalloc</computeroutput>,
1455 <computeroutput>bzfree</computeroutput> and
1456 <computeroutput>opaque</computeroutput> should be set if a custom
1457 memory allocator is required, or made
1458 <computeroutput>NULL</computeroutput> for the normal
1459 <computeroutput>malloc</computeroutput> /
1460 <computeroutput>free</computeroutput> routines. Upon return, the
1461 internal state will have been initialised, and
1462 <computeroutput>total_in</computeroutput> and
1463 <computeroutput>total_out</computeroutput> will be zero.</para>
1465 <para>For the meaning of parameter
1466 <computeroutput>verbosity</computeroutput>, see
1467 <computeroutput>BZ2_bzCompressInit</computeroutput>.</para>
1469 <para>If <computeroutput>small</computeroutput> is nonzero, the
1470 library will use an alternative decompression algorithm which
1471 uses less memory but at the cost of decompressing more slowly
1472 (roughly speaking, half the speed, but the maximum memory
1473 requirement drops to around 2300k). See <xref linkend="using"/>
1474 for more information on memory management.</para>
1476 <para>Note that the amount of memory needed to decompress a
1477 stream cannot be determined until the stream's header has been
1479 <computeroutput>BZ2_bzDecompressInit</computeroutput> succeeds, a
1480 subsequent <computeroutput>BZ2_bzDecompress</computeroutput>
1482 <computeroutput>BZ_MEM_ERROR</computeroutput>.</para>
1484 <para>Possible return values:</para>
1488 if the library has been mis-compiled
1490 if ( small != 0 && small != 1 )
1491 or (verbosity < 0 || verbosity > 4)
1493 if insufficient memory is available
1496 <para>Allowable next actions:</para>
1500 if BZ_OK was returned
1501 no specific action required in case of error
1507 <sect2 id="bzDecompress" xreflabel="BZ2_bzDecompress">
1508 <title><computeroutput>BZ2_bzDecompress</computeroutput></title>
1511 int BZ2_bzDecompress ( bz_stream *strm );
1514 <para>Provides more input and/out output buffer space for the
1515 library. The caller maintains input and output buffers, and uses
1516 <computeroutput>BZ2_bzDecompress</computeroutput> to transfer
1517 data between them.</para>
1519 <para>Before each call to
1520 <computeroutput>BZ2_bzDecompress</computeroutput>,
1521 <computeroutput>next_in</computeroutput> should point at the
1522 compressed data, and <computeroutput>avail_in</computeroutput>
1523 should indicate how many bytes the library may read.
1524 <computeroutput>BZ2_bzDecompress</computeroutput> updates
1525 <computeroutput>next_in</computeroutput>,
1526 <computeroutput>avail_in</computeroutput> and
1527 <computeroutput>total_in</computeroutput> to reflect the number
1528 of bytes it has read.</para>
1530 <para>Similarly, <computeroutput>next_out</computeroutput> should
1531 point to a buffer in which the uncompressed output is to be
1532 placed, with <computeroutput>avail_out</computeroutput>
1533 indicating how much output space is available.
1534 <computeroutput>BZ2_bzCompress</computeroutput> updates
1535 <computeroutput>next_out</computeroutput>,
1536 <computeroutput>avail_out</computeroutput> and
1537 <computeroutput>total_out</computeroutput> to reflect the number
1538 of bytes output.</para>
1540 <para>You may provide and remove as little or as much data as you
1541 like on each call of
1542 <computeroutput>BZ2_bzDecompress</computeroutput>. In the limit,
1543 it is acceptable to supply and remove data one byte at a time,
1544 although this would be terribly inefficient. You should always
1545 ensure that at least one byte of output space is available at
1548 <para>Use of <computeroutput>BZ2_bzDecompress</computeroutput> is
1550 <computeroutput>BZ2_bzCompress</computeroutput>.</para>
1552 <para>You should provide input and remove output as described
1553 above, and repeatedly call
1554 <computeroutput>BZ2_bzDecompress</computeroutput> until
1555 <computeroutput>BZ_STREAM_END</computeroutput> is returned.
1556 Appearance of <computeroutput>BZ_STREAM_END</computeroutput>
1557 denotes that <computeroutput>BZ2_bzDecompress</computeroutput>
1558 has detected the logical end of the compressed stream.
1559 <computeroutput>BZ2_bzDecompress</computeroutput> will not
1560 produce <computeroutput>BZ_STREAM_END</computeroutput> until all
1561 output data has been placed into the output buffer, so once
1562 <computeroutput>BZ_STREAM_END</computeroutput> appears, you are
1563 guaranteed to have available all the decompressed output, and
1564 <computeroutput>BZ2_bzDecompressEnd</computeroutput> can safely
1567 <para>If case of an error return value, you should call
1568 <computeroutput>BZ2_bzDecompressEnd</computeroutput> to clean up
1569 and release memory.</para>
1571 <para>Possible return values:</para>
1575 if strm is NULL or strm->s is NULL
1576 or strm->avail_out < 1
1578 if a data integrity error is detected in the compressed stream
1580 if the compressed stream doesn't begin with the right magic bytes
1582 if there wasn't enough memory available
1584 if the logical end of the data stream was detected and all
1585 output in has been consumed, eg s-->avail_out > 0
1590 <para>Allowable next actions:</para>
1594 if BZ_OK was returned
1602 <sect2 id="bzDecompress-end" xreflabel="BZ2_bzDecompressEnd">
1603 <title><computeroutput>BZ2_bzDecompressEnd</computeroutput></title>
1606 int BZ2_bzDecompressEnd ( bz_stream *strm );
1609 <para>Releases all memory associated with a decompression
1612 <para>Possible return values:</para>
1616 if strm is NULL or strm->s is NULL
1621 <para>Allowable next actions:</para>
1632 <sect1 id="hl-interface" xreflabel="High-level interface">
1633 <title>High-level interface</title>
1635 <para>This interface provides functions for reading and writing
1636 <computeroutput>bzip2</computeroutput> format files. First, some
1637 general points.</para>
1639 <itemizedlist mark='bullet'>
1641 <listitem><para>All of the functions take an
1642 <computeroutput>int*</computeroutput> first argument,
1643 <computeroutput>bzerror</computeroutput>. After each call,
1644 <computeroutput>bzerror</computeroutput> should be consulted
1645 first to determine the outcome of the call. If
1646 <computeroutput>bzerror</computeroutput> is
1647 <computeroutput>BZ_OK</computeroutput>, the call completed
1648 successfully, and only then should the return value of the
1649 function (if any) be consulted. If
1650 <computeroutput>bzerror</computeroutput> is
1651 <computeroutput>BZ_IO_ERROR</computeroutput>, there was an
1652 error reading/writing the underlying compressed file, and you
1653 should then consult <computeroutput>errno</computeroutput> /
1654 <computeroutput>perror</computeroutput> to determine the cause
1655 of the difficulty. <computeroutput>bzerror</computeroutput>
1656 may also be set to various other values; precise details are
1657 given on a per-function basis below.</para></listitem>
1659 <listitem><para>If <computeroutput>bzerror</computeroutput> indicates
1660 an error (ie, anything except
1661 <computeroutput>BZ_OK</computeroutput> and
1662 <computeroutput>BZ_STREAM_END</computeroutput>), you should
1664 <computeroutput>BZ2_bzReadClose</computeroutput> (or
1665 <computeroutput>BZ2_bzWriteClose</computeroutput>, depending on
1666 whether you are attempting to read or to write) to free up all
1667 resources associated with the stream. Once an error has been
1668 indicated, behaviour of all calls except
1669 <computeroutput>BZ2_bzReadClose</computeroutput>
1670 (<computeroutput>BZ2_bzWriteClose</computeroutput>) is
1671 undefined. The implication is that (1)
1672 <computeroutput>bzerror</computeroutput> should be checked
1673 after each call, and (2) if
1674 <computeroutput>bzerror</computeroutput> indicates an error,
1675 <computeroutput>BZ2_bzReadClose</computeroutput>
1676 (<computeroutput>BZ2_bzWriteClose</computeroutput>) should then
1677 be called to clean up.</para></listitem>
1679 <listitem><para>The <computeroutput>FILE*</computeroutput> arguments
1680 passed to <computeroutput>BZ2_bzReadOpen</computeroutput> /
1681 <computeroutput>BZ2_bzWriteOpen</computeroutput> should be set
1682 to binary mode. Most Unix systems will do this by default, but
1683 other platforms, including Windows and Mac, will not. If you
1684 omit this, you may encounter problems when moving code to new
1685 platforms.</para></listitem>
1687 <listitem><para>Memory allocation requests are handled by
1688 <computeroutput>malloc</computeroutput> /
1689 <computeroutput>free</computeroutput>. At present there is no
1690 facility for user-defined memory allocators in the file I/O
1691 functions (could easily be added, though).</para></listitem>
1697 <sect2 id="bzreadopen" xreflabel="BZ2_bzReadOpen">
1698 <title><computeroutput>BZ2_bzReadOpen</computeroutput></title>
1701 typedef void BZFILE;
1703 BZFILE *BZ2_bzReadOpen( int *bzerror, FILE *f,
1704 int verbosity, int small,
1705 void *unused, int nUnused );
1708 <para>Prepare to read compressed data from file handle
1709 <computeroutput>f</computeroutput>.
1710 <computeroutput>f</computeroutput> should refer to a file which
1711 has been opened for reading, and for which the error indicator
1712 (<computeroutput>ferror(f)</computeroutput>)is not set. If
1713 <computeroutput>small</computeroutput> is 1, the library will try
1714 to decompress using less memory, at the expense of speed.</para>
1716 <para>For reasons explained below,
1717 <computeroutput>BZ2_bzRead</computeroutput> will decompress the
1718 <computeroutput>nUnused</computeroutput> bytes starting at
1719 <computeroutput>unused</computeroutput>, before starting to read
1720 from the file <computeroutput>f</computeroutput>. At most
1721 <computeroutput>BZ_MAX_UNUSED</computeroutput> bytes may be
1722 supplied like this. If this facility is not required, you should
1723 pass <computeroutput>NULL</computeroutput> and
1724 <computeroutput>0</computeroutput> for
1725 <computeroutput>unused</computeroutput> and
1726 n<computeroutput>Unused</computeroutput> respectively.</para>
1728 <para>For the meaning of parameters
1729 <computeroutput>small</computeroutput> and
1730 <computeroutput>verbosity</computeroutput>, see
1731 <computeroutput>BZ2_bzDecompressInit</computeroutput>.</para>
1733 <para>The amount of memory needed to decompress a file cannot be
1734 determined until the file's header has been read. So it is
1735 possible that <computeroutput>BZ2_bzReadOpen</computeroutput>
1736 returns <computeroutput>BZ_OK</computeroutput> but a subsequent
1737 call of <computeroutput>BZ2_bzRead</computeroutput> will return
1738 <computeroutput>BZ_MEM_ERROR</computeroutput>.</para>
1740 <para>Possible assignments to
1741 <computeroutput>bzerror</computeroutput>:</para>
1745 if the library has been mis-compiled
1748 or small is neither 0 nor 1
1749 or ( unused == NULL && nUnused != 0 )
1750 or ( unused != NULL && !(0 <= nUnused <= BZ_MAX_UNUSED) )
1752 if ferror(f) is nonzero
1754 if insufficient memory is available
1759 <para>Possible return values:</para>
1762 Pointer to an abstract BZFILE
1768 <para>Allowable next actions:</para>
1780 <sect2 id="bzread" xreflabel="BZ2_bzRead">
1781 <title><computeroutput>BZ2_bzRead</computeroutput></title>
1784 int BZ2_bzRead ( int *bzerror, BZFILE *b, void *buf, int len );
1787 <para>Reads up to <computeroutput>len</computeroutput>
1788 (uncompressed) bytes from the compressed file
1789 <computeroutput>b</computeroutput> into the buffer
1790 <computeroutput>buf</computeroutput>. If the read was
1791 successful, <computeroutput>bzerror</computeroutput> is set to
1792 <computeroutput>BZ_OK</computeroutput> and the number of bytes
1793 read is returned. If the logical end-of-stream was detected,
1794 <computeroutput>bzerror</computeroutput> will be set to
1795 <computeroutput>BZ_STREAM_END</computeroutput>, and the number of
1796 bytes read is returned. All other
1797 <computeroutput>bzerror</computeroutput> values denote an
1800 <para><computeroutput>BZ2_bzRead</computeroutput> will supply
1801 <computeroutput>len</computeroutput> bytes, unless the logical
1802 stream end is detected or an error occurs. Because of this, it
1803 is possible to detect the stream end by observing when the number
1804 of bytes returned is less than the number requested.
1805 Nevertheless, this is regarded as inadvisable; you should instead
1806 check <computeroutput>bzerror</computeroutput> after every call
1808 <computeroutput>BZ_STREAM_END</computeroutput>.</para>
1810 <para>Internally, <computeroutput>BZ2_bzRead</computeroutput>
1811 copies data from the compressed file in chunks of size
1812 <computeroutput>BZ_MAX_UNUSED</computeroutput> bytes before
1813 decompressing it. If the file contains more bytes than strictly
1814 needed to reach the logical end-of-stream,
1815 <computeroutput>BZ2_bzRead</computeroutput> will almost certainly
1816 read some of the trailing data before signalling
1817 <computeroutput>BZ_SEQUENCE_END</computeroutput>. To collect the
1818 read but unused data once
1819 <computeroutput>BZ_SEQUENCE_END</computeroutput> has appeared,
1820 call <computeroutput>BZ2_bzReadGetUnused</computeroutput>
1822 <computeroutput>BZ2_bzReadClose</computeroutput>.</para>
1824 <para>Possible assignments to
1825 <computeroutput>bzerror</computeroutput>:</para>
1829 if b is NULL or buf is NULL or len < 0
1831 if b was opened with BZ2_bzWriteOpen
1833 if there is an error reading from the compressed file
1835 if the compressed file ended before
1836 the logical end-of-stream was detected
1838 if a data integrity error was detected in the compressed stream
1840 if the stream does not begin with the requisite header bytes
1841 (ie, is not a bzip2 data file). This is really
1842 a special case of BZ_DATA_ERROR.
1844 if insufficient memory was available
1846 if the logical end of stream was detected.
1851 <para>Possible return values:</para>
1854 number of bytes read
1855 if bzerror is BZ_OK or BZ_STREAM_END
1860 <para>Allowable next actions:</para>
1863 collect data from buf, then BZ2_bzRead or BZ2_bzReadClose
1865 collect data from buf, then BZ2_bzReadClose or BZ2_bzReadGetUnused
1866 if bzerror is BZ_SEQUENCE_END
1874 <sect2 id="bzreadgetunused" xreflabel="BZ2_bzReadGetUnused">
1875 <title><computeroutput>BZ2_bzReadGetUnused</computeroutput></title>
1878 void BZ2_bzReadGetUnused( int* bzerror, BZFILE *b,
1879 void** unused, int* nUnused );
1882 <para>Returns data which was read from the compressed file but
1883 was not needed to get to the logical end-of-stream.
1884 <computeroutput>*unused</computeroutput> is set to the address of
1885 the data, and <computeroutput>*nUnused</computeroutput> to the
1886 number of bytes. <computeroutput>*nUnused</computeroutput> will
1887 be set to a value between <computeroutput>0</computeroutput> and
1888 <computeroutput>BZ_MAX_UNUSED</computeroutput> inclusive.</para>
1890 <para>This function may only be called once
1891 <computeroutput>BZ2_bzRead</computeroutput> has signalled
1892 <computeroutput>BZ_STREAM_END</computeroutput> but before
1893 <computeroutput>BZ2_bzReadClose</computeroutput>.</para>
1895 <para>Possible assignments to
1896 <computeroutput>bzerror</computeroutput>:</para>
1901 or unused is NULL or nUnused is NULL
1903 if BZ_STREAM_END has not been signalled
1904 or if b was opened with BZ2_bzWriteOpen
1909 <para>Allowable next actions:</para>
1918 <sect2 id="bzreadclose" xreflabel="BZ2_bzReadClose">
1919 <title><computeroutput>BZ2_bzReadClose</computeroutput></title>
1922 void BZ2_bzReadClose ( int *bzerror, BZFILE *b );
1925 <para>Releases all memory pertaining to the compressed file
1926 <computeroutput>b</computeroutput>.
1927 <computeroutput>BZ2_bzReadClose</computeroutput> does not call
1928 <computeroutput>fclose</computeroutput> on the underlying file
1929 handle, so you should do that yourself if appropriate.
1930 <computeroutput>BZ2_bzReadClose</computeroutput> should be called
1931 to clean up after all error situations.</para>
1933 <para>Possible assignments to
1934 <computeroutput>bzerror</computeroutput>:</para>
1938 if b was opened with BZ2_bzOpenWrite
1943 <para>Allowable next actions:</para>
1952 <sect2 id="bzwriteopen" xreflabel="BZ2_bzWriteOpen">
1953 <title><computeroutput>BZ2_bzWriteOpen</computeroutput></title>
1956 BZFILE *BZ2_bzWriteOpen( int *bzerror, FILE *f,
1957 int blockSize100k, int verbosity,
1961 <para>Prepare to write compressed data to file handle
1962 <computeroutput>f</computeroutput>.
1963 <computeroutput>f</computeroutput> should refer to a file which
1964 has been opened for writing, and for which the error indicator
1965 (<computeroutput>ferror(f)</computeroutput>)is not set.</para>
1967 <para>For the meaning of parameters
1968 <computeroutput>blockSize100k</computeroutput>,
1969 <computeroutput>verbosity</computeroutput> and
1970 <computeroutput>workFactor</computeroutput>, see
1971 <computeroutput>BZ2_bzCompressInit</computeroutput>.</para>
1973 <para>All required memory is allocated at this stage, so if the
1974 call completes successfully,
1975 <computeroutput>BZ_MEM_ERROR</computeroutput> cannot be signalled
1976 by a subsequent call to
1977 <computeroutput>BZ2_bzWrite</computeroutput>.</para>
1979 <para>Possible assignments to
1980 <computeroutput>bzerror</computeroutput>:</para>
1984 if the library has been mis-compiled
1987 or blockSize100k < 1 or blockSize100k > 9
1989 if ferror(f) is nonzero
1991 if insufficient memory is available
1996 <para>Possible return values:</para>
1999 Pointer to an abstract BZFILE
2005 <para>Allowable next actions:</para>
2010 (you could go directly to BZ2_bzWriteClose, but this would be pretty pointless)
2018 <sect2 id="bzwrite" xreflabel="BZ2_bzWrite">
2019 <title><computeroutput>BZ2_bzWrite</computeroutput></title>
2022 void BZ2_bzWrite ( int *bzerror, BZFILE *b, void *buf, int len );
2025 <para>Absorbs <computeroutput>len</computeroutput> bytes from the
2026 buffer <computeroutput>buf</computeroutput>, eventually to be
2027 compressed and written to the file.</para>
2029 <para>Possible assignments to
2030 <computeroutput>bzerror</computeroutput>:</para>
2034 if b is NULL or buf is NULL or len < 0
2036 if b was opened with BZ2_bzReadOpen
2038 if there is an error writing the compressed file.
2046 <sect2 id="bzwriteclose" xreflabel="BZ2_bzWriteClose">
2047 <title><computeroutput>BZ2_bzWriteClose</computeroutput></title>
2050 void BZ2_bzWriteClose( int *bzerror, BZFILE* f,
2052 unsigned int* nbytes_in,
2053 unsigned int* nbytes_out );
2055 void BZ2_bzWriteClose64( int *bzerror, BZFILE* f,
2057 unsigned int* nbytes_in_lo32,
2058 unsigned int* nbytes_in_hi32,
2059 unsigned int* nbytes_out_lo32,
2060 unsigned int* nbytes_out_hi32 );
2063 <para>Compresses and flushes to the compressed file all data so
2064 far supplied by <computeroutput>BZ2_bzWrite</computeroutput>.
2065 The logical end-of-stream markers are also written, so subsequent
2066 calls to <computeroutput>BZ2_bzWrite</computeroutput> are
2067 illegal. All memory associated with the compressed file
2068 <computeroutput>b</computeroutput> is released.
2069 <computeroutput>fflush</computeroutput> is called on the
2070 compressed file, but it is not
2071 <computeroutput>fclose</computeroutput>'d.</para>
2073 <para>If <computeroutput>BZ2_bzWriteClose</computeroutput> is
2074 called to clean up after an error, the only action is to release
2075 the memory. The library records the error codes issued by
2076 previous calls, so this situation will be detected automatically.
2077 There is no attempt to complete the compression operation, nor to
2078 <computeroutput>fflush</computeroutput> the compressed file. You
2079 can force this behaviour to happen even in the case of no error,
2080 by passing a nonzero value to
2081 <computeroutput>abandon</computeroutput>.</para>
2083 <para>If <computeroutput>nbytes_in</computeroutput> is non-null,
2084 <computeroutput>*nbytes_in</computeroutput> will be set to be the
2085 total volume of uncompressed data handled. Similarly,
2086 <computeroutput>nbytes_out</computeroutput> will be set to the
2087 total volume of compressed data written. For compatibility with
2088 older versions of the library,
2089 <computeroutput>BZ2_bzWriteClose</computeroutput> only yields the
2090 lower 32 bits of these counts. Use
2091 <computeroutput>BZ2_bzWriteClose64</computeroutput> if you want
2092 the full 64 bit counts. These two functions are otherwise
2093 absolutely identical.</para>
2095 <para>Possible assignments to
2096 <computeroutput>bzerror</computeroutput>:</para>
2100 if b was opened with BZ2_bzReadOpen
2102 if there is an error writing the compressed file
2110 <sect2 id="embed" xreflabel="Handling embedded compressed data streams">
2111 <title>Handling embedded compressed data streams</title>
2113 <para>The high-level library facilitates use of
2114 <computeroutput>bzip2</computeroutput> data streams which form
2115 some part of a surrounding, larger data stream.</para>
2117 <itemizedlist mark='bullet'>
2119 <listitem><para>For writing, the library takes an open file handle,
2120 writes compressed data to it,
2121 <computeroutput>fflush</computeroutput>es it but does not
2122 <computeroutput>fclose</computeroutput> it. The calling
2123 application can write its own data before and after the
2124 compressed data stream, using that same file handle.</para></listitem>
2126 <listitem><para>Reading is more complex, and the facilities are not as
2127 general as they could be since generality is hard to reconcile
2128 with efficiency. <computeroutput>BZ2_bzRead</computeroutput>
2129 reads from the compressed file in blocks of size
2130 <computeroutput>BZ_MAX_UNUSED</computeroutput> bytes, and in
2131 doing so probably will overshoot the logical end of compressed
2132 stream. To recover this data once decompression has ended,
2133 call <computeroutput>BZ2_bzReadGetUnused</computeroutput> after
2134 the last call of <computeroutput>BZ2_bzRead</computeroutput>
2136 <computeroutput>BZ_STREAM_END</computeroutput>) but before
2138 <computeroutput>BZ2_bzReadClose</computeroutput>.</para></listitem>
2142 <para>This mechanism makes it easy to decompress multiple
2143 <computeroutput>bzip2</computeroutput> streams placed end-to-end.
2144 As the end of one stream, when
2145 <computeroutput>BZ2_bzRead</computeroutput> returns
2146 <computeroutput>BZ_STREAM_END</computeroutput>, call
2147 <computeroutput>BZ2_bzReadGetUnused</computeroutput> to collect
2148 the unused data (copy it into your own buffer somewhere). That
2149 data forms the start of the next compressed stream. To start
2150 uncompressing that next stream, call
2151 <computeroutput>BZ2_bzReadOpen</computeroutput> again, feeding in
2152 the unused data via the <computeroutput>unused</computeroutput> /
2153 <computeroutput>nUnused</computeroutput> parameters. Keep doing
2154 this until <computeroutput>BZ_STREAM_END</computeroutput> return
2155 coincides with the physical end of file
2156 (<computeroutput>feof(f)</computeroutput>). In this situation
2157 <computeroutput>BZ2_bzReadGetUnused</computeroutput> will of
2158 course return no data.</para>
2160 <para>This should give some feel for how the high-level interface
2161 can be used. If you require extra flexibility, you'll have to
2162 bite the bullet and get to grips with the low-level
2168 <sect2 id="std-rdwr" xreflabel="Standard file-reading/writing code">
2169 <title>Standard file-reading/writing code</title>
2171 <para>Here's how you'd write data to a compressed file:</para>
2177 char buf[ /* whatever size you like */ ];
2181 f = fopen ( "myfile.bz2", "w" );
2185 b = BZ2_bzWriteOpen( &bzerror, f, 9 );
2186 if (bzerror != BZ_OK) {
2187 BZ2_bzWriteClose ( b );
2191 while ( /* condition */ ) {
2192 /* get data to write into buf, and set nBuf appropriately */
2193 nWritten = BZ2_bzWrite ( &bzerror, b, buf, nBuf );
2194 if (bzerror == BZ_IO_ERROR) {
2195 BZ2_bzWriteClose ( &bzerror, b );
2200 BZ2_bzWriteClose( &bzerror, b );
2201 if (bzerror == BZ_IO_ERROR) {
2206 <para>And to read from a compressed file:</para>
2212 char buf[ /* whatever size you like */ ];
2216 f = fopen ( "myfile.bz2", "r" );
2220 b = BZ2_bzReadOpen ( &bzerror, f, 0, NULL, 0 );
2221 if ( bzerror != BZ_OK ) {
2222 BZ2_bzReadClose ( &bzerror, b );
2227 while ( bzerror == BZ_OK && /* arbitrary other conditions */) {
2228 nBuf = BZ2_bzRead ( &bzerror, b, buf, /* size of buf */ );
2229 if ( bzerror == BZ_OK ) {
2230 /* do something with buf[0 .. nBuf-1] */
2233 if ( bzerror != BZ_STREAM_END ) {
2234 BZ2_bzReadClose ( &bzerror, b );
2237 BZ2_bzReadClose ( &bzerror, b );
2246 <sect1 id="util-fns" xreflabel="Utility functions">
2247 <title>Utility functions</title>
2250 <sect2 id="bzbufftobuffcompress" xreflabel="BZ2_bzBuffToBuffCompress">
2251 <title><computeroutput>BZ2_bzBuffToBuffCompress</computeroutput></title>
2254 int BZ2_bzBuffToBuffCompress( char* dest,
2255 unsigned int* destLen,
2257 unsigned int sourceLen,
2263 <para>Attempts to compress the data in <computeroutput>source[0
2264 .. sourceLen-1]</computeroutput> into the destination buffer,
2265 <computeroutput>dest[0 .. *destLen-1]</computeroutput>. If the
2266 destination buffer is big enough,
2267 <computeroutput>*destLen</computeroutput> is set to the size of
2268 the compressed data, and <computeroutput>BZ_OK</computeroutput>
2269 is returned. If the compressed data won't fit,
2270 <computeroutput>*destLen</computeroutput> is unchanged, and
2271 <computeroutput>BZ_OUTBUFF_FULL</computeroutput> is
2274 <para>Compression in this manner is a one-shot event, done with a
2275 single call to this function. The resulting compressed data is a
2276 complete <computeroutput>bzip2</computeroutput> format data
2277 stream. There is no mechanism for making additional calls to
2278 provide extra input data. If you want that kind of mechanism,
2279 use the low-level interface.</para>
2281 <para>For the meaning of parameters
2282 <computeroutput>blockSize100k</computeroutput>,
2283 <computeroutput>verbosity</computeroutput> and
2284 <computeroutput>workFactor</computeroutput>, see
2285 <computeroutput>BZ2_bzCompressInit</computeroutput>.</para>
2287 <para>To guarantee that the compressed data will fit in its
2288 buffer, allocate an output buffer of size 1% larger than the
2289 uncompressed data, plus six hundred extra bytes.</para>
2291 <para><computeroutput>BZ2_bzBuffToBuffDecompress</computeroutput>
2292 will not write data at or beyond
2293 <computeroutput>dest[*destLen]</computeroutput>, even in case of
2294 buffer overflow.</para>
2296 <para>Possible return values:</para>
2300 if the library has been mis-compiled
2302 if dest is NULL or destLen is NULL
2303 or blockSize100k < 1 or blockSize100k > 9
2304 or verbosity < 0 or verbosity > 4
2305 or workFactor < 0 or workFactor > 250
2307 if insufficient memory is available
2309 if the size of the compressed data exceeds *destLen
2317 <sect2 id="bzbufftobuffdecompress" xreflabel="BZ2_bzBuffToBuffDecompress">
2318 <title><computeroutput>BZ2_bzBuffToBuffDecompress</computeroutput></title>
2321 int BZ2_bzBuffToBuffDecompress( char* dest,
2322 unsigned int* destLen,
2324 unsigned int sourceLen,
2329 <para>Attempts to decompress the data in <computeroutput>source[0
2330 .. sourceLen-1]</computeroutput> into the destination buffer,
2331 <computeroutput>dest[0 .. *destLen-1]</computeroutput>. If the
2332 destination buffer is big enough,
2333 <computeroutput>*destLen</computeroutput> is set to the size of
2334 the uncompressed data, and <computeroutput>BZ_OK</computeroutput>
2335 is returned. If the compressed data won't fit,
2336 <computeroutput>*destLen</computeroutput> is unchanged, and
2337 <computeroutput>BZ_OUTBUFF_FULL</computeroutput> is
2340 <para><computeroutput>source</computeroutput> is assumed to hold
2341 a complete <computeroutput>bzip2</computeroutput> format data
2343 <computeroutput>BZ2_bzBuffToBuffDecompress</computeroutput> tries
2344 to decompress the entirety of the stream into the output
2347 <para>For the meaning of parameters
2348 <computeroutput>small</computeroutput> and
2349 <computeroutput>verbosity</computeroutput>, see
2350 <computeroutput>BZ2_bzDecompressInit</computeroutput>.</para>
2352 <para>Because the compression ratio of the compressed data cannot
2353 be known in advance, there is no easy way to guarantee that the
2354 output buffer will be big enough. You may of course make
2355 arrangements in your code to record the size of the uncompressed
2356 data, but such a mechanism is beyond the scope of this
2359 <para><computeroutput>BZ2_bzBuffToBuffDecompress</computeroutput>
2360 will not write data at or beyond
2361 <computeroutput>dest[*destLen]</computeroutput>, even in case of
2362 buffer overflow.</para>
2364 <para>Possible return values:</para>
2368 if the library has been mis-compiled
2370 if dest is NULL or destLen is NULL
2371 or small != 0 && small != 1
2372 or verbosity < 0 or verbosity > 4
2374 if insufficient memory is available
2376 if the size of the compressed data exceeds *destLen
2378 if a data integrity error was detected in the compressed data
2380 if the compressed data doesn't begin with the right magic bytes
2382 if the compressed data ends unexpectedly
2392 <sect1 id="zlib-compat" xreflabel="zlib compatibility functions">
2393 <title><computeroutput>zlib</computeroutput> compatibility functions</title>
2395 <para>Yoshioka Tsuneo has contributed some functions to give
2396 better <computeroutput>zlib</computeroutput> compatibility.
2397 These functions are <computeroutput>BZ2_bzopen</computeroutput>,
2398 <computeroutput>BZ2_bzread</computeroutput>,
2399 <computeroutput>BZ2_bzwrite</computeroutput>,
2400 <computeroutput>BZ2_bzflush</computeroutput>,
2401 <computeroutput>BZ2_bzclose</computeroutput>,
2402 <computeroutput>BZ2_bzerror</computeroutput> and
2403 <computeroutput>BZ2_bzlibVersion</computeroutput>. These
2404 functions are not (yet) officially part of the library. If they
2405 break, you get to keep all the pieces. Nevertheless, I think
2406 they work ok.</para>
2409 typedef void BZFILE;
2411 const char * BZ2_bzlibVersion ( void );
2414 <para>Returns a string indicating the library version.</para>
2417 BZFILE * BZ2_bzopen ( const char *path, const char *mode );
2418 BZFILE * BZ2_bzdopen ( int fd, const char *mode );
2421 <para>Opens a <computeroutput>.bz2</computeroutput> file for
2422 reading or writing, using either its name or a pre-existing file
2423 descriptor. Analogous to <computeroutput>fopen</computeroutput>
2424 and <computeroutput>fdopen</computeroutput>.</para>
2427 int BZ2_bzread ( BZFILE* b, void* buf, int len );
2428 int BZ2_bzwrite ( BZFILE* b, void* buf, int len );
2431 <para>Reads/writes data from/to a previously opened
2432 <computeroutput>BZFILE</computeroutput>. Analogous to
2433 <computeroutput>fread</computeroutput> and
2434 <computeroutput>fwrite</computeroutput>.</para>
2437 int BZ2_bzflush ( BZFILE* b );
2438 void BZ2_bzclose ( BZFILE* b );
2441 <para>Flushes/closes a <computeroutput>BZFILE</computeroutput>.
2442 <computeroutput>BZ2_bzflush</computeroutput> doesn't actually do
2443 anything. Analogous to <computeroutput>fflush</computeroutput>
2444 and <computeroutput>fclose</computeroutput>.</para>
2447 const char * BZ2_bzerror ( BZFILE *b, int *errnum )
2450 <para>Returns a string describing the more recent error status of
2451 <computeroutput>b</computeroutput>, and also sets
2452 <computeroutput>*errnum</computeroutput> to its numerical
2458 <sect1 id="stdio-free"
2459 xreflabel="Using the library in a stdio-free environment">
2460 <title>Using the library in a <computeroutput>stdio</computeroutput>-free environment</title>
2463 <sect2 id="stdio-bye" xreflabel="Getting rid of stdio">
2464 <title>Getting rid of <computeroutput>stdio</computeroutput></title>
2466 <para>In a deeply embedded application, you might want to use
2467 just the memory-to-memory functions. You can do this
2468 conveniently by compiling the library with preprocessor symbol
2469 <computeroutput>BZ_NO_STDIO</computeroutput> defined. Doing this
2470 gives you a library containing only the following eight
2473 <para><computeroutput>BZ2_bzCompressInit</computeroutput>,
2474 <computeroutput>BZ2_bzCompress</computeroutput>,
2475 <computeroutput>BZ2_bzCompressEnd</computeroutput>
2476 <computeroutput>BZ2_bzDecompressInit</computeroutput>,
2477 <computeroutput>BZ2_bzDecompress</computeroutput>,
2478 <computeroutput>BZ2_bzDecompressEnd</computeroutput>
2479 <computeroutput>BZ2_bzBuffToBuffCompress</computeroutput>,
2480 <computeroutput>BZ2_bzBuffToBuffDecompress</computeroutput></para>
2482 <para>When compiled like this, all functions will ignore
2483 <computeroutput>verbosity</computeroutput> settings.</para>
2488 <sect2 id="critical-error" xreflabel="Critical error handling">
2489 <title>Critical error handling</title>
2491 <para><computeroutput>libbzip2</computeroutput> contains a number
2492 of internal assertion checks which should, needless to say, never
2493 be activated. Nevertheless, if an assertion should fail,
2494 behaviour depends on whether or not the library was compiled with
2495 <computeroutput>BZ_NO_STDIO</computeroutput> set.</para>
2497 <para>For a normal compile, an assertion failure yields the
2501 <para>bzip2/libbzip2: internal error number N.</para>
2502 <para>This is a bug in bzip2/libbzip2, &bz-version; of &bz-date;.
2503 Please report it to me at: &bz-email;. If this happened
2504 when you were using some program which uses libbzip2 as a
2505 component, you should also report this bug to the author(s)
2506 of that program. Please make an effort to report this bug;
2507 timely and accurate bug reports eventually lead to higher
2508 quality software. Thanks. Julian Seward, &bz-date;.
2509 </para></blockquote>
2511 <para>where <computeroutput>N</computeroutput> is some error code
2512 number. If <computeroutput>N == 1007</computeroutput>, it also
2513 prints some extra text advising the reader that unreliable memory
2514 is often associated with internal error 1007. (This is a
2515 frequently-observed-phenomenon with versions 1.0.0/1.0.1).</para>
2517 <para><computeroutput>exit(3)</computeroutput> is then
2520 <para>For a <computeroutput>stdio</computeroutput>-free library,
2521 assertion failures result in a call to a function declared
2525 extern void bz_internal_error ( int errcode );
2528 <para>The relevant code is passed as a parameter. You should
2529 supply such a function.</para>
2531 <para>In either case, once an assertion failure has occurred, any
2532 <computeroutput>bz_stream</computeroutput> records involved can
2533 be regarded as invalid. You should not attempt to resume normal
2534 operation with them.</para>
2536 <para>You may, of course, change critical error handling to suit
2537 your needs. As I said above, critical errors indicate bugs in
2538 the library and should not occur. All "normal" error situations
2539 are indicated via error return codes from functions, and can be
2540 recovered from.</para>
2547 <sect1 id="win-dll" xreflabel="Making a Windows DLL">
2548 <title>Making a Windows DLL</title>
2550 <para>Everything related to Windows has been contributed by
2552 (<computeroutput>tsuneo@rr.iij4u.or.jp</computeroutput>), so
2553 you should send your queries to him (but perhaps Cc: me,
2554 <computeroutput>&bz-email;</computeroutput>).</para>
2556 <para>My vague understanding of what to do is: using Visual C++
2557 5.0, open the project file
2558 <computeroutput>libbz2.dsp</computeroutput>, and build. That's
2561 <para>If you can't open the project file for some reason, make a
2562 new one, naming these files:
2563 <computeroutput>blocksort.c</computeroutput>,
2564 <computeroutput>bzlib.c</computeroutput>,
2565 <computeroutput>compress.c</computeroutput>,
2566 <computeroutput>crctable.c</computeroutput>,
2567 <computeroutput>decompress.c</computeroutput>,
2568 <computeroutput>huffman.c</computeroutput>,
2569 <computeroutput>randtable.c</computeroutput> and
2570 <computeroutput>libbz2.def</computeroutput>. You will also need
2571 to name the header files <computeroutput>bzlib.h</computeroutput>
2572 and <computeroutput>bzlib_private.h</computeroutput>.</para>
2574 <para>If you don't use VC++, you may need to define the
2576 <computeroutput>_WIN32</computeroutput>.</para>
2578 <para>Finally, <computeroutput>dlltest.c</computeroutput> is a
2579 sample program using the DLL. It has a project file,
2580 <computeroutput>dlltest.dsp</computeroutput>.</para>
2582 <para>If you just want a makefile for Visual C, have a look at
2583 <computeroutput>makefile.msc</computeroutput>.</para>
2585 <para>Be aware that if you compile
2586 <computeroutput>bzip2</computeroutput> itself on Win32, you must
2587 set <computeroutput>BZ_UNIX</computeroutput> to 0 and
2588 <computeroutput>BZ_LCCWIN32</computeroutput> to 1, in the file
2589 <computeroutput>bzip2.c</computeroutput>, before compiling.
2590 Otherwise the resulting binary won't work correctly.</para>
2592 <para>I haven't tried any of this stuff myself, but it all looks
2601 <chapter id="misc" xreflabel="Miscellanea">
2602 <title>Miscellanea</title>
2604 <para>These are just some random thoughts of mine. Your mileage
2608 <sect1 id="limits" xreflabel="Limitations of the compressed file format">
2609 <title>Limitations of the compressed file format</title>
2611 <para><computeroutput>bzip2-1.0.X</computeroutput>,
2612 <computeroutput>0.9.5</computeroutput> and
2613 <computeroutput>0.9.0</computeroutput> use exactly the same file
2614 format as the original version,
2615 <computeroutput>bzip2-0.1</computeroutput>. This decision was
2616 made in the interests of stability. Creating yet another
2617 incompatible compressed file format would create further
2618 confusion and disruption for users.</para>
2620 <para>Nevertheless, this is not a painless decision. Development
2621 work since the release of
2622 <computeroutput>bzip2-0.1</computeroutput> in August 1997 has
2623 shown complexities in the file format which slow down
2624 decompression and, in retrospect, are unnecessary. These
2627 <itemizedlist mark='bullet'>
2629 <listitem><para>The run-length encoder, which is the first of the
2630 compression transformations, is entirely irrelevant. The
2631 original purpose was to protect the sorting algorithm from the
2632 very worst case input: a string of repeated symbols. But
2633 algorithm steps Q6a and Q6b in the original Burrows-Wheeler
2634 technical report (SRC-124) show how repeats can be handled
2635 without difficulty in block sorting.</para></listitem>
2637 <listitem><para>The randomisation mechanism doesn't really need to be
2638 there. Udi Manber and Gene Myers published a suffix array
2639 construction algorithm a few years back, which can be employed
2640 to sort any block, no matter how repetitive, in O(N log N)
2641 time. Subsequent work by Kunihiko Sadakane has produced a
2642 derivative O(N (log N)^2) algorithm which usually outperforms
2643 the Manber-Myers algorithm.</para>
2645 <para>I could have changed to Sadakane's algorithm, but I find
2646 it to be slower than <computeroutput>bzip2</computeroutput>'s
2647 existing algorithm for most inputs, and the randomisation
2648 mechanism protects adequately against bad cases. I didn't
2649 think it was a good tradeoff to make. Partly this is due to
2650 the fact that I was not flooded with email complaints about
2651 <computeroutput>bzip2-0.1</computeroutput>'s performance on
2652 repetitive data, so perhaps it isn't a problem for real
2655 <para>Probably the best long-term solution, and the one I have
2656 incorporated into 0.9.5 and above, is to use the existing
2657 sorting algorithm initially, and fall back to a O(N (log N)^2)
2658 algorithm if the standard algorithm gets into
2659 difficulties.</para></listitem>
2661 <listitem><para>The compressed file format was never designed to be
2662 handled by a library, and I have had to jump though some hoops
2663 to produce an efficient implementation of decompression. It's
2664 a bit hairy. Try passing
2665 <computeroutput>decompress.c</computeroutput> through the C
2666 preprocessor and you'll see what I mean. Much of this
2667 complexity could have been avoided if the compressed size of
2668 each block of data was recorded in the data stream.</para></listitem>
2670 <listitem><para>An Adler-32 checksum, rather than a CRC32 checksum,
2671 would be faster to compute.</para></listitem>
2675 <para>It would be fair to say that the
2676 <computeroutput>bzip2</computeroutput> format was frozen before I
2677 properly and fully understood the performance consequences of
2680 <para>Improvements which I was able to incorporate into 0.9.0,
2681 despite using the same file format, are:</para>
2683 <itemizedlist mark='bullet'>
2685 <listitem><para>Single array implementation of the inverse BWT. This
2686 significantly speeds up decompression, presumably because it
2687 reduces the number of cache misses.</para></listitem>
2689 <listitem><para>Faster inverse MTF transform for large MTF values.
2690 The new implementation is based on the notion of sliding blocks
2691 of values.</para></listitem>
2693 <listitem><para><computeroutput>bzip2-0.9.0</computeroutput> now reads
2694 and writes files with <computeroutput>fread</computeroutput>
2695 and <computeroutput>fwrite</computeroutput>; version 0.1 used
2696 <computeroutput>putc</computeroutput> and
2697 <computeroutput>getc</computeroutput>. Duh! Well, you live
2698 and learn.</para></listitem>
2702 <para>Further ahead, it would be nice to be able to do random
2703 access into files. This will require some careful design of
2704 compressed file formats.</para>
2709 <sect1 id="port-issues" xreflabel="Portability issues">
2710 <title>Portability issues</title>
2712 <para>After some consideration, I have decided not to use GNU
2713 <computeroutput>autoconf</computeroutput> to configure 0.9.5 or
2716 <para><computeroutput>autoconf</computeroutput>, admirable and
2717 wonderful though it is, mainly assists with portability problems
2718 between Unix-like platforms. But
2719 <computeroutput>bzip2</computeroutput> doesn't have much in the
2720 way of portability problems on Unix; most of the difficulties
2721 appear when porting to the Mac, or to Microsoft's operating
2722 systems. <computeroutput>autoconf</computeroutput> doesn't help
2723 in those cases, and brings in a whole load of new
2726 <para>Most people should be able to compile the library and
2727 program under Unix straight out-of-the-box, so to speak,
2728 especially if you have a version of GNU C available.</para>
2730 <para>There are a couple of
2731 <computeroutput>__inline__</computeroutput> directives in the
2732 code. GNU C (<computeroutput>gcc</computeroutput>) should be
2733 able to handle them. If you're not using GNU C, your C compiler
2734 shouldn't see them at all. If your compiler does, for some
2735 reason, see them and doesn't like them, just
2736 <computeroutput>#define</computeroutput>
2737 <computeroutput>__inline__</computeroutput> to be
2738 <computeroutput>/* */</computeroutput>. One easy way to do this
2739 is to compile with the flag
2740 <computeroutput>-D__inline__=</computeroutput>, which should be
2741 understood by most Unix compilers.</para>
2743 <para>If you still have difficulties, try compiling with the
2744 macro <computeroutput>BZ_STRICT_ANSI</computeroutput> defined.
2745 This should enable you to build the library in a strictly ANSI
2746 compliant environment. Building the program itself like this is
2747 dangerous and not supported, since you remove
2748 <computeroutput>bzip2</computeroutput>'s checks against
2749 compressing directories, symbolic links, devices, and other
2750 not-really-a-file entities. This could cause filesystem
2753 <para>One other thing: if you create a
2754 <computeroutput>bzip2</computeroutput> binary for public distribution,
2755 please consider linking it statically (<computeroutput>gcc
2756 -static</computeroutput>). This avoids all sorts of library-version
2757 issues that others may encounter later on.</para>
2759 <para>If you build <computeroutput>bzip2</computeroutput> on
2760 Win32, you must set <computeroutput>BZ_UNIX</computeroutput> to 0
2761 and <computeroutput>BZ_LCCWIN32</computeroutput> to 1, in the
2762 file <computeroutput>bzip2.c</computeroutput>, before compiling.
2763 Otherwise the resulting binary won't work correctly.</para>
2768 <sect1 id="bugs" xreflabel="Reporting bugs">
2769 <title>Reporting bugs</title>
2771 <para>I tried pretty hard to make sure
2772 <computeroutput>bzip2</computeroutput> is bug free, both by
2773 design and by testing. Hopefully you'll never need to read this
2774 section for real.</para>
2776 <para>Nevertheless, if <computeroutput>bzip2</computeroutput> dies
2777 with a segmentation fault, a bus error or an internal assertion
2778 failure, it will ask you to email me a bug report. Experience from
2779 years of feedback of bzip2 users indicates that almost all these
2780 problems can be traced to either compiler bugs or hardware
2783 <itemizedlist mark='bullet'>
2785 <listitem><para>Recompile the program with no optimisation, and
2786 see if it works. And/or try a different compiler. I heard all
2787 sorts of stories about various flavours of GNU C (and other
2788 compilers) generating bad code for
2789 <computeroutput>bzip2</computeroutput>, and I've run across two
2790 such examples myself.</para>
2792 <para>2.7.X versions of GNU C are known to generate bad code
2793 from time to time, at high optimisation levels. If you get
2794 problems, try using the flags
2795 <computeroutput>-O2</computeroutput>
2796 <computeroutput>-fomit-frame-pointer</computeroutput>
2797 <computeroutput>-fno-strength-reduce</computeroutput>. You
2798 should specifically <emphasis>not</emphasis> use
2799 <computeroutput>-funroll-loops</computeroutput>.</para>
2801 <para>You may notice that the Makefile runs six tests as part
2802 of the build process. If the program passes all of these, it's
2803 a pretty good (but not 100%) indication that the compiler has
2804 done its job correctly.</para></listitem>
2806 <listitem><para>If <computeroutput>bzip2</computeroutput>
2807 crashes randomly, and the crashes are not repeatable, you may
2808 have a flaky memory subsystem.
2809 <computeroutput>bzip2</computeroutput> really hammers your
2810 memory hierarchy, and if it's a bit marginal, you may get these
2811 problems. Ditto if your disk or I/O subsystem is slowly
2812 failing. Yup, this really does happen.</para>
2814 <para>Try using a different machine of the same type, and see
2815 if you can repeat the problem.</para></listitem>
2817 <listitem><para>This isn't really a bug, but ... If
2818 <computeroutput>bzip2</computeroutput> tells you your file is
2819 corrupted on decompression, and you obtained the file via FTP,
2820 there is a possibility that you forgot to tell FTP to do a
2821 binary mode transfer. That absolutely will cause the file to
2822 be non-decompressible. You'll have to transfer it
2823 again.</para></listitem>
2827 <para>If you've incorporated
2828 <computeroutput>libbzip2</computeroutput> into your own program
2829 and are getting problems, please, please, please, check that the
2830 parameters you are passing in calls to the library, are correct,
2831 and in accordance with what the documentation says is allowable.
2832 I have tried to make the library robust against such problems,
2833 but I'm sure I haven't succeeded.</para>
2835 <para>Finally, if the above comments don't help, you'll have to
2836 send me a bug report. Now, it's just amazing how many people
2837 will send me a bug report saying something like:</para>
2840 bzip2 crashed with segmentation fault on my machine
2843 <para>and absolutely nothing else. Needless to say, a such a
2844 report is <emphasis>totally, utterly, completely and
2845 comprehensively 100% useless; a waste of your time, my time, and
2846 net bandwidth</emphasis>. With no details at all, there's no way
2847 I can possibly begin to figure out what the problem is.</para>
2849 <para>The rules of the game are: facts, facts, facts. Don't omit
2850 them because "oh, they won't be relevant". At the bare
2854 Machine type. Operating system version.
2855 Exact version of bzip2 (do bzip2 -V).
2856 Exact version of the compiler used.
2857 Flags passed to the compiler.
2860 <para>However, the most important single thing that will help me
2861 is the file that you were trying to compress or decompress at the
2862 time the problem happened. Without that, my ability to do
2863 anything more than speculate about the cause, is limited.</para>
2868 <sect1 id="package" xreflabel="Did you get the right package?">
2869 <title>Did you get the right package?</title>
2871 <para><computeroutput>bzip2</computeroutput> is a resource hog.
2872 It soaks up large amounts of CPU cycles and memory. Also, it
2873 gives very large latencies. In the worst case, you can feed many
2874 megabytes of uncompressed data into the library before getting
2875 any compressed output, so this probably rules out applications
2876 requiring interactive behaviour.</para>
2878 <para>These aren't faults of my implementation, I hope, but more
2879 an intrinsic property of the Burrows-Wheeler transform
2880 (unfortunately). Maybe this isn't what you want.</para>
2882 <para>If you want a compressor and/or library which is faster,
2883 uses less memory but gets pretty good compression, and has
2884 minimal latency, consider Jean-loup Gailly's and Mark Adler's
2885 work, <computeroutput>zlib-1.2.1</computeroutput> and
2886 <computeroutput>gzip-1.2.4</computeroutput>. Look for them at
2887 <ulink url="http://www.zlib.org">http://www.zlib.org</ulink> and
2888 <ulink url="http://www.gzip.org">http://www.gzip.org</ulink>
2889 respectively.</para>
2891 <para>For something faster and lighter still, you might try Markus F
2892 X J Oberhumer's <computeroutput>LZO</computeroutput> real-time
2893 compression/decompression library, at
2894 <ulink url="http://www.oberhumer.com/opensource">http://www.oberhumer.com/opensource</ulink>.</para>
2900 <sect1 id="reading" xreflabel="Further Reading">
2901 <title>Further Reading</title>
2903 <para><computeroutput>bzip2</computeroutput> is not research
2904 work, in the sense that it doesn't present any new ideas.
2905 Rather, it's an engineering exercise based on existing
2908 <para>Four documents describe essentially all the ideas behind
2909 <computeroutput>bzip2</computeroutput>:</para>
2911 <literallayout>Michael Burrows and D. J. Wheeler:
2912 "A block-sorting lossless data compression algorithm"
2914 Digital SRC Research Report 124.
2915 ftp://ftp.digital.com/pub/DEC/SRC/research-reports/SRC-124.ps.gz
2916 If you have trouble finding it, try searching at the
2917 New Zealand Digital Library, http://www.nzdl.org.
2919 Daniel S. Hirschberg and Debra A. LeLewer
2920 "Efficient Decoding of Prefix Codes"
2921 Communications of the ACM, April 1990, Vol 33, Number 4.
2922 You might be able to get an electronic copy of this
2923 from the ACM Digital Library.
2926 Program bred3.c and accompanying document bred3.ps.
2927 This contains the idea behind the multi-table Huffman coding scheme.
2928 ftp://ftp.cl.cam.ac.uk/users/djw3/
2930 Jon L. Bentley and Robert Sedgewick
2931 "Fast Algorithms for Sorting and Searching Strings"
2932 Available from Sedgewick's web page,
2933 www.cs.princeton.edu/~rs
2936 <para>The following paper gives valuable additional insights into
2937 the algorithm, but is not immediately the basis of any code used
2940 <literallayout>Peter Fenwick:
2941 Block Sorting Text Compression
2942 Proceedings of the 19th Australasian Computer Science Conference,
2943 Melbourne, Australia. Jan 31 - Feb 2, 1996.
2944 ftp://ftp.cs.auckland.ac.nz/pub/peter-f/ACSC96paper.ps</literallayout>
2946 <para>Kunihiko Sadakane's sorting algorithm, mentioned above, is
2947 available from:</para>
2949 <literallayout>http://naomi.is.s.u-tokyo.ac.jp/~sada/papers/Sada98b.ps.gz
2952 <para>The Manber-Myers suffix array construction algorithm is
2953 described in a paper available from:</para>
2955 <literallayout>http://www.cs.arizona.edu/people/gene/PAPERS/suffix.ps
2958 <para>Finally, the following papers document some
2959 investigations I made into the performance of sorting
2960 and decompression algorithms:</para>
2962 <literallayout>Julian Seward
2963 On the Performance of BWT Sorting Algorithms
2964 Proceedings of the IEEE Data Compression Conference 2000
2965 Snowbird, Utah. 28-30 March 2000.
2968 Space-time Tradeoffs in the Inverse B-W Transform
2969 Proceedings of the IEEE Data Compression Conference 2001
2970 Snowbird, Utah. 27-29 March 2001.