source: trunk/src/image/miniz.cc @ 484

Last change on this file since 484 was 484, checked in by epyon, 10 years ago
  • resource manager updates
  • nv-image added
  • missing stl memory added
  • several other missing files
File size: 130.1 KB
RevLine 
[484]1#include "nv/image/miniz.hh"
2#include "nv/core/profiler.hh"
3
4using namespace nv;
5
6#if defined( _M_IX86 ) || defined( _M_X64 ) || defined( __i386__ ) || defined( __i386 ) || defined( __i486__ ) || defined( __i486 ) || defined( i386 ) || defined( __ia64__ ) || defined( __x86_64__ )
7// MINIZ_X86_OR_X64_CPU is only used to help set the below macros.
8#define MINIZ_X86_OR_X64_CPU 1
9#endif
10
11#if (__BYTE_ORDER__==__ORDER_LITTLE_ENDIAN__) || MINIZ_X86_OR_X64_CPU
12// Set MINIZ_LITTLE_ENDIAN to 1 if the processor is little endian.
13#define MINIZ_LITTLE_ENDIAN 1
14#endif
15
16#if MINIZ_X86_OR_X64_CPU
17// Set MINIZ_USE_UNALIGNED_LOADS_AND_STORES to 1 on CPU's that permit efficient integer loads and stores from unaligned addresses.
18#define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 1
19#endif
20
21#if defined(_M_X64) || defined(_WIN64) || defined(__MINGW64__) || defined(_LP64) || defined(__LP64__) || defined(__ia64__) || defined(__x86_64__)
22// 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).
23#define MINIZ_HAS_64BIT_REGISTERS 1
24#endif
25
26#ifdef __cplusplus
27extern "C" {
28#endif
29
30        // ------------------- zlib-style API Definitions.
31
32        // 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!
33        typedef unsigned long mz_ulong;
34
35        // 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.
36        void mz_free( void *p );
37
38#define MZ_ADLER32_INIT (1)
39        // mz_adler32() returns the initial adler-32 value to use when called with ptr==NULL.
40        mz_ulong mz_adler32( mz_ulong adler, const unsigned char *ptr, size_t buf_len );
41
42#define MZ_CRC32_INIT (0)
43        // mz_crc32() returns the initial CRC-32 value to use when called with ptr==NULL.
44        mz_ulong mz_crc32( mz_ulong crc, const unsigned char *ptr, size_t buf_len );
45
46        // Compression strategies.
47        enum { MZ_DEFAULT_STRATEGY = 0, MZ_FILTERED = 1, MZ_HUFFMAN_ONLY = 2, MZ_RLE = 3, MZ_FIXED = 4 };
48
49        // Method
50#define MZ_DEFLATED 8
51
52#ifndef MINIZ_NO_ZLIB_APIS
53
54        // Heap allocation callbacks.
55        // Note that mz_alloc_func parameter types purpsosely differ from zlib's: items/size is size_t, not unsigned long.
56        typedef void *( *mz_alloc_func )( void *opaque, size_t items, size_t size );
57        typedef void( *mz_free_func )( void *opaque, void *address );
58        typedef void *( *mz_realloc_func )( void *opaque, void *address, size_t items, size_t size );
59
60#define MZ_VERSION          "9.1.15"
61#define MZ_VERNUM           0x91F0
62#define MZ_VER_MAJOR        9
63#define MZ_VER_MINOR        1
64#define MZ_VER_REVISION     15
65#define MZ_VER_SUBREVISION  0
66
67        // 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).
68        enum { MZ_NO_FLUSH = 0, MZ_PARTIAL_FLUSH = 1, MZ_SYNC_FLUSH = 2, MZ_FULL_FLUSH = 3, MZ_FINISH = 4, MZ_BLOCK = 5 };
69
70        // Return status codes. MZ_PARAM_ERROR is non-standard.
71        enum { MZ_OK = 0, MZ_STREAM_END = 1, MZ_NEED_DICT = 2, MZ_ERRNO = -1, MZ_STREAM_ERROR = -2, MZ_DATA_ERROR = -3, MZ_MEM_ERROR = -4, MZ_BUF_ERROR = -5, MZ_VERSION_ERROR = -6, MZ_PARAM_ERROR = -10000 };
72
73        // 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.
74        enum { MZ_NO_COMPRESSION = 0, MZ_BEST_SPEED = 1, MZ_BEST_COMPRESSION = 9, MZ_UBER_COMPRESSION = 10, MZ_DEFAULT_LEVEL = 6, MZ_DEFAULT_COMPRESSION = -1 };
75
76        // Window bits
77#define MZ_DEFAULT_WINDOW_BITS 15
78
79        struct mz_internal_state;
80
81        // Compression/decompression stream struct.
82        typedef struct mz_stream_s
83        {
84                const unsigned char *next_in;     // pointer to next byte to read
85                unsigned int avail_in;            // number of bytes available at next_in
86                mz_ulong total_in;                // total number of bytes consumed so far
87
88                unsigned char *next_out;          // pointer to next byte to write
89                unsigned int avail_out;           // number of bytes that can be written to next_out
90                mz_ulong total_out;               // total number of bytes produced so far
91
92                char *msg;                        // error msg (unused)
93                struct mz_internal_state *state;  // internal state, allocated by zalloc/zfree
94
95                mz_alloc_func zalloc;             // optional heap allocation function (defaults to malloc)
96                mz_free_func zfree;               // optional heap free function (defaults to free)
97                void *opaque;                     // heap alloc function user pointer
98
99                int data_type;                    // data_type (unused)
100                mz_ulong adler;                   // adler32 of the source or uncompressed data
101                mz_ulong reserved;                // not used
102        } mz_stream;
103
104        typedef mz_stream *mz_streamp;
105
106        // Returns the version string of miniz.c.
107        const char *mz_version( void );
108
109        // mz_deflateInit() initializes a compressor with default options:
110        // Parameters:
111        //  pStream must point to an initialized mz_stream struct.
112        //  level must be between [MZ_NO_COMPRESSION, MZ_BEST_COMPRESSION].
113        //  level 1 enables a specially optimized compression function that's been optimized purely for performance, not ratio.
114        //  (This special func. is currently only enabled when MINIZ_USE_UNALIGNED_LOADS_AND_STORES and MINIZ_LITTLE_ENDIAN are defined.)
115        // Return values:
116        //  MZ_OK on success.
117        //  MZ_STREAM_ERROR if the stream is bogus.
118        //  MZ_PARAM_ERROR if the input parameters are bogus.
119        //  MZ_MEM_ERROR on out of memory.
120        int mz_deflateInit( mz_streamp pStream, int level );
121
122        // mz_deflateInit2() is like mz_deflate(), except with more control:
123        // Additional parameters:
124        //   method must be MZ_DEFLATED
125        //   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)
126        //   mem_level must be between [1, 9] (it's checked but ignored by miniz.c)
127        int mz_deflateInit2( mz_streamp pStream, int level, int method, int window_bits, int mem_level, int strategy );
128
129        // Quickly resets a compressor without having to reallocate anything. Same as calling mz_deflateEnd() followed by mz_deflateInit()/mz_deflateInit2().
130        int mz_deflateReset( mz_streamp pStream );
131
132        // mz_deflate() compresses the input to output, consuming as much of the input and producing as much output as possible.
133        // Parameters:
134        //   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.
135        //   flush may be MZ_NO_FLUSH, MZ_PARTIAL_FLUSH/MZ_SYNC_FLUSH, MZ_FULL_FLUSH, or MZ_FINISH.
136        // Return values:
137        //   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).
138        //   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.
139        //   MZ_STREAM_ERROR if the stream is bogus.
140        //   MZ_PARAM_ERROR if one of the parameters is invalid.
141        //   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.)
142        int mz_deflate( mz_streamp pStream, int flush );
143
144        // mz_deflateEnd() deinitializes a compressor:
145        // Return values:
146        //  MZ_OK on success.
147        //  MZ_STREAM_ERROR if the stream is bogus.
148        int mz_deflateEnd( mz_streamp pStream );
149
150        // 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.
151        mz_ulong mz_deflateBound( mz_streamp pStream, mz_ulong source_len );
152
153        // Single-call compression functions mz_compress() and mz_compress2():
154        // Returns MZ_OK on success, or one of the error codes from mz_deflate() on failure.
155        int mz_compress( unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len );
156        int mz_compress2( unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len, int level );
157
158        // mz_compressBound() returns a (very) conservative upper bound on the amount of data that could be generated by calling mz_compress().
159        mz_ulong mz_compressBound( mz_ulong source_len );
160
161        // Initializes a decompressor.
162        int mz_inflateInit( mz_streamp pStream );
163
164        // 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:
165        // window_bits must be MZ_DEFAULT_WINDOW_BITS (to parse zlib header/footer) or -MZ_DEFAULT_WINDOW_BITS (raw deflate).
166        int mz_inflateInit2( mz_streamp pStream, int window_bits );
167
168        // 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.
169        // Parameters:
170        //   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.
171        //   flush may be MZ_NO_FLUSH, MZ_SYNC_FLUSH, or MZ_FINISH.
172        //   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).
173        //   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.
174        // Return values:
175        //   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.
176        //   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.
177        //   MZ_STREAM_ERROR if the stream is bogus.
178        //   MZ_DATA_ERROR if the deflate stream is invalid.
179        //   MZ_PARAM_ERROR if one of the parameters is invalid.
180        //   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
181        //   with more input data, or with more room in the output buffer (except when using single call decompression, described above).
182        int mz_inflate( mz_streamp pStream, int flush );
183
184        // Deinitializes a decompressor.
185        int mz_inflateEnd( mz_streamp pStream );
186
187        // Single-call decompression.
188        // Returns MZ_OK on success, or one of the error codes from mz_inflate() on failure.
189        int mz_uncompress( unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len );
190
191        // Returns a string description of the specified error code, or NULL if the error code is invalid.
192        const char *mz_error( int err );
193
194        // 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.
195        // Define MINIZ_NO_ZLIB_COMPATIBLE_NAMES to disable zlib-compatibility if you use zlib in the same project.
196#ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES
197        typedef unsigned char Byte;
198        typedef unsigned int uInt;
199        typedef mz_ulong uLong;
200        typedef Byte Bytef;
201        typedef uInt uIntf;
202        typedef char charf;
203        typedef int intf;
204        typedef void *voidpf;
205        typedef uLong uLongf;
206        typedef void *voidp;
207        typedef void *const voidpc;
208#define Z_NULL                0
209#define Z_NO_FLUSH            MZ_NO_FLUSH
210#define Z_PARTIAL_FLUSH       MZ_PARTIAL_FLUSH
211#define Z_SYNC_FLUSH          MZ_SYNC_FLUSH
212#define Z_FULL_FLUSH          MZ_FULL_FLUSH
213#define Z_FINISH              MZ_FINISH
214#define Z_BLOCK               MZ_BLOCK
215#define Z_OK                  MZ_OK
216#define Z_STREAM_END          MZ_STREAM_END
217#define Z_NEED_DICT           MZ_NEED_DICT
218#define Z_ERRNO               MZ_ERRNO
219#define Z_STREAM_ERROR        MZ_STREAM_ERROR
220#define Z_DATA_ERROR          MZ_DATA_ERROR
221#define Z_MEM_ERROR           MZ_MEM_ERROR
222#define Z_BUF_ERROR           MZ_BUF_ERROR
223#define Z_VERSION_ERROR       MZ_VERSION_ERROR
224#define Z_PARAM_ERROR         MZ_PARAM_ERROR
225#define Z_NO_COMPRESSION      MZ_NO_COMPRESSION
226#define Z_BEST_SPEED          MZ_BEST_SPEED
227#define Z_BEST_COMPRESSION    MZ_BEST_COMPRESSION
228#define Z_DEFAULT_COMPRESSION MZ_DEFAULT_COMPRESSION
229#define Z_DEFAULT_STRATEGY    MZ_DEFAULT_STRATEGY
230#define Z_FILTERED            MZ_FILTERED
231#define Z_HUFFMAN_ONLY        MZ_HUFFMAN_ONLY
232#define Z_RLE                 MZ_RLE
233#define Z_FIXED               MZ_FIXED
234#define Z_DEFLATED            MZ_DEFLATED
235#define Z_DEFAULT_WINDOW_BITS MZ_DEFAULT_WINDOW_BITS
236#define alloc_func            mz_alloc_func
237#define free_func             mz_free_func
238#define internal_state        mz_internal_state
239#define z_stream              mz_stream
240#define deflateInit           mz_deflateInit
241#define deflateInit2          mz_deflateInit2
242#define deflateReset          mz_deflateReset
243#define deflate               mz_deflate
244#define deflateEnd            mz_deflateEnd
245#define deflateBound          mz_deflateBound
246#define compress              mz_compress
247#define compress2             mz_compress2
248#define compressBound         mz_compressBound
249#define inflateInit           mz_inflateInit
250#define inflateInit2          mz_inflateInit2
251#define inflate               mz_inflate
252#define inflateEnd            mz_inflateEnd
253#define uncompress            mz_uncompress
254#define crc32                 mz_crc32
255#define adler32               mz_adler32
256#define MAX_WBITS             15
257#define MAX_MEM_LEVEL         9
258#define zError                mz_error
259#define ZLIB_VERSION          MZ_VERSION
260#define ZLIB_VERNUM           MZ_VERNUM
261#define ZLIB_VER_MAJOR        MZ_VER_MAJOR
262#define ZLIB_VER_MINOR        MZ_VER_MINOR
263#define ZLIB_VER_REVISION     MZ_VER_REVISION
264#define ZLIB_VER_SUBREVISION  MZ_VER_SUBREVISION
265#define zlibVersion           mz_version
266#define zlib_version          mz_version()
267#endif // #ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES
268
269#endif // MINIZ_NO_ZLIB_APIS
270
271        // ------------------- Types and macros
272
273        typedef unsigned char mz_uint8;
274        typedef signed short mz_int16;
275        typedef unsigned short mz_uint16;
276        typedef unsigned int mz_uint32;
277        typedef unsigned int mz_uint;
278        typedef long long mz_int64;
279        typedef unsigned long long mz_uint64;
280        typedef int mz_bool;
281
282#define MZ_FALSE (0)
283#define MZ_TRUE (1)
284
285        // An attempt to work around MSVC's spammy "warning C4127: conditional expression is constant" message.
286#ifdef _MSC_VER
287#define MZ_MACRO_END while (0, 0)
288#else
289#define MZ_MACRO_END while (0)
290#endif
291
292        // ------------------- ZIP archive reading/writing
293
294#ifndef MINIZ_NO_ARCHIVE_APIS
295
296        enum
297        {
298                MZ_ZIP_MAX_IO_BUF_SIZE = 64 * 1024,
299                MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE = 260,
300                MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE = 256
301        };
302
303        typedef struct
304        {
305                mz_uint32 m_file_index;
306                mz_uint32 m_central_dir_ofs;
307                mz_uint16 m_version_made_by;
308                mz_uint16 m_version_needed;
309                mz_uint16 m_bit_flag;
310                mz_uint16 m_method;
311#ifndef MINIZ_NO_TIME
312                time_t m_time;
313#endif
314                mz_uint32 m_crc32;
315                mz_uint64 m_comp_size;
316                mz_uint64 m_uncomp_size;
317                mz_uint16 m_internal_attr;
318                mz_uint32 m_external_attr;
319                mz_uint64 m_local_header_ofs;
320                mz_uint32 m_comment_size;
321                char m_filename[MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE];
322                char m_comment[MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE];
323        } mz_zip_archive_file_stat;
324
325        typedef size_t( *mz_file_read_func )( void *pOpaque, mz_uint64 file_ofs, void *pBuf, size_t n );
326        typedef size_t( *mz_file_write_func )( void *pOpaque, mz_uint64 file_ofs, const void *pBuf, size_t n );
327
328        struct mz_zip_internal_state_tag;
329        typedef struct mz_zip_internal_state_tag mz_zip_internal_state;
330
331        typedef enum
332        {
333                MZ_ZIP_MODE_INVALID = 0,
334                MZ_ZIP_MODE_READING = 1,
335                MZ_ZIP_MODE_WRITING = 2,
336                MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED = 3
337        } mz_zip_mode;
338
339        typedef struct mz_zip_archive_tag
340        {
341                mz_uint64 m_archive_size;
342                mz_uint64 m_central_directory_file_ofs;
343                mz_uint m_total_files;
344                mz_zip_mode m_zip_mode;
345
346                mz_uint m_file_offset_alignment;
347
348                mz_alloc_func m_pAlloc;
349                mz_free_func m_pFree;
350                mz_realloc_func m_pRealloc;
351                void *m_pAlloc_opaque;
352
353                mz_file_read_func m_pRead;
354                mz_file_write_func m_pWrite;
355                void *m_pIO_opaque;
356
357                mz_zip_internal_state *m_pState;
358
359        } mz_zip_archive;
360
361        typedef enum
362        {
363                MZ_ZIP_FLAG_CASE_SENSITIVE = 0x0100,
364                MZ_ZIP_FLAG_IGNORE_PATH = 0x0200,
365                MZ_ZIP_FLAG_COMPRESSED_DATA = 0x0400,
366                MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY = 0x0800
367        } mz_zip_flags;
368
369        // ZIP archive reading
370
371        // Inits a ZIP archive reader.
372        // These functions read and validate the archive's central directory.
373        mz_bool mz_zip_reader_init( mz_zip_archive *pZip, mz_uint64 size, mz_uint32 flags );
374        mz_bool mz_zip_reader_init_mem( mz_zip_archive *pZip, const void *pMem, size_t size, mz_uint32 flags );
375
376#ifndef MINIZ_NO_STDIO
377        mz_bool mz_zip_reader_init_file( mz_zip_archive *pZip, const char *pFilename, mz_uint32 flags );
378#endif
379
380        // Returns the total number of files in the archive.
381        mz_uint mz_zip_reader_get_num_files( mz_zip_archive *pZip );
382
383        // Returns detailed information about an archive file entry.
384        mz_bool mz_zip_reader_file_stat( mz_zip_archive *pZip, mz_uint file_index, mz_zip_archive_file_stat *pStat );
385
386        // Determines if an archive file entry is a directory entry.
387        mz_bool mz_zip_reader_is_file_a_directory( mz_zip_archive *pZip, mz_uint file_index );
388        mz_bool mz_zip_reader_is_file_encrypted( mz_zip_archive *pZip, mz_uint file_index );
389
390        // Retrieves the filename of an archive file entry.
391        // Returns the number of bytes written to pFilename, or if filename_buf_size is 0 this function returns the number of bytes needed to fully store the filename.
392        mz_uint mz_zip_reader_get_filename( mz_zip_archive *pZip, mz_uint file_index, char *pFilename, mz_uint filename_buf_size );
393
394        // Attempts to locates a file in the archive's central directory.
395        // Valid flags: MZ_ZIP_FLAG_CASE_SENSITIVE, MZ_ZIP_FLAG_IGNORE_PATH
396        // Returns -1 if the file cannot be found.
397        int mz_zip_reader_locate_file( mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags );
398
399        // Extracts a archive file to a memory buffer using no memory allocation.
400        mz_bool mz_zip_reader_extract_to_mem_no_alloc( mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size );
401        mz_bool mz_zip_reader_extract_file_to_mem_no_alloc( mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size );
402
403        // Extracts a archive file to a memory buffer.
404        mz_bool mz_zip_reader_extract_to_mem( mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags );
405        mz_bool mz_zip_reader_extract_file_to_mem( mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags );
406
407        // Extracts a archive file to a dynamically allocated heap buffer.
408        void *mz_zip_reader_extract_to_heap( mz_zip_archive *pZip, mz_uint file_index, size_t *pSize, mz_uint flags );
409        void *mz_zip_reader_extract_file_to_heap( mz_zip_archive *pZip, const char *pFilename, size_t *pSize, mz_uint flags );
410
411        // Extracts a archive file using a callback function to output the file's data.
412        mz_bool mz_zip_reader_extract_to_callback( mz_zip_archive *pZip, mz_uint file_index, mz_file_write_func pCallback, void *pOpaque, mz_uint flags );
413        mz_bool mz_zip_reader_extract_file_to_callback( mz_zip_archive *pZip, const char *pFilename, mz_file_write_func pCallback, void *pOpaque, mz_uint flags );
414
415#ifndef MINIZ_NO_STDIO
416        // Extracts a archive file to a disk file and sets its last accessed and modified times.
417        // This function only extracts files, not archive directory records.
418        mz_bool mz_zip_reader_extract_to_file( mz_zip_archive *pZip, mz_uint file_index, const char *pDst_filename, mz_uint flags );
419        mz_bool mz_zip_reader_extract_file_to_file( mz_zip_archive *pZip, const char *pArchive_filename, const char *pDst_filename, mz_uint flags );
420#endif
421
422        // Ends archive reading, freeing all allocations, and closing the input archive file if mz_zip_reader_init_file() was used.
423        mz_bool mz_zip_reader_end( mz_zip_archive *pZip );
424
425        // ZIP archive writing
426
427#ifndef MINIZ_NO_ARCHIVE_WRITING_APIS
428
429        // Inits a ZIP archive writer.
430        mz_bool mz_zip_writer_init( mz_zip_archive *pZip, mz_uint64 existing_size );
431        mz_bool mz_zip_writer_init_heap( mz_zip_archive *pZip, size_t size_to_reserve_at_beginning, size_t initial_allocation_size );
432
433#ifndef MINIZ_NO_STDIO
434        mz_bool mz_zip_writer_init_file( mz_zip_archive *pZip, const char *pFilename, mz_uint64 size_to_reserve_at_beginning );
435#endif
436
437        // Converts a ZIP archive reader object into a writer object, to allow efficient in-place file appends to occur on an existing archive.
438        // For archives opened using mz_zip_reader_init_file, pFilename must be the archive's filename so it can be reopened for writing. If the file can't be reopened, mz_zip_reader_end() will be called.
439        // For archives opened using mz_zip_reader_init_mem, the memory block must be growable using the realloc callback (which defaults to realloc unless you've overridden it).
440        // Finally, for archives opened using mz_zip_reader_init, the mz_zip_archive's user provided m_pWrite function cannot be NULL.
441        // Note: In-place archive modification is not recommended unless you know what you're doing, because if execution stops or something goes wrong before
442        // the archive is finalized the file's central directory will be hosed.
443        mz_bool mz_zip_writer_init_from_reader( mz_zip_archive *pZip, const char *pFilename );
444
445        // Adds the contents of a memory buffer to an archive. These functions record the current local time into the archive.
446        // To add a directory entry, call this method with an archive name ending in a forwardslash with empty buffer.
447        // level_and_flags - compression level (0-10, see MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or just set to MZ_DEFAULT_COMPRESSION.
448        mz_bool mz_zip_writer_add_mem( mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, mz_uint level_and_flags );
449        mz_bool mz_zip_writer_add_mem_ex( mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, mz_uint64 uncomp_size, mz_uint32 uncomp_crc32 );
450
451#ifndef MINIZ_NO_STDIO
452        // Adds the contents of a disk file to an archive. This function also records the disk file's modified time into the archive.
453        // level_and_flags - compression level (0-10, see MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or just set to MZ_DEFAULT_COMPRESSION.
454        mz_bool mz_zip_writer_add_file( mz_zip_archive *pZip, const char *pArchive_name, const char *pSrc_filename, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags );
455#endif
456
457        // Adds a file to an archive by fully cloning the data from another archive.
458        // This function fully clones the source file's compressed data (no recompression), along with its full filename, extra data, and comment fields.
459        mz_bool mz_zip_writer_add_from_zip_reader( mz_zip_archive *pZip, mz_zip_archive *pSource_zip, mz_uint file_index );
460
461        // Finalizes the archive by writing the central directory records followed by the end of central directory record.
462        // After an archive is finalized, the only valid call on the mz_zip_archive struct is mz_zip_writer_end().
463        // An archive must be manually finalized by calling this function for it to be valid.
464        mz_bool mz_zip_writer_finalize_archive( mz_zip_archive *pZip );
465        mz_bool mz_zip_writer_finalize_heap_archive( mz_zip_archive *pZip, void **pBuf, size_t *pSize );
466
467        // Ends archive writing, freeing all allocations, and closing the output file if mz_zip_writer_init_file() was used.
468        // Note for the archive to be valid, it must have been finalized before ending.
469        mz_bool mz_zip_writer_end( mz_zip_archive *pZip );
470
471        // Misc. high-level helper functions:
472
473        // mz_zip_add_mem_to_archive_file_in_place() efficiently (but not atomically) appends a memory blob to a ZIP archive.
474        // level_and_flags - compression level (0-10, see MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or just set to MZ_DEFAULT_COMPRESSION.
475        mz_bool mz_zip_add_mem_to_archive_file_in_place( const char *pZip_filename, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags );
476
477        // Reads a single file from an archive into a heap block.
478        // Returns NULL on failure.
479        void *mz_zip_extract_archive_file_to_heap( const char *pZip_filename, const char *pArchive_name, size_t *pSize, mz_uint zip_flags );
480
481#endif // #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS
482
483#endif // #ifndef MINIZ_NO_ARCHIVE_APIS
484
485        // ------------------- Low-level Decompression API Definitions
486
487        // Decompression flags used by tinfl_decompress().
488        // 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.
489        // 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.
490        // 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).
491        // TINFL_FLAG_COMPUTE_ADLER32: Force adler-32 checksum computation of the decompressed bytes.
492        enum
493        {
494                TINFL_FLAG_PARSE_ZLIB_HEADER = 1,
495                TINFL_FLAG_HAS_MORE_INPUT = 2,
496                TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF = 4,
497                TINFL_FLAG_COMPUTE_ADLER32 = 8
498        };
499
500        // High level decompression functions:
501        // tinfl_decompress_mem_to_heap() decompresses a block in memory to a heap block allocated via malloc().
502        // On entry:
503        //  pSrc_buf, src_buf_len: Pointer and size of the Deflate or zlib source data to decompress.
504        // On return:
505        //  Function returns a pointer to the decompressed data, or NULL on failure.
506        //  *pOut_len will be set to the decompressed data's size, which could be larger than src_buf_len on uncompressible data.
507        //  The caller must call mz_free() on the returned block when it's no longer needed.
508        void *tinfl_decompress_mem_to_heap( const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags );
509
510        // tinfl_decompress_mem_to_mem() decompresses a block in memory to another block in memory.
511        // Returns TINFL_DECOMPRESS_MEM_TO_MEM_FAILED on failure, or the number of bytes written on success.
512#define TINFL_DECOMPRESS_MEM_TO_MEM_FAILED ((size_t)(-1))
513        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 );
514
515        // 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.
516        // Returns 1 on success or 0 on failure.
517        typedef int( *tinfl_put_buf_func_ptr )( const void* pBuf, int len, void *pUser );
518        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 );
519
520        struct tinfl_decompressor_tag; typedef struct tinfl_decompressor_tag tinfl_decompressor;
521
522        // Max size of LZ dictionary.
523#define TINFL_LZ_DICT_SIZE 32768
524
525        // Return status.
526        typedef enum
527        {
528                TINFL_STATUS_BAD_PARAM = -3,
529                TINFL_STATUS_ADLER32_MISMATCH = -2,
530                TINFL_STATUS_FAILED = -1,
531                TINFL_STATUS_DONE = 0,
532                TINFL_STATUS_NEEDS_MORE_INPUT = 1,
533                TINFL_STATUS_HAS_MORE_OUTPUT = 2
534        } tinfl_status;
535
536        // Initializes the decompressor to its initial state.
537#define tinfl_init(r) do { (r)->m_state = 0; } MZ_MACRO_END
538#define tinfl_get_adler32(r) (r)->m_check_adler32
539
540        // 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.
541        // 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.
542        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 );
543
544        // Internal/private bits follow.
545        enum
546        {
547                TINFL_MAX_HUFF_TABLES = 3, TINFL_MAX_HUFF_SYMBOLS_0 = 288, TINFL_MAX_HUFF_SYMBOLS_1 = 32, TINFL_MAX_HUFF_SYMBOLS_2 = 19,
548                TINFL_FAST_LOOKUP_BITS = 10, TINFL_FAST_LOOKUP_SIZE = 1 << TINFL_FAST_LOOKUP_BITS
549        };
550
551        typedef struct
552        {
553                mz_uint8 m_code_size[TINFL_MAX_HUFF_SYMBOLS_0];
554                mz_int16 m_look_up[TINFL_FAST_LOOKUP_SIZE], m_tree[TINFL_MAX_HUFF_SYMBOLS_0 * 2];
555        } tinfl_huff_table;
556
557#if MINIZ_HAS_64BIT_REGISTERS
558#define TINFL_USE_64BIT_BITBUF 1
559#endif
560
561#if TINFL_USE_64BIT_BITBUF
562        typedef mz_uint64 tinfl_bit_buf_t;
563#define TINFL_BITBUF_SIZE (64)
564#else
565        typedef mz_uint32 tinfl_bit_buf_t;
566#define TINFL_BITBUF_SIZE (32)
567#endif
568
569        struct tinfl_decompressor_tag
570        {
571                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];
572                tinfl_bit_buf_t m_bit_buf;
573                size_t m_dist_from_out_buf_start;
574                tinfl_huff_table m_tables[TINFL_MAX_HUFF_TABLES];
575                mz_uint8 m_raw_header[4], m_len_codes[TINFL_MAX_HUFF_SYMBOLS_0 + TINFL_MAX_HUFF_SYMBOLS_1 + 137];
576        };
577
578        // ------------------- Low-level Compression API Definitions
579
580        // Set TDEFL_LESS_MEMORY to 1 to use less memory (compression will be slightly slower, and raw/dynamic blocks will be output more frequently).
581#define TDEFL_LESS_MEMORY 0
582
583        // tdefl_init() compression flags logically OR'd together (low 12 bits contain the max. number of probes per dictionary search):
584        // 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).
585        enum
586        {
587                TDEFL_HUFFMAN_ONLY = 0, TDEFL_DEFAULT_MAX_PROBES = 128, TDEFL_MAX_PROBES_MASK = 0xFFF
588        };
589
590        // 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.
591        // TDEFL_COMPUTE_ADLER32: Always compute the adler-32 of the input data (even when not writing zlib headers).
592        // TDEFL_GREEDY_PARSING_FLAG: Set to use faster greedy parsing, instead of more efficient lazy parsing.
593        // 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).
594        // TDEFL_RLE_MATCHES: Only look for RLE matches (matches with a distance of 1)
595        // TDEFL_FILTER_MATCHES: Discards matches <= 5 chars if enabled.
596        // TDEFL_FORCE_ALL_STATIC_BLOCKS: Disable usage of optimized Huffman tables.
597        // TDEFL_FORCE_ALL_RAW_BLOCKS: Only use raw (uncompressed) deflate blocks.
598        // The low 12 bits are reserved to control the max # of hash probes per dictionary lookup (see TDEFL_MAX_PROBES_MASK).
599        enum
600        {
601                TDEFL_WRITE_ZLIB_HEADER = 0x01000,
602                TDEFL_COMPUTE_ADLER32 = 0x02000,
603                TDEFL_GREEDY_PARSING_FLAG = 0x04000,
604                TDEFL_NONDETERMINISTIC_PARSING_FLAG = 0x08000,
605                TDEFL_RLE_MATCHES = 0x10000,
606                TDEFL_FILTER_MATCHES = 0x20000,
607                TDEFL_FORCE_ALL_STATIC_BLOCKS = 0x40000,
608                TDEFL_FORCE_ALL_RAW_BLOCKS = 0x80000
609        };
610
611        // High level compression functions:
612        // tdefl_compress_mem_to_heap() compresses a block in memory to a heap block allocated via malloc().
613        // On entry:
614        //  pSrc_buf, src_buf_len: Pointer and size of source block to compress.
615        //  flags: The max match finder probes (default is 128) logically OR'd against the above flags. Higher probes are slower but improve compression.
616        // On return:
617        //  Function returns a pointer to the compressed data, or NULL on failure.
618        //  *pOut_len will be set to the compressed data's size, which could be larger than src_buf_len on uncompressible data.
619        //  The caller must free() the returned block when it's no longer needed.
620        void *tdefl_compress_mem_to_heap( const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags );
621
622        // tdefl_compress_mem_to_mem() compresses a block in memory to another block in memory.
623        // Returns 0 on failure.
624        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 );
625
626        // Compresses an image to a compressed PNG file in memory.
627        // On entry:
628        //  pImage, w, h, and num_chans describe the image to compress. num_chans may be 1, 2, 3, or 4.
629        //  The image pitch in bytes per scanline will be w*num_chans. The leftmost pixel on the top scanline is stored first in memory.
630        //  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
631        //  If flip is true, the image will be flipped on the Y axis (useful for OpenGL apps).
632        // On return:
633        //  Function returns a pointer to the compressed data, or NULL on failure.
634        //  *pLen_out will be set to the size of the PNG image file.
635        //  The caller must mz_free() the returned heap block (which will typically be larger than *pLen_out) when it's no longer needed.
636        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 );
637        void *tdefl_write_image_to_png_file_in_memory( const void *pImage, int w, int h, int num_chans, size_t *pLen_out );
638
639        // Output stream interface. The compressor uses this interface to write compressed data. It'll typically be called TDEFL_OUT_BUF_SIZE at a time.
640        typedef mz_bool( *tdefl_put_buf_func_ptr )( const void* pBuf, int len, void *pUser );
641
642        // tdefl_compress_mem_to_output() compresses a block to an output stream. The above helpers use this function internally.
643        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 );
644
645        enum { TDEFL_MAX_HUFF_TABLES = 3, TDEFL_MAX_HUFF_SYMBOLS_0 = 288, TDEFL_MAX_HUFF_SYMBOLS_1 = 32, TDEFL_MAX_HUFF_SYMBOLS_2 = 19, TDEFL_LZ_DICT_SIZE = 32768, TDEFL_LZ_DICT_SIZE_MASK = TDEFL_LZ_DICT_SIZE - 1, TDEFL_MIN_MATCH_LEN = 3, TDEFL_MAX_MATCH_LEN = 258 };
646
647        // TDEFL_OUT_BUF_SIZE MUST be large enough to hold a single entire compressed output block (using static/fixed Huffman codes).
648#if TDEFL_LESS_MEMORY
649        enum { TDEFL_LZ_CODE_BUF_SIZE = 24 * 1024, TDEFL_OUT_BUF_SIZE = ( TDEFL_LZ_CODE_BUF_SIZE * 13 ) / 10, TDEFL_MAX_HUFF_SYMBOLS = 288, TDEFL_LZ_HASH_BITS = 12, TDEFL_LEVEL1_HASH_SIZE_MASK = 4095, TDEFL_LZ_HASH_SHIFT = ( TDEFL_LZ_HASH_BITS + 2 ) / 3, TDEFL_LZ_HASH_SIZE = 1 << TDEFL_LZ_HASH_BITS };
650#else
651        enum { TDEFL_LZ_CODE_BUF_SIZE = 64 * 1024, TDEFL_OUT_BUF_SIZE = ( TDEFL_LZ_CODE_BUF_SIZE * 13 ) / 10, TDEFL_MAX_HUFF_SYMBOLS = 288, TDEFL_LZ_HASH_BITS = 15, TDEFL_LEVEL1_HASH_SIZE_MASK = 4095, TDEFL_LZ_HASH_SHIFT = ( TDEFL_LZ_HASH_BITS + 2 ) / 3, TDEFL_LZ_HASH_SIZE = 1 << TDEFL_LZ_HASH_BITS };
652#endif
653
654        // 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.
655        typedef enum
656        {
657                TDEFL_STATUS_BAD_PARAM = -2,
658                TDEFL_STATUS_PUT_BUF_FAILED = -1,
659                TDEFL_STATUS_OKAY = 0,
660                TDEFL_STATUS_DONE = 1,
661        } tdefl_status;
662
663        // Must map to MZ_NO_FLUSH, MZ_SYNC_FLUSH, etc. enums
664        typedef enum
665        {
666                TDEFL_NO_FLUSH = 0,
667                TDEFL_SYNC_FLUSH = 2,
668                TDEFL_FULL_FLUSH = 3,
669                TDEFL_FINISH = 4
670        } tdefl_flush;
671
672        // tdefl's compression state structure.
673        typedef struct
674        {
675                tdefl_put_buf_func_ptr m_pPut_buf_func;
676                void *m_pPut_buf_user;
677                mz_uint m_flags, m_max_probes[2];
678                int m_greedy_parsing;
679                mz_uint m_adler32, m_lookahead_pos, m_lookahead_size, m_dict_size;
680                mz_uint8 *m_pLZ_code_buf, *m_pLZ_flags, *m_pOutput_buf, *m_pOutput_buf_end;
681                mz_uint m_num_flags_left, m_total_lz_bytes, m_lz_code_buf_dict_pos, m_bits_in, m_bit_buffer;
682                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;
683                tdefl_status m_prev_return_status;
684                const void *m_pIn_buf;
685                void *m_pOut_buf;
686                size_t *m_pIn_buf_size, *m_pOut_buf_size;
687                tdefl_flush m_flush;
688                const mz_uint8 *m_pSrc;
689                size_t m_src_buf_left, m_out_buf_ofs;
690                mz_uint8 m_dict[TDEFL_LZ_DICT_SIZE + TDEFL_MAX_MATCH_LEN - 1];
691                mz_uint16 m_huff_count[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS];
692                mz_uint16 m_huff_codes[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS];
693                mz_uint8 m_huff_code_sizes[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS];
694                mz_uint8 m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE];
695                mz_uint16 m_next[TDEFL_LZ_DICT_SIZE];
696                mz_uint16 m_hash[TDEFL_LZ_HASH_SIZE];
697                mz_uint8 m_output_buf[TDEFL_OUT_BUF_SIZE];
698        } tdefl_compressor;
699
700        // Initializes the compressor.
701        // There is no corresponding deinit() function because the tdefl API's do not dynamically allocate memory.
702        // 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.
703        // If pBut_buf_func is NULL the user should always call the tdefl_compress() API.
704        // flags: See the above enums (TDEFL_HUFFMAN_ONLY, TDEFL_WRITE_ZLIB_HEADER, etc.)
705        tdefl_status tdefl_init( tdefl_compressor *d, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags );
706
707        // 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.
708        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 );
709
710        // tdefl_compress_buffer() is only usable when the tdefl_init() is called with a non-NULL tdefl_put_buf_func_ptr.
711        // tdefl_compress_buffer() always consumes the entire input buffer.
712        tdefl_status tdefl_compress_buffer( tdefl_compressor *d, const void *pIn_buf, size_t in_buf_size, tdefl_flush flush );
713
714        tdefl_status tdefl_get_prev_return_status( tdefl_compressor *d );
715        mz_uint32 tdefl_get_adler32( tdefl_compressor *d );
716
717        // 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.
718#ifndef MINIZ_NO_ZLIB_APIS
719        // Create tdefl_compress() flags given zlib-style compression parameters.
720        // level may range from [0,10] (where 10 is absolute max compression, but may be much slower on some files)
721        // window_bits may be -15 (raw deflate) or 15 (zlib)
722        // strategy may be either MZ_DEFAULT_STRATEGY, MZ_FILTERED, MZ_HUFFMAN_ONLY, MZ_RLE, or MZ_FIXED
723        mz_uint tdefl_create_comp_flags_from_zip_params( int level, int window_bits, int strategy );
724#endif // #ifndef MINIZ_NO_ZLIB_APIS
725
726#ifdef __cplusplus
727}
728#endif
729
730
731// ------------------- End of Header: Implementation follows. (If you only want the header, define MINIZ_HEADER_FILE_ONLY.)
732
733typedef unsigned char mz_validate_uint16[sizeof( mz_uint16 ) == 2 ? 1 : -1];
734typedef unsigned char mz_validate_uint32[sizeof( mz_uint32 ) == 4 ? 1 : -1];
735typedef unsigned char mz_validate_uint64[sizeof( mz_uint64 ) == 8 ? 1 : -1];
736
737#include <string.h>
738#include <assert.h>
739
740#define MZ_ASSERT(x) assert(x)
741
742#ifdef MINIZ_NO_MALLOC
743#define MZ_MALLOC(x) NULL
744#define MZ_FREE(x) (void)x, ((void)0)
745#define MZ_REALLOC(p, x) NULL
746#else
747#define MZ_MALLOC(x) nvmalloc(x)
748#define MZ_FREE(x) nvfree(x)
749#define MZ_REALLOC(p, x) nvrealloc(p, x)
750#endif
751
752#define MZ_MAX(a,b) (((a)>(b))?(a):(b))
753#define MZ_MIN(a,b) (((a)<(b))?(a):(b))
754#define MZ_CLEAR_OBJ(obj) nvmemset(&(obj), 0, sizeof(obj))
755
756#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN
757#define MZ_READ_LE16(p) *((const mz_uint16 *)(p))
758#define MZ_READ_LE32(p) *((const mz_uint32 *)(p))
759#else
760#define MZ_READ_LE16(p) ((mz_uint32)(((const mz_uint8 *)(p))[0]) | ((mz_uint32)(((const mz_uint8 *)(p))[1]) << 8U))
761#define MZ_READ_LE32(p) ((mz_uint32)(((const mz_uint8 *)(p))[0]) | ((mz_uint32)(((const mz_uint8 *)(p))[1]) << 8U) | ((mz_uint32)(((const mz_uint8 *)(p))[2]) << 16U) | ((mz_uint32)(((const mz_uint8 *)(p))[3]) << 24U))
762#endif
763
764#ifdef _MSC_VER
765#define MZ_FORCEINLINE __forceinline
766#elif defined(__GNUC__)
767#define MZ_FORCEINLINE inline __attribute__((__always_inline__))
768#else
769#define MZ_FORCEINLINE inline
770#endif
771
772#ifdef __cplusplus
773extern "C" {
774#endif
775
776        // ------------------- zlib-style API's
777
778        mz_ulong mz_adler32( mz_ulong adler, const unsigned char *ptr, size_t buf_len )
779        {
780                mz_uint32 i, s1 = (mz_uint32)( adler & 0xffff ), s2 = (mz_uint32)( adler >> 16 ); size_t block_len = buf_len % 5552;
781                if ( !ptr ) return MZ_ADLER32_INIT;
782                while ( buf_len )
783                {
784                        for ( i = 0; i + 7 < block_len; i += 8, ptr += 8 )
785                        {
786                                s1 += ptr[0], s2 += s1; s1 += ptr[1], s2 += s1; s1 += ptr[2], s2 += s1; s1 += ptr[3], s2 += s1;
787                                s1 += ptr[4], s2 += s1; s1 += ptr[5], s2 += s1; s1 += ptr[6], s2 += s1; s1 += ptr[7], s2 += s1;
788                        }
789                        for ( ; i < block_len; ++i ) s1 += *ptr++, s2 += s1;
790                        s1 %= 65521U, s2 %= 65521U; buf_len -= block_len; block_len = 5552;
791                }
792                return ( s2 << 16 ) + s1;
793        }
794
795        // Karl Malbrain's compact CRC-32. See "A compact CCITT crc16 and crc32 C implementation that balances processor cache usage against speed": http://www.geocities.com/malbrain/
796        mz_ulong mz_crc32( mz_ulong crc, const mz_uint8 *ptr, size_t buf_len )
797        {
798                static const mz_uint32 s_crc32[16] = { 0, 0x1db71064, 0x3b6e20c8, 0x26d930ac, 0x76dc4190, 0x6b6b51f4, 0x4db26158, 0x5005713c,
799                        0xedb88320, 0xf00f9344, 0xd6d6a3e8, 0xcb61b38c, 0x9b64c2b0, 0x86d3d2d4, 0xa00ae278, 0xbdbdf21c };
800                mz_uint32 crcu32 = (mz_uint32)crc;
801                if ( !ptr ) return MZ_CRC32_INIT;
802                crcu32 = ~crcu32; while ( buf_len-- ) { mz_uint8 b = *ptr++; crcu32 = ( crcu32 >> 4 ) ^ s_crc32[( crcu32 & 0xF ) ^ ( b & 0xF )]; crcu32 = ( crcu32 >> 4 ) ^ s_crc32[( crcu32 & 0xF ) ^ ( b >> 4 )]; }
803                return ~crcu32;
804        }
805
806        void mz_free( void *p )
807        {
808                MZ_FREE( p );
809        }
810
811#ifndef MINIZ_NO_ZLIB_APIS
812
813        static void *def_alloc_func( void *opaque, size_t items, size_t size ) { (void)opaque, (void)items, (void)size; return MZ_MALLOC( items * size ); }
814        static void def_free_func( void *opaque, void *address ) { (void)opaque, (void)address; MZ_FREE( address ); }
815        static void *def_realloc_func( void *opaque, void *address, size_t items, size_t size ) { (void)opaque, (void)address, (void)items, (void)size; return MZ_REALLOC( address, items * size ); }
816
817        const char *mz_version( void )
818        {
819                return MZ_VERSION;
820        }
821
822        int mz_deflateInit( mz_streamp pStream, int level )
823        {
824                return mz_deflateInit2( pStream, level, MZ_DEFLATED, MZ_DEFAULT_WINDOW_BITS, 9, MZ_DEFAULT_STRATEGY );
825        }
826
827        int mz_deflateInit2( mz_streamp pStream, int level, int method, int window_bits, int mem_level, int strategy )
828        {
829                tdefl_compressor *pComp;
830                mz_uint comp_flags = TDEFL_COMPUTE_ADLER32 | tdefl_create_comp_flags_from_zip_params( level, window_bits, strategy );
831
832                if ( !pStream ) return MZ_STREAM_ERROR;
833                if ( ( method != MZ_DEFLATED ) || ( ( mem_level < 1 ) || ( mem_level > 9 ) ) || ( ( window_bits != MZ_DEFAULT_WINDOW_BITS ) && ( -window_bits != MZ_DEFAULT_WINDOW_BITS ) ) ) return MZ_PARAM_ERROR;
834
835                pStream->data_type = 0;
836                pStream->adler = MZ_ADLER32_INIT;
837                pStream->msg = NULL;
838                pStream->reserved = 0;
839                pStream->total_in = 0;
840                pStream->total_out = 0;
841                if ( !pStream->zalloc ) pStream->zalloc = def_alloc_func;
842                if ( !pStream->zfree ) pStream->zfree = def_free_func;
843
844                pComp = (tdefl_compressor *)pStream->zalloc( pStream->opaque, 1, sizeof( tdefl_compressor ) );
845                if ( !pComp )
846                        return MZ_MEM_ERROR;
847
848                pStream->state = ( struct mz_internal_state * )pComp;
849
850                if ( tdefl_init( pComp, NULL, NULL, comp_flags ) != TDEFL_STATUS_OKAY )
851                {
852                        mz_deflateEnd( pStream );
853                        return MZ_PARAM_ERROR;
854                }
855
856                return MZ_OK;
857        }
858
859        int mz_deflateReset( mz_streamp pStream )
860        {
861                if ( ( !pStream ) || ( !pStream->state ) || ( !pStream->zalloc ) || ( !pStream->zfree ) ) return MZ_STREAM_ERROR;
862                pStream->total_in = pStream->total_out = 0;
863                tdefl_init( (tdefl_compressor*)pStream->state, NULL, NULL, ( (tdefl_compressor*)pStream->state )->m_flags );
864                return MZ_OK;
865        }
866
867        int mz_deflate( mz_streamp pStream, int flush )
868        {
869                size_t in_bytes, out_bytes;
870                mz_ulong orig_total_in, orig_total_out;
871                int mz_status = MZ_OK;
872
873                if ( ( !pStream ) || ( !pStream->state ) || ( flush < 0 ) || ( flush > MZ_FINISH ) || ( !pStream->next_out ) ) return MZ_STREAM_ERROR;
874                if ( !pStream->avail_out ) return MZ_BUF_ERROR;
875
876                if ( flush == MZ_PARTIAL_FLUSH ) flush = MZ_SYNC_FLUSH;
877
878                if ( ( (tdefl_compressor*)pStream->state )->m_prev_return_status == TDEFL_STATUS_DONE )
879                        return ( flush == MZ_FINISH ) ? MZ_STREAM_END : MZ_BUF_ERROR;
880
881                orig_total_in = pStream->total_in; orig_total_out = pStream->total_out;
882                for ( ; ; )
883                {
884                        tdefl_status defl_status;
885                        in_bytes = pStream->avail_in; out_bytes = pStream->avail_out;
886
887                        defl_status = tdefl_compress( (tdefl_compressor*)pStream->state, pStream->next_in, &in_bytes, pStream->next_out, &out_bytes, (tdefl_flush)flush );
888                        pStream->next_in += (mz_uint)in_bytes; pStream->avail_in -= (mz_uint)in_bytes;
889                        pStream->total_in += (mz_uint)in_bytes; pStream->adler = tdefl_get_adler32( (tdefl_compressor*)pStream->state );
890
891                        pStream->next_out += (mz_uint)out_bytes; pStream->avail_out -= (mz_uint)out_bytes;
892                        pStream->total_out += (mz_uint)out_bytes;
893
894                        if ( defl_status < 0 )
895                        {
896                                mz_status = MZ_STREAM_ERROR;
897                                break;
898                        }
899                        else if ( defl_status == TDEFL_STATUS_DONE )
900                        {
901                                mz_status = MZ_STREAM_END;
902                                break;
903                        }
904                        else if ( !pStream->avail_out )
905                                break;
906                        else if ( ( !pStream->avail_in ) && ( flush != MZ_FINISH ) )
907                        {
908                                if ( ( flush ) || ( pStream->total_in != orig_total_in ) || ( pStream->total_out != orig_total_out ) )
909                                        break;
910                                return MZ_BUF_ERROR; // Can't make forward progress without some input.
911                        }
912                }
913                return mz_status;
914        }
915
916        int mz_deflateEnd( mz_streamp pStream )
917        {
918                if ( !pStream ) return MZ_STREAM_ERROR;
919                if ( pStream->state )
920                {
921                        pStream->zfree( pStream->opaque, pStream->state );
922                        pStream->state = NULL;
923                }
924                return MZ_OK;
925        }
926
927        mz_ulong mz_deflateBound( mz_streamp pStream, mz_ulong source_len )
928        {
929                (void)pStream;
930                // This is really over conservative. (And lame, but it's actually pretty tricky to compute a true upper bound given the way tdefl's blocking works.)
931                return MZ_MAX( 128 + ( source_len * 110 ) / 100, 128 + source_len + ( ( source_len / ( 31 * 1024 ) ) + 1 ) * 5 );
932        }
933
934        int mz_compress2( unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len, int level )
935        {
936                int status;
937                mz_stream stream;
938                memset( &stream, 0, sizeof( stream ) );
939
940                // In case mz_ulong is 64-bits (argh I hate longs).
941                if ( ( source_len | *pDest_len ) > 0xFFFFFFFFU ) return MZ_PARAM_ERROR;
942
943                stream.next_in = pSource;
944                stream.avail_in = (mz_uint32)source_len;
945                stream.next_out = pDest;
946                stream.avail_out = (mz_uint32)*pDest_len;
947
948                status = mz_deflateInit( &stream, level );
949                if ( status != MZ_OK ) return status;
950
951                status = mz_deflate( &stream, MZ_FINISH );
952                if ( status != MZ_STREAM_END )
953                {
954                        mz_deflateEnd( &stream );
955                        return ( status == MZ_OK ) ? MZ_BUF_ERROR : status;
956                }
957
958                *pDest_len = stream.total_out;
959                return mz_deflateEnd( &stream );
960        }
961
962        int mz_compress( unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len )
963        {
964                return mz_compress2( pDest, pDest_len, pSource, source_len, MZ_DEFAULT_COMPRESSION );
965        }
966
967        mz_ulong mz_compressBound( mz_ulong source_len )
968        {
969                return mz_deflateBound( NULL, source_len );
970        }
971
972        typedef struct
973        {
974                tinfl_decompressor m_decomp;
975                mz_uint m_dict_ofs, m_dict_avail, m_first_call, m_has_flushed; int m_window_bits;
976                mz_uint8 m_dict[TINFL_LZ_DICT_SIZE];
977                tinfl_status m_last_status;
978        } inflate_state;
979
980        int mz_inflateInit2( mz_streamp pStream, int window_bits )
981        {
982                inflate_state *pDecomp;
983                if ( !pStream ) return MZ_STREAM_ERROR;
984                if ( ( window_bits != MZ_DEFAULT_WINDOW_BITS ) && ( -window_bits != MZ_DEFAULT_WINDOW_BITS ) ) return MZ_PARAM_ERROR;
985
986                pStream->data_type = 0;
987                pStream->adler = 0;
988                pStream->msg = NULL;
989                pStream->total_in = 0;
990                pStream->total_out = 0;
991                pStream->reserved = 0;
992                if ( !pStream->zalloc ) pStream->zalloc = def_alloc_func;
993                if ( !pStream->zfree ) pStream->zfree = def_free_func;
994
995                pDecomp = (inflate_state*)pStream->zalloc( pStream->opaque, 1, sizeof( inflate_state ) );
996                if ( !pDecomp ) return MZ_MEM_ERROR;
997
998                pStream->state = ( struct mz_internal_state * )pDecomp;
999
1000                tinfl_init( &pDecomp->m_decomp );
1001                pDecomp->m_dict_ofs = 0;
1002                pDecomp->m_dict_avail = 0;
1003                pDecomp->m_last_status = TINFL_STATUS_NEEDS_MORE_INPUT;
1004                pDecomp->m_first_call = 1;
1005                pDecomp->m_has_flushed = 0;
1006                pDecomp->m_window_bits = window_bits;
1007
1008                return MZ_OK;
1009        }
1010
1011        int mz_inflateInit( mz_streamp pStream )
1012        {
1013                return mz_inflateInit2( pStream, MZ_DEFAULT_WINDOW_BITS );
1014        }
1015
1016        int mz_inflate( mz_streamp pStream, int flush )
1017        {
1018                inflate_state* pState;
1019                mz_uint n, first_call, decomp_flags = TINFL_FLAG_COMPUTE_ADLER32;
1020                size_t in_bytes, out_bytes, orig_avail_in;
1021                tinfl_status status;
1022
1023                if ( ( !pStream ) || ( !pStream->state ) ) return MZ_STREAM_ERROR;
1024                if ( flush == MZ_PARTIAL_FLUSH ) flush = MZ_SYNC_FLUSH;
1025                if ( ( flush ) && ( flush != MZ_SYNC_FLUSH ) && ( flush != MZ_FINISH ) ) return MZ_STREAM_ERROR;
1026
1027                pState = (inflate_state*)pStream->state;
1028                if ( pState->m_window_bits > 0 ) decomp_flags |= TINFL_FLAG_PARSE_ZLIB_HEADER;
1029                orig_avail_in = pStream->avail_in;
1030
1031                first_call = pState->m_first_call; pState->m_first_call = 0;
1032                if ( pState->m_last_status < 0 ) return MZ_DATA_ERROR;
1033
1034                if ( pState->m_has_flushed && ( flush != MZ_FINISH ) ) return MZ_STREAM_ERROR;
1035                pState->m_has_flushed |= ( flush == MZ_FINISH );
1036
1037                if ( ( flush == MZ_FINISH ) && ( first_call ) )
1038                {
1039                        // MZ_FINISH on the first call implies that the input and output buffers are large enough to hold the entire compressed/decompressed file.
1040                        decomp_flags |= TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF;
1041                        in_bytes = pStream->avail_in; out_bytes = pStream->avail_out;
1042                        status = tinfl_decompress( &pState->m_decomp, pStream->next_in, &in_bytes, pStream->next_out, pStream->next_out, &out_bytes, decomp_flags );
1043                        pState->m_last_status = status;
1044                        pStream->next_in += (mz_uint)in_bytes; pStream->avail_in -= (mz_uint)in_bytes; pStream->total_in += (mz_uint)in_bytes;
1045                        pStream->adler = tinfl_get_adler32( &pState->m_decomp );
1046                        pStream->next_out += (mz_uint)out_bytes; pStream->avail_out -= (mz_uint)out_bytes; pStream->total_out += (mz_uint)out_bytes;
1047
1048                        if ( status < 0 )
1049                                return MZ_DATA_ERROR;
1050                        else if ( status != TINFL_STATUS_DONE )
1051                        {
1052                                pState->m_last_status = TINFL_STATUS_FAILED;
1053                                return MZ_BUF_ERROR;
1054                        }
1055                        return MZ_STREAM_END;
1056                }
1057                // flush != MZ_FINISH then we must assume there's more input.
1058                if ( flush != MZ_FINISH ) decomp_flags |= TINFL_FLAG_HAS_MORE_INPUT;
1059
1060                if ( pState->m_dict_avail )
1061                {
1062                        n = MZ_MIN( pState->m_dict_avail, pStream->avail_out );
1063                        memcpy( pStream->next_out, pState->m_dict + pState->m_dict_ofs, n );
1064                        pStream->next_out += n; pStream->avail_out -= n; pStream->total_out += n;
1065                        pState->m_dict_avail -= n; pState->m_dict_ofs = ( pState->m_dict_ofs + n ) & ( TINFL_LZ_DICT_SIZE - 1 );
1066                        return ( ( pState->m_last_status == TINFL_STATUS_DONE ) && ( !pState->m_dict_avail ) ) ? MZ_STREAM_END : MZ_OK;
1067                }
1068
1069                for ( ; ; )
1070                {
1071                        in_bytes = pStream->avail_in;
1072                        out_bytes = TINFL_LZ_DICT_SIZE - pState->m_dict_ofs;
1073
1074                        status = tinfl_decompress( &pState->m_decomp, pStream->next_in, &in_bytes, pState->m_dict, pState->m_dict + pState->m_dict_ofs, &out_bytes, decomp_flags );
1075                        pState->m_last_status = status;
1076
1077                        pStream->next_in += (mz_uint)in_bytes; pStream->avail_in -= (mz_uint)in_bytes;
1078                        pStream->total_in += (mz_uint)in_bytes; pStream->adler = tinfl_get_adler32( &pState->m_decomp );
1079
1080                        pState->m_dict_avail = (mz_uint)out_bytes;
1081
1082                        n = MZ_MIN( pState->m_dict_avail, pStream->avail_out );
1083                        memcpy( pStream->next_out, pState->m_dict + pState->m_dict_ofs, n );
1084                        pStream->next_out += n; pStream->avail_out -= n; pStream->total_out += n;
1085                        pState->m_dict_avail -= n; pState->m_dict_ofs = ( pState->m_dict_ofs + n ) & ( TINFL_LZ_DICT_SIZE - 1 );
1086
1087                        if ( status < 0 )
1088                                return MZ_DATA_ERROR; // Stream is corrupted (there could be some uncompressed data left in the output dictionary - oh well).
1089                        else if ( ( status == TINFL_STATUS_NEEDS_MORE_INPUT ) && ( !orig_avail_in ) )
1090                                return MZ_BUF_ERROR; // Signal caller that we can't make forward progress without supplying more input or by setting flush to MZ_FINISH.
1091                        else if ( flush == MZ_FINISH )
1092                        {
1093                                // The output buffer MUST be large to hold the remaining uncompressed data when flush==MZ_FINISH.
1094                                if ( status == TINFL_STATUS_DONE )
1095                                        return pState->m_dict_avail ? MZ_BUF_ERROR : MZ_STREAM_END;
1096                                // status here must be TINFL_STATUS_HAS_MORE_OUTPUT, which means there's at least 1 more byte on the way. If there's no more room left in the output buffer then something is wrong.
1097                                else if ( !pStream->avail_out )
1098                                        return MZ_BUF_ERROR;
1099                        }
1100                        else if ( ( status == TINFL_STATUS_DONE ) || ( !pStream->avail_in ) || ( !pStream->avail_out ) || ( pState->m_dict_avail ) )
1101                                break;
1102                }
1103
1104                return ( ( status == TINFL_STATUS_DONE ) && ( !pState->m_dict_avail ) ) ? MZ_STREAM_END : MZ_OK;
1105        }
1106
1107        int mz_inflateEnd( mz_streamp pStream )
1108        {
1109                if ( !pStream )
1110                        return MZ_STREAM_ERROR;
1111                if ( pStream->state )
1112                {
1113                        pStream->zfree( pStream->opaque, pStream->state );
1114                        pStream->state = NULL;
1115                }
1116                return MZ_OK;
1117        }
1118
1119        int mz_uncompress( unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len )
1120        {
1121                mz_stream stream;
1122                int status;
1123                memset( &stream, 0, sizeof( stream ) );
1124
1125                // In case mz_ulong is 64-bits (argh I hate longs).
1126                if ( ( source_len | *pDest_len ) > 0xFFFFFFFFU ) return MZ_PARAM_ERROR;
1127
1128                stream.next_in = pSource;
1129                stream.avail_in = (mz_uint32)source_len;
1130                stream.next_out = pDest;
1131                stream.avail_out = (mz_uint32)*pDest_len;
1132
1133                status = mz_inflateInit( &stream );
1134                if ( status != MZ_OK )
1135                        return status;
1136
1137                status = mz_inflate( &stream, MZ_FINISH );
1138                if ( status != MZ_STREAM_END )
1139                {
1140                        mz_inflateEnd( &stream );
1141                        return ( ( status == MZ_BUF_ERROR ) && ( !stream.avail_in ) ) ? MZ_DATA_ERROR : status;
1142                }
1143                *pDest_len = stream.total_out;
1144
1145                return mz_inflateEnd( &stream );
1146        }
1147
1148        const char *mz_error( int err )
1149        {
1150                static struct { int m_err; const char *m_pDesc; } s_error_descs[] =
1151                {
1152                        { MZ_OK, "" },{ MZ_STREAM_END, "stream end" },{ MZ_NEED_DICT, "need dictionary" },{ MZ_ERRNO, "file error" },{ MZ_STREAM_ERROR, "stream error" },
1153                        { MZ_DATA_ERROR, "data error" },{ MZ_MEM_ERROR, "out of memory" },{ MZ_BUF_ERROR, "buf error" },{ MZ_VERSION_ERROR, "version error" },{ MZ_PARAM_ERROR, "parameter error" }
1154                };
1155                mz_uint i; for ( i = 0; i < sizeof( s_error_descs ) / sizeof( s_error_descs[0] ); ++i ) if ( s_error_descs[i].m_err == err ) return s_error_descs[i].m_pDesc;
1156                return NULL;
1157        }
1158
1159#endif //MINIZ_NO_ZLIB_APIS
1160
1161        // ------------------- Low-level Decompression (completely independent from all compression API's)
1162
1163#define TINFL_MEMCPY(d, s, l) memcpy(d, s, l)
1164#define TINFL_MEMSET(p, c, l) memset(p, c, l)
1165
1166#define TINFL_CR_BEGIN switch(r->m_state) { case 0:
1167#define TINFL_CR_RETURN(state_index, result) do { status = result; r->m_state = state_index; goto common_exit; case state_index:; } MZ_MACRO_END
1168#define TINFL_CR_RETURN_FOREVER(state_index, result) do { for ( ; ; ) { TINFL_CR_RETURN(state_index, result); } } MZ_MACRO_END
1169#define TINFL_CR_FINISH }
1170
1171        // TODO: If the caller has indicated that there's no more input, and we attempt to read beyond the input buf, then something is wrong with the input because the inflator never
1172        // reads ahead more than it needs to. Currently TINFL_GET_BYTE() pads the end of the stream with 0's in this scenario.
1173#define TINFL_GET_BYTE(state_index, c) do { \
1174  if (pIn_buf_cur >= pIn_buf_end) { \
1175    for ( ; ; ) { \
1176      if (decomp_flags & TINFL_FLAG_HAS_MORE_INPUT) { \
1177        TINFL_CR_RETURN(state_index, TINFL_STATUS_NEEDS_MORE_INPUT); \
1178        if (pIn_buf_cur < pIn_buf_end) { \
1179          c = *pIn_buf_cur++; \
1180          break; \
1181        } \
1182      } else { \
1183        c = 0; \
1184        break; \
1185      } \
1186    } \
1187  } else c = *pIn_buf_cur++; } MZ_MACRO_END
1188
1189#define TINFL_NEED_BITS(state_index, n) do { mz_uint c; TINFL_GET_BYTE(state_index, c); bit_buf |= (((tinfl_bit_buf_t)c) << num_bits); num_bits += 8; } while (num_bits < (mz_uint)(n))
1190#define TINFL_SKIP_BITS(state_index, n) do { if (num_bits < (mz_uint)(n)) { TINFL_NEED_BITS(state_index, n); } bit_buf >>= (n); num_bits -= (n); } MZ_MACRO_END
1191#define TINFL_GET_BITS(state_index, b, n) do { if (num_bits < (mz_uint)(n)) { TINFL_NEED_BITS(state_index, n); } b = bit_buf & ((1 << (n)) - 1); bit_buf >>= (n); num_bits -= (n); } MZ_MACRO_END
1192
1193        // TINFL_HUFF_BITBUF_FILL() is only used rarely, when the number of bytes remaining in the input buffer falls below 2.
1194        // It reads just enough bytes from the input stream that are needed to decode the next Huffman code (and absolutely no more). It works by trying to fully decode a
1195        // Huffman code by using whatever bits are currently present in the bit buffer. If this fails, it reads another byte, and tries again until it succeeds or until the
1196        // bit buffer contains >=15 bits (deflate's max. Huffman code size).
1197#define TINFL_HUFF_BITBUF_FILL(state_index, pHuff) \
1198  do { \
1199    temp = (pHuff)->m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]; \
1200    if (temp >= 0) { \
1201      code_len = temp >> 9; \
1202      if ((code_len) && (num_bits >= code_len)) \
1203      break; \
1204    } else if (num_bits > TINFL_FAST_LOOKUP_BITS) { \
1205       code_len = TINFL_FAST_LOOKUP_BITS; \
1206       do { \
1207          temp = (pHuff)->m_tree[~temp + ((bit_buf >> code_len++) & 1)]; \
1208       } while ((temp < 0) && (num_bits >= (code_len + 1))); if (temp >= 0) break; \
1209    } TINFL_GET_BYTE(state_index, c); bit_buf |= (((tinfl_bit_buf_t)c) << num_bits); num_bits += 8; \
1210  } while (num_bits < 15);
1211
1212        // TINFL_HUFF_DECODE() decodes the next Huffman coded symbol. It's more complex than you would initially expect because the zlib API expects the decompressor to never read
1213        // beyond the final byte of the deflate stream. (In other words, when this macro wants to read another byte from the input, it REALLY needs another byte in order to fully
1214        // decode the next Huffman code.) Handling this properly is particularly important on raw deflate (non-zlib) streams, which aren't followed by a byte aligned adler-32.
1215        // The slow path is only executed at the very end of the input buffer.
1216#define TINFL_HUFF_DECODE(state_index, sym, pHuff) do { \
1217  int temp; mz_uint code_len, c; \
1218  if (num_bits < 15) { \
1219    if ((pIn_buf_end - pIn_buf_cur) < 2) { \
1220       TINFL_HUFF_BITBUF_FILL(state_index, pHuff); \
1221    } else { \
1222       bit_buf |= (((tinfl_bit_buf_t)pIn_buf_cur[0]) << num_bits) | (((tinfl_bit_buf_t)pIn_buf_cur[1]) << (num_bits + 8)); pIn_buf_cur += 2; num_bits += 16; \
1223    } \
1224  } \
1225  if ((temp = (pHuff)->m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0) \
1226    code_len = temp >> 9, temp &= 511; \
1227  else { \
1228    code_len = TINFL_FAST_LOOKUP_BITS; do { temp = (pHuff)->m_tree[~temp + ((bit_buf >> code_len++) & 1)]; } while (temp < 0); \
1229  } sym = temp; bit_buf >>= code_len; num_bits -= code_len; } MZ_MACRO_END
1230
1231        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 )
1232        {
1233                static const int s_length_base[31] = { 3,4,5,6,7,8,9,10,11,13, 15,17,19,23,27,31,35,43,51,59, 67,83,99,115,131,163,195,227,258,0,0 };
1234                static const int s_length_extra[31] = { 0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0 };
1235                static const int s_dist_base[32] = { 1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193, 257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0 };
1236                static const int s_dist_extra[32] = { 0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13 };
1237                static const mz_uint8 s_length_dezigzag[19] = { 16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15 };
1238                static const int s_min_table_sizes[3] = { 257, 1, 4 };
1239
1240                tinfl_status status = TINFL_STATUS_FAILED; mz_uint32 num_bits, dist, counter, num_extra; tinfl_bit_buf_t bit_buf;
1241                const mz_uint8 *pIn_buf_cur = pIn_buf_next, *const pIn_buf_end = pIn_buf_next + *pIn_buf_size;
1242                mz_uint8 *pOut_buf_cur = pOut_buf_next, *const pOut_buf_end = pOut_buf_next + *pOut_buf_size;
1243                size_t out_buf_size_mask = ( decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF ) ? (size_t)-1 : ( ( pOut_buf_next - pOut_buf_start ) + *pOut_buf_size ) - 1, dist_from_out_buf_start;
1244
1245                // Ensure the output buffer's size is a power of 2, unless the output buffer is large enough to hold the entire output file (in which case it doesn't matter).
1246                if ( ( ( out_buf_size_mask + 1 ) & out_buf_size_mask ) || ( pOut_buf_next < pOut_buf_start ) ) { *pIn_buf_size = *pOut_buf_size = 0; return TINFL_STATUS_BAD_PARAM; }
1247
1248                num_bits = r->m_num_bits; bit_buf = r->m_bit_buf; dist = r->m_dist; counter = r->m_counter; num_extra = r->m_num_extra; dist_from_out_buf_start = r->m_dist_from_out_buf_start;
1249                TINFL_CR_BEGIN
1250
1251                        bit_buf = num_bits = dist = counter = num_extra = r->m_zhdr0 = r->m_zhdr1 = 0; r->m_z_adler32 = r->m_check_adler32 = 1;
1252                if ( decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER )
1253                {
1254                        TINFL_GET_BYTE( 1, r->m_zhdr0 ); TINFL_GET_BYTE( 2, r->m_zhdr1 );
1255                        counter = ( ( ( r->m_zhdr0 * 256 + r->m_zhdr1 ) % 31 != 0 ) || ( r->m_zhdr1 & 32 ) || ( ( r->m_zhdr0 & 15 ) != 8 ) );
1256                        if ( !( decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF ) ) counter |= ( ( ( 1U << ( 8U + ( r->m_zhdr0 >> 4 ) ) ) > 32768U ) || ( ( out_buf_size_mask + 1 ) < (size_t)( 1U << ( 8U + ( r->m_zhdr0 >> 4 ) ) ) ) );
1257                        if ( counter ) { TINFL_CR_RETURN_FOREVER( 36, TINFL_STATUS_FAILED ); }
1258                }
1259
1260                do
1261                {
1262                        TINFL_GET_BITS( 3, r->m_final, 3 ); r->m_type = r->m_final >> 1;
1263                        if ( r->m_type == 0 )
1264                        {
1265                                TINFL_SKIP_BITS( 5, num_bits & 7 );
1266                                for ( counter = 0; counter < 4; ++counter ) { if ( num_bits ) TINFL_GET_BITS( 6, r->m_raw_header[counter], 8 ); else TINFL_GET_BYTE( 7, r->m_raw_header[counter] ); }
1267                                if ( ( counter = ( r->m_raw_header[0] | ( r->m_raw_header[1] << 8 ) ) ) != (mz_uint)( 0xFFFF ^ ( r->m_raw_header[2] | ( r->m_raw_header[3] << 8 ) ) ) ) { TINFL_CR_RETURN_FOREVER( 39, TINFL_STATUS_FAILED ); }
1268                                while ( ( counter ) && ( num_bits ) )
1269                                {
1270                                        TINFL_GET_BITS( 51, dist, 8 );
1271                                        while ( pOut_buf_cur >= pOut_buf_end ) { TINFL_CR_RETURN( 52, TINFL_STATUS_HAS_MORE_OUTPUT ); }
1272                                        *pOut_buf_cur++ = (mz_uint8)dist;
1273                                        counter--;
1274                                }
1275                                while ( counter )
1276                                {
1277                                        size_t n; while ( pOut_buf_cur >= pOut_buf_end ) { TINFL_CR_RETURN( 9, TINFL_STATUS_HAS_MORE_OUTPUT ); }
1278                                        while ( pIn_buf_cur >= pIn_buf_end )
1279                                        {
1280                                                if ( decomp_flags & TINFL_FLAG_HAS_MORE_INPUT )
1281                                                {
1282                                                        TINFL_CR_RETURN( 38, TINFL_STATUS_NEEDS_MORE_INPUT );
1283                                                }
1284                                                else
1285                                                {
1286                                                        TINFL_CR_RETURN_FOREVER( 40, TINFL_STATUS_FAILED );
1287                                                }
1288                                        }
1289                                        n = MZ_MIN( MZ_MIN( (size_t)( pOut_buf_end - pOut_buf_cur ), (size_t)( pIn_buf_end - pIn_buf_cur ) ), counter );
1290                                        TINFL_MEMCPY( pOut_buf_cur, pIn_buf_cur, n ); pIn_buf_cur += n; pOut_buf_cur += n; counter -= (mz_uint)n;
1291                                }
1292                        }
1293                        else if ( r->m_type == 3 )
1294                        {
1295                                TINFL_CR_RETURN_FOREVER( 10, TINFL_STATUS_FAILED );
1296                        }
1297                        else
1298                        {
1299                                if ( r->m_type == 1 )
1300                                {
1301                                        mz_uint8 *p = r->m_tables[0].m_code_size; mz_uint i;
1302                                        r->m_table_sizes[0] = 288; r->m_table_sizes[1] = 32; TINFL_MEMSET( r->m_tables[1].m_code_size, 5, 32 );
1303                                        for ( i = 0; i <= 143; ++i ) *p++ = 8; for ( ; i <= 255; ++i ) *p++ = 9; for ( ; i <= 279; ++i ) *p++ = 7; for ( ; i <= 287; ++i ) *p++ = 8;
1304                                }
1305                                else
1306                                {
1307                                        for ( counter = 0; counter < 3; counter++ ) { TINFL_GET_BITS( 11, r->m_table_sizes[counter], "\05\05\04"[counter] ); r->m_table_sizes[counter] += s_min_table_sizes[counter]; }
1308                                        MZ_CLEAR_OBJ( r->m_tables[2].m_code_size ); for ( counter = 0; counter < r->m_table_sizes[2]; counter++ ) { mz_uint s; TINFL_GET_BITS( 14, s, 3 ); r->m_tables[2].m_code_size[s_length_dezigzag[counter]] = (mz_uint8)s; }
1309                                        r->m_table_sizes[2] = 19;
1310                                }
1311                                for ( ; (int)r->m_type >= 0; r->m_type-- )
1312                                {
1313                                        int tree_next, tree_cur; tinfl_huff_table *pTable;
1314                                        mz_uint i, j, used_syms, total, sym_index, next_code[17], total_syms[16]; pTable = &r->m_tables[r->m_type]; MZ_CLEAR_OBJ( total_syms ); MZ_CLEAR_OBJ( pTable->m_look_up ); MZ_CLEAR_OBJ( pTable->m_tree );
1315                                        for ( i = 0; i < r->m_table_sizes[r->m_type]; ++i ) total_syms[pTable->m_code_size[i]]++;
1316                                        used_syms = 0, total = 0; next_code[0] = next_code[1] = 0;
1317                                        for ( i = 1; i <= 15; ++i ) { used_syms += total_syms[i]; next_code[i + 1] = ( total = ( ( total + total_syms[i] ) << 1 ) ); }
1318                                        if ( ( 65536 != total ) && ( used_syms > 1 ) )
1319                                        {
1320                                                TINFL_CR_RETURN_FOREVER( 35, TINFL_STATUS_FAILED );
1321                                        }
1322                                        for ( tree_next = -1, sym_index = 0; sym_index < r->m_table_sizes[r->m_type]; ++sym_index )
1323                                        {
1324                                                mz_uint rev_code = 0, l, cur_code, code_size = pTable->m_code_size[sym_index]; if ( !code_size ) continue;
1325                                                cur_code = next_code[code_size]++; for ( l = code_size; l > 0; l--, cur_code >>= 1 ) rev_code = ( rev_code << 1 ) | ( cur_code & 1 );
1326                                                if ( code_size <= TINFL_FAST_LOOKUP_BITS ) { mz_int16 k = (mz_int16)( ( code_size << 9 ) | sym_index ); while ( rev_code < TINFL_FAST_LOOKUP_SIZE ) { pTable->m_look_up[rev_code] = k; rev_code += ( 1 << code_size ); } continue; }
1327                                                if ( 0 == ( tree_cur = pTable->m_look_up[rev_code & ( TINFL_FAST_LOOKUP_SIZE - 1 )] ) ) { pTable->m_look_up[rev_code & ( TINFL_FAST_LOOKUP_SIZE - 1 )] = (mz_int16)tree_next; tree_cur = tree_next; tree_next -= 2; }
1328                                                rev_code >>= ( TINFL_FAST_LOOKUP_BITS - 1 );
1329                                                for ( j = code_size; j > ( TINFL_FAST_LOOKUP_BITS + 1 ); j-- )
1330                                                {
1331                                                        tree_cur -= ( ( rev_code >>= 1 ) & 1 );
1332                                                        if ( !pTable->m_tree[-tree_cur - 1] ) { pTable->m_tree[-tree_cur - 1] = (mz_int16)tree_next; tree_cur = tree_next; tree_next -= 2; }
1333                                                        else tree_cur = pTable->m_tree[-tree_cur - 1];
1334                                                }
1335                                                tree_cur -= ( ( rev_code >>= 1 ) & 1 ); pTable->m_tree[-tree_cur - 1] = (mz_int16)sym_index;
1336                                        }
1337                                        if ( r->m_type == 2 )
1338                                        {
1339                                                for ( counter = 0; counter < ( r->m_table_sizes[0] + r->m_table_sizes[1] ); )
1340                                                {
1341                                                        mz_uint s; TINFL_HUFF_DECODE( 16, dist, &r->m_tables[2] ); if ( dist < 16 ) { r->m_len_codes[counter++] = (mz_uint8)dist; continue; }
1342                                                        if ( ( dist == 16 ) && ( !counter ) )
1343                                                        {
1344                                                                TINFL_CR_RETURN_FOREVER( 17, TINFL_STATUS_FAILED );
1345                                                        }
1346                                                        num_extra = "\02\03\07"[dist - 16]; TINFL_GET_BITS( 18, s, num_extra ); s += "\03\03\013"[dist - 16];
1347                                                        TINFL_MEMSET( r->m_len_codes + counter, ( dist == 16 ) ? r->m_len_codes[counter - 1] : 0, s ); counter += s;
1348                                                }
1349                                                if ( ( r->m_table_sizes[0] + r->m_table_sizes[1] ) != counter )
1350                                                {
1351                                                        TINFL_CR_RETURN_FOREVER( 21, TINFL_STATUS_FAILED );
1352                                                }
1353                                                TINFL_MEMCPY( r->m_tables[0].m_code_size, r->m_len_codes, r->m_table_sizes[0] ); TINFL_MEMCPY( r->m_tables[1].m_code_size, r->m_len_codes + r->m_table_sizes[0], r->m_table_sizes[1] );
1354                                        }
1355                                }
1356                                for ( ; ; )
1357                                {
1358                                        mz_uint8 *pSrc;
1359                                        for ( ; ; )
1360                                        {
1361                                                if ( ( ( pIn_buf_end - pIn_buf_cur ) < 4 ) || ( ( pOut_buf_end - pOut_buf_cur ) < 2 ) )
1362                                                {
1363                                                        TINFL_HUFF_DECODE( 23, counter, &r->m_tables[0] );
1364                                                        if ( counter >= 256 )
1365                                                                break;
1366                                                        while ( pOut_buf_cur >= pOut_buf_end ) { TINFL_CR_RETURN( 24, TINFL_STATUS_HAS_MORE_OUTPUT ); }
1367                                                        *pOut_buf_cur++ = (mz_uint8)counter;
1368                                                }
1369                                                else
1370                                                {
1371                                                        int sym2; mz_uint code_len;
1372#if TINFL_USE_64BIT_BITBUF
1373                                                        if ( num_bits < 30 ) { bit_buf |= ( ( (tinfl_bit_buf_t)MZ_READ_LE32( pIn_buf_cur ) ) << num_bits ); pIn_buf_cur += 4; num_bits += 32; }
1374#else
1375                                                        if ( num_bits < 15 ) { bit_buf |= ( ( (tinfl_bit_buf_t)MZ_READ_LE16( pIn_buf_cur ) ) << num_bits ); pIn_buf_cur += 2; num_bits += 16; }
1376#endif
1377                                                        if ( ( sym2 = r->m_tables[0].m_look_up[bit_buf & ( TINFL_FAST_LOOKUP_SIZE - 1 )] ) >= 0 )
1378                                                                code_len = sym2 >> 9;
1379                                                        else
1380                                                        {
1381                                                                code_len = TINFL_FAST_LOOKUP_BITS; do { sym2 = r->m_tables[0].m_tree[~sym2 + ( ( bit_buf >> code_len++ ) & 1 )]; } while ( sym2 < 0 );
1382                                                        }
1383                                                        counter = sym2; bit_buf >>= code_len; num_bits -= code_len;
1384                                                        if ( counter & 256 )
1385                                                                break;
1386
1387#if !TINFL_USE_64BIT_BITBUF
1388                                                        if ( num_bits < 15 ) { bit_buf |= ( ( (tinfl_bit_buf_t)MZ_READ_LE16( pIn_buf_cur ) ) << num_bits ); pIn_buf_cur += 2; num_bits += 16; }
1389#endif
1390                                                        if ( ( sym2 = r->m_tables[0].m_look_up[bit_buf & ( TINFL_FAST_LOOKUP_SIZE - 1 )] ) >= 0 )
1391                                                                code_len = sym2 >> 9;
1392                                                        else
1393                                                        {
1394                                                                code_len = TINFL_FAST_LOOKUP_BITS; do { sym2 = r->m_tables[0].m_tree[~sym2 + ( ( bit_buf >> code_len++ ) & 1 )]; } while ( sym2 < 0 );
1395                                                        }
1396                                                        bit_buf >>= code_len; num_bits -= code_len;
1397
1398                                                        pOut_buf_cur[0] = (mz_uint8)counter;
1399                                                        if ( sym2 & 256 )
1400                                                        {
1401                                                                pOut_buf_cur++;
1402                                                                counter = sym2;
1403                                                                break;
1404                                                        }
1405                                                        pOut_buf_cur[1] = (mz_uint8)sym2;
1406                                                        pOut_buf_cur += 2;
1407                                                }
1408                                        }
1409                                        if ( ( counter &= 511 ) == 256 ) break;
1410
1411                                        num_extra = s_length_extra[counter - 257]; counter = s_length_base[counter - 257];
1412                                        if ( num_extra ) { mz_uint extra_bits; TINFL_GET_BITS( 25, extra_bits, num_extra ); counter += extra_bits; }
1413
1414                                        TINFL_HUFF_DECODE( 26, dist, &r->m_tables[1] );
1415                                        num_extra = s_dist_extra[dist]; dist = s_dist_base[dist];
1416                                        if ( num_extra ) { mz_uint extra_bits; TINFL_GET_BITS( 27, extra_bits, num_extra ); dist += extra_bits; }
1417
1418                                        dist_from_out_buf_start = pOut_buf_cur - pOut_buf_start;
1419                                        if ( ( dist > dist_from_out_buf_start ) && ( decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF ) )
1420                                        {
1421                                                TINFL_CR_RETURN_FOREVER( 37, TINFL_STATUS_FAILED );
1422                                        }
1423
1424                                        pSrc = pOut_buf_start + ( ( dist_from_out_buf_start - dist ) & out_buf_size_mask );
1425
1426                                        if ( ( MZ_MAX( pOut_buf_cur, pSrc ) + counter ) > pOut_buf_end )
1427                                        {
1428                                                while ( counter-- )
1429                                                {
1430                                                        while ( pOut_buf_cur >= pOut_buf_end ) { TINFL_CR_RETURN( 53, TINFL_STATUS_HAS_MORE_OUTPUT ); }
1431                                                        *pOut_buf_cur++ = pOut_buf_start[( dist_from_out_buf_start++ - dist ) & out_buf_size_mask];
1432                                                }
1433                                                continue;
1434                                        }
1435#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES
1436                                        else if ( ( counter >= 9 ) && ( counter <= dist ) )
1437                                        {
1438                                                const mz_uint8 *pSrc_end = pSrc + ( counter & ~7 );
1439                                                do
1440                                                {
1441                                                        ( (mz_uint32 *)pOut_buf_cur )[0] = ( (const mz_uint32 *)pSrc )[0];
1442                                                        ( (mz_uint32 *)pOut_buf_cur )[1] = ( (const mz_uint32 *)pSrc )[1];
1443                                                        pOut_buf_cur += 8;
1444                                                } while ( ( pSrc += 8 ) < pSrc_end );
1445                                                if ( ( counter &= 7 ) < 3 )
1446                                                {
1447                                                        if ( counter )
1448                                                        {
1449                                                                pOut_buf_cur[0] = pSrc[0];
1450                                                                if ( counter > 1 )
1451                                                                        pOut_buf_cur[1] = pSrc[1];
1452                                                                pOut_buf_cur += counter;
1453                                                        }
1454                                                        continue;
1455                                                }
1456                                        }
1457#endif
1458                                        do
1459                                        {
1460                                                pOut_buf_cur[0] = pSrc[0];
1461                                                pOut_buf_cur[1] = pSrc[1];
1462                                                pOut_buf_cur[2] = pSrc[2];
1463                                                pOut_buf_cur += 3; pSrc += 3;
1464                                        } while ( (int)( counter -= 3 ) > 2 );
1465                                        if ( (int)counter > 0 )
1466                                        {
1467                                                pOut_buf_cur[0] = pSrc[0];
1468                                                if ( (int)counter > 1 )
1469                                                        pOut_buf_cur[1] = pSrc[1];
1470                                                pOut_buf_cur += counter;
1471                                        }
1472                                }
1473                        }
1474                } while ( !( r->m_final & 1 ) );
1475                if ( decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER )
1476                {
1477                        TINFL_SKIP_BITS( 32, num_bits & 7 ); for ( counter = 0; counter < 4; ++counter ) { mz_uint s; if ( num_bits ) TINFL_GET_BITS( 41, s, 8 ); else TINFL_GET_BYTE( 42, s ); r->m_z_adler32 = ( r->m_z_adler32 << 8 ) | s; }
1478                }
1479                TINFL_CR_RETURN_FOREVER( 34, TINFL_STATUS_DONE );
1480                TINFL_CR_FINISH
1481
1482                        common_exit :
1483                r->m_num_bits = num_bits; r->m_bit_buf = bit_buf; r->m_dist = dist; r->m_counter = counter; r->m_num_extra = num_extra; r->m_dist_from_out_buf_start = dist_from_out_buf_start;
1484                *pIn_buf_size = pIn_buf_cur - pIn_buf_next; *pOut_buf_size = pOut_buf_cur - pOut_buf_next;
1485                if ( ( decomp_flags & ( TINFL_FLAG_PARSE_ZLIB_HEADER | TINFL_FLAG_COMPUTE_ADLER32 ) ) && ( status >= 0 ) )
1486                {
1487                        const mz_uint8 *ptr = pOut_buf_next; size_t buf_len = *pOut_buf_size;
1488                        mz_uint32 i, s1 = r->m_check_adler32 & 0xffff, s2 = r->m_check_adler32 >> 16; size_t block_len = buf_len % 5552;
1489                        while ( buf_len )
1490                        {
1491                                for ( i = 0; i + 7 < block_len; i += 8, ptr += 8 )
1492                                {
1493                                        s1 += ptr[0], s2 += s1; s1 += ptr[1], s2 += s1; s1 += ptr[2], s2 += s1; s1 += ptr[3], s2 += s1;
1494                                        s1 += ptr[4], s2 += s1; s1 += ptr[5], s2 += s1; s1 += ptr[6], s2 += s1; s1 += ptr[7], s2 += s1;
1495                                }
1496                                for ( ; i < block_len; ++i ) s1 += *ptr++, s2 += s1;
1497                                s1 %= 65521U, s2 %= 65521U; buf_len -= block_len; block_len = 5552;
1498                        }
1499                        r->m_check_adler32 = ( s2 << 16 ) + s1; if ( ( status == TINFL_STATUS_DONE ) && ( decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER ) && ( r->m_check_adler32 != r->m_z_adler32 ) ) status = TINFL_STATUS_ADLER32_MISMATCH;
1500                }
1501                return status;
1502        }
1503
1504        // Higher level helper functions.
1505        void *tinfl_decompress_mem_to_heap( const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags )
1506        {
1507                tinfl_decompressor decomp; void *pBuf = NULL, *pNew_buf; size_t src_buf_ofs = 0, out_buf_capacity = 0;
1508                *pOut_len = 0;
1509                tinfl_init( &decomp );
1510                for ( ; ; )
1511                {
1512                        size_t src_buf_size = src_buf_len - src_buf_ofs, dst_buf_size = out_buf_capacity - *pOut_len, new_out_buf_capacity;
1513                        tinfl_status status = tinfl_decompress( &decomp, (const mz_uint8*)pSrc_buf + src_buf_ofs, &src_buf_size, (mz_uint8*)pBuf, pBuf ? (mz_uint8*)pBuf + *pOut_len : NULL, &dst_buf_size,
1514                                ( flags & ~TINFL_FLAG_HAS_MORE_INPUT ) | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF );
1515                        if ( ( status < 0 ) || ( status == TINFL_STATUS_NEEDS_MORE_INPUT ) )
1516                        {
1517                                MZ_FREE( pBuf ); *pOut_len = 0; return NULL;
1518                        }
1519                        src_buf_ofs += src_buf_size;
1520                        *pOut_len += dst_buf_size;
1521                        if ( status == TINFL_STATUS_DONE ) break;
1522                        new_out_buf_capacity = out_buf_capacity * 2; if ( new_out_buf_capacity < 128 ) new_out_buf_capacity = 128;
1523                        pNew_buf = MZ_REALLOC( pBuf, new_out_buf_capacity );
1524                        if ( !pNew_buf )
1525                        {
1526                                MZ_FREE( pBuf ); *pOut_len = 0; return NULL;
1527                        }
1528                        pBuf = pNew_buf; out_buf_capacity = new_out_buf_capacity;
1529                }
1530                return pBuf;
1531        }
1532
1533        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 )
1534        {
1535                tinfl_decompressor decomp; tinfl_status status; tinfl_init( &decomp );
1536                status = tinfl_decompress( &decomp, (const mz_uint8*)pSrc_buf, &src_buf_len, (mz_uint8*)pOut_buf, (mz_uint8*)pOut_buf, &out_buf_len, ( flags & ~TINFL_FLAG_HAS_MORE_INPUT ) | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF );
1537                return ( status != TINFL_STATUS_DONE ) ? TINFL_DECOMPRESS_MEM_TO_MEM_FAILED : out_buf_len;
1538        }
1539
1540        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 )
1541        {
1542                int result = 0;
1543                tinfl_decompressor decomp;
1544                mz_uint8 *pDict = (mz_uint8*)MZ_MALLOC( TINFL_LZ_DICT_SIZE ); size_t in_buf_ofs = 0, dict_ofs = 0;
1545                if ( !pDict )
1546                        return TINFL_STATUS_FAILED;
1547                tinfl_init( &decomp );
1548                for ( ; ; )
1549                {
1550                        size_t in_buf_size = *pIn_buf_size - in_buf_ofs, dst_buf_size = TINFL_LZ_DICT_SIZE - dict_ofs;
1551                        tinfl_status status = tinfl_decompress( &decomp, (const mz_uint8*)pIn_buf + in_buf_ofs, &in_buf_size, pDict, pDict + dict_ofs, &dst_buf_size,
1552                                ( flags & ~( TINFL_FLAG_HAS_MORE_INPUT | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF ) ) );
1553                        in_buf_ofs += in_buf_size;
1554                        if ( ( dst_buf_size ) && ( !( *pPut_buf_func )( pDict + dict_ofs, (int)dst_buf_size, pPut_buf_user ) ) )
1555                                break;
1556                        if ( status != TINFL_STATUS_HAS_MORE_OUTPUT )
1557                        {
1558                                result = ( status == TINFL_STATUS_DONE );
1559                                break;
1560                        }
1561                        dict_ofs = ( dict_ofs + dst_buf_size ) & ( TINFL_LZ_DICT_SIZE - 1 );
1562                }
1563                MZ_FREE( pDict );
1564                *pIn_buf_size = in_buf_ofs;
1565                return result;
1566        }
1567
1568        // ------------------- Low-level Compression (independent from all decompression API's)
1569
1570        // Purposely making these tables static for faster init and thread safety.
1571        static const mz_uint16 s_tdefl_len_sym[256] = {
1572                257,258,259,260,261,262,263,264,265,265,266,266,267,267,268,268,269,269,269,269,270,270,270,270,271,271,271,271,272,272,272,272,
1573                273,273,273,273,273,273,273,273,274,274,274,274,274,274,274,274,275,275,275,275,275,275,275,275,276,276,276,276,276,276,276,276,
1574                277,277,277,277,277,277,277,277,277,277,277,277,277,277,277,277,278,278,278,278,278,278,278,278,278,278,278,278,278,278,278,278,
1575                279,279,279,279,279,279,279,279,279,279,279,279,279,279,279,279,280,280,280,280,280,280,280,280,280,280,280,280,280,280,280,280,
1576                281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,
1577                282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,
1578                283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,
1579                284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,285 };
1580
1581        static const mz_uint8 s_tdefl_len_extra[256] = {
1582                0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
1583                4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,
1584                5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,
1585                5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,0 };
1586
1587        static const mz_uint8 s_tdefl_small_dist_sym[512] = {
1588                0,1,2,3,4,4,5,5,6,6,6,6,7,7,7,7,8,8,8,8,8,8,8,8,9,9,9,9,9,9,9,9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
1589                11,11,11,11,11,11,11,11,11,11,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,13,
1590                13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,14,14,14,14,14,14,14,14,14,14,14,14,
1591                14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
1592                14,14,14,14,14,14,14,14,14,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
1593                15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,16,16,16,16,16,16,16,16,16,16,16,16,16,
1594                16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
1595                16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
1596                16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
1597                17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
1598                17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
1599                17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17 };
1600
1601        static const mz_uint8 s_tdefl_small_dist_extra[512] = {
1602                0,0,0,0,1,1,1,1,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,
1603                5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
1604                6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
1605                6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
1606                7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
1607                7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
1608                7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
1609                7,7,7,7,7,7,7,7 };
1610
1611        static const mz_uint8 s_tdefl_large_dist_sym[128] = {
1612                0,0,18,19,20,20,21,21,22,22,22,22,23,23,23,23,24,24,24,24,24,24,24,24,25,25,25,25,25,25,25,25,26,26,26,26,26,26,26,26,26,26,26,26,
1613                26,26,26,26,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,
1614                28,28,28,28,28,28,28,28,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29 };
1615
1616        static const mz_uint8 s_tdefl_large_dist_extra[128] = {
1617                0,0,8,8,9,9,9,9,10,10,10,10,10,10,10,10,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
1618                12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
1619                13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13 };
1620
1621        // Radix sorts tdefl_sym_freq[] array by 16-bit key m_key. Returns ptr to sorted values.
1622        typedef struct { mz_uint16 m_key, m_sym_index; } tdefl_sym_freq;
1623        static tdefl_sym_freq* tdefl_radix_sort_syms( mz_uint num_syms, tdefl_sym_freq* pSyms0, tdefl_sym_freq* pSyms1 )
1624        {
1625                mz_uint32 total_passes = 2, pass_shift, pass, i, hist[256 * 2]; tdefl_sym_freq* pCur_syms = pSyms0, *pNew_syms = pSyms1; MZ_CLEAR_OBJ( hist );
1626                for ( i = 0; i < num_syms; i++ ) { mz_uint freq = pSyms0[i].m_key; hist[freq & 0xFF]++; hist[256 + ( ( freq >> 8 ) & 0xFF )]++; }
1627                while ( ( total_passes > 1 ) && ( num_syms == hist[( total_passes - 1 ) * 256] ) ) total_passes--;
1628                for ( pass_shift = 0, pass = 0; pass < total_passes; pass++, pass_shift += 8 )
1629                {
1630                        const mz_uint32* pHist = &hist[pass << 8];
1631                        mz_uint offsets[256], cur_ofs = 0;
1632                        for ( i = 0; i < 256; i++ ) { offsets[i] = cur_ofs; cur_ofs += pHist[i]; }
1633                        for ( i = 0; i < num_syms; i++ ) pNew_syms[offsets[( pCur_syms[i].m_key >> pass_shift ) & 0xFF]++] = pCur_syms[i];
1634                        { tdefl_sym_freq* t = pCur_syms; pCur_syms = pNew_syms; pNew_syms = t; }
1635                }
1636                return pCur_syms;
1637        }
1638
1639        // tdefl_calculate_minimum_redundancy() originally written by: Alistair Moffat, alistair@cs.mu.oz.au, Jyrki Katajainen, jyrki@diku.dk, November 1996.
1640        static void tdefl_calculate_minimum_redundancy( tdefl_sym_freq *A, int n )
1641        {
1642                int root, leaf, next, avbl, used, dpth;
1643                if ( n == 0 ) return; else if ( n == 1 ) { A[0].m_key = 1; return; }
1644                A[0].m_key += A[1].m_key; root = 0; leaf = 2;
1645                for ( next = 1; next < n - 1; next++ )
1646                {
1647                        if ( leaf >= n || A[root].m_key < A[leaf].m_key ) { A[next].m_key = A[root].m_key; A[root++].m_key = (mz_uint16)next; }
1648                        else A[next].m_key = A[leaf++].m_key;
1649                        if ( leaf >= n || ( root < next && A[root].m_key < A[leaf].m_key ) ) { A[next].m_key = (mz_uint16)( A[next].m_key + A[root].m_key ); A[root++].m_key = (mz_uint16)next; }
1650                        else A[next].m_key = (mz_uint16)( A[next].m_key + A[leaf++].m_key );
1651                }
1652                A[n - 2].m_key = 0; for ( next = n - 3; next >= 0; next-- ) A[next].m_key = A[A[next].m_key].m_key + 1;
1653                avbl = 1; used = dpth = 0; root = n - 2; next = n - 1;
1654                while ( avbl > 0 )
1655                {
1656                        while ( root >= 0 && (int)A[root].m_key == dpth ) { used++; root--; }
1657                        while ( avbl > used ) { A[next--].m_key = (mz_uint16)( dpth ); avbl--; }
1658                        avbl = 2 * used; dpth++; used = 0;
1659                }
1660        }
1661
1662        // Limits canonical Huffman code table's max code size.
1663        enum { TDEFL_MAX_SUPPORTED_HUFF_CODESIZE = 32 };
1664        static void tdefl_huffman_enforce_max_code_size( int *pNum_codes, int code_list_len, int max_code_size )
1665        {
1666                int i; mz_uint32 total = 0; if ( code_list_len <= 1 ) return;
1667                for ( i = max_code_size + 1; i <= TDEFL_MAX_SUPPORTED_HUFF_CODESIZE; i++ ) pNum_codes[max_code_size] += pNum_codes[i];
1668                for ( i = max_code_size; i > 0; i-- ) total += ( ( (mz_uint32)pNum_codes[i] ) << ( max_code_size - i ) );
1669                while ( total != ( 1UL << max_code_size ) )
1670                {
1671                        pNum_codes[max_code_size]--;
1672                        for ( i = max_code_size - 1; i > 0; i-- ) if ( pNum_codes[i] ) { pNum_codes[i]--; pNum_codes[i + 1] += 2; break; }
1673                        total--;
1674                }
1675        }
1676
1677        static void tdefl_optimize_huffman_table( tdefl_compressor *d, int table_num, int table_len, int code_size_limit, int static_table )
1678        {
1679                int i, j, l, num_codes[1 + TDEFL_MAX_SUPPORTED_HUFF_CODESIZE]; mz_uint next_code[TDEFL_MAX_SUPPORTED_HUFF_CODESIZE + 1]; MZ_CLEAR_OBJ( num_codes );
1680                if ( static_table )
1681                {
1682                        for ( i = 0; i < table_len; i++ ) num_codes[d->m_huff_code_sizes[table_num][i]]++;
1683                }
1684                else
1685                {
1686                        tdefl_sym_freq syms0[TDEFL_MAX_HUFF_SYMBOLS], syms1[TDEFL_MAX_HUFF_SYMBOLS], *pSyms;
1687                        int num_used_syms = 0;
1688                        const mz_uint16 *pSym_count = &d->m_huff_count[table_num][0];
1689                        for ( i = 0; i < table_len; i++ ) if ( pSym_count[i] ) { syms0[num_used_syms].m_key = (mz_uint16)pSym_count[i]; syms0[num_used_syms++].m_sym_index = (mz_uint16)i; }
1690
1691                        pSyms = tdefl_radix_sort_syms( num_used_syms, syms0, syms1 ); tdefl_calculate_minimum_redundancy( pSyms, num_used_syms );
1692
1693                        for ( i = 0; i < num_used_syms; i++ ) num_codes[pSyms[i].m_key]++;
1694
1695                        tdefl_huffman_enforce_max_code_size( num_codes, num_used_syms, code_size_limit );
1696
1697                        MZ_CLEAR_OBJ( d->m_huff_code_sizes[table_num] ); MZ_CLEAR_OBJ( d->m_huff_codes[table_num] );
1698                        for ( i = 1, j = num_used_syms; i <= code_size_limit; i++ )
1699                                for ( l = num_codes[i]; l > 0; l-- ) d->m_huff_code_sizes[table_num][pSyms[--j].m_sym_index] = (mz_uint8)( i );
1700                }
1701
1702                next_code[1] = 0; for ( j = 0, i = 2; i <= code_size_limit; i++ ) next_code[i] = j = ( ( j + num_codes[i - 1] ) << 1 );
1703
1704                for ( i = 0; i < table_len; i++ )
1705                {
1706                        mz_uint rev_code = 0, code, code_size; if ( ( code_size = d->m_huff_code_sizes[table_num][i] ) == 0 ) continue;
1707                        code = next_code[code_size]++; for ( l = code_size; l > 0; l--, code >>= 1 ) rev_code = ( rev_code << 1 ) | ( code & 1 );
1708                        d->m_huff_codes[table_num][i] = (mz_uint16)rev_code;
1709                }
1710        }
1711
1712#define TDEFL_PUT_BITS(b, l) do { \
1713  mz_uint bits = b; mz_uint len = l; MZ_ASSERT(bits <= ((1U << len) - 1U)); \
1714  d->m_bit_buffer |= (bits << d->m_bits_in); d->m_bits_in += len; \
1715  while (d->m_bits_in >= 8) { \
1716    if (d->m_pOutput_buf < d->m_pOutput_buf_end) \
1717      *d->m_pOutput_buf++ = (mz_uint8)(d->m_bit_buffer); \
1718      d->m_bit_buffer >>= 8; \
1719      d->m_bits_in -= 8; \
1720  } \
1721} MZ_MACRO_END
1722
1723#define TDEFL_RLE_PREV_CODE_SIZE() { if (rle_repeat_count) { \
1724  if (rle_repeat_count < 3) { \
1725    d->m_huff_count[2][prev_code_size] = (mz_uint16)(d->m_huff_count[2][prev_code_size] + rle_repeat_count); \
1726    while (rle_repeat_count--) packed_code_sizes[num_packed_code_sizes++] = prev_code_size; \
1727  } else { \
1728    d->m_huff_count[2][16] = (mz_uint16)(d->m_huff_count[2][16] + 1); packed_code_sizes[num_packed_code_sizes++] = 16; packed_code_sizes[num_packed_code_sizes++] = (mz_uint8)(rle_repeat_count - 3); \
1729} rle_repeat_count = 0; } }
1730
1731#define TDEFL_RLE_ZERO_CODE_SIZE() { if (rle_z_count) { \
1732  if (rle_z_count < 3) { \
1733    d->m_huff_count[2][0] = (mz_uint16)(d->m_huff_count[2][0] + rle_z_count); while (rle_z_count--) packed_code_sizes[num_packed_code_sizes++] = 0; \
1734  } else if (rle_z_count <= 10) { \
1735    d->m_huff_count[2][17] = (mz_uint16)(d->m_huff_count[2][17] + 1); packed_code_sizes[num_packed_code_sizes++] = 17; packed_code_sizes[num_packed_code_sizes++] = (mz_uint8)(rle_z_count - 3); \
1736  } else { \
1737    d->m_huff_count[2][18] = (mz_uint16)(d->m_huff_count[2][18] + 1); packed_code_sizes[num_packed_code_sizes++] = 18; packed_code_sizes[num_packed_code_sizes++] = (mz_uint8)(rle_z_count - 11); \
1738} rle_z_count = 0; } }
1739
1740        static mz_uint8 s_tdefl_packed_code_size_syms_swizzle[] = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 };
1741
1742        static void tdefl_start_dynamic_block( tdefl_compressor *d )
1743        {
1744                int num_lit_codes, num_dist_codes, num_bit_lengths; mz_uint i, total_code_sizes_to_pack, num_packed_code_sizes, rle_z_count, rle_repeat_count, packed_code_sizes_index;
1745                mz_uint8 code_sizes_to_pack[TDEFL_MAX_HUFF_SYMBOLS_0 + TDEFL_MAX_HUFF_SYMBOLS_1], packed_code_sizes[TDEFL_MAX_HUFF_SYMBOLS_0 + TDEFL_MAX_HUFF_SYMBOLS_1], prev_code_size = 0xFF;
1746
1747                d->m_huff_count[0][256] = 1;
1748
1749                tdefl_optimize_huffman_table( d, 0, TDEFL_MAX_HUFF_SYMBOLS_0, 15, MZ_FALSE );
1750                tdefl_optimize_huffman_table( d, 1, TDEFL_MAX_HUFF_SYMBOLS_1, 15, MZ_FALSE );
1751
1752                for ( num_lit_codes = 286; num_lit_codes > 257; num_lit_codes-- ) if ( d->m_huff_code_sizes[0][num_lit_codes - 1] ) break;
1753                for ( num_dist_codes = 30; num_dist_codes > 1; num_dist_codes-- ) if ( d->m_huff_code_sizes[1][num_dist_codes - 1] ) break;
1754
1755                memcpy( code_sizes_to_pack, &d->m_huff_code_sizes[0][0], num_lit_codes );
1756                memcpy( code_sizes_to_pack + num_lit_codes, &d->m_huff_code_sizes[1][0], num_dist_codes );
1757                total_code_sizes_to_pack = num_lit_codes + num_dist_codes; num_packed_code_sizes = 0; rle_z_count = 0; rle_repeat_count = 0;
1758
1759                memset( &d->m_huff_count[2][0], 0, sizeof( d->m_huff_count[2][0] ) * TDEFL_MAX_HUFF_SYMBOLS_2 );
1760                for ( i = 0; i < total_code_sizes_to_pack; i++ )
1761                {
1762                        mz_uint8 code_size = code_sizes_to_pack[i];
1763                        if ( !code_size )
1764                        {
1765                                TDEFL_RLE_PREV_CODE_SIZE();
1766                                if ( ++rle_z_count == 138 ) { TDEFL_RLE_ZERO_CODE_SIZE(); }
1767                        }
1768                        else
1769                        {
1770                                TDEFL_RLE_ZERO_CODE_SIZE();
1771                                if ( code_size != prev_code_size )
1772                                {
1773                                        TDEFL_RLE_PREV_CODE_SIZE();
1774                                        d->m_huff_count[2][code_size] = (mz_uint16)( d->m_huff_count[2][code_size] + 1 ); packed_code_sizes[num_packed_code_sizes++] = code_size;
1775                                }
1776                                else if ( ++rle_repeat_count == 6 )
1777                                {
1778                                        TDEFL_RLE_PREV_CODE_SIZE();
1779                                }
1780                        }
1781                        prev_code_size = code_size;
1782                }
1783                if ( rle_repeat_count ) { TDEFL_RLE_PREV_CODE_SIZE(); }
1784                else { TDEFL_RLE_ZERO_CODE_SIZE(); }
1785
1786                tdefl_optimize_huffman_table( d, 2, TDEFL_MAX_HUFF_SYMBOLS_2, 7, MZ_FALSE );
1787
1788                TDEFL_PUT_BITS( 2, 2 );
1789
1790                TDEFL_PUT_BITS( num_lit_codes - 257, 5 );
1791                TDEFL_PUT_BITS( num_dist_codes - 1, 5 );
1792
1793                for ( num_bit_lengths = 18; num_bit_lengths >= 0; num_bit_lengths-- ) if ( d->m_huff_code_sizes[2][s_tdefl_packed_code_size_syms_swizzle[num_bit_lengths]] ) break;
1794                num_bit_lengths = MZ_MAX( 4, ( num_bit_lengths + 1 ) ); TDEFL_PUT_BITS( num_bit_lengths - 4, 4 );
1795                for ( i = 0; (int)i < num_bit_lengths; i++ ) TDEFL_PUT_BITS( d->m_huff_code_sizes[2][s_tdefl_packed_code_size_syms_swizzle[i]], 3 );
1796
1797                for ( packed_code_sizes_index = 0; packed_code_sizes_index < num_packed_code_sizes; )
1798                {
1799                        mz_uint code = packed_code_sizes[packed_code_sizes_index++]; MZ_ASSERT( code < TDEFL_MAX_HUFF_SYMBOLS_2 );
1800                        TDEFL_PUT_BITS( d->m_huff_codes[2][code], d->m_huff_code_sizes[2][code] );
1801                        if ( code >= 16 ) TDEFL_PUT_BITS( packed_code_sizes[packed_code_sizes_index++], "\02\03\07"[code - 16] );
1802                }
1803        }
1804
1805        static void tdefl_start_static_block( tdefl_compressor *d )
1806        {
1807                mz_uint i;
1808                mz_uint8 *p = &d->m_huff_code_sizes[0][0];
1809
1810                for ( i = 0; i <= 143; ++i ) *p++ = 8;
1811                for ( ; i <= 255; ++i ) *p++ = 9;
1812                for ( ; i <= 279; ++i ) *p++ = 7;
1813                for ( ; i <= 287; ++i ) *p++ = 8;
1814
1815                memset( d->m_huff_code_sizes[1], 5, 32 );
1816
1817                tdefl_optimize_huffman_table( d, 0, 288, 15, MZ_TRUE );
1818                tdefl_optimize_huffman_table( d, 1, 32, 15, MZ_TRUE );
1819
1820                TDEFL_PUT_BITS( 1, 2 );
1821        }
1822
1823        static const mz_uint mz_bitmasks[17] = { 0x0000, 0x0001, 0x0003, 0x0007, 0x000F, 0x001F, 0x003F, 0x007F, 0x00FF, 0x01FF, 0x03FF, 0x07FF, 0x0FFF, 0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF };
1824
1825#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN && MINIZ_HAS_64BIT_REGISTERS
1826        static mz_bool tdefl_compress_lz_codes( tdefl_compressor *d )
1827        {
1828                mz_uint flags;
1829                mz_uint8 *pLZ_codes;
1830                mz_uint8 *pOutput_buf = d->m_pOutput_buf;
1831                mz_uint8 *pLZ_code_buf_end = d->m_pLZ_code_buf;
1832                mz_uint64 bit_buffer = d->m_bit_buffer;
1833                mz_uint bits_in = d->m_bits_in;
1834
1835#define TDEFL_PUT_BITS_FAST(b, l) { bit_buffer |= (((mz_uint64)(b)) << bits_in); bits_in += (l); }
1836
1837                flags = 1;
1838                for ( pLZ_codes = d->m_lz_code_buf; pLZ_codes < pLZ_code_buf_end; flags >>= 1 )
1839                {
1840                        if ( flags == 1 )
1841                                flags = *pLZ_codes++ | 0x100;
1842
1843                        if ( flags & 1 )
1844                        {
1845                                mz_uint s0, s1, n0, n1, sym, num_extra_bits;
1846                                mz_uint match_len = pLZ_codes[0], match_dist = *(const mz_uint16 *)( pLZ_codes + 1 ); pLZ_codes += 3;
1847
1848                                MZ_ASSERT( d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]] );
1849                                TDEFL_PUT_BITS_FAST( d->m_huff_codes[0][s_tdefl_len_sym[match_len]], d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]] );
1850                                TDEFL_PUT_BITS_FAST( match_len & mz_bitmasks[s_tdefl_len_extra[match_len]], s_tdefl_len_extra[match_len] );
1851
1852                                // This sequence coaxes MSVC into using cmov's vs. jmp's.
1853                                s0 = s_tdefl_small_dist_sym[match_dist & 511];
1854                                n0 = s_tdefl_small_dist_extra[match_dist & 511];
1855                                s1 = s_tdefl_large_dist_sym[match_dist >> 8];
1856                                n1 = s_tdefl_large_dist_extra[match_dist >> 8];
1857                                sym = ( match_dist < 512 ) ? s0 : s1;
1858                                num_extra_bits = ( match_dist < 512 ) ? n0 : n1;
1859
1860                                MZ_ASSERT( d->m_huff_code_sizes[1][sym] );
1861                                TDEFL_PUT_BITS_FAST( d->m_huff_codes[1][sym], d->m_huff_code_sizes[1][sym] );
1862                                TDEFL_PUT_BITS_FAST( match_dist & mz_bitmasks[num_extra_bits], num_extra_bits );
1863                        }
1864                        else
1865                        {
1866                                mz_uint lit = *pLZ_codes++;
1867                                MZ_ASSERT( d->m_huff_code_sizes[0][lit] );
1868                                TDEFL_PUT_BITS_FAST( d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit] );
1869
1870                                if ( ( ( flags & 2 ) == 0 ) && ( pLZ_codes < pLZ_code_buf_end ) )
1871                                {
1872                                        flags >>= 1;
1873                                        lit = *pLZ_codes++;
1874                                        MZ_ASSERT( d->m_huff_code_sizes[0][lit] );
1875                                        TDEFL_PUT_BITS_FAST( d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit] );
1876
1877                                        if ( ( ( flags & 2 ) == 0 ) && ( pLZ_codes < pLZ_code_buf_end ) )
1878                                        {
1879                                                flags >>= 1;
1880                                                lit = *pLZ_codes++;
1881                                                MZ_ASSERT( d->m_huff_code_sizes[0][lit] );
1882                                                TDEFL_PUT_BITS_FAST( d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit] );
1883                                        }
1884                                }
1885                        }
1886
1887                        if ( pOutput_buf >= d->m_pOutput_buf_end )
1888                                return MZ_FALSE;
1889
1890                        *(mz_uint64*)pOutput_buf = bit_buffer;
1891                        pOutput_buf += ( bits_in >> 3 );
1892                        bit_buffer >>= ( bits_in & ~7 );
1893                        bits_in &= 7;
1894                }
1895
1896#undef TDEFL_PUT_BITS_FAST
1897
1898                d->m_pOutput_buf = pOutput_buf;
1899                d->m_bits_in = 0;
1900                d->m_bit_buffer = 0;
1901
1902                while ( bits_in )
1903                {
1904                        mz_uint32 n = MZ_MIN( bits_in, 16 );
1905                        TDEFL_PUT_BITS( (mz_uint)bit_buffer & mz_bitmasks[n], n );
1906                        bit_buffer >>= n;
1907                        bits_in -= n;
1908                }
1909
1910                TDEFL_PUT_BITS( d->m_huff_codes[0][256], d->m_huff_code_sizes[0][256] );
1911
1912                return ( d->m_pOutput_buf < d->m_pOutput_buf_end );
1913        }
1914#else
1915        static mz_bool tdefl_compress_lz_codes( tdefl_compressor *d )
1916        {
1917                mz_uint flags;
1918                mz_uint8 *pLZ_codes;
1919
1920                flags = 1;
1921                for ( pLZ_codes = d->m_lz_code_buf; pLZ_codes < d->m_pLZ_code_buf; flags >>= 1 )
1922                {
1923                        if ( flags == 1 )
1924                                flags = *pLZ_codes++ | 0x100;
1925                        if ( flags & 1 )
1926                        {
1927                                mz_uint sym, num_extra_bits;
1928                                mz_uint match_len = pLZ_codes[0], match_dist = ( pLZ_codes[1] | ( pLZ_codes[2] << 8 ) ); pLZ_codes += 3;
1929
1930                                MZ_ASSERT( d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]] );
1931                                TDEFL_PUT_BITS( d->m_huff_codes[0][s_tdefl_len_sym[match_len]], d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]] );
1932                                TDEFL_PUT_BITS( match_len & mz_bitmasks[s_tdefl_len_extra[match_len]], s_tdefl_len_extra[match_len] );
1933
1934                                if ( match_dist < 512 )
1935                                {
1936                                        sym = s_tdefl_small_dist_sym[match_dist]; num_extra_bits = s_tdefl_small_dist_extra[match_dist];
1937                                }
1938                                else
1939                                {
1940                                        sym = s_tdefl_large_dist_sym[match_dist >> 8]; num_extra_bits = s_tdefl_large_dist_extra[match_dist >> 8];
1941                                }
1942                                MZ_ASSERT( d->m_huff_code_sizes[1][sym] );
1943                                TDEFL_PUT_BITS( d->m_huff_codes[1][sym], d->m_huff_code_sizes[1][sym] );
1944                                TDEFL_PUT_BITS( match_dist & mz_bitmasks[num_extra_bits], num_extra_bits );
1945                        }
1946                        else
1947                        {
1948                                mz_uint lit = *pLZ_codes++;
1949                                MZ_ASSERT( d->m_huff_code_sizes[0][lit] );
1950                                TDEFL_PUT_BITS( d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit] );
1951                        }
1952                }
1953
1954                TDEFL_PUT_BITS( d->m_huff_codes[0][256], d->m_huff_code_sizes[0][256] );
1955
1956                return ( d->m_pOutput_buf < d->m_pOutput_buf_end );
1957        }
1958#endif // MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN && MINIZ_HAS_64BIT_REGISTERS
1959
1960        static mz_bool tdefl_compress_block( tdefl_compressor *d, mz_bool static_block )
1961        {
1962                if ( static_block )
1963                        tdefl_start_static_block( d );
1964                else
1965                        tdefl_start_dynamic_block( d );
1966                return tdefl_compress_lz_codes( d );
1967        }
1968
1969        static int tdefl_flush_block( tdefl_compressor *d, int flush )
1970        {
1971                mz_uint saved_bit_buf, saved_bits_in;
1972                mz_uint8 *pSaved_output_buf;
1973                mz_bool comp_block_succeeded = MZ_FALSE;
1974                int n, use_raw_block = ( ( d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS ) != 0 ) && ( d->m_lookahead_pos - d->m_lz_code_buf_dict_pos ) <= d->m_dict_size;
1975                mz_uint8 *pOutput_buf_start = ( ( d->m_pPut_buf_func == NULL ) && ( ( *d->m_pOut_buf_size - d->m_out_buf_ofs ) >= TDEFL_OUT_BUF_SIZE ) ) ? ( (mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs ) : d->m_output_buf;
1976
1977                d->m_pOutput_buf = pOutput_buf_start;
1978                d->m_pOutput_buf_end = d->m_pOutput_buf + TDEFL_OUT_BUF_SIZE - 16;
1979
1980                MZ_ASSERT( !d->m_output_flush_remaining );
1981                d->m_output_flush_ofs = 0;
1982                d->m_output_flush_remaining = 0;
1983
1984                *d->m_pLZ_flags = (mz_uint8)( *d->m_pLZ_flags >> d->m_num_flags_left );
1985                d->m_pLZ_code_buf -= ( d->m_num_flags_left == 8 );
1986
1987                if ( ( d->m_flags & TDEFL_WRITE_ZLIB_HEADER ) && ( !d->m_block_index ) )
1988                {
1989                        TDEFL_PUT_BITS( 0x78, 8 ); TDEFL_PUT_BITS( 0x01, 8 );
1990                }
1991
1992                TDEFL_PUT_BITS( flush == TDEFL_FINISH, 1 );
1993
1994                pSaved_output_buf = d->m_pOutput_buf; saved_bit_buf = d->m_bit_buffer; saved_bits_in = d->m_bits_in;
1995
1996                if ( !use_raw_block )
1997                        comp_block_succeeded = tdefl_compress_block( d, ( d->m_flags & TDEFL_FORCE_ALL_STATIC_BLOCKS ) || ( d->m_total_lz_bytes < 48 ) );
1998
1999                // If the block gets expanded, forget the current contents of the output buffer and send a raw block instead.
2000                if ( ( ( use_raw_block ) || ( ( d->m_total_lz_bytes ) && ( ( d->m_pOutput_buf - pSaved_output_buf + 1U ) >= d->m_total_lz_bytes ) ) ) &&
2001                        ( ( d->m_lookahead_pos - d->m_lz_code_buf_dict_pos ) <= d->m_dict_size ) )
2002                {
2003                        mz_uint i; d->m_pOutput_buf = pSaved_output_buf; d->m_bit_buffer = saved_bit_buf, d->m_bits_in = saved_bits_in;
2004                        TDEFL_PUT_BITS( 0, 2 );
2005                        if ( d->m_bits_in ) { TDEFL_PUT_BITS( 0, 8 - d->m_bits_in ); }
2006                        for ( i = 2; i; --i, d->m_total_lz_bytes ^= 0xFFFF )
2007                        {
2008                                TDEFL_PUT_BITS( d->m_total_lz_bytes & 0xFFFF, 16 );
2009                        }
2010                        for ( i = 0; i < d->m_total_lz_bytes; ++i )
2011                        {
2012                                TDEFL_PUT_BITS( d->m_dict[( d->m_lz_code_buf_dict_pos + i ) & TDEFL_LZ_DICT_SIZE_MASK], 8 );
2013                        }
2014                }
2015                // Check for the extremely unlikely (if not impossible) case of the compressed block not fitting into the output buffer when using dynamic codes.
2016                else if ( !comp_block_succeeded )
2017                {
2018                        d->m_pOutput_buf = pSaved_output_buf; d->m_bit_buffer = saved_bit_buf, d->m_bits_in = saved_bits_in;
2019                        tdefl_compress_block( d, MZ_TRUE );
2020                }
2021
2022                if ( flush )
2023                {
2024                        if ( flush == TDEFL_FINISH )
2025                        {
2026                                if ( d->m_bits_in ) { TDEFL_PUT_BITS( 0, 8 - d->m_bits_in ); }
2027                                if ( d->m_flags & TDEFL_WRITE_ZLIB_HEADER ) { mz_uint i, a = d->m_adler32; for ( i = 0; i < 4; i++ ) { TDEFL_PUT_BITS( ( a >> 24 ) & 0xFF, 8 ); a <<= 8; } }
2028                        }
2029                        else
2030                        {
2031                                mz_uint i, z = 0; TDEFL_PUT_BITS( 0, 3 ); if ( d->m_bits_in ) { TDEFL_PUT_BITS( 0, 8 - d->m_bits_in ); } for ( i = 2; i; --i, z ^= 0xFFFF ) { TDEFL_PUT_BITS( z & 0xFFFF, 16 ); }
2032                        }
2033                }
2034
2035                MZ_ASSERT( d->m_pOutput_buf < d->m_pOutput_buf_end );
2036
2037                memset( &d->m_huff_count[0][0], 0, sizeof( d->m_huff_count[0][0] ) * TDEFL_MAX_HUFF_SYMBOLS_0 );
2038                memset( &d->m_huff_count[1][0], 0, sizeof( d->m_huff_count[1][0] ) * TDEFL_MAX_HUFF_SYMBOLS_1 );
2039
2040                d->m_pLZ_code_buf = d->m_lz_code_buf + 1; d->m_pLZ_flags = d->m_lz_code_buf; d->m_num_flags_left = 8; d->m_lz_code_buf_dict_pos += d->m_total_lz_bytes; d->m_total_lz_bytes = 0; d->m_block_index++;
2041
2042                if ( ( n = (int)( d->m_pOutput_buf - pOutput_buf_start ) ) != 0 )
2043                {
2044                        if ( d->m_pPut_buf_func )
2045                        {
2046                                *d->m_pIn_buf_size = d->m_pSrc - (const mz_uint8 *)d->m_pIn_buf;
2047                                if ( !( *d->m_pPut_buf_func )( d->m_output_buf, n, d->m_pPut_buf_user ) )
2048                                        return ( d->m_prev_return_status = TDEFL_STATUS_PUT_BUF_FAILED );
2049                        }
2050                        else if ( pOutput_buf_start == d->m_output_buf )
2051                        {
2052                                int bytes_to_copy = (int)MZ_MIN( (size_t)n, (size_t)( *d->m_pOut_buf_size - d->m_out_buf_ofs ) );
2053                                memcpy( (mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs, d->m_output_buf, bytes_to_copy );
2054                                d->m_out_buf_ofs += bytes_to_copy;
2055                                if ( ( n -= bytes_to_copy ) != 0 )
2056                                {
2057                                        d->m_output_flush_ofs = bytes_to_copy;
2058                                        d->m_output_flush_remaining = n;
2059                                }
2060                        }
2061                        else
2062                        {
2063                                d->m_out_buf_ofs += n;
2064                        }
2065                }
2066
2067                return d->m_output_flush_remaining;
2068        }
2069
2070#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES
2071#define TDEFL_READ_UNALIGNED_WORD(p) *(const mz_uint16*)(p)
2072        static MZ_FORCEINLINE void tdefl_find_match( tdefl_compressor *d, mz_uint lookahead_pos, mz_uint max_dist, mz_uint max_match_len, mz_uint *pMatch_dist, mz_uint *pMatch_len )
2073        {
2074                mz_uint dist, pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK, match_len = *pMatch_len, probe_pos = pos, next_probe_pos, probe_len;
2075                mz_uint num_probes_left = d->m_max_probes[match_len >= 32];
2076                const mz_uint16 *s = (const mz_uint16*)( d->m_dict + pos ), *p, *q;
2077                mz_uint16 c01 = TDEFL_READ_UNALIGNED_WORD( &d->m_dict[pos + match_len - 1] ), s01 = TDEFL_READ_UNALIGNED_WORD( s );
2078                MZ_ASSERT( max_match_len <= TDEFL_MAX_MATCH_LEN ); if ( max_match_len <= match_len ) return;
2079                for ( ; ; )
2080                {
2081                        for ( ; ; )
2082                        {
2083                                if ( --num_probes_left == 0 ) return;
2084#define TDEFL_PROBE \
2085        next_probe_pos = d->m_next[probe_pos]; \
2086        if ((!next_probe_pos) || ((dist = (mz_uint16)(lookahead_pos - next_probe_pos)) > max_dist)) return; \
2087        probe_pos = next_probe_pos & TDEFL_LZ_DICT_SIZE_MASK; \
2088        if (TDEFL_READ_UNALIGNED_WORD(&d->m_dict[probe_pos + match_len - 1]) == c01) break;
2089                                TDEFL_PROBE; TDEFL_PROBE; TDEFL_PROBE;
2090                        }
2091                        if ( !dist ) break; q = (const mz_uint16*)( d->m_dict + probe_pos ); if ( TDEFL_READ_UNALIGNED_WORD( q ) != s01 ) continue; p = s; probe_len = 32;
2092                        do {} while ( ( TDEFL_READ_UNALIGNED_WORD( ++p ) == TDEFL_READ_UNALIGNED_WORD( ++q ) ) && ( TDEFL_READ_UNALIGNED_WORD( ++p ) == TDEFL_READ_UNALIGNED_WORD( ++q ) ) &&
2093                                ( TDEFL_READ_UNALIGNED_WORD( ++p ) == TDEFL_READ_UNALIGNED_WORD( ++q ) ) && ( TDEFL_READ_UNALIGNED_WORD( ++p ) == TDEFL_READ_UNALIGNED_WORD( ++q ) ) && ( --probe_len > 0 ) );
2094                        if ( !probe_len )
2095                        {
2096                                *pMatch_dist = dist; *pMatch_len = MZ_MIN( max_match_len, TDEFL_MAX_MATCH_LEN ); break;
2097                        }
2098                        else if ( ( probe_len = ( (mz_uint)( p - s ) * 2 ) + (mz_uint)( *(const mz_uint8*)p == *(const mz_uint8*)q ) ) > match_len )
2099                        {
2100                                *pMatch_dist = dist; if ( ( *pMatch_len = match_len = MZ_MIN( max_match_len, probe_len ) ) == max_match_len ) break;
2101                                c01 = TDEFL_READ_UNALIGNED_WORD( &d->m_dict[pos + match_len - 1] );
2102                        }
2103                }
2104        }
2105#else
2106        static MZ_FORCEINLINE void tdefl_find_match( tdefl_compressor *d, mz_uint lookahead_pos, mz_uint max_dist, mz_uint max_match_len, mz_uint *pMatch_dist, mz_uint *pMatch_len )
2107        {
2108                mz_uint dist, pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK, match_len = *pMatch_len, probe_pos = pos, next_probe_pos, probe_len;
2109                mz_uint num_probes_left = d->m_max_probes[match_len >= 32];
2110                const mz_uint8 *s = d->m_dict + pos, *p, *q;
2111                mz_uint8 c0 = d->m_dict[pos + match_len], c1 = d->m_dict[pos + match_len - 1];
2112                MZ_ASSERT( max_match_len <= TDEFL_MAX_MATCH_LEN ); if ( max_match_len <= match_len ) return;
2113                for ( ; ; )
2114                {
2115                        for ( ; ; )
2116                        {
2117                                if ( --num_probes_left == 0 ) return;
2118#define TDEFL_PROBE \
2119        next_probe_pos = d->m_next[probe_pos]; \
2120        if ((!next_probe_pos) || ((dist = (mz_uint16)(lookahead_pos - next_probe_pos)) > max_dist)) return; \
2121        probe_pos = next_probe_pos & TDEFL_LZ_DICT_SIZE_MASK; \
2122        if ((d->m_dict[probe_pos + match_len] == c0) && (d->m_dict[probe_pos + match_len - 1] == c1)) break;
2123                                TDEFL_PROBE; TDEFL_PROBE; TDEFL_PROBE;
2124                        }
2125                        if ( !dist ) break; p = s; q = d->m_dict + probe_pos; for ( probe_len = 0; probe_len < max_match_len; probe_len++ ) if ( *p++ != *q++ ) break;
2126                        if ( probe_len > match_len )
2127                        {
2128                                *pMatch_dist = dist; if ( ( *pMatch_len = match_len = probe_len ) == max_match_len ) return;
2129                                c0 = d->m_dict[pos + match_len]; c1 = d->m_dict[pos + match_len - 1];
2130                        }
2131                }
2132        }
2133#endif // #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES
2134
2135#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN
2136        static mz_bool tdefl_compress_fast( tdefl_compressor *d )
2137        {
2138                // Faster, minimally featured LZRW1-style match+parse loop with better register utilization. Intended for applications where raw throughput is valued more highly than ratio.
2139                mz_uint lookahead_pos = d->m_lookahead_pos, lookahead_size = d->m_lookahead_size, dict_size = d->m_dict_size, total_lz_bytes = d->m_total_lz_bytes, num_flags_left = d->m_num_flags_left;
2140                mz_uint8 *pLZ_code_buf = d->m_pLZ_code_buf, *pLZ_flags = d->m_pLZ_flags;
2141                mz_uint cur_pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK;
2142
2143                while ( ( d->m_src_buf_left ) || ( ( d->m_flush ) && ( lookahead_size ) ) )
2144                {
2145                        const mz_uint TDEFL_COMP_FAST_LOOKAHEAD_SIZE = 4096;
2146                        mz_uint dst_pos = ( lookahead_pos + lookahead_size ) & TDEFL_LZ_DICT_SIZE_MASK;
2147                        mz_uint num_bytes_to_process = (mz_uint)MZ_MIN( d->m_src_buf_left, TDEFL_COMP_FAST_LOOKAHEAD_SIZE - lookahead_size );
2148                        d->m_src_buf_left -= num_bytes_to_process;
2149                        lookahead_size += num_bytes_to_process;
2150
2151                        while ( num_bytes_to_process )
2152                        {
2153                                mz_uint32 n = MZ_MIN( TDEFL_LZ_DICT_SIZE - dst_pos, num_bytes_to_process );
2154                                memcpy( d->m_dict + dst_pos, d->m_pSrc, n );
2155                                if ( dst_pos < ( TDEFL_MAX_MATCH_LEN - 1 ) )
2156                                        memcpy( d->m_dict + TDEFL_LZ_DICT_SIZE + dst_pos, d->m_pSrc, MZ_MIN( n, ( TDEFL_MAX_MATCH_LEN - 1 ) - dst_pos ) );
2157                                d->m_pSrc += n;
2158                                dst_pos = ( dst_pos + n ) & TDEFL_LZ_DICT_SIZE_MASK;
2159                                num_bytes_to_process -= n;
2160                        }
2161
2162                        dict_size = MZ_MIN( TDEFL_LZ_DICT_SIZE - lookahead_size, dict_size );
2163                        if ( ( !d->m_flush ) && ( lookahead_size < TDEFL_COMP_FAST_LOOKAHEAD_SIZE ) ) break;
2164
2165                        while ( lookahead_size >= 4 )
2166                        {
2167                                mz_uint cur_match_dist, cur_match_len = 1;
2168                                mz_uint8 *pCur_dict = d->m_dict + cur_pos;
2169                                mz_uint first_trigram = ( *(const mz_uint32 *)pCur_dict ) & 0xFFFFFF;
2170                                mz_uint hash = ( first_trigram ^ ( first_trigram >> ( 24 - ( TDEFL_LZ_HASH_BITS - 8 ) ) ) ) & TDEFL_LEVEL1_HASH_SIZE_MASK;
2171                                mz_uint probe_pos = d->m_hash[hash];
2172                                d->m_hash[hash] = (mz_uint16)lookahead_pos;
2173
2174                                if ( ( ( cur_match_dist = (mz_uint16)( lookahead_pos - probe_pos ) ) <= dict_size ) && ( ( *(const mz_uint32 *)( d->m_dict + ( probe_pos &= TDEFL_LZ_DICT_SIZE_MASK ) ) & 0xFFFFFF ) == first_trigram ) )
2175                                {
2176                                        const mz_uint16 *p = (const mz_uint16 *)pCur_dict;
2177                                        const mz_uint16 *q = (const mz_uint16 *)( d->m_dict + probe_pos );
2178                                        mz_uint32 probe_len = 32;
2179                                        do {} while ( ( TDEFL_READ_UNALIGNED_WORD( ++p ) == TDEFL_READ_UNALIGNED_WORD( ++q ) ) && ( TDEFL_READ_UNALIGNED_WORD( ++p ) == TDEFL_READ_UNALIGNED_WORD( ++q ) ) &&
2180                                                ( TDEFL_READ_UNALIGNED_WORD( ++p ) == TDEFL_READ_UNALIGNED_WORD( ++q ) ) && ( TDEFL_READ_UNALIGNED_WORD( ++p ) == TDEFL_READ_UNALIGNED_WORD( ++q ) ) && ( --probe_len > 0 ) );
2181                                        cur_match_len = ( (mz_uint)( p - (const mz_uint16 *)pCur_dict ) * 2 ) + (mz_uint)( *(const mz_uint8 *)p == *(const mz_uint8 *)q );
2182                                        if ( !probe_len )
2183                                                cur_match_len = cur_match_dist ? TDEFL_MAX_MATCH_LEN : 0;
2184
2185                                        if ( ( cur_match_len < TDEFL_MIN_MATCH_LEN ) || ( ( cur_match_len == TDEFL_MIN_MATCH_LEN ) && ( cur_match_dist >= 8U * 1024U ) ) )
2186                                        {
2187                                                cur_match_len = 1;
2188                                                *pLZ_code_buf++ = (mz_uint8)first_trigram;
2189                                                *pLZ_flags = (mz_uint8)( *pLZ_flags >> 1 );
2190                                                d->m_huff_count[0][(mz_uint8)first_trigram]++;
2191                                        }
2192                                        else
2193                                        {
2194                                                mz_uint32 s0, s1;
2195                                                cur_match_len = MZ_MIN( cur_match_len, lookahead_size );
2196
2197                                                MZ_ASSERT( ( cur_match_len >= TDEFL_MIN_MATCH_LEN ) && ( cur_match_dist >= 1 ) && ( cur_match_dist <= TDEFL_LZ_DICT_SIZE ) );
2198
2199                                                cur_match_dist--;
2200
2201                                                pLZ_code_buf[0] = (mz_uint8)( cur_match_len - TDEFL_MIN_MATCH_LEN );
2202                                                *(mz_uint16 *)( &pLZ_code_buf[1] ) = (mz_uint16)cur_match_dist;
2203                                                pLZ_code_buf += 3;
2204                                                *pLZ_flags = (mz_uint8)( ( *pLZ_flags >> 1 ) | 0x80 );
2205
2206                                                s0 = s_tdefl_small_dist_sym[cur_match_dist & 511];
2207                                                s1 = s_tdefl_large_dist_sym[cur_match_dist >> 8];
2208                                                d->m_huff_count[1][( cur_match_dist < 512 ) ? s0 : s1]++;
2209
2210                                                d->m_huff_count[0][s_tdefl_len_sym[cur_match_len - TDEFL_MIN_MATCH_LEN]]++;
2211                                        }
2212                                }
2213                                else
2214                                {
2215                                        *pLZ_code_buf++ = (mz_uint8)first_trigram;
2216                                        *pLZ_flags = (mz_uint8)( *pLZ_flags >> 1 );
2217                                        d->m_huff_count[0][(mz_uint8)first_trigram]++;
2218                                }
2219
2220                                if ( --num_flags_left == 0 ) { num_flags_left = 8; pLZ_flags = pLZ_code_buf++; }
2221
2222                                total_lz_bytes += cur_match_len;
2223                                lookahead_pos += cur_match_len;
2224                                dict_size = MZ_MIN( dict_size + cur_match_len, TDEFL_LZ_DICT_SIZE );
2225                                cur_pos = ( cur_pos + cur_match_len ) & TDEFL_LZ_DICT_SIZE_MASK;
2226                                MZ_ASSERT( lookahead_size >= cur_match_len );
2227                                lookahead_size -= cur_match_len;
2228
2229                                if ( pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8] )
2230                                {
2231                                        int n;
2232                                        d->m_lookahead_pos = lookahead_pos; d->m_lookahead_size = lookahead_size; d->m_dict_size = dict_size;
2233                                        d->m_total_lz_bytes = total_lz_bytes; d->m_pLZ_code_buf = pLZ_code_buf; d->m_pLZ_flags = pLZ_flags; d->m_num_flags_left = num_flags_left;
2234                                        if ( ( n = tdefl_flush_block( d, 0 ) ) != 0 )
2235                                                return ( n < 0 ) ? MZ_FALSE : MZ_TRUE;
2236                                        total_lz_bytes = d->m_total_lz_bytes; pLZ_code_buf = d->m_pLZ_code_buf; pLZ_flags = d->m_pLZ_flags; num_flags_left = d->m_num_flags_left;
2237                                }
2238                        }
2239
2240                        while ( lookahead_size )
2241                        {
2242                                mz_uint8 lit = d->m_dict[cur_pos];
2243
2244                                total_lz_bytes++;
2245                                *pLZ_code_buf++ = lit;
2246                                *pLZ_flags = (mz_uint8)( *pLZ_flags >> 1 );
2247                                if ( --num_flags_left == 0 ) { num_flags_left = 8; pLZ_flags = pLZ_code_buf++; }
2248
2249                                d->m_huff_count[0][lit]++;
2250
2251                                lookahead_pos++;
2252                                dict_size = MZ_MIN( dict_size + 1, TDEFL_LZ_DICT_SIZE );
2253                                cur_pos = ( cur_pos + 1 ) & TDEFL_LZ_DICT_SIZE_MASK;
2254                                lookahead_size--;
2255
2256                                if ( pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8] )
2257                                {
2258                                        int n;
2259                                        d->m_lookahead_pos = lookahead_pos; d->m_lookahead_size = lookahead_size; d->m_dict_size = dict_size;
2260                                        d->m_total_lz_bytes = total_lz_bytes; d->m_pLZ_code_buf = pLZ_code_buf; d->m_pLZ_flags = pLZ_flags; d->m_num_flags_left = num_flags_left;
2261                                        if ( ( n = tdefl_flush_block( d, 0 ) ) != 0 )
2262                                                return ( n < 0 ) ? MZ_FALSE : MZ_TRUE;
2263                                        total_lz_bytes = d->m_total_lz_bytes; pLZ_code_buf = d->m_pLZ_code_buf; pLZ_flags = d->m_pLZ_flags; num_flags_left = d->m_num_flags_left;
2264                                }
2265                        }
2266                }
2267
2268                d->m_lookahead_pos = lookahead_pos; d->m_lookahead_size = lookahead_size; d->m_dict_size = dict_size;
2269                d->m_total_lz_bytes = total_lz_bytes; d->m_pLZ_code_buf = pLZ_code_buf; d->m_pLZ_flags = pLZ_flags; d->m_num_flags_left = num_flags_left;
2270                return MZ_TRUE;
2271        }
2272#endif // MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN
2273
2274        static MZ_FORCEINLINE void tdefl_record_literal( tdefl_compressor *d, mz_uint8 lit )
2275        {
2276                d->m_total_lz_bytes++;
2277                *d->m_pLZ_code_buf++ = lit;
2278                *d->m_pLZ_flags = (mz_uint8)( *d->m_pLZ_flags >> 1 ); if ( --d->m_num_flags_left == 0 ) { d->m_num_flags_left = 8; d->m_pLZ_flags = d->m_pLZ_code_buf++; }
2279                d->m_huff_count[0][lit]++;
2280        }
2281
2282        static MZ_FORCEINLINE void tdefl_record_match( tdefl_compressor *d, mz_uint match_len, mz_uint match_dist )
2283        {
2284                mz_uint32 s0, s1;
2285
2286                MZ_ASSERT( ( match_len >= TDEFL_MIN_MATCH_LEN ) && ( match_dist >= 1 ) && ( match_dist <= TDEFL_LZ_DICT_SIZE ) );
2287
2288                d->m_total_lz_bytes += match_len;
2289
2290                d->m_pLZ_code_buf[0] = (mz_uint8)( match_len - TDEFL_MIN_MATCH_LEN );
2291
2292                match_dist -= 1;
2293                d->m_pLZ_code_buf[1] = (mz_uint8)( match_dist & 0xFF );
2294                d->m_pLZ_code_buf[2] = (mz_uint8)( match_dist >> 8 ); d->m_pLZ_code_buf += 3;
2295
2296                *d->m_pLZ_flags = (mz_uint8)( ( *d->m_pLZ_flags >> 1 ) | 0x80 ); if ( --d->m_num_flags_left == 0 ) { d->m_num_flags_left = 8; d->m_pLZ_flags = d->m_pLZ_code_buf++; }
2297
2298                s0 = s_tdefl_small_dist_sym[match_dist & 511]; s1 = s_tdefl_large_dist_sym[( match_dist >> 8 ) & 127];
2299                d->m_huff_count[1][( match_dist < 512 ) ? s0 : s1]++;
2300
2301                if ( match_len >= TDEFL_MIN_MATCH_LEN ) d->m_huff_count[0][s_tdefl_len_sym[match_len - TDEFL_MIN_MATCH_LEN]]++;
2302        }
2303
2304        static mz_bool tdefl_compress_normal( tdefl_compressor *d )
2305        {
2306                const mz_uint8 *pSrc = d->m_pSrc; size_t src_buf_left = d->m_src_buf_left;
2307                tdefl_flush flush = d->m_flush;
2308
2309                while ( ( src_buf_left ) || ( ( flush ) && ( d->m_lookahead_size ) ) )
2310                {
2311                        mz_uint len_to_move, cur_match_dist, cur_match_len, cur_pos;
2312                        // Update dictionary and hash chains. Keeps the lookahead size equal to TDEFL_MAX_MATCH_LEN.
2313                        if ( ( d->m_lookahead_size + d->m_dict_size ) >= ( TDEFL_MIN_MATCH_LEN - 1 ) )
2314                        {
2315                                mz_uint dst_pos = ( d->m_lookahead_pos + d->m_lookahead_size ) & TDEFL_LZ_DICT_SIZE_MASK, ins_pos = d->m_lookahead_pos + d->m_lookahead_size - 2;
2316                                mz_uint hash = ( d->m_dict[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] << TDEFL_LZ_HASH_SHIFT ) ^ d->m_dict[( ins_pos + 1 ) & TDEFL_LZ_DICT_SIZE_MASK];
2317                                mz_uint num_bytes_to_process = (mz_uint)MZ_MIN( src_buf_left, TDEFL_MAX_MATCH_LEN - d->m_lookahead_size );
2318                                const mz_uint8 *pSrc_end = pSrc + num_bytes_to_process;
2319                                src_buf_left -= num_bytes_to_process;
2320                                d->m_lookahead_size += num_bytes_to_process;
2321                                while ( pSrc != pSrc_end )
2322                                {
2323                                        mz_uint8 c = *pSrc++; d->m_dict[dst_pos] = c; if ( dst_pos < ( TDEFL_MAX_MATCH_LEN - 1 ) ) d->m_dict[TDEFL_LZ_DICT_SIZE + dst_pos] = c;
2324                                        hash = ( ( hash << TDEFL_LZ_HASH_SHIFT ) ^ c ) & ( TDEFL_LZ_HASH_SIZE - 1 );
2325                                        d->m_next[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] = d->m_hash[hash]; d->m_hash[hash] = (mz_uint16)( ins_pos );
2326                                        dst_pos = ( dst_pos + 1 ) & TDEFL_LZ_DICT_SIZE_MASK; ins_pos++;
2327                                }
2328                        }
2329                        else
2330                        {
2331                                while ( ( src_buf_left ) && ( d->m_lookahead_size < TDEFL_MAX_MATCH_LEN ) )
2332                                {
2333                                        mz_uint8 c = *pSrc++;
2334                                        mz_uint dst_pos = ( d->m_lookahead_pos + d->m_lookahead_size ) & TDEFL_LZ_DICT_SIZE_MASK;
2335                                        src_buf_left--;
2336                                        d->m_dict[dst_pos] = c;
2337                                        if ( dst_pos < ( TDEFL_MAX_MATCH_LEN - 1 ) )
2338                                                d->m_dict[TDEFL_LZ_DICT_SIZE + dst_pos] = c;
2339                                        if ( ( ++d->m_lookahead_size + d->m_dict_size ) >= TDEFL_MIN_MATCH_LEN )
2340                                        {
2341                                                mz_uint ins_pos = d->m_lookahead_pos + ( d->m_lookahead_size - 1 ) - 2;
2342                                                mz_uint hash = ( ( d->m_dict[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] << ( TDEFL_LZ_HASH_SHIFT * 2 ) ) ^ ( d->m_dict[( ins_pos + 1 ) & TDEFL_LZ_DICT_SIZE_MASK] << TDEFL_LZ_HASH_SHIFT ) ^ c ) & ( TDEFL_LZ_HASH_SIZE - 1 );
2343                                                d->m_next[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] = d->m_hash[hash]; d->m_hash[hash] = (mz_uint16)( ins_pos );
2344                                        }
2345                                }
2346                        }
2347                        d->m_dict_size = MZ_MIN( TDEFL_LZ_DICT_SIZE - d->m_lookahead_size, d->m_dict_size );
2348                        if ( ( !flush ) && ( d->m_lookahead_size < TDEFL_MAX_MATCH_LEN ) )
2349                                break;
2350
2351                        // Simple lazy/greedy parsing state machine.
2352                        len_to_move = 1; cur_match_dist = 0; cur_match_len = d->m_saved_match_len ? d->m_saved_match_len : ( TDEFL_MIN_MATCH_LEN - 1 ); cur_pos = d->m_lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK;
2353                        if ( d->m_flags & ( TDEFL_RLE_MATCHES | TDEFL_FORCE_ALL_RAW_BLOCKS ) )
2354                        {
2355                                if ( ( d->m_dict_size ) && ( !( d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS ) ) )
2356                                {
2357                                        mz_uint8 c = d->m_dict[( cur_pos - 1 ) & TDEFL_LZ_DICT_SIZE_MASK];
2358                                        cur_match_len = 0; while ( cur_match_len < d->m_lookahead_size ) { if ( d->m_dict[cur_pos + cur_match_len] != c ) break; cur_match_len++; }
2359                                        if ( cur_match_len < TDEFL_MIN_MATCH_LEN ) cur_match_len = 0; else cur_match_dist = 1;
2360                                }
2361                        }
2362                        else
2363                        {
2364                                tdefl_find_match( d, d->m_lookahead_pos, d->m_dict_size, d->m_lookahead_size, &cur_match_dist, &cur_match_len );
2365                        }
2366                        if ( ( ( cur_match_len == TDEFL_MIN_MATCH_LEN ) && ( cur_match_dist >= 8U * 1024U ) ) || ( cur_pos == cur_match_dist ) || ( ( d->m_flags & TDEFL_FILTER_MATCHES ) && ( cur_match_len <= 5 ) ) )
2367                        {
2368                                cur_match_dist = cur_match_len = 0;
2369                        }
2370                        if ( d->m_saved_match_len )
2371                        {
2372                                if ( cur_match_len > d->m_saved_match_len )
2373                                {
2374                                        tdefl_record_literal( d, (mz_uint8)d->m_saved_lit );
2375                                        if ( cur_match_len >= 128 )
2376                                        {
2377                                                tdefl_record_match( d, cur_match_len, cur_match_dist );
2378                                                d->m_saved_match_len = 0; len_to_move = cur_match_len;
2379                                        }
2380                                        else
2381                                        {
2382                                                d->m_saved_lit = d->m_dict[cur_pos]; d->m_saved_match_dist = cur_match_dist; d->m_saved_match_len = cur_match_len;
2383                                        }
2384                                }
2385                                else
2386                                {
2387                                        tdefl_record_match( d, d->m_saved_match_len, d->m_saved_match_dist );
2388                                        len_to_move = d->m_saved_match_len - 1; d->m_saved_match_len = 0;
2389                                }
2390                        }
2391                        else if ( !cur_match_dist )
2392                                tdefl_record_literal( d, d->m_dict[MZ_MIN( cur_pos, sizeof( d->m_dict ) - 1 )] );
2393                        else if ( ( d->m_greedy_parsing ) || ( d->m_flags & TDEFL_RLE_MATCHES ) || ( cur_match_len >= 128 ) )
2394                        {
2395                                tdefl_record_match( d, cur_match_len, cur_match_dist );
2396                                len_to_move = cur_match_len;
2397                        }
2398                        else
2399                        {
2400                                d->m_saved_lit = d->m_dict[MZ_MIN( cur_pos, sizeof( d->m_dict ) - 1 )]; d->m_saved_match_dist = cur_match_dist; d->m_saved_match_len = cur_match_len;
2401                        }
2402                        // Move the lookahead forward by len_to_move bytes.
2403                        d->m_lookahead_pos += len_to_move;
2404                        MZ_ASSERT( d->m_lookahead_size >= len_to_move );
2405                        d->m_lookahead_size -= len_to_move;
2406                        d->m_dict_size = MZ_MIN( d->m_dict_size + len_to_move, TDEFL_LZ_DICT_SIZE );
2407                        // Check if it's time to flush the current LZ codes to the internal output buffer.
2408                        if ( ( d->m_pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8] ) ||
2409                                ( ( d->m_total_lz_bytes > 31 * 1024 ) && ( ( ( ( (mz_uint)( d->m_pLZ_code_buf - d->m_lz_code_buf ) * 115 ) >> 7 ) >= d->m_total_lz_bytes ) || ( d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS ) ) ) )
2410                        {
2411                                int n;
2412                                d->m_pSrc = pSrc; d->m_src_buf_left = src_buf_left;
2413                                if ( ( n = tdefl_flush_block( d, 0 ) ) != 0 )
2414                                        return ( n < 0 ) ? MZ_FALSE : MZ_TRUE;
2415                        }
2416                }
2417
2418                d->m_pSrc = pSrc; d->m_src_buf_left = src_buf_left;
2419                return MZ_TRUE;
2420        }
2421
2422        static tdefl_status tdefl_flush_output_buffer( tdefl_compressor *d )
2423        {
2424                if ( d->m_pIn_buf_size )
2425                {
2426                        *d->m_pIn_buf_size = d->m_pSrc - (const mz_uint8 *)d->m_pIn_buf;
2427                }
2428
2429                if ( d->m_pOut_buf_size )
2430                {
2431                        size_t n = MZ_MIN( *d->m_pOut_buf_size - d->m_out_buf_ofs, d->m_output_flush_remaining );
2432                        memcpy( (mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs, d->m_output_buf + d->m_output_flush_ofs, n );
2433                        d->m_output_flush_ofs += (mz_uint)n;
2434                        d->m_output_flush_remaining -= (mz_uint)n;
2435                        d->m_out_buf_ofs += n;
2436
2437                        *d->m_pOut_buf_size = d->m_out_buf_ofs;
2438                }
2439
2440                return ( d->m_finished && !d->m_output_flush_remaining ) ? TDEFL_STATUS_DONE : TDEFL_STATUS_OKAY;
2441        }
2442
2443        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 )
2444        {
2445                if ( !d )
2446                {
2447                        if ( pIn_buf_size ) *pIn_buf_size = 0;
2448                        if ( pOut_buf_size ) *pOut_buf_size = 0;
2449                        return TDEFL_STATUS_BAD_PARAM;
2450                }
2451
2452                d->m_pIn_buf = pIn_buf; d->m_pIn_buf_size = pIn_buf_size;
2453                d->m_pOut_buf = pOut_buf; d->m_pOut_buf_size = pOut_buf_size;
2454                d->m_pSrc = (const mz_uint8 *)( pIn_buf ); d->m_src_buf_left = pIn_buf_size ? *pIn_buf_size : 0;
2455                d->m_out_buf_ofs = 0;
2456                d->m_flush = flush;
2457
2458                if ( ( ( d->m_pPut_buf_func != NULL ) == ( ( pOut_buf != NULL ) || ( pOut_buf_size != NULL ) ) ) || ( d->m_prev_return_status != TDEFL_STATUS_OKAY ) ||
2459                        ( d->m_wants_to_finish && ( flush != TDEFL_FINISH ) ) || ( pIn_buf_size && *pIn_buf_size && !pIn_buf ) || ( pOut_buf_size && *pOut_buf_size && !pOut_buf ) )
2460                {
2461                        if ( pIn_buf_size ) *pIn_buf_size = 0;
2462                        if ( pOut_buf_size ) *pOut_buf_size = 0;
2463                        return ( d->m_prev_return_status = TDEFL_STATUS_BAD_PARAM );
2464                }
2465                d->m_wants_to_finish |= ( flush == TDEFL_FINISH );
2466
2467                if ( ( d->m_output_flush_remaining ) || ( d->m_finished ) )
2468                        return ( d->m_prev_return_status = tdefl_flush_output_buffer( d ) );
2469
2470#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN
2471                if ( ( ( d->m_flags & TDEFL_MAX_PROBES_MASK ) == 1 ) &&
2472                        ( ( d->m_flags & TDEFL_GREEDY_PARSING_FLAG ) != 0 ) &&
2473                        ( ( d->m_flags & ( TDEFL_FILTER_MATCHES | TDEFL_FORCE_ALL_RAW_BLOCKS | TDEFL_RLE_MATCHES ) ) == 0 ) )
2474                {
2475                        if ( !tdefl_compress_fast( d ) )
2476                                return d->m_prev_return_status;
2477                }
2478                else
2479#endif // #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN
2480                {
2481                        if ( !tdefl_compress_normal( d ) )
2482                                return d->m_prev_return_status;
2483                }
2484
2485                if ( ( d->m_flags & ( TDEFL_WRITE_ZLIB_HEADER | TDEFL_COMPUTE_ADLER32 ) ) && ( pIn_buf ) )
2486                        d->m_adler32 = (mz_uint32)mz_adler32( d->m_adler32, (const mz_uint8 *)pIn_buf, d->m_pSrc - (const mz_uint8 *)pIn_buf );
2487
2488                if ( ( flush ) && ( !d->m_lookahead_size ) && ( !d->m_src_buf_left ) && ( !d->m_output_flush_remaining ) )
2489                {
2490                        if ( tdefl_flush_block( d, flush ) < 0 )
2491                                return d->m_prev_return_status;
2492                        d->m_finished = ( flush == TDEFL_FINISH );
2493                        if ( flush == TDEFL_FULL_FLUSH ) { MZ_CLEAR_OBJ( d->m_hash ); MZ_CLEAR_OBJ( d->m_next ); d->m_dict_size = 0; }
2494                }
2495
2496                return ( d->m_prev_return_status = tdefl_flush_output_buffer( d ) );
2497        }
2498
2499        tdefl_status tdefl_compress_buffer( tdefl_compressor *d, const void *pIn_buf, size_t in_buf_size, tdefl_flush flush )
2500        {
2501                MZ_ASSERT( d->m_pPut_buf_func ); return tdefl_compress( d, pIn_buf, &in_buf_size, NULL, NULL, flush );
2502        }
2503
2504        tdefl_status tdefl_init( tdefl_compressor *d, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags )
2505        {
2506                d->m_pPut_buf_func = pPut_buf_func; d->m_pPut_buf_user = pPut_buf_user;
2507                d->m_flags = (mz_uint)( flags ); d->m_max_probes[0] = 1 + ( ( flags & 0xFFF ) + 2 ) / 3; d->m_greedy_parsing = ( flags & TDEFL_GREEDY_PARSING_FLAG ) != 0;
2508                d->m_max_probes[1] = 1 + ( ( ( flags & 0xFFF ) >> 2 ) + 2 ) / 3;
2509                if ( !( flags & TDEFL_NONDETERMINISTIC_PARSING_FLAG ) ) MZ_CLEAR_OBJ( d->m_hash );
2510                d->m_lookahead_pos = d->m_lookahead_size = d->m_dict_size = d->m_total_lz_bytes = d->m_lz_code_buf_dict_pos = d->m_bits_in = 0;
2511                d->m_output_flush_ofs = d->m_output_flush_remaining = d->m_finished = d->m_block_index = d->m_bit_buffer = d->m_wants_to_finish = 0;
2512                d->m_pLZ_code_buf = d->m_lz_code_buf + 1; d->m_pLZ_flags = d->m_lz_code_buf; d->m_num_flags_left = 8;
2513                d->m_pOutput_buf = d->m_output_buf; d->m_pOutput_buf_end = d->m_output_buf; d->m_prev_return_status = TDEFL_STATUS_OKAY;
2514                d->m_saved_match_dist = d->m_saved_match_len = d->m_saved_lit = 0; d->m_adler32 = 1;
2515                d->m_pIn_buf = NULL; d->m_pOut_buf = NULL;
2516                d->m_pIn_buf_size = NULL; d->m_pOut_buf_size = NULL;
2517                d->m_flush = TDEFL_NO_FLUSH; d->m_pSrc = NULL; d->m_src_buf_left = 0; d->m_out_buf_ofs = 0;
2518                memset( &d->m_huff_count[0][0], 0, sizeof( d->m_huff_count[0][0] ) * TDEFL_MAX_HUFF_SYMBOLS_0 );
2519                memset( &d->m_huff_count[1][0], 0, sizeof( d->m_huff_count[1][0] ) * TDEFL_MAX_HUFF_SYMBOLS_1 );
2520                return TDEFL_STATUS_OKAY;
2521        }
2522
2523        tdefl_status tdefl_get_prev_return_status( tdefl_compressor *d )
2524        {
2525                return d->m_prev_return_status;
2526        }
2527
2528        mz_uint32 tdefl_get_adler32( tdefl_compressor *d )
2529        {
2530                return d->m_adler32;
2531        }
2532
2533        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 )
2534        {
2535                tdefl_compressor *pComp; mz_bool succeeded; if ( ( ( buf_len ) && ( !pBuf ) ) || ( !pPut_buf_func ) ) return MZ_FALSE;
2536                pComp = (tdefl_compressor*)MZ_MALLOC( sizeof( tdefl_compressor ) ); if ( !pComp ) return MZ_FALSE;
2537                succeeded = ( tdefl_init( pComp, pPut_buf_func, pPut_buf_user, flags ) == TDEFL_STATUS_OKAY );
2538                succeeded = succeeded && ( tdefl_compress_buffer( pComp, pBuf, buf_len, TDEFL_FINISH ) == TDEFL_STATUS_DONE );
2539                MZ_FREE( pComp ); return succeeded;
2540        }
2541
2542        typedef struct
2543        {
2544                size_t m_size, m_capacity;
2545                mz_uint8 *m_pBuf;
2546                mz_bool m_expandable;
2547        } tdefl_output_buffer;
2548
2549        static mz_bool tdefl_output_buffer_putter( const void *pBuf, int len, void *pUser )
2550        {
2551                tdefl_output_buffer *p = (tdefl_output_buffer *)pUser;
2552                size_t new_size = p->m_size + len;
2553                if ( new_size > p->m_capacity )
2554                {
2555                        size_t new_capacity = p->m_capacity; mz_uint8 *pNew_buf; if ( !p->m_expandable ) return MZ_FALSE;
2556                        do { new_capacity = MZ_MAX( 128U, new_capacity << 1U ); } while ( new_size > new_capacity );
2557                        pNew_buf = (mz_uint8*)MZ_REALLOC( p->m_pBuf, new_capacity ); if ( !pNew_buf ) return MZ_FALSE;
2558                        p->m_pBuf = pNew_buf; p->m_capacity = new_capacity;
2559                }
2560                memcpy( (mz_uint8*)p->m_pBuf + p->m_size, pBuf, len ); p->m_size = new_size;
2561                return MZ_TRUE;
2562        }
2563
2564        void *tdefl_compress_mem_to_heap( const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags )
2565        {
2566                tdefl_output_buffer out_buf; MZ_CLEAR_OBJ( out_buf );
2567                if ( !pOut_len ) return MZ_FALSE; else *pOut_len = 0;
2568                out_buf.m_expandable = MZ_TRUE;
2569                if ( !tdefl_compress_mem_to_output( pSrc_buf, src_buf_len, tdefl_output_buffer_putter, &out_buf, flags ) ) return NULL;
2570                *pOut_len = out_buf.m_size; return out_buf.m_pBuf;
2571        }
2572
2573        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 )
2574        {
2575                tdefl_output_buffer out_buf; MZ_CLEAR_OBJ( out_buf );
2576                if ( !pOut_buf ) return 0;
2577                out_buf.m_pBuf = (mz_uint8*)pOut_buf; out_buf.m_capacity = out_buf_len;
2578                if ( !tdefl_compress_mem_to_output( pSrc_buf, src_buf_len, tdefl_output_buffer_putter, &out_buf, flags ) ) return 0;
2579                return out_buf.m_size;
2580        }
2581
2582#ifndef MINIZ_NO_ZLIB_APIS
2583        static const mz_uint s_tdefl_num_probes[11] = { 0, 1, 6, 32,  16, 32, 128, 256,  512, 768, 1500 };
2584
2585        // level may actually range from [0,10] (10 is a "hidden" max level, where we want a bit more compression and it's fine if throughput to fall off a cliff on some files).
2586        mz_uint tdefl_create_comp_flags_from_zip_params( int level, int window_bits, int strategy )
2587        {
2588                mz_uint comp_flags = s_tdefl_num_probes[( level >= 0 ) ? MZ_MIN( 10, level ) : MZ_DEFAULT_LEVEL] | ( ( level <= 3 ) ? TDEFL_GREEDY_PARSING_FLAG : 0 );
2589                if ( window_bits > 0 ) comp_flags |= TDEFL_WRITE_ZLIB_HEADER;
2590
2591                if ( !level ) comp_flags |= TDEFL_FORCE_ALL_RAW_BLOCKS;
2592                else if ( strategy == MZ_FILTERED ) comp_flags |= TDEFL_FILTER_MATCHES;
2593                else if ( strategy == MZ_HUFFMAN_ONLY ) comp_flags &= ~TDEFL_MAX_PROBES_MASK;
2594                else if ( strategy == MZ_FIXED ) comp_flags |= TDEFL_FORCE_ALL_STATIC_BLOCKS;
2595                else if ( strategy == MZ_RLE ) comp_flags |= TDEFL_RLE_MATCHES;
2596
2597                return comp_flags;
2598        }
2599#endif //MINIZ_NO_ZLIB_APIS
2600
2601#ifdef _MSC_VER
2602#pragma warning (push)
2603#pragma warning (disable:4204) // nonstandard extension used : non-constant aggregate initializer (also supported by GNU C and C99, so no big deal)
2604#endif
2605
2606        // Simple PNG writer function by Alex Evans, 2011. Released into the public domain: https://gist.github.com/908299, more context at
2607        // http://altdevblogaday.org/2011/04/06/a-smaller-jpg-encoder/.
2608        // This is actually a modification of Alex's original code so PNG files generated by this function pass pngcheck.
2609        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 )
2610        {
2611                // Using a local copy of this array here in case MINIZ_NO_ZLIB_APIS was defined.
2612                static const mz_uint s_tdefl_png_num_probes[11] = { 0, 1, 6, 32,  16, 32, 128, 256,  512, 768, 1500 };
2613                tdefl_compressor *pComp = (tdefl_compressor *)MZ_MALLOC( sizeof( tdefl_compressor ) ); tdefl_output_buffer out_buf; int i, bpl = w * num_chans, y, z; mz_uint32 c; *pLen_out = 0;
2614                if ( !pComp ) return NULL;
2615                MZ_CLEAR_OBJ( out_buf ); out_buf.m_expandable = MZ_TRUE; out_buf.m_capacity = 57 + MZ_MAX( 64, ( 1 + bpl )*h ); if ( NULL == ( out_buf.m_pBuf = (mz_uint8*)MZ_MALLOC( out_buf.m_capacity ) ) ) { MZ_FREE( pComp ); return NULL; }
2616                // write dummy header
2617                for ( z = 41; z; --z ) tdefl_output_buffer_putter( &z, 1, &out_buf );
2618                // compress image data
2619                tdefl_init( pComp, tdefl_output_buffer_putter, &out_buf, s_tdefl_png_num_probes[MZ_MIN( 10, level )] | TDEFL_WRITE_ZLIB_HEADER );
2620                for ( y = 0; y < h; ++y ) { tdefl_compress_buffer( pComp, &z, 1, TDEFL_NO_FLUSH ); tdefl_compress_buffer( pComp, (mz_uint8*)pImage + ( flip ? ( h - 1 - y ) : y ) * bpl, bpl, TDEFL_NO_FLUSH ); }
2621                if ( tdefl_compress_buffer( pComp, NULL, 0, TDEFL_FINISH ) != TDEFL_STATUS_DONE ) { MZ_FREE( pComp ); MZ_FREE( out_buf.m_pBuf ); return NULL; }
2622                // write real header
2623                *pLen_out = out_buf.m_size - 41;
2624                {
2625                        static const mz_uint8 chans[] = { 0x00, 0x00, 0x04, 0x02, 0x06 };
2626                        mz_uint8 pnghdr[41] = { 0x89,0x50,0x4e,0x47,0x0d,0x0a,0x1a,0x0a,0x00,0x00,0x00,0x0d,0x49,0x48,0x44,0x52,
2627                                0,0,(mz_uint8)( w >> 8 ),(mz_uint8)w,0,0,(mz_uint8)( h >> 8 ),(mz_uint8)h,8,chans[num_chans],0,0,0,0,0,0,0,
2628                                (mz_uint8)( *pLen_out >> 24 ),(mz_uint8)( *pLen_out >> 16 ),(mz_uint8)( *pLen_out >> 8 ),(mz_uint8)*pLen_out,0x49,0x44,0x41,0x54 };
2629                        c = (mz_uint32)mz_crc32( MZ_CRC32_INIT, pnghdr + 12, 17 ); for ( i = 0; i < 4; ++i, c <<= 8 ) ( (mz_uint8*)( pnghdr + 29 ) )[i] = (mz_uint8)( c >> 24 );
2630                        memcpy( out_buf.m_pBuf, pnghdr, 41 );
2631                }
2632                // write footer (IDAT CRC-32, followed by IEND chunk)
2633                if ( !tdefl_output_buffer_putter( "\0\0\0\0\0\0\0\0\x49\x45\x4e\x44\xae\x42\x60\x82", 16, &out_buf ) ) { *pLen_out = 0; MZ_FREE( pComp ); MZ_FREE( out_buf.m_pBuf ); return NULL; }
2634                c = (mz_uint32)mz_crc32( MZ_CRC32_INIT, out_buf.m_pBuf + 41 - 4, *pLen_out + 4 ); for ( i = 0; i < 4; ++i, c <<= 8 ) ( out_buf.m_pBuf + out_buf.m_size - 16 )[i] = (mz_uint8)( c >> 24 );
2635                // compute final size of file, grab compressed data buffer and return
2636                *pLen_out += 57; MZ_FREE( pComp ); return out_buf.m_pBuf;
2637        }
2638        void *tdefl_write_image_to_png_file_in_memory( const void *pImage, int w, int h, int num_chans, size_t *pLen_out )
2639        {
2640                // Level 6 corresponds to TDEFL_DEFAULT_MAX_PROBES or MZ_DEFAULT_LEVEL (but we can't depend on MZ_DEFAULT_LEVEL being available in case the zlib API's where #defined out)
2641                return tdefl_write_image_to_png_file_in_memory_ex( pImage, w, h, num_chans, pLen_out, 6, MZ_FALSE );
2642        }
2643
2644#ifdef _MSC_VER
2645#pragma warning (pop)
2646#endif
2647
2648
2649#ifdef __cplusplus
2650}
2651#endif
2652
2653void * nv::miniz_decompress( const void *source_buf, size_t source_buf_len, size_t *out_len, bool parse_header )
2654{
2655        NV_PROFILE( "decompress" );
2656        return tinfl_decompress_mem_to_heap( source_buf, source_buf_len, out_len, parse_header ? TINFL_FLAG_PARSE_ZLIB_HEADER : 0 );
2657}
Note: See TracBrowser for help on using the repository browser.