1 /**************************************************************************
3 * Copyright 2013-2014 RAD Game Tools and Valve Software
4 * Copyright 2010-2014 Rich Geldreich and Tenacious Software LLC
7 * Permission is hereby granted, free of charge, to any person obtaining a copy
8 * of this software and associated documentation files (the "Software"), to deal
9 * in the Software without restriction, including without limitation the rights
10 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 * copies of the Software, and to permit persons to whom the Software is
12 * furnished to do so, subject to the following conditions:
14 * The above copyright notice and this permission notice shall be included in
15 * all copies or substantial portions of the Software.
17 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25 **************************************************************************/
27 /* miniz.c v1.15 - public domain deflate/inflate, zlib-subset, ZIP reading/writing/appending, PNG writing
28 See "unlicense" statement at the end of this file.
29 Rich Geldreich <richgel99@gmail.com>, last updated Oct. 13, 2013
30 Implements RFC 1950: http://www.ietf.org/rfc/rfc1950.txt and RFC 1951: http://www.ietf.org/rfc/rfc1951.txt
32 Most API's defined in miniz.c are optional. For example, to disable the archive related functions just define
33 MINIZ_NO_ARCHIVE_APIS, or to get rid of all stdio usage define MINIZ_NO_STDIO (see the list below for more macros).
36 10/13/13 v1.15 - Interim bugfix release while I work on the next major release with Zip64 support (almost there!):
37 - Critical fix for the MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY bug (thanks kahmyong.moon@hp.com) which could cause locate files to not find files. This bug
38 would only have occured in earlier versions if you explicitly used this flag, OR if you used mz_zip_extract_archive_file_to_heap() or mz_zip_add_mem_to_archive_file_in_place()
39 (which used this flag). If you can't switch to v1.15 but want to fix this bug, just remove the uses of this flag from both helper funcs (and of course don't use the flag).
40 - Bugfix in mz_zip_reader_extract_to_mem_no_alloc() from kymoon when pUser_read_buf is not NULL and compressed size is > uncompressed size
41 - Fixing mz_zip_reader_extract_*() funcs so they don't try to extract compressed data from directory entries, to account for weird zipfiles which contain zero-size compressed data on dir entries.
42 Hopefully this fix won't cause any issues on weird zip archives, because it assumes the low 16-bits of zip external attributes are DOS attributes (which I believe they always are in practice).
43 - Fixing mz_zip_reader_is_file_a_directory() so it doesn't check the internal attributes, just the filename and external attributes
44 - mz_zip_reader_init_file() - missing MZ_FCLOSE() call if the seek failed
45 - Added cmake support for Linux builds which builds all the examples, tested with clang v3.3 and gcc v4.6.
46 - Clang fix for tdefl_write_image_to_png_file_in_memory() from toffaletti
47 - Merged MZ_FORCEINLINE fix from hdeanclark
48 - Fix <time.h> include before config #ifdef, thanks emil.brink
49 - Added tdefl_write_image_to_png_file_in_memory_ex(): supports Y flipping (super useful for OpenGL apps), and explicit control over the compression level (so you can
50 set it to 1 for real-time compression).
51 - Merged in some compiler fixes from paulharris's github repro.
52 - Retested this build under Windows (VS 2010, including static analysis), tcc 0.9.26, gcc v4.6 and clang v3.3.
53 - Added example6.c, which dumps an image of the mandelbrot set to a PNG file.
54 - Modified example2 to help test the MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY flag more.
55 5/20/12 v1.14 - MinGW32/64 GCC 4.6.1 compiler fixes: added MZ_FORCEINLINE, #include <time.h> (thanks fermtect).
56 5/19/12 v1.13 - From jason@cornsyrup.org and kelwert@mtu.edu - Fix mz_crc32() so it doesn't compute the wrong CRC-32's when mz_ulong is 64-bit.
57 - Temporarily/locally slammed in "typedef unsigned long mz_ulong" and re-ran a randomized regression test on ~500k files.
58 - Eliminated a bunch of warnings when compiling with GCC 32-bit/64.
59 - Ran all examples, miniz.c, and tinfl.c through MSVC 2008's /analyze (static analysis) option and fixed all warnings (except for the silly
60 "Use of the comma-operator in a tested expression.." analysis warning, which I purposely use to work around a MSVC compiler warning).
61 - Created 32-bit and 64-bit Codeblocks projects/workspace. Built and tested Linux executables. The codeblocks workspace is compatible with Linux+Win32/x64.
62 - Added miniz_tester solution/project, which is a useful little app derived from LZHAM's tester app that I use as part of the regression test.
63 - Ran miniz.c and tinfl.c through another series of regression testing on ~500,000 files and archives.
64 - Modified example5.c so it purposely disables a bunch of high-level functionality (MINIZ_NO_STDIO, etc.). (Thanks to corysama for the MINIZ_NO_STDIO bug report.)
65 - Fix ftell() usage in examples so they exit with an error on files which are too large (a limitation of the examples, not miniz itself).
66 4/12/12 v1.12 - More comments, added low-level example5.c, fixed a couple minor level_and_flags issues in the archive API's.
67 level_and_flags can now be set to MZ_DEFAULT_COMPRESSION. Thanks to Bruce Dawson <bruced@valvesoftware.com> for the feedback/bug report.
68 5/28/11 v1.11 - Added statement from unlicense.org
69 5/27/11 v1.10 - Substantial compressor optimizations:
70 - Level 1 is now ~4x faster than before. The L1 compressor's throughput now varies between 70-110MB/sec. on a
71 - Core i7 (actual throughput varies depending on the type of data, and x64 vs. x86).
72 - Improved baseline L2-L9 compression perf. Also, greatly improved compression perf. issues on some file types.
73 - Refactored the compression code for better readability and maintainability.
74 - Added level 10 compression level (L10 has slightly better ratio than level 9, but could have a potentially large
75 drop in throughput on some files).
76 5/15/11 v1.09 - Initial stable release.
78 * Low-level Deflate/Inflate implementation notes:
80 Compression: Use the "tdefl" API's. The compressor supports raw, static, and dynamic blocks, lazy or
81 greedy parsing, match length filtering, RLE-only, and Huffman-only streams. It performs and compresses
82 approximately as well as zlib.
84 Decompression: Use the "tinfl" API's. The entire decompressor is implemented as a single function
85 coroutine: see tinfl_decompress(). It supports decompression into a 32KB (or larger power of 2) wrapping buffer, or into a memory
86 block large enough to hold the entire file.
88 The low-level tdefl/tinfl API's do not make any use of dynamic memory allocation.
90 * zlib-style API notes:
92 miniz.c implements a fairly large subset of zlib. There's enough functionality present for it to be a drop-in
93 zlib replacement in many apps:
94 The z_stream struct, optional memory allocation callbacks
95 deflateInit/deflateInit2/deflate/deflateReset/deflateEnd/deflateBound
96 inflateInit/inflateInit2/inflate/inflateEnd
97 compress, compress2, compressBound, uncompress
98 CRC-32, Adler-32 - Using modern, minimal code size, CPU cache friendly routines.
99 Supports raw deflate streams or standard zlib streams with adler-32 checking.
102 The callback API's are not implemented yet. No support for gzip headers or zlib static dictionaries.
103 I've tried to closely emulate zlib's various flavors of stream flushing and return status codes, but
104 there are no guarantees that miniz.c pulls this off perfectly.
106 * PNG writing: See the tdefl_write_image_to_png_file_in_memory() function, originally written by
107 Alex Evans. Supports 1-4 bytes/pixel images.
109 * ZIP archive API notes:
111 The ZIP archive API's where designed with simplicity and efficiency in mind, with just enough abstraction to
112 get the job done with minimal fuss. There are simple API's to retrieve file information, read files from
113 existing archives, create new archives, append new files to existing archives, or clone archive data from
114 one archive to another. It supports archives located in memory or the heap, on disk (using stdio.h),
115 or you can specify custom file read/write callbacks.
117 - Archive reading: Just call this function to read a single file from a disk archive:
119 void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const char *pArchive_name,
120 size_t *pSize, mz_uint zip_flags);
122 For more complex cases, use the "mz_zip_reader" functions. Upon opening an archive, the entire central
123 directory is located and read as-is into memory, and subsequent file access only occurs when reading individual files.
125 - Archives file scanning: The simple way is to use this function to scan a loaded archive for a specific file:
127 int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags);
129 The locate operation can optionally check file comments too, which (as one example) can be used to identify
130 multiple versions of the same file in an archive. This function uses a simple linear search through the central
131 directory, so it's not very fast.
133 Alternately, you can iterate through all the files in an archive (using mz_zip_reader_get_num_files()) and
134 retrieve detailed info on each file by calling mz_zip_reader_file_stat().
136 - Archive creation: Use the "mz_zip_writer" functions. The ZIP writer immediately writes compressed file data
137 to disk and builds an exact image of the central directory in memory. The central directory image is written
138 all at once at the end of the archive file when the archive is finalized.
140 The archive writer can optionally align each file's local header and file data to any power of 2 alignment,
141 which can be useful when the archive will be read from optical media. Also, the writer supports placing
142 arbitrary data blobs at the very beginning of ZIP archives. Archives written using either feature are still
143 readable by any ZIP tool.
145 - Archive appending: The simple way to add a single file to an archive is to call this function:
147 mz_bool mz_zip_add_mem_to_archive_file_in_place(const char *pZip_filename, const char *pArchive_name,
148 const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags);
150 The archive will be created if it doesn't already exist, otherwise it'll be appended to.
151 Note the appending is done in-place and is not an atomic operation, so if something goes wrong
152 during the operation it's possible the archive could be left without a central directory (although the local
153 file headers and file data will be fine, so the archive will be recoverable).
155 For more complex archive modification scenarios:
156 1. The safest way is to use a mz_zip_reader to read the existing archive, cloning only those bits you want to
157 preserve into a new archive using using the mz_zip_writer_add_from_zip_reader() function (which compiles the
158 compressed file data as-is). When you're done, delete the old archive and rename the newly written archive, and
159 you're done. This is safe but requires a bunch of temporary disk space or heap memory.
161 2. Or, you can convert an mz_zip_reader in-place to an mz_zip_writer using mz_zip_writer_init_from_reader(),
162 append new files as needed, then finalize the archive which will write an updated central directory to the
163 original archive. (This is basically what mz_zip_add_mem_to_archive_file_in_place() does.) There's a
164 possibility that the archive's central directory could be lost with this method if anything goes wrong, though.
166 - ZIP archive support limitations:
167 No zip64 or spanning support. Extraction functions can only handle unencrypted, stored or deflated files.
168 Requires streams capable of seeking.
170 * This is a header file library, like stb_image.c. To get only a header file, either cut and paste the
171 below header, or create miniz.h, #define MINIZ_HEADER_FILE_ONLY, and then include miniz.c from it.
173 * Important: For best perf. be sure to customize the below macros for your target platform:
174 #define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 1
175 #define MINIZ_LITTLE_ENDIAN 1
176 #define MINIZ_HAS_64BIT_REGISTERS 1
178 * On platforms using glibc, Be sure to "#define _LARGEFILE64_SOURCE 1" before including miniz.c to ensure miniz
179 uses the 64-bit variants: fopen64(), stat64(), etc. Otherwise you won't be able to process large files
180 (i.e. 32-bit stat() fails for me on files > 0x7FFFFFFF bytes).
184 #ifndef MINIZ_HEADER_INCLUDED
185 #define MINIZ_HEADER_INCLUDED
187 #include "vogl_miniz_common.h"
189 // Defines to completely disable specific portions of miniz.c:
190 // If all macros here are defined the only functionality remaining will be CRC-32, adler-32, tinfl, and tdefl.
192 // Define MINIZ_NO_STDIO to disable all usage and any functions which rely on stdio for file I/O.
193 //#define MINIZ_NO_STDIO
195 // If MINIZ_NO_TIME is specified then the ZIP archive functions will not be able to get the current time, or
196 // get/set file times, and the C run-time funcs that get/set times won't be called.
197 // The current downside is the times written to your archives will be from 1979.
198 //#define MINIZ_NO_TIME
200 // Define MINIZ_NO_ARCHIVE_APIS to disable all ZIP archive API's.
201 //#define MINIZ_NO_ARCHIVE_APIS
203 // Define MINIZ_NO_ARCHIVE_APIS to disable all writing related ZIP archive API's.
204 //#define MINIZ_NO_ARCHIVE_WRITING_APIS
206 // Define MINIZ_NO_ZLIB_APIS to remove all ZLIB-style compression/decompression API's.
207 //#define MINIZ_NO_ZLIB_APIS
209 // Define MINIZ_NO_ZLIB_COMPATIBLE_NAME to disable zlib names, to prevent conflicts against stock zlib.
210 #define MINIZ_NO_ZLIB_COMPATIBLE_NAMES
212 // Define MINIZ_NO_MALLOC to disable all calls to malloc, free, and realloc.
213 // Note if MINIZ_NO_MALLOC is defined then the user must always provide custom user alloc/free/realloc
214 // callbacks to the zlib and archive API's, and a few stand-alone helper API's which don't provide custom user
215 // functions (such as tdefl_compress_mem_to_heap() and tinfl_decompress_mem_to_heap()) won't work.
216 //#define MINIZ_NO_MALLOC
218 #if defined(__TINYC__) && (defined(__linux) || defined(__linux__))
219 // TODO: Work around "error: include file 'sys\utime.h' when compiling with tcc on Linux
220 #define MINIZ_NO_TIME
223 #if !defined(MINIZ_NO_TIME) && !defined(MINIZ_NO_ARCHIVE_APIS)
227 #if defined(_M_IX86) || defined(_M_X64) || defined(__i386__) || defined(__i386) || defined(__i486__) || defined(__i486) || defined(i386) || defined(__ia64__) || defined(__x86_64__)
228 // MINIZ_X86_OR_X64_CPU is only used to help set the below macros.
229 #define MINIZ_X86_OR_X64_CPU 1
232 #if (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__) || MINIZ_X86_OR_X64_CPU
233 // Set MINIZ_LITTLE_ENDIAN to 1 if the processor is little endian.
234 #define MINIZ_LITTLE_ENDIAN 1
237 #if MINIZ_X86_OR_X64_CPU
238 // Set MINIZ_USE_UNALIGNED_LOADS_AND_STORES to 1 on CPU's that permit efficient integer loads and stores from unaligned addresses.
239 #define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 1
242 #if defined(_M_X64) || defined(_WIN64) || defined(__MINGW64__) || defined(_LP64) || defined(__LP64__) || defined(__ia64__) || defined(__x86_64__)
243 // Set MINIZ_HAS_64BIT_REGISTERS to 1 if operations on 64-bit integers are reasonably fast (and don't involve compiler generated calls to helper functions).
244 #define MINIZ_HAS_64BIT_REGISTERS 1
251 // ------------------- zlib-style API Definitions.
253 // For more compatibility with zlib, miniz.c uses unsigned long for some parameters/struct members. Beware: mz_ulong can be either 32 or 64-bits!
254 typedef unsigned long mz_ulong;
256 // mz_free() internally uses the MZ_FREE() macro (which by default calls free() unless you've modified the MZ_MALLOC macro) to release a block allocated from the heap.
257 void mz_free(void *p);
259 #define MZ_ADLER32_INIT (1)
260 // mz_adler32() returns the initial adler-32 value to use when called with ptr==NULL.
261 mz_ulong mz_adler32(mz_ulong adler, const unsigned char *ptr, size_t buf_len);
263 #define MZ_CRC32_INIT (0)
264 // mz_crc32() returns the initial CRC-32 value to use when called with ptr==NULL.
265 mz_ulong mz_crc32(mz_ulong crc, const unsigned char *ptr, size_t buf_len);
267 // Compression strategies.
270 MZ_DEFAULT_STRATEGY = 0,
278 #define MZ_DEFLATED 8
280 #ifndef MINIZ_NO_ZLIB_APIS
282 // Heap allocation callbacks.
283 // Note that mz_alloc_func parameter types purpsosely differ from zlib's: items/size is size_t, not unsigned long.
284 typedef void *(*mz_alloc_func)(void *opaque, size_t items, size_t size);
285 typedef void (*mz_free_func)(void *opaque, void *address);
286 typedef void *(*mz_realloc_func)(void *opaque, void *address, size_t items, size_t size);
288 #define MZ_VERSION "9.1.15"
289 #define MZ_VERNUM 0x91F0
290 #define MZ_VER_MAJOR 9
291 #define MZ_VER_MINOR 1
292 #define MZ_VER_REVISION 15
293 #define MZ_VER_SUBREVISION 0
295 // Flush values. For typical usage you only need MZ_NO_FLUSH and MZ_FINISH. The other values are for advanced use (refer to the zlib docs).
299 MZ_PARTIAL_FLUSH = 1,
306 // Return status codes. MZ_PARAM_ERROR is non-standard.
313 MZ_STREAM_ERROR = -2,
317 MZ_VERSION_ERROR = -6,
318 MZ_PARAM_ERROR = -10000
321 // Compression levels: 0-9 are the standard zlib-style levels, 10 is best possible compression (not zlib compatible, and may be very slow), MZ_DEFAULT_COMPRESSION=MZ_DEFAULT_LEVEL.
324 MZ_NO_COMPRESSION = 0,
326 MZ_BEST_COMPRESSION = 9,
327 MZ_UBER_COMPRESSION = 10,
328 MZ_DEFAULT_LEVEL = 6,
329 MZ_DEFAULT_COMPRESSION = -1
333 #define MZ_DEFAULT_WINDOW_BITS 15
335 struct mz_internal_state;
337 // Compression/decompression stream struct.
338 typedef struct mz_stream_s
340 const unsigned char *next_in; // pointer to next byte to read
341 unsigned int avail_in; // number of bytes available at next_in
342 mz_ulong total_in; // total number of bytes consumed so far
344 unsigned char *next_out; // pointer to next byte to write
345 unsigned int avail_out; // number of bytes that can be written to next_out
346 mz_ulong total_out; // total number of bytes produced so far
348 char *msg; // error msg (unused)
349 struct mz_internal_state *state; // internal state, allocated by zalloc/zfree
351 mz_alloc_func zalloc; // optional heap allocation function (defaults to malloc)
352 mz_free_func zfree; // optional heap free function (defaults to free)
353 void *opaque; // heap alloc function user pointer
355 int data_type; // data_type (unused)
356 mz_ulong adler; // adler32 of the source or uncompressed data
357 mz_ulong reserved; // not used
360 typedef mz_stream *mz_streamp;
362 // Returns the version string of miniz.c.
363 const char *mz_version(void);
365 // mz_deflateInit() initializes a compressor with default options:
367 // pStream must point to an initialized mz_stream struct.
368 // level must be between [MZ_NO_COMPRESSION, MZ_BEST_COMPRESSION].
369 // level 1 enables a specially optimized compression function that's been optimized purely for performance, not ratio.
370 // (This special func. is currently only enabled when MINIZ_USE_UNALIGNED_LOADS_AND_STORES and MINIZ_LITTLE_ENDIAN are defined.)
373 // MZ_STREAM_ERROR if the stream is bogus.
374 // MZ_PARAM_ERROR if the input parameters are bogus.
375 // MZ_MEM_ERROR on out of memory.
376 int mz_deflateInit(mz_streamp pStream, int level);
378 // mz_deflateInit2() is like mz_deflate(), except with more control:
379 // Additional parameters:
380 // method must be MZ_DEFLATED
381 // window_bits must be MZ_DEFAULT_WINDOW_BITS (to wrap the deflate stream with zlib header/adler-32 footer) or -MZ_DEFAULT_WINDOW_BITS (raw deflate/no header or footer)
382 // mem_level must be between [1, 9] (it's checked but ignored by miniz.c)
383 int mz_deflateInit2(mz_streamp pStream, int level, int method, int window_bits, int mem_level, int strategy);
385 // Quickly resets a compressor without having to reallocate anything. Same as calling mz_deflateEnd() followed by mz_deflateInit()/mz_deflateInit2().
386 int mz_deflateReset(mz_streamp pStream);
388 // mz_deflate() compresses the input to output, consuming as much of the input and producing as much output as possible.
390 // pStream is the stream to read from and write to. You must initialize/update the next_in, avail_in, next_out, and avail_out members.
391 // flush may be MZ_NO_FLUSH, MZ_PARTIAL_FLUSH/MZ_SYNC_FLUSH, MZ_FULL_FLUSH, or MZ_FINISH.
393 // MZ_OK on success (when flushing, or if more input is needed but not available, and/or there's more output to be written but the output buffer is full).
394 // MZ_STREAM_END if all input has been consumed and all output bytes have been written. Don't call mz_deflate() on the stream anymore.
395 // MZ_STREAM_ERROR if the stream is bogus.
396 // MZ_PARAM_ERROR if one of the parameters is invalid.
397 // MZ_BUF_ERROR if no forward progress is possible because the input and/or output buffers are empty. (Fill up the input buffer or free up some output space and try again.)
398 int mz_deflate(mz_streamp pStream, int flush);
400 // mz_deflateEnd() deinitializes a compressor:
403 // MZ_STREAM_ERROR if the stream is bogus.
404 int mz_deflateEnd(mz_streamp pStream);
406 // mz_deflateBound() returns a (very) conservative upper bound on the amount of data that could be generated by deflate(), assuming flush is set to only MZ_NO_FLUSH or MZ_FINISH.
407 mz_ulong mz_deflateBound(mz_streamp pStream, mz_ulong source_len);
409 // Single-call compression functions mz_compress() and mz_compress2():
410 // Returns MZ_OK on success, or one of the error codes from mz_deflate() on failure.
411 int mz_compress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len);
412 int mz_compress2(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len, int level);
414 // mz_compressBound() returns a (very) conservative upper bound on the amount of data that could be generated by calling mz_compress().
415 mz_ulong mz_compressBound(mz_ulong source_len);
417 // Initializes a decompressor.
418 int mz_inflateInit(mz_streamp pStream);
420 // mz_inflateInit2() is like mz_inflateInit() with an additional option that controls the window size and whether or not the stream has been wrapped with a zlib header/footer:
421 // window_bits must be MZ_DEFAULT_WINDOW_BITS (to parse zlib header/footer) or -MZ_DEFAULT_WINDOW_BITS (raw deflate).
422 int mz_inflateInit2(mz_streamp pStream, int window_bits);
424 // Decompresses the input stream to the output, consuming only as much of the input as needed, and writing as much to the output as possible.
426 // pStream is the stream to read from and write to. You must initialize/update the next_in, avail_in, next_out, and avail_out members.
427 // flush may be MZ_NO_FLUSH, MZ_SYNC_FLUSH, or MZ_FINISH.
428 // On the first call, if flush is MZ_FINISH it's assumed the input and output buffers are both sized large enough to decompress the entire stream in a single call (this is slightly faster).
429 // MZ_FINISH implies that there are no more source bytes available beside what's already in the input buffer, and that the output buffer is large enough to hold the rest of the decompressed data.
431 // MZ_OK on success. Either more input is needed but not available, and/or there's more output to be written but the output buffer is full.
432 // MZ_STREAM_END if all needed input has been consumed and all output bytes have been written. For zlib streams, the adler-32 of the decompressed data has also been verified.
433 // MZ_STREAM_ERROR if the stream is bogus.
434 // MZ_DATA_ERROR if the deflate stream is invalid.
435 // MZ_PARAM_ERROR if one of the parameters is invalid.
436 // MZ_BUF_ERROR if no forward progress is possible because the input buffer is empty but the inflater needs more input to continue, or if the output buffer is not large enough. Call mz_inflate() again
437 // with more input data, or with more room in the output buffer (except when using single call decompression, described above).
438 int mz_inflate(mz_streamp pStream, int flush);
440 // Deinitializes a decompressor.
441 int mz_inflateEnd(mz_streamp pStream);
443 // Single-call decompression.
444 // Returns MZ_OK on success, or one of the error codes from mz_inflate() on failure.
445 int mz_uncompress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len);
447 // Returns a string description of the specified error code, or NULL if the error code is invalid.
448 const char *mz_error(int err);
450 // Redefine zlib-compatible names to miniz equivalents, so miniz.c can be used as a drop-in replacement for the subset of zlib that miniz.c supports.
451 // Define MINIZ_NO_ZLIB_COMPATIBLE_NAMES to disable zlib-compatibility if you use zlib in the same project.
452 #ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES
453 typedef unsigned char Byte;
454 typedef unsigned int uInt;
455 typedef mz_ulong uLong;
460 typedef void *voidpf;
461 typedef uLong uLongf;
463 typedef void *const voidpc;
465 #define Z_NO_FLUSH MZ_NO_FLUSH
466 #define Z_PARTIAL_FLUSH MZ_PARTIAL_FLUSH
467 #define Z_SYNC_FLUSH MZ_SYNC_FLUSH
468 #define Z_FULL_FLUSH MZ_FULL_FLUSH
469 #define Z_FINISH MZ_FINISH
470 #define Z_BLOCK MZ_BLOCK
472 #define Z_STREAM_END MZ_STREAM_END
473 #define Z_NEED_DICT MZ_NEED_DICT
474 #define Z_ERRNO MZ_ERRNO
475 #define Z_STREAM_ERROR MZ_STREAM_ERROR
476 #define Z_DATA_ERROR MZ_DATA_ERROR
477 #define Z_MEM_ERROR MZ_MEM_ERROR
478 #define Z_BUF_ERROR MZ_BUF_ERROR
479 #define Z_VERSION_ERROR MZ_VERSION_ERROR
480 #define Z_PARAM_ERROR MZ_PARAM_ERROR
481 #define Z_NO_COMPRESSION MZ_NO_COMPRESSION
482 #define Z_BEST_SPEED MZ_BEST_SPEED
483 #define Z_BEST_COMPRESSION MZ_BEST_COMPRESSION
484 #define Z_DEFAULT_COMPRESSION MZ_DEFAULT_COMPRESSION
485 #define Z_DEFAULT_STRATEGY MZ_DEFAULT_STRATEGY
486 #define Z_FILTERED MZ_FILTERED
487 #define Z_HUFFMAN_ONLY MZ_HUFFMAN_ONLY
489 #define Z_FIXED MZ_FIXED
490 #define Z_DEFLATED MZ_DEFLATED
491 #define Z_DEFAULT_WINDOW_BITS MZ_DEFAULT_WINDOW_BITS
492 #define alloc_func mz_alloc_func
493 #define free_func mz_free_func
494 #define internal_state mz_internal_state
495 #define z_stream mz_stream
496 #define deflateInit mz_deflateInit
497 #define deflateInit2 mz_deflateInit2
498 #define deflateReset mz_deflateReset
499 #define deflate mz_deflate
500 #define deflateEnd mz_deflateEnd
501 #define deflateBound mz_deflateBound
502 #define compress mz_compress
503 #define compress2 mz_compress2
504 #define compressBound mz_compressBound
505 #define inflateInit mz_inflateInit
506 #define inflateInit2 mz_inflateInit2
507 #define inflate mz_inflate
508 #define inflateEnd mz_inflateEnd
509 #define uncompress mz_uncompress
510 #define crc32 mz_crc32
511 #define adler32 mz_adler32
513 #define MAX_MEM_LEVEL 9
514 #define zError mz_error
515 #define ZLIB_VERSION MZ_VERSION
516 #define ZLIB_VERNUM MZ_VERNUM
517 #define ZLIB_VER_MAJOR MZ_VER_MAJOR
518 #define ZLIB_VER_MINOR MZ_VER_MINOR
519 #define ZLIB_VER_REVISION MZ_VER_REVISION
520 #define ZLIB_VER_SUBREVISION MZ_VER_SUBREVISION
521 #define zlibVersion mz_version
522 #define zlib_version mz_version()
523 #endif // #ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES
525 #endif // MINIZ_NO_ZLIB_APIS
527 // ------------------- Types and macros
529 typedef unsigned char mz_uint8;
530 typedef signed short mz_int16;
531 typedef unsigned short mz_uint16;
532 typedef unsigned int mz_uint32;
533 typedef unsigned int mz_uint;
534 typedef int64_t mz_int64;
535 typedef uint64_t mz_uint64;
541 // Works around MSVC's spammy "warning C4127: conditional expression is constant" message.
543 #define MZ_MACRO_END while (0, 0)
545 #define MZ_MACRO_END while (0)
549 // ------------------- Low-level Decompression API Definitions
551 // Decompression flags used by tinfl_decompress().
552 // TINFL_FLAG_PARSE_ZLIB_HEADER: If set, the input has a valid zlib header and ends with an adler32 checksum (it's a valid zlib stream). Otherwise, the input is a raw deflate stream.
553 // TINFL_FLAG_HAS_MORE_INPUT: If set, there are more input bytes available beyond the end of the supplied input buffer. If clear, the input buffer contains all remaining input.
554 // TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF: If set, the output buffer is large enough to hold the entire decompressed stream. If clear, the output buffer is at least the size of the dictionary (typically 32KB).
555 // TINFL_FLAG_COMPUTE_ADLER32: Force adler-32 checksum computation of the decompressed bytes.
558 TINFL_FLAG_PARSE_ZLIB_HEADER = 1,
559 TINFL_FLAG_HAS_MORE_INPUT = 2,
560 TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF = 4,
561 TINFL_FLAG_COMPUTE_ADLER32 = 8
564 // High level decompression functions:
565 // tinfl_decompress_mem_to_heap() decompresses a block in memory to a heap block allocated via malloc().
567 // pSrc_buf, src_buf_len: Pointer and size of the Deflate or zlib source data to decompress.
569 // Function returns a pointer to the decompressed data, or NULL on failure.
570 // *pOut_len will be set to the decompressed data's size, which could be larger than src_buf_len on uncompressible data.
571 // The caller must call mz_free() on the returned block when it's no longer needed.
572 void *tinfl_decompress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags);
574 // tinfl_decompress_mem_to_mem() decompresses a block in memory to another block in memory.
575 // Returns TINFL_DECOMPRESS_MEM_TO_MEM_FAILED on failure, or the number of bytes written on success.
576 #define TINFL_DECOMPRESS_MEM_TO_MEM_FAILED ((size_t)(-1))
577 size_t tinfl_decompress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags);
579 // tinfl_decompress_mem_to_callback() decompresses a block in memory to an internal 32KB buffer, and a user provided callback function will be called to flush the buffer.
580 // Returns 1 on success or 0 on failure.
581 typedef int (*tinfl_put_buf_func_ptr)(const void *pBuf, int len, void *pUser);
582 int tinfl_decompress_mem_to_callback(const void *pIn_buf, size_t *pIn_buf_size, tinfl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags);
584 struct tinfl_decompressor_tag;
585 typedef struct tinfl_decompressor_tag tinfl_decompressor;
587 // Max size of LZ dictionary.
588 #define TINFL_LZ_DICT_SIZE 32768
593 // This flags indicates the inflator needs 1 or more input bytes to make forward progress, but the caller is indicating that no more are available. The compressed data
594 // is probably corrupted. If you call the inflator again with more bytes it'll try to continue processing the input but this is a BAD sign (either the data is corrupted or you called it incorrectly).
595 // If you call it again with no input you'll just get TINFL_STATUS_FAILED_CANNOT_MAKE_PROGRESS again.
596 TINFL_STATUS_FAILED_CANNOT_MAKE_PROGRESS = -4,
598 // This flag indicates that one or more of the input parameters was obviously bogus. (You can try calling it again, but if you get this error the calling code is wrong.)
599 TINFL_STATUS_BAD_PARAM = -3,
600 TINFL_STATUS_ADLER32_MISMATCH = -2,
601 TINFL_STATUS_FAILED = -1,
602 TINFL_STATUS_DONE = 0,
603 TINFL_STATUS_NEEDS_MORE_INPUT = 1,
604 TINFL_STATUS_HAS_MORE_OUTPUT = 2
607 // Initializes the decompressor to its initial state.
608 #define tinfl_init(r) \
614 #define tinfl_get_adler32(r) (r)->m_check_adler32
616 // Main low-level decompressor coroutine function. This is the only function actually needed for decompression. All the other functions are just high-level helpers for improved usability.
617 // This is a universal API, i.e. it can be used as a building block to build any desired higher level decompression API. In the limit case, it can be called once per every byte input or output.
618 tinfl_status tinfl_decompress(tinfl_decompressor *r, const mz_uint8 *pIn_buf_next, size_t *pIn_buf_size, mz_uint8 *pOut_buf_start, mz_uint8 *pOut_buf_next, size_t *pOut_buf_size, const mz_uint32 decomp_flags);
620 // Internal/private bits follow.
623 TINFL_MAX_HUFF_TABLES = 3,
624 TINFL_MAX_HUFF_SYMBOLS_0 = 288,
625 TINFL_MAX_HUFF_SYMBOLS_1 = 32,
626 TINFL_MAX_HUFF_SYMBOLS_2 = 19,
627 TINFL_FAST_LOOKUP_BITS = 10,
628 TINFL_FAST_LOOKUP_SIZE = 1 << TINFL_FAST_LOOKUP_BITS
633 mz_uint8 m_code_size[TINFL_MAX_HUFF_SYMBOLS_0];
634 mz_int16 m_look_up[TINFL_FAST_LOOKUP_SIZE], m_tree[TINFL_MAX_HUFF_SYMBOLS_0 * 2];
637 #if MINIZ_HAS_64BIT_REGISTERS
638 #define TINFL_USE_64BIT_BITBUF 1
641 #if TINFL_USE_64BIT_BITBUF
642 typedef mz_uint64 tinfl_bit_buf_t;
643 #define TINFL_BITBUF_SIZE (64)
645 typedef mz_uint32 tinfl_bit_buf_t;
646 #define TINFL_BITBUF_SIZE (32)
649 struct tinfl_decompressor_tag
651 mz_uint32 m_state, m_num_bits, m_zhdr0, m_zhdr1, m_z_adler32, m_final, m_type, m_check_adler32, m_dist, m_counter, m_num_extra, m_table_sizes[TINFL_MAX_HUFF_TABLES];
652 tinfl_bit_buf_t m_bit_buf;
653 size_t m_dist_from_out_buf_start;
654 tinfl_huff_table m_tables[TINFL_MAX_HUFF_TABLES];
655 mz_uint8 m_raw_header[4], m_len_codes[TINFL_MAX_HUFF_SYMBOLS_0 + TINFL_MAX_HUFF_SYMBOLS_1 + 137];
658 // ------------------- Low-level Compression API Definitions
660 // Set TDEFL_LESS_MEMORY to 1 to use less memory (compression will be slightly slower, and raw/dynamic blocks will be output more frequently).
661 #define TDEFL_LESS_MEMORY 0
663 // tdefl_init() compression flags logically OR'd together (low 12 bits contain the max. number of probes per dictionary search):
664 // TDEFL_DEFAULT_MAX_PROBES: The compressor defaults to 128 dictionary probes per dictionary search. 0=Huffman only, 1=Huffman+LZ (fastest/crap compression), 4095=Huffman+LZ (slowest/best compression).
667 TDEFL_HUFFMAN_ONLY = 0,
668 TDEFL_DEFAULT_MAX_PROBES = 128,
669 TDEFL_MAX_PROBES_MASK = 0xFFF
672 // TDEFL_WRITE_ZLIB_HEADER: If set, the compressor outputs a zlib header before the deflate data, and the Adler-32 of the source data at the end. Otherwise, you'll get raw deflate data.
673 // TDEFL_COMPUTE_ADLER32: Always compute the adler-32 of the input data (even when not writing zlib headers).
674 // TDEFL_GREEDY_PARSING_FLAG: Set to use faster greedy parsing, instead of more efficient lazy parsing.
675 // TDEFL_NONDETERMINISTIC_PARSING_FLAG: Enable to decrease the compressor's initialization time to the minimum, but the output may vary from run to run given the same input (depending on the contents of memory).
676 // TDEFL_RLE_MATCHES: Only look for RLE matches (matches with a distance of 1)
677 // TDEFL_FILTER_MATCHES: Discards matches <= 5 chars if enabled.
678 // TDEFL_FORCE_ALL_STATIC_BLOCKS: Disable usage of optimized Huffman tables.
679 // TDEFL_FORCE_ALL_RAW_BLOCKS: Only use raw (uncompressed) deflate blocks.
680 // The low 12 bits are reserved to control the max # of hash probes per dictionary lookup (see TDEFL_MAX_PROBES_MASK).
683 TDEFL_WRITE_ZLIB_HEADER = 0x01000,
684 TDEFL_COMPUTE_ADLER32 = 0x02000,
685 TDEFL_GREEDY_PARSING_FLAG = 0x04000,
686 TDEFL_NONDETERMINISTIC_PARSING_FLAG = 0x08000,
687 TDEFL_RLE_MATCHES = 0x10000,
688 TDEFL_FILTER_MATCHES = 0x20000,
689 TDEFL_FORCE_ALL_STATIC_BLOCKS = 0x40000,
690 TDEFL_FORCE_ALL_RAW_BLOCKS = 0x80000
693 // High level compression functions:
694 // tdefl_compress_mem_to_heap() compresses a block in memory to a heap block allocated via malloc().
696 // pSrc_buf, src_buf_len: Pointer and size of source block to compress.
697 // flags: The max match finder probes (default is 128) logically OR'd against the above flags. Higher probes are slower but improve compression.
699 // Function returns a pointer to the compressed data, or NULL on failure.
700 // *pOut_len will be set to the compressed data's size, which could be larger than src_buf_len on uncompressible data.
701 // The caller must free() the returned block when it's no longer needed.
702 void *tdefl_compress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags);
704 // tdefl_compress_mem_to_mem() compresses a block in memory to another block in memory.
705 // Returns 0 on failure.
706 size_t tdefl_compress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags);
708 // Compresses an image to a compressed PNG file in memory.
710 // pImage, w, h, and num_chans describe the image to compress. num_chans may be 1, 2, 3, or 4.
711 // The image pitch in bytes per scanline will be w*num_chans. The leftmost pixel on the top scanline is stored first in memory.
712 // level may range from [0,10], use MZ_NO_COMPRESSION, MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc. or a decent default is MZ_DEFAULT_LEVEL
713 // If flip is true, the image will be flipped on the Y axis (useful for OpenGL apps).
715 // Function returns a pointer to the compressed data, or NULL on failure.
716 // *pLen_out will be set to the size of the PNG image file.
717 // The caller must mz_free() the returned heap block (which will typically be larger than *pLen_out) when it's no longer needed.
718 void *tdefl_write_image_to_png_file_in_memory_ex(const void *pImage, int w, int h, int num_chans, size_t *pLen_out, mz_uint level, mz_bool flip);
719 void *tdefl_write_image_to_png_file_in_memory(const void *pImage, int w, int h, int num_chans, size_t *pLen_out);
721 // Output stream interface. The compressor uses this interface to write compressed data. It'll typically be called TDEFL_OUT_BUF_SIZE at a time.
722 typedef mz_bool (*tdefl_put_buf_func_ptr)(const void *pBuf, int len, void *pUser);
724 // tdefl_compress_mem_to_output() compresses a block to an output stream. The above helpers use this function internally.
725 mz_bool tdefl_compress_mem_to_output(const void *pBuf, size_t buf_len, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags);
729 TDEFL_MAX_HUFF_TABLES = 3,
730 TDEFL_MAX_HUFF_SYMBOLS_0 = 288,
731 TDEFL_MAX_HUFF_SYMBOLS_1 = 32,
732 TDEFL_MAX_HUFF_SYMBOLS_2 = 19,
733 TDEFL_LZ_DICT_SIZE = 32768,
734 TDEFL_LZ_DICT_SIZE_MASK = TDEFL_LZ_DICT_SIZE - 1,
735 TDEFL_MIN_MATCH_LEN = 3,
736 TDEFL_MAX_MATCH_LEN = 258
739 // TDEFL_OUT_BUF_SIZE MUST be large enough to hold a single entire compressed output block (using static/fixed Huffman codes).
740 #if TDEFL_LESS_MEMORY
743 TDEFL_LZ_CODE_BUF_SIZE = 24 * 1024,
744 TDEFL_OUT_BUF_SIZE = (TDEFL_LZ_CODE_BUF_SIZE * 13) / 10,
745 TDEFL_MAX_HUFF_SYMBOLS = 288,
746 TDEFL_LZ_HASH_BITS = 12,
747 TDEFL_LEVEL1_HASH_SIZE_MASK = 4095,
748 TDEFL_LZ_HASH_SHIFT = (TDEFL_LZ_HASH_BITS + 2) / 3,
749 TDEFL_LZ_HASH_SIZE = 1 << TDEFL_LZ_HASH_BITS
754 TDEFL_LZ_CODE_BUF_SIZE = 64 * 1024,
755 TDEFL_OUT_BUF_SIZE = (TDEFL_LZ_CODE_BUF_SIZE * 13) / 10,
756 TDEFL_MAX_HUFF_SYMBOLS = 288,
757 TDEFL_LZ_HASH_BITS = 15,
758 TDEFL_LEVEL1_HASH_SIZE_MASK = 4095,
759 TDEFL_LZ_HASH_SHIFT = (TDEFL_LZ_HASH_BITS + 2) / 3,
760 TDEFL_LZ_HASH_SIZE = 1 << TDEFL_LZ_HASH_BITS
764 // The low-level tdefl functions below may be used directly if the above helper functions aren't flexible enough. The low-level functions don't make any heap allocations, unlike the above helper functions.
767 TDEFL_STATUS_BAD_PARAM = -2,
768 TDEFL_STATUS_PUT_BUF_FAILED = -1,
769 TDEFL_STATUS_OKAY = 0,
770 TDEFL_STATUS_DONE = 1,
773 // Must map to MZ_NO_FLUSH, MZ_SYNC_FLUSH, etc. enums
777 TDEFL_SYNC_FLUSH = 2,
778 TDEFL_FULL_FLUSH = 3,
782 // tdefl's compression state structure.
785 tdefl_put_buf_func_ptr m_pPut_buf_func;
786 void *m_pPut_buf_user;
787 mz_uint m_flags, m_max_probes[2];
788 int m_greedy_parsing;
789 mz_uint m_adler32, m_lookahead_pos, m_lookahead_size, m_dict_size;
790 mz_uint8 *m_pLZ_code_buf, *m_pLZ_flags, *m_pOutput_buf, *m_pOutput_buf_end;
791 mz_uint m_num_flags_left, m_total_lz_bytes, m_lz_code_buf_dict_pos, m_bits_in, m_bit_buffer;
792 mz_uint m_saved_match_dist, m_saved_match_len, m_saved_lit, m_output_flush_ofs, m_output_flush_remaining, m_finished, m_block_index, m_wants_to_finish;
793 tdefl_status m_prev_return_status;
794 const void *m_pIn_buf;
796 size_t *m_pIn_buf_size, *m_pOut_buf_size;
798 const mz_uint8 *m_pSrc;
799 size_t m_src_buf_left, m_out_buf_ofs;
800 mz_uint8 m_dict[TDEFL_LZ_DICT_SIZE + TDEFL_MAX_MATCH_LEN - 1];
801 mz_uint16 m_huff_count[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS];
802 mz_uint16 m_huff_codes[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS];
803 mz_uint8 m_huff_code_sizes[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS];
804 mz_uint8 m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE];
805 mz_uint16 m_next[TDEFL_LZ_DICT_SIZE];
806 mz_uint16 m_hash[TDEFL_LZ_HASH_SIZE];
807 mz_uint8 m_output_buf[TDEFL_OUT_BUF_SIZE];
810 // Initializes the compressor.
811 // There is no corresponding deinit() function because the tdefl API's do not dynamically allocate memory.
812 // pBut_buf_func: If NULL, output data will be supplied to the specified callback. In this case, the user should call the tdefl_compress_buffer() API for compression.
813 // If pBut_buf_func is NULL the user should always call the tdefl_compress() API.
814 // flags: See the above enums (TDEFL_HUFFMAN_ONLY, TDEFL_WRITE_ZLIB_HEADER, etc.)
815 tdefl_status tdefl_init(tdefl_compressor *d, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags);
817 // Compresses a block of data, consuming as much of the specified input buffer as possible, and writing as much compressed data to the specified output buffer as possible.
818 tdefl_status tdefl_compress(tdefl_compressor *d, const void *pIn_buf, size_t *pIn_buf_size, void *pOut_buf, size_t *pOut_buf_size, tdefl_flush flush);
820 // tdefl_compress_buffer() is only usable when the tdefl_init() is called with a non-NULL tdefl_put_buf_func_ptr.
821 // tdefl_compress_buffer() always consumes the entire input buffer.
822 tdefl_status tdefl_compress_buffer(tdefl_compressor *d, const void *pIn_buf, size_t in_buf_size, tdefl_flush flush);
824 tdefl_status tdefl_get_prev_return_status(tdefl_compressor *d);
825 mz_uint32 tdefl_get_adler32(tdefl_compressor *d);
827 // Can't use tdefl_create_comp_flags_from_zip_params if MINIZ_NO_ZLIB_APIS isn't defined, because it uses some of its macros.
828 #ifndef MINIZ_NO_ZLIB_APIS
829 // Create tdefl_compress() flags given zlib-style compression parameters.
830 // level may range from [0,10] (where 10 is absolute max compression, but may be much slower on some files)
831 // window_bits may be -15 (raw deflate) or 15 (zlib)
832 // strategy may be either MZ_DEFAULT_STRATEGY, MZ_FILTERED, MZ_HUFFMAN_ONLY, MZ_RLE, or MZ_FIXED
833 mz_uint tdefl_create_comp_flags_from_zip_params(int level, int window_bits, int strategy);
834 #endif // #ifndef MINIZ_NO_ZLIB_APIS
840 //#endif // MINIZ_HEADER_INCLUDED