basisu_miniz.h 120 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531
  1. /* miniz.c v1.15 - deflate/inflate, zlib-subset, ZIP reading/writing/appending, PNG writing
  2. Implements RFC 1950: http://www.ietf.org/rfc/rfc1950.txt and RFC 1951: http://www.ietf.org/rfc/rfc1951.txt
  3. Forked from the public domain/unlicense version at: https://code.google.com/archive/p/miniz/
  4. Copyright (C) 2019-2021 Binomial LLC. All Rights Reserved.
  5. Licensed under the Apache License, Version 2.0 (the "License");
  6. you may not use this file except in compliance with the License.
  7. You may obtain a copy of the License at
  8. http://www.apache.org/licenses/LICENSE-2.0
  9. Unless required by applicable law or agreed to in writing, software
  10. distributed under the License is distributed on an "AS IS" BASIS,
  11. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. See the License for the specific language governing permissions and
  13. limitations under the License.
  14. */
  15. #ifndef MINIZ_HEADER_INCLUDED
  16. #define MINIZ_HEADER_INCLUDED
  17. #include <stdlib.h>
  18. // Defines to completely disable specific portions of miniz.c:
  19. // If all macros here are defined the only functionality remaining will be CRC-32, adler-32, tinfl, and tdefl.
  20. // Define MINIZ_NO_STDIO to disable all usage and any functions which rely on stdio for file I/O.
  21. //#define MINIZ_NO_STDIO
  22. // If MINIZ_NO_TIME is specified then the ZIP archive functions will not be able to get the current time, or
  23. // get/set file times, and the C run-time funcs that get/set times won't be called.
  24. // The current downside is the times written to your archives will be from 1979.
  25. //#define MINIZ_NO_TIME
  26. // Define MINIZ_NO_ARCHIVE_APIS to disable all ZIP archive API's.
  27. //#define MINIZ_NO_ARCHIVE_APIS
  28. // Define MINIZ_NO_ARCHIVE_APIS to disable all writing related ZIP archive API's.
  29. //#define MINIZ_NO_ARCHIVE_WRITING_APIS
  30. // Define MINIZ_NO_ZLIB_APIS to remove all ZLIB-style compression/decompression API's.
  31. //#define MINIZ_NO_ZLIB_APIS
  32. // Define MINIZ_NO_ZLIB_COMPATIBLE_NAME to disable zlib names, to prevent conflicts against stock zlib.
  33. //#define MINIZ_NO_ZLIB_COMPATIBLE_NAMES
  34. // Define MINIZ_NO_MALLOC to disable all calls to malloc, free, and realloc.
  35. // Note if MINIZ_NO_MALLOC is defined then the user must always provide custom user alloc/free/realloc
  36. // callbacks to the zlib and archive API's, and a few stand-alone helper API's which don't provide custom user
  37. // functions (such as tdefl_compress_mem_to_heap() and tinfl_decompress_mem_to_heap()) won't work.
  38. //#define MINIZ_NO_MALLOC
  39. #if defined(__TINYC__) && (defined(__linux) || defined(__linux__))
  40. // TODO: Work around "error: include file 'sys\utime.h' when compiling with tcc on Linux
  41. #define MINIZ_NO_TIME
  42. #endif
  43. #if !defined(MINIZ_NO_TIME) && !defined(MINIZ_NO_ARCHIVE_APIS)
  44. #include <time.h>
  45. #endif
  46. #if defined(_M_IX86) || defined(_M_X64) || defined(__i386__) || defined(__i386) || defined(__i486__) || defined(__i486) || defined(i386) || defined(__ia64__) || defined(__x86_64__)
  47. // MINIZ_X86_OR_X64_CPU is only used to help set the below macros.
  48. #define MINIZ_X86_OR_X64_CPU 1
  49. #endif
  50. #if (__BYTE_ORDER__==__ORDER_LITTLE_ENDIAN__) || MINIZ_X86_OR_X64_CPU
  51. // Set MINIZ_LITTLE_ENDIAN to 1 if the processor is little endian.
  52. #define MINIZ_LITTLE_ENDIAN 1
  53. #endif
  54. #if MINIZ_X86_OR_X64_CPU
  55. // Set MINIZ_USE_UNALIGNED_LOADS_AND_STORES to 1 on CPU's that permit efficient integer loads and stores from unaligned addresses.
  56. #define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 1
  57. #endif
  58. // Using unaligned loads and stores causes errors when using UBSan. Jam it off.
  59. #if defined(__has_feature)
  60. #if __has_feature(undefined_behavior_sanitizer)
  61. #undef MINIZ_USE_UNALIGNED_LOADS_AND_STORES
  62. #define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 0
  63. #endif
  64. #endif
  65. #if defined(_M_X64) || defined(_WIN64) || defined(__MINGW64__) || defined(_LP64) || defined(__LP64__) || defined(__ia64__) || defined(__x86_64__)
  66. // 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).
  67. #define MINIZ_HAS_64BIT_REGISTERS 1
  68. #endif
  69. namespace buminiz {
  70. // ------------------- zlib-style API Definitions.
  71. // 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!
  72. typedef unsigned long mz_ulong;
  73. // 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.
  74. void mz_free(void *p);
  75. #define MZ_ADLER32_INIT (1)
  76. // mz_adler32() returns the initial adler-32 value to use when called with ptr==NULL.
  77. mz_ulong mz_adler32(mz_ulong adler, const unsigned char *ptr, size_t buf_len);
  78. #define MZ_CRC32_INIT (0)
  79. // mz_crc32() returns the initial CRC-32 value to use when called with ptr==NULL.
  80. mz_ulong mz_crc32(mz_ulong crc, const unsigned char *ptr, size_t buf_len);
  81. // Compression strategies.
  82. enum { MZ_DEFAULT_STRATEGY = 0, MZ_FILTERED = 1, MZ_HUFFMAN_ONLY = 2, MZ_RLE = 3, MZ_FIXED = 4 };
  83. // Method
  84. #define MZ_DEFLATED 8
  85. #ifndef MINIZ_NO_ZLIB_APIS
  86. // Heap allocation callbacks.
  87. // Note that mz_alloc_func parameter types purpsosely differ from zlib's: items/size is size_t, not unsigned long.
  88. typedef void *(*mz_alloc_func)(void *opaque, size_t items, size_t size);
  89. typedef void (*mz_free_func)(void *opaque, void *address);
  90. typedef void *(*mz_realloc_func)(void *opaque, void *address, size_t items, size_t size);
  91. #define MZ_VERSION "9.1.15"
  92. #define MZ_VERNUM 0x91F0
  93. #define MZ_VER_MAJOR 9
  94. #define MZ_VER_MINOR 1
  95. #define MZ_VER_REVISION 15
  96. #define MZ_VER_SUBREVISION 0
  97. // 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).
  98. enum { MZ_NO_FLUSH = 0, MZ_PARTIAL_FLUSH = 1, MZ_SYNC_FLUSH = 2, MZ_FULL_FLUSH = 3, MZ_FINISH = 4, MZ_BLOCK = 5 };
  99. // Return status codes. MZ_PARAM_ERROR is non-standard.
  100. 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 };
  101. // 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.
  102. 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 };
  103. // Window bits
  104. #define MZ_DEFAULT_WINDOW_BITS 15
  105. struct mz_internal_state;
  106. // Compression/decompression stream struct.
  107. typedef struct mz_stream_s
  108. {
  109. const unsigned char *next_in; // pointer to next byte to read
  110. unsigned int avail_in; // number of bytes available at next_in
  111. mz_ulong total_in; // total number of bytes consumed so far
  112. unsigned char *next_out; // pointer to next byte to write
  113. unsigned int avail_out; // number of bytes that can be written to next_out
  114. mz_ulong total_out; // total number of bytes produced so far
  115. char *msg; // error msg (unused)
  116. struct mz_internal_state *state; // internal state, allocated by zalloc/zfree
  117. mz_alloc_func zalloc; // optional heap allocation function (defaults to malloc)
  118. mz_free_func zfree; // optional heap free function (defaults to free)
  119. void *opaque; // heap alloc function user pointer
  120. int data_type; // data_type (unused)
  121. mz_ulong adler; // adler32 of the source or uncompressed data
  122. mz_ulong reserved; // not used
  123. } mz_stream;
  124. typedef mz_stream *mz_streamp;
  125. // Returns the version string of miniz.c.
  126. const char *mz_version(void);
  127. // mz_deflateInit() initializes a compressor with default options:
  128. // Parameters:
  129. // pStream must point to an initialized mz_stream struct.
  130. // level must be between [MZ_NO_COMPRESSION, MZ_BEST_COMPRESSION].
  131. // level 1 enables a specially optimized compression function that's been optimized purely for performance, not ratio.
  132. // (This special func. is currently only enabled when MINIZ_USE_UNALIGNED_LOADS_AND_STORES and MINIZ_LITTLE_ENDIAN are defined.)
  133. // Return values:
  134. // MZ_OK on success.
  135. // MZ_STREAM_ERROR if the stream is bogus.
  136. // MZ_PARAM_ERROR if the input parameters are bogus.
  137. // MZ_MEM_ERROR on out of memory.
  138. int mz_deflateInit(mz_streamp pStream, int level);
  139. // mz_deflateInit2() is like mz_deflate(), except with more control:
  140. // Additional parameters:
  141. // method must be MZ_DEFLATED
  142. // 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)
  143. // mem_level must be between [1, 9] (it's checked but ignored by miniz.c)
  144. int mz_deflateInit2(mz_streamp pStream, int level, int method, int window_bits, int mem_level, int strategy);
  145. // Quickly resets a compressor without having to reallocate anything. Same as calling mz_deflateEnd() followed by mz_deflateInit()/mz_deflateInit2().
  146. int mz_deflateReset(mz_streamp pStream);
  147. // mz_deflate() compresses the input to output, consuming as much of the input and producing as much output as possible.
  148. // Parameters:
  149. // 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.
  150. // flush may be MZ_NO_FLUSH, MZ_PARTIAL_FLUSH/MZ_SYNC_FLUSH, MZ_FULL_FLUSH, or MZ_FINISH.
  151. // Return values:
  152. // 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).
  153. // 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.
  154. // MZ_STREAM_ERROR if the stream is bogus.
  155. // MZ_PARAM_ERROR if one of the parameters is invalid.
  156. // 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.)
  157. int mz_deflate(mz_streamp pStream, int flush);
  158. // mz_deflateEnd() deinitializes a compressor:
  159. // Return values:
  160. // MZ_OK on success.
  161. // MZ_STREAM_ERROR if the stream is bogus.
  162. int mz_deflateEnd(mz_streamp pStream);
  163. // 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.
  164. mz_ulong mz_deflateBound(mz_streamp pStream, mz_ulong source_len);
  165. // Single-call compression functions mz_compress() and mz_compress2():
  166. // Returns MZ_OK on success, or one of the error codes from mz_deflate() on failure.
  167. int mz_compress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len);
  168. int mz_compress2(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len, int level);
  169. // mz_compressBound() returns a (very) conservative upper bound on the amount of data that could be generated by calling mz_compress().
  170. mz_ulong mz_compressBound(mz_ulong source_len);
  171. // Initializes a decompressor.
  172. int mz_inflateInit(mz_streamp pStream);
  173. // 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:
  174. // window_bits must be MZ_DEFAULT_WINDOW_BITS (to parse zlib header/footer) or -MZ_DEFAULT_WINDOW_BITS (raw deflate).
  175. int mz_inflateInit2(mz_streamp pStream, int window_bits);
  176. // 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.
  177. // Parameters:
  178. // 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.
  179. // flush may be MZ_NO_FLUSH, MZ_SYNC_FLUSH, or MZ_FINISH.
  180. // 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).
  181. // 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.
  182. // Return values:
  183. // 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.
  184. // 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.
  185. // MZ_STREAM_ERROR if the stream is bogus.
  186. // MZ_DATA_ERROR if the deflate stream is invalid.
  187. // MZ_PARAM_ERROR if one of the parameters is invalid.
  188. // 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
  189. // with more input data, or with more room in the output buffer (except when using single call decompression, described above).
  190. int mz_inflate(mz_streamp pStream, int flush);
  191. int mz_inflate2(mz_streamp pStream, int flush, int adler32_checking);
  192. // Deinitializes a decompressor.
  193. int mz_inflateEnd(mz_streamp pStream);
  194. // Single-call decompression.
  195. // Returns MZ_OK on success, or one of the error codes from mz_inflate() on failure.
  196. int mz_uncompress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len);
  197. // Returns a string description of the specified error code, or NULL if the error code is invalid.
  198. const char *mz_error(int err);
  199. // 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.
  200. // Define MINIZ_NO_ZLIB_COMPATIBLE_NAMES to disable zlib-compatibility if you use zlib in the same project.
  201. #ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES
  202. typedef unsigned char Byte;
  203. typedef unsigned int uInt;
  204. typedef mz_ulong uLong;
  205. typedef Byte Bytef;
  206. typedef uInt uIntf;
  207. typedef char charf;
  208. typedef int intf;
  209. typedef void *voidpf;
  210. typedef uLong uLongf;
  211. typedef void *voidp;
  212. typedef void *const voidpc;
  213. #define Z_NULL 0
  214. #define Z_NO_FLUSH MZ_NO_FLUSH
  215. #define Z_PARTIAL_FLUSH MZ_PARTIAL_FLUSH
  216. #define Z_SYNC_FLUSH MZ_SYNC_FLUSH
  217. #define Z_FULL_FLUSH MZ_FULL_FLUSH
  218. #define Z_FINISH MZ_FINISH
  219. #define Z_BLOCK MZ_BLOCK
  220. #define Z_OK MZ_OK
  221. #define Z_STREAM_END MZ_STREAM_END
  222. #define Z_NEED_DICT MZ_NEED_DICT
  223. #define Z_ERRNO MZ_ERRNO
  224. #define Z_STREAM_ERROR MZ_STREAM_ERROR
  225. #define Z_DATA_ERROR MZ_DATA_ERROR
  226. #define Z_MEM_ERROR MZ_MEM_ERROR
  227. #define Z_BUF_ERROR MZ_BUF_ERROR
  228. #define Z_VERSION_ERROR MZ_VERSION_ERROR
  229. #define Z_PARAM_ERROR MZ_PARAM_ERROR
  230. #define Z_NO_COMPRESSION MZ_NO_COMPRESSION
  231. #define Z_BEST_SPEED MZ_BEST_SPEED
  232. #define Z_BEST_COMPRESSION MZ_BEST_COMPRESSION
  233. #define Z_DEFAULT_COMPRESSION MZ_DEFAULT_COMPRESSION
  234. #define Z_DEFAULT_STRATEGY MZ_DEFAULT_STRATEGY
  235. #define Z_FILTERED MZ_FILTERED
  236. #define Z_HUFFMAN_ONLY MZ_HUFFMAN_ONLY
  237. #define Z_RLE MZ_RLE
  238. #define Z_FIXED MZ_FIXED
  239. #define Z_DEFLATED MZ_DEFLATED
  240. #define Z_DEFAULT_WINDOW_BITS MZ_DEFAULT_WINDOW_BITS
  241. #define alloc_func mz_alloc_func
  242. #define free_func mz_free_func
  243. #define internal_state mz_internal_state
  244. #define z_stream mz_stream
  245. #define deflateInit mz_deflateInit
  246. #define deflateInit2 mz_deflateInit2
  247. #define deflateReset mz_deflateReset
  248. #define deflate mz_deflate
  249. #define deflateEnd mz_deflateEnd
  250. #define deflateBound mz_deflateBound
  251. #define compress mz_compress
  252. #define compress2 mz_compress2
  253. #define compressBound mz_compressBound
  254. #define inflateInit mz_inflateInit
  255. #define inflateInit2 mz_inflateInit2
  256. #define inflate mz_inflate
  257. #define inflateEnd mz_inflateEnd
  258. #define uncompress mz_uncompress
  259. #define crc32 mz_crc32
  260. #define adler32 mz_adler32
  261. #define MAX_WBITS 15
  262. #define MAX_MEM_LEVEL 9
  263. #define zError mz_error
  264. #define ZLIB_VERSION MZ_VERSION
  265. #define ZLIB_VERNUM MZ_VERNUM
  266. #define ZLIB_VER_MAJOR MZ_VER_MAJOR
  267. #define ZLIB_VER_MINOR MZ_VER_MINOR
  268. #define ZLIB_VER_REVISION MZ_VER_REVISION
  269. #define ZLIB_VER_SUBREVISION MZ_VER_SUBREVISION
  270. #define zlibVersion mz_version
  271. #define zlib_version mz_version()
  272. #endif // #ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES
  273. #endif // MINIZ_NO_ZLIB_APIS
  274. // ------------------- Types and macros
  275. typedef unsigned char mz_uint8;
  276. typedef signed short mz_int16;
  277. typedef unsigned short mz_uint16;
  278. typedef unsigned int mz_uint32;
  279. typedef unsigned int mz_uint;
  280. typedef long long mz_int64;
  281. typedef unsigned long long mz_uint64;
  282. typedef int mz_bool;
  283. #define MZ_FALSE (0)
  284. #define MZ_TRUE (1)
  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. // ------------------- Low-level Decompression API Definitions
  292. // Decompression flags used by tinfl_decompress().
  293. // 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.
  294. // 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.
  295. // 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).
  296. // TINFL_FLAG_COMPUTE_ADLER32: Force adler-32 checksum computation of the decompressed bytes.
  297. enum
  298. {
  299. TINFL_FLAG_PARSE_ZLIB_HEADER = 1,
  300. TINFL_FLAG_HAS_MORE_INPUT = 2,
  301. TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF = 4,
  302. TINFL_FLAG_COMPUTE_ADLER32 = 8
  303. };
  304. // High level decompression functions:
  305. // tinfl_decompress_mem_to_heap() decompresses a block in memory to a heap block allocated via malloc().
  306. // On entry:
  307. // pSrc_buf, src_buf_len: Pointer and size of the Deflate or zlib source data to decompress.
  308. // On return:
  309. // Function returns a pointer to the decompressed data, or NULL on failure.
  310. // *pOut_len will be set to the decompressed data's size, which could be larger than src_buf_len on uncompressible data.
  311. // The caller must call mz_free() on the returned block when it's no longer needed.
  312. void *tinfl_decompress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags);
  313. // tinfl_decompress_mem_to_mem() decompresses a block in memory to another block in memory.
  314. // Returns TINFL_DECOMPRESS_MEM_TO_MEM_FAILED on failure, or the number of bytes written on success.
  315. #define TINFL_DECOMPRESS_MEM_TO_MEM_FAILED ((size_t)(-1))
  316. 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);
  317. // 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.
  318. // Returns 1 on success or 0 on failure.
  319. typedef int (*tinfl_put_buf_func_ptr)(const void* pBuf, int len, void *pUser);
  320. 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);
  321. struct tinfl_decompressor_tag; typedef struct tinfl_decompressor_tag tinfl_decompressor;
  322. // Max size of LZ dictionary.
  323. #define TINFL_LZ_DICT_SIZE 32768
  324. // Return status.
  325. typedef enum
  326. {
  327. TINFL_STATUS_BAD_PARAM = -3,
  328. TINFL_STATUS_ADLER32_MISMATCH = -2,
  329. TINFL_STATUS_FAILED = -1,
  330. TINFL_STATUS_DONE = 0,
  331. TINFL_STATUS_NEEDS_MORE_INPUT = 1,
  332. TINFL_STATUS_HAS_MORE_OUTPUT = 2
  333. } tinfl_status;
  334. // Initializes the decompressor to its initial state.
  335. #define tinfl_init(r) do { (r)->m_state = 0; } MZ_MACRO_END
  336. #define tinfl_get_adler32(r) (r)->m_check_adler32
  337. // 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.
  338. // 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.
  339. 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);
  340. // Internal/private bits follow.
  341. enum
  342. {
  343. TINFL_MAX_HUFF_TABLES = 3, TINFL_MAX_HUFF_SYMBOLS_0 = 288, TINFL_MAX_HUFF_SYMBOLS_1 = 32, TINFL_MAX_HUFF_SYMBOLS_2 = 19,
  344. TINFL_FAST_LOOKUP_BITS = 10, TINFL_FAST_LOOKUP_SIZE = 1 << TINFL_FAST_LOOKUP_BITS
  345. };
  346. typedef struct
  347. {
  348. mz_uint8 m_code_size[TINFL_MAX_HUFF_SYMBOLS_0];
  349. mz_int16 m_look_up[TINFL_FAST_LOOKUP_SIZE], m_tree[TINFL_MAX_HUFF_SYMBOLS_0 * 2];
  350. } tinfl_huff_table;
  351. #if MINIZ_HAS_64BIT_REGISTERS
  352. #define TINFL_USE_64BIT_BITBUF 1
  353. #endif
  354. #if TINFL_USE_64BIT_BITBUF
  355. typedef mz_uint64 tinfl_bit_buf_t;
  356. #define TINFL_BITBUF_SIZE (64)
  357. #else
  358. typedef mz_uint32 tinfl_bit_buf_t;
  359. #define TINFL_BITBUF_SIZE (32)
  360. #endif
  361. struct tinfl_decompressor_tag
  362. {
  363. 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];
  364. tinfl_bit_buf_t m_bit_buf;
  365. size_t m_dist_from_out_buf_start;
  366. tinfl_huff_table m_tables[TINFL_MAX_HUFF_TABLES];
  367. mz_uint8 m_raw_header[4], m_len_codes[TINFL_MAX_HUFF_SYMBOLS_0 + TINFL_MAX_HUFF_SYMBOLS_1 + 137];
  368. };
  369. // ------------------- Low-level Compression API Definitions
  370. // Set TDEFL_LESS_MEMORY to 1 to use less memory (compression will be slightly slower, and raw/dynamic blocks will be output more frequently).
  371. #define TDEFL_LESS_MEMORY 0
  372. // tdefl_init() compression flags logically OR'd together (low 12 bits contain the max. number of probes per dictionary search):
  373. // 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).
  374. enum
  375. {
  376. TDEFL_HUFFMAN_ONLY = 0, TDEFL_DEFAULT_MAX_PROBES = 128, TDEFL_MAX_PROBES_MASK = 0xFFF
  377. };
  378. // 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.
  379. // TDEFL_COMPUTE_ADLER32: Always compute the adler-32 of the input data (even when not writing zlib headers).
  380. // TDEFL_GREEDY_PARSING_FLAG: Set to use faster greedy parsing, instead of more efficient lazy parsing.
  381. // 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).
  382. // TDEFL_RLE_MATCHES: Only look for RLE matches (matches with a distance of 1)
  383. // TDEFL_FILTER_MATCHES: Discards matches <= 5 chars if enabled.
  384. // TDEFL_FORCE_ALL_STATIC_BLOCKS: Disable usage of optimized Huffman tables.
  385. // TDEFL_FORCE_ALL_RAW_BLOCKS: Only use raw (uncompressed) deflate blocks.
  386. // The low 12 bits are reserved to control the max # of hash probes per dictionary lookup (see TDEFL_MAX_PROBES_MASK).
  387. enum
  388. {
  389. TDEFL_WRITE_ZLIB_HEADER = 0x01000,
  390. TDEFL_COMPUTE_ADLER32 = 0x02000,
  391. TDEFL_GREEDY_PARSING_FLAG = 0x04000,
  392. TDEFL_NONDETERMINISTIC_PARSING_FLAG = 0x08000,
  393. TDEFL_RLE_MATCHES = 0x10000,
  394. TDEFL_FILTER_MATCHES = 0x20000,
  395. TDEFL_FORCE_ALL_STATIC_BLOCKS = 0x40000,
  396. TDEFL_FORCE_ALL_RAW_BLOCKS = 0x80000
  397. };
  398. // High level compression functions:
  399. // tdefl_compress_mem_to_heap() compresses a block in memory to a heap block allocated via malloc().
  400. // On entry:
  401. // pSrc_buf, src_buf_len: Pointer and size of source block to compress.
  402. // flags: The max match finder probes (default is 128) logically OR'd against the above flags. Higher probes are slower but improve compression.
  403. // On return:
  404. // Function returns a pointer to the compressed data, or NULL on failure.
  405. // *pOut_len will be set to the compressed data's size, which could be larger than src_buf_len on uncompressible data.
  406. // The caller must free() the returned block when it's no longer needed.
  407. void *tdefl_compress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags);
  408. // tdefl_compress_mem_to_mem() compresses a block in memory to another block in memory.
  409. // Returns 0 on failure.
  410. 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);
  411. // Compresses an image to a compressed PNG file in memory.
  412. // On entry:
  413. // pImage, w, h, and num_chans describe the image to compress. num_chans may be 1, 2, 3, or 4.
  414. // The image pitch in bytes per scanline will be w*num_chans. The leftmost pixel on the top scanline is stored first in memory.
  415. // 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
  416. // If flip is true, the image will be flipped on the Y axis (useful for OpenGL apps).
  417. // On return:
  418. // Function returns a pointer to the compressed data, or NULL on failure.
  419. // *pLen_out will be set to the size of the PNG image file.
  420. // The caller must mz_free() the returned heap block (which will typically be larger than *pLen_out) when it's no longer needed.
  421. 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);
  422. void *tdefl_write_image_to_png_file_in_memory(const void *pImage, int w, int h, int num_chans, size_t *pLen_out);
  423. // Output stream interface. The compressor uses this interface to write compressed data. It'll typically be called TDEFL_OUT_BUF_SIZE at a time.
  424. typedef mz_bool (*tdefl_put_buf_func_ptr)(const void* pBuf, int len, void *pUser);
  425. // tdefl_compress_mem_to_output() compresses a block to an output stream. The above helpers use this function internally.
  426. 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);
  427. 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 };
  428. // TDEFL_OUT_BUF_SIZE MUST be large enough to hold a single entire compressed output block (using static/fixed Huffman codes).
  429. #if TDEFL_LESS_MEMORY
  430. 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 };
  431. #else
  432. 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 };
  433. #endif
  434. // 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.
  435. typedef enum
  436. {
  437. TDEFL_STATUS_BAD_PARAM = -2,
  438. TDEFL_STATUS_PUT_BUF_FAILED = -1,
  439. TDEFL_STATUS_OKAY = 0,
  440. TDEFL_STATUS_DONE = 1,
  441. } tdefl_status;
  442. // Must map to MZ_NO_FLUSH, MZ_SYNC_FLUSH, etc. enums
  443. typedef enum
  444. {
  445. TDEFL_NO_FLUSH = 0,
  446. TDEFL_SYNC_FLUSH = 2,
  447. TDEFL_FULL_FLUSH = 3,
  448. TDEFL_FINISH = 4
  449. } tdefl_flush;
  450. // tdefl's compression state structure.
  451. typedef struct
  452. {
  453. tdefl_put_buf_func_ptr m_pPut_buf_func;
  454. void *m_pPut_buf_user;
  455. mz_uint m_flags, m_max_probes[2];
  456. int m_greedy_parsing;
  457. mz_uint m_adler32, m_lookahead_pos, m_lookahead_size, m_dict_size;
  458. mz_uint8 *m_pLZ_code_buf, *m_pLZ_flags, *m_pOutput_buf, *m_pOutput_buf_end;
  459. mz_uint m_num_flags_left, m_total_lz_bytes, m_lz_code_buf_dict_pos, m_bits_in, m_bit_buffer;
  460. 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;
  461. tdefl_status m_prev_return_status;
  462. const void *m_pIn_buf;
  463. void *m_pOut_buf;
  464. size_t *m_pIn_buf_size, *m_pOut_buf_size;
  465. tdefl_flush m_flush;
  466. const mz_uint8 *m_pSrc;
  467. size_t m_src_buf_left, m_out_buf_ofs;
  468. mz_uint8 m_dict[TDEFL_LZ_DICT_SIZE + TDEFL_MAX_MATCH_LEN - 1];
  469. mz_uint16 m_huff_count[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS];
  470. mz_uint16 m_huff_codes[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS];
  471. mz_uint8 m_huff_code_sizes[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS];
  472. mz_uint8 m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE];
  473. mz_uint16 m_next[TDEFL_LZ_DICT_SIZE];
  474. mz_uint16 m_hash[TDEFL_LZ_HASH_SIZE];
  475. mz_uint8 m_output_buf[TDEFL_OUT_BUF_SIZE];
  476. } tdefl_compressor;
  477. // Initializes the compressor.
  478. // There is no corresponding deinit() function because the tdefl API's do not dynamically allocate memory.
  479. // 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.
  480. // If pBut_buf_func is NULL the user should always call the tdefl_compress() API.
  481. // flags: See the above enums (TDEFL_HUFFMAN_ONLY, TDEFL_WRITE_ZLIB_HEADER, etc.)
  482. tdefl_status tdefl_init(tdefl_compressor *d, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags);
  483. // 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.
  484. 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);
  485. // tdefl_compress_buffer() is only usable when the tdefl_init() is called with a non-NULL tdefl_put_buf_func_ptr.
  486. // tdefl_compress_buffer() always consumes the entire input buffer.
  487. tdefl_status tdefl_compress_buffer(tdefl_compressor *d, const void *pIn_buf, size_t in_buf_size, tdefl_flush flush);
  488. tdefl_status tdefl_get_prev_return_status(tdefl_compressor *d);
  489. mz_uint32 tdefl_get_adler32(tdefl_compressor *d);
  490. // 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.
  491. #ifndef MINIZ_NO_ZLIB_APIS
  492. // Create tdefl_compress() flags given zlib-style compression parameters.
  493. // level may range from [0,10] (where 10 is absolute max compression, but may be much slower on some files)
  494. // window_bits may be -15 (raw deflate) or 15 (zlib)
  495. // strategy may be either MZ_DEFAULT_STRATEGY, MZ_FILTERED, MZ_HUFFMAN_ONLY, MZ_RLE, or MZ_FIXED
  496. mz_uint tdefl_create_comp_flags_from_zip_params(int level, int window_bits, int strategy);
  497. #endif // #ifndef MINIZ_NO_ZLIB_APIS
  498. } // namespace buminiz
  499. #endif // MINIZ_HEADER_INCLUDED
  500. // ------------------- End of Header: Implementation follows. (If you only want the header, define MINIZ_HEADER_FILE_ONLY.)
  501. #ifndef MINIZ_HEADER_FILE_ONLY
  502. #include <string.h>
  503. #include <assert.h>
  504. namespace buminiz {
  505. typedef unsigned char mz_validate_uint16[sizeof(mz_uint16)==2 ? 1 : -1];
  506. typedef unsigned char mz_validate_uint32[sizeof(mz_uint32)==4 ? 1 : -1];
  507. typedef unsigned char mz_validate_uint64[sizeof(mz_uint64)==8 ? 1 : -1];
  508. #define MZ_ASSERT(x) assert(x)
  509. #ifdef MINIZ_NO_MALLOC
  510. #define MZ_MALLOC(x) NULL
  511. #define MZ_FREE(x) (void)x, ((void)0)
  512. #define MZ_REALLOC(p, x) NULL
  513. #else
  514. #define MZ_MALLOC(x) malloc(x)
  515. #define MZ_FREE(x) free(x)
  516. #define MZ_REALLOC(p, x) realloc(p, x)
  517. #endif
  518. #define MZ_MAX(a,b) (((a)>(b))?(a):(b))
  519. #define MZ_MIN(a,b) (((a)<(b))?(a):(b))
  520. #define MZ_CLEAR_OBJ(obj) memset(&(obj), 0, sizeof(obj))
  521. #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN
  522. #define MZ_READ_LE16(p) *((const mz_uint16 *)(p))
  523. #define MZ_READ_LE32(p) *((const mz_uint32 *)(p))
  524. #else
  525. #define MZ_READ_LE16(p) ((mz_uint32)(((const mz_uint8 *)(p))[0]) | ((mz_uint32)(((const mz_uint8 *)(p))[1]) << 8U))
  526. #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))
  527. #endif
  528. #ifdef _MSC_VER
  529. #define MZ_FORCEINLINE __forceinline
  530. #elif defined(__GNUC__)
  531. #define MZ_FORCEINLINE inline __attribute__((__always_inline__))
  532. #else
  533. #define MZ_FORCEINLINE inline
  534. #endif
  535. // ------------------- zlib-style API's
  536. mz_ulong mz_adler32(mz_ulong adler, const unsigned char *ptr, size_t buf_len)
  537. {
  538. mz_uint32 i, s1 = (mz_uint32)(adler & 0xffff), s2 = (mz_uint32)(adler >> 16); size_t block_len = buf_len % 5552;
  539. if (!ptr) return MZ_ADLER32_INIT;
  540. while (buf_len) {
  541. for (i = 0; i + 7 < block_len; i += 8, ptr += 8) {
  542. s1 += ptr[0], s2 += s1; s1 += ptr[1], s2 += s1; s1 += ptr[2], s2 += s1; s1 += ptr[3], s2 += s1;
  543. s1 += ptr[4], s2 += s1; s1 += ptr[5], s2 += s1; s1 += ptr[6], s2 += s1; s1 += ptr[7], s2 += s1;
  544. }
  545. for ( ; i < block_len; ++i) s1 += *ptr++, s2 += s1;
  546. s1 %= 65521U, s2 %= 65521U; buf_len -= block_len; block_len = 5552;
  547. }
  548. return (s2 << 16) + s1;
  549. }
  550. // 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/
  551. mz_ulong mz_crc32(mz_ulong crc, const mz_uint8 *ptr, size_t buf_len)
  552. {
  553. static const mz_uint32 s_crc32[16] = { 0, 0x1db71064, 0x3b6e20c8, 0x26d930ac, 0x76dc4190, 0x6b6b51f4, 0x4db26158, 0x5005713c,
  554. 0xedb88320, 0xf00f9344, 0xd6d6a3e8, 0xcb61b38c, 0x9b64c2b0, 0x86d3d2d4, 0xa00ae278, 0xbdbdf21c };
  555. mz_uint32 crcu32 = (mz_uint32)crc;
  556. if (!ptr) return MZ_CRC32_INIT;
  557. 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)]; }
  558. return ~crcu32;
  559. }
  560. void mz_free(void *p)
  561. {
  562. MZ_FREE(p);
  563. }
  564. #ifndef MINIZ_NO_ZLIB_APIS
  565. static void *def_alloc_func(void *opaque, size_t items, size_t size) { (void)opaque, (void)items, (void)size; return MZ_MALLOC(items * size); }
  566. static void def_free_func(void *opaque, void *address) { (void)opaque, (void)address; MZ_FREE(address); }
  567. //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); }
  568. const char *mz_version(void)
  569. {
  570. return MZ_VERSION;
  571. }
  572. int mz_deflateInit(mz_streamp pStream, int level)
  573. {
  574. return mz_deflateInit2(pStream, level, MZ_DEFLATED, MZ_DEFAULT_WINDOW_BITS, 9, MZ_DEFAULT_STRATEGY);
  575. }
  576. int mz_deflateInit2(mz_streamp pStream, int level, int method, int window_bits, int mem_level, int strategy)
  577. {
  578. tdefl_compressor *pComp;
  579. mz_uint comp_flags = TDEFL_COMPUTE_ADLER32 | tdefl_create_comp_flags_from_zip_params(level, window_bits, strategy);
  580. if (!pStream) return MZ_STREAM_ERROR;
  581. 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;
  582. pStream->data_type = 0;
  583. pStream->adler = MZ_ADLER32_INIT;
  584. pStream->msg = NULL;
  585. pStream->reserved = 0;
  586. pStream->total_in = 0;
  587. pStream->total_out = 0;
  588. if (!pStream->zalloc) pStream->zalloc = def_alloc_func;
  589. if (!pStream->zfree) pStream->zfree = def_free_func;
  590. pComp = (tdefl_compressor *)pStream->zalloc(pStream->opaque, 1, sizeof(tdefl_compressor));
  591. if (!pComp)
  592. return MZ_MEM_ERROR;
  593. pStream->state = (struct mz_internal_state *)pComp;
  594. if (tdefl_init(pComp, NULL, NULL, comp_flags) != TDEFL_STATUS_OKAY)
  595. {
  596. mz_deflateEnd(pStream);
  597. return MZ_PARAM_ERROR;
  598. }
  599. return MZ_OK;
  600. }
  601. int mz_deflateReset(mz_streamp pStream)
  602. {
  603. if ((!pStream) || (!pStream->state) || (!pStream->zalloc) || (!pStream->zfree)) return MZ_STREAM_ERROR;
  604. pStream->total_in = pStream->total_out = 0;
  605. tdefl_init((tdefl_compressor*)pStream->state, NULL, NULL, ((tdefl_compressor*)pStream->state)->m_flags);
  606. return MZ_OK;
  607. }
  608. int mz_deflate(mz_streamp pStream, int flush)
  609. {
  610. size_t in_bytes, out_bytes;
  611. mz_ulong orig_total_in, orig_total_out;
  612. int mz_status = MZ_OK;
  613. if ((!pStream) || (!pStream->state) || (flush < 0) || (flush > MZ_FINISH) || (!pStream->next_out)) return MZ_STREAM_ERROR;
  614. if (!pStream->avail_out) return MZ_BUF_ERROR;
  615. if (flush == MZ_PARTIAL_FLUSH) flush = MZ_SYNC_FLUSH;
  616. if (((tdefl_compressor*)pStream->state)->m_prev_return_status == TDEFL_STATUS_DONE)
  617. return (flush == MZ_FINISH) ? MZ_STREAM_END : MZ_BUF_ERROR;
  618. orig_total_in = pStream->total_in; orig_total_out = pStream->total_out;
  619. for ( ; ; )
  620. {
  621. tdefl_status defl_status;
  622. in_bytes = pStream->avail_in; out_bytes = pStream->avail_out;
  623. defl_status = tdefl_compress((tdefl_compressor*)pStream->state, pStream->next_in, &in_bytes, pStream->next_out, &out_bytes, (tdefl_flush)flush);
  624. pStream->next_in += (mz_uint)in_bytes; pStream->avail_in -= (mz_uint)in_bytes;
  625. pStream->total_in += (mz_uint)in_bytes; pStream->adler = tdefl_get_adler32((tdefl_compressor*)pStream->state);
  626. pStream->next_out += (mz_uint)out_bytes; pStream->avail_out -= (mz_uint)out_bytes;
  627. pStream->total_out += (mz_uint)out_bytes;
  628. if (defl_status < 0)
  629. {
  630. mz_status = MZ_STREAM_ERROR;
  631. break;
  632. }
  633. else if (defl_status == TDEFL_STATUS_DONE)
  634. {
  635. mz_status = MZ_STREAM_END;
  636. break;
  637. }
  638. else if (!pStream->avail_out)
  639. break;
  640. else if ((!pStream->avail_in) && (flush != MZ_FINISH))
  641. {
  642. if ((flush) || (pStream->total_in != orig_total_in) || (pStream->total_out != orig_total_out))
  643. break;
  644. return MZ_BUF_ERROR; // Can't make forward progress without some input.
  645. }
  646. }
  647. return mz_status;
  648. }
  649. int mz_deflateEnd(mz_streamp pStream)
  650. {
  651. if (!pStream) return MZ_STREAM_ERROR;
  652. if (pStream->state)
  653. {
  654. pStream->zfree(pStream->opaque, pStream->state);
  655. pStream->state = NULL;
  656. }
  657. return MZ_OK;
  658. }
  659. mz_ulong mz_deflateBound(mz_streamp pStream, mz_ulong source_len)
  660. {
  661. (void)pStream;
  662. // 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.)
  663. mz_uint64 a = 128ULL + (source_len * 110ULL) / 100ULL;
  664. mz_uint64 b = 128ULL + (mz_uint64)source_len + ((source_len / (31 * 1024)) + 1ULL) * 5ULL;
  665. mz_uint64 t = MZ_MAX(a, b);
  666. if (((mz_ulong)t) != t)
  667. t = (mz_ulong)(-1);
  668. return (mz_ulong)t;
  669. }
  670. int mz_compress2(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len, int level)
  671. {
  672. int status;
  673. mz_stream stream;
  674. memset(&stream, 0, sizeof(stream));
  675. // In case mz_ulong is 64-bits (argh I hate longs).
  676. if ((source_len | *pDest_len) > 0xFFFFFFFFU) return MZ_PARAM_ERROR;
  677. stream.next_in = pSource;
  678. stream.avail_in = (mz_uint32)source_len;
  679. stream.next_out = pDest;
  680. stream.avail_out = (mz_uint32)*pDest_len;
  681. status = mz_deflateInit(&stream, level);
  682. if (status != MZ_OK) return status;
  683. status = mz_deflate(&stream, MZ_FINISH);
  684. if (status != MZ_STREAM_END)
  685. {
  686. mz_deflateEnd(&stream);
  687. return (status == MZ_OK) ? MZ_BUF_ERROR : status;
  688. }
  689. *pDest_len = stream.total_out;
  690. return mz_deflateEnd(&stream);
  691. }
  692. int mz_compress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len)
  693. {
  694. return mz_compress2(pDest, pDest_len, pSource, source_len, MZ_DEFAULT_COMPRESSION);
  695. }
  696. mz_ulong mz_compressBound(mz_ulong source_len)
  697. {
  698. return mz_deflateBound(NULL, source_len);
  699. }
  700. typedef struct
  701. {
  702. tinfl_decompressor m_decomp;
  703. mz_uint m_dict_ofs, m_dict_avail, m_first_call, m_has_flushed; int m_window_bits;
  704. mz_uint8 m_dict[TINFL_LZ_DICT_SIZE];
  705. tinfl_status m_last_status;
  706. } inflate_state;
  707. int mz_inflateInit2(mz_streamp pStream, int window_bits)
  708. {
  709. inflate_state *pDecomp;
  710. if (!pStream) return MZ_STREAM_ERROR;
  711. if ((window_bits != MZ_DEFAULT_WINDOW_BITS) && (-window_bits != MZ_DEFAULT_WINDOW_BITS)) return MZ_PARAM_ERROR;
  712. pStream->data_type = 0;
  713. pStream->adler = 0;
  714. pStream->msg = NULL;
  715. pStream->total_in = 0;
  716. pStream->total_out = 0;
  717. pStream->reserved = 0;
  718. if (!pStream->zalloc) pStream->zalloc = def_alloc_func;
  719. if (!pStream->zfree) pStream->zfree = def_free_func;
  720. pDecomp = (inflate_state*)pStream->zalloc(pStream->opaque, 1, sizeof(inflate_state));
  721. if (!pDecomp) return MZ_MEM_ERROR;
  722. pStream->state = (struct mz_internal_state *)pDecomp;
  723. tinfl_init(&pDecomp->m_decomp);
  724. pDecomp->m_dict_ofs = 0;
  725. pDecomp->m_dict_avail = 0;
  726. pDecomp->m_last_status = TINFL_STATUS_NEEDS_MORE_INPUT;
  727. pDecomp->m_first_call = 1;
  728. pDecomp->m_has_flushed = 0;
  729. pDecomp->m_window_bits = window_bits;
  730. return MZ_OK;
  731. }
  732. int mz_inflateInit(mz_streamp pStream)
  733. {
  734. return mz_inflateInit2(pStream, MZ_DEFAULT_WINDOW_BITS);
  735. }
  736. int mz_inflate2(mz_streamp pStream, int flush, int adler32_checking)
  737. {
  738. inflate_state* pState;
  739. mz_uint n, first_call, decomp_flags = adler32_checking ? TINFL_FLAG_COMPUTE_ADLER32 : 0;
  740. size_t in_bytes, out_bytes, orig_avail_in;
  741. tinfl_status status;
  742. if ((!pStream) || (!pStream->state)) return MZ_STREAM_ERROR;
  743. if (flush == MZ_PARTIAL_FLUSH) flush = MZ_SYNC_FLUSH;
  744. if ((flush) && (flush != MZ_SYNC_FLUSH) && (flush != MZ_FINISH)) return MZ_STREAM_ERROR;
  745. pState = (inflate_state*)pStream->state;
  746. if (pState->m_window_bits > 0) decomp_flags |= TINFL_FLAG_PARSE_ZLIB_HEADER;
  747. orig_avail_in = pStream->avail_in;
  748. first_call = pState->m_first_call; pState->m_first_call = 0;
  749. if (pState->m_last_status < 0) return MZ_DATA_ERROR;
  750. if (pState->m_has_flushed && (flush != MZ_FINISH)) return MZ_STREAM_ERROR;
  751. pState->m_has_flushed |= (flush == MZ_FINISH);
  752. if ((flush == MZ_FINISH) && (first_call))
  753. {
  754. // MZ_FINISH on the first call implies that the input and output buffers are large enough to hold the entire compressed/decompressed file.
  755. decomp_flags |= TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF;
  756. in_bytes = pStream->avail_in; out_bytes = pStream->avail_out;
  757. status = tinfl_decompress(&pState->m_decomp, pStream->next_in, &in_bytes, pStream->next_out, pStream->next_out, &out_bytes, decomp_flags);
  758. pState->m_last_status = status;
  759. pStream->next_in += (mz_uint)in_bytes; pStream->avail_in -= (mz_uint)in_bytes; pStream->total_in += (mz_uint)in_bytes;
  760. pStream->adler = tinfl_get_adler32(&pState->m_decomp);
  761. pStream->next_out += (mz_uint)out_bytes; pStream->avail_out -= (mz_uint)out_bytes; pStream->total_out += (mz_uint)out_bytes;
  762. if (status < 0)
  763. return MZ_DATA_ERROR;
  764. else if (status != TINFL_STATUS_DONE)
  765. {
  766. pState->m_last_status = TINFL_STATUS_FAILED;
  767. return MZ_BUF_ERROR;
  768. }
  769. return MZ_STREAM_END;
  770. }
  771. // flush != MZ_FINISH then we must assume there's more input.
  772. if (flush != MZ_FINISH) decomp_flags |= TINFL_FLAG_HAS_MORE_INPUT;
  773. if (pState->m_dict_avail)
  774. {
  775. n = MZ_MIN(pState->m_dict_avail, pStream->avail_out);
  776. memcpy(pStream->next_out, pState->m_dict + pState->m_dict_ofs, n);
  777. pStream->next_out += n; pStream->avail_out -= n; pStream->total_out += n;
  778. pState->m_dict_avail -= n; pState->m_dict_ofs = (pState->m_dict_ofs + n) & (TINFL_LZ_DICT_SIZE - 1);
  779. return ((pState->m_last_status == TINFL_STATUS_DONE) && (!pState->m_dict_avail)) ? MZ_STREAM_END : MZ_OK;
  780. }
  781. for ( ; ; )
  782. {
  783. in_bytes = pStream->avail_in;
  784. out_bytes = TINFL_LZ_DICT_SIZE - pState->m_dict_ofs;
  785. 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);
  786. pState->m_last_status = status;
  787. pStream->next_in += (mz_uint)in_bytes; pStream->avail_in -= (mz_uint)in_bytes;
  788. pStream->total_in += (mz_uint)in_bytes; pStream->adler = tinfl_get_adler32(&pState->m_decomp);
  789. pState->m_dict_avail = (mz_uint)out_bytes;
  790. n = MZ_MIN(pState->m_dict_avail, pStream->avail_out);
  791. memcpy(pStream->next_out, pState->m_dict + pState->m_dict_ofs, n);
  792. pStream->next_out += n; pStream->avail_out -= n; pStream->total_out += n;
  793. pState->m_dict_avail -= n; pState->m_dict_ofs = (pState->m_dict_ofs + n) & (TINFL_LZ_DICT_SIZE - 1);
  794. if (status < 0)
  795. return MZ_DATA_ERROR; // Stream is corrupted (there could be some uncompressed data left in the output dictionary - oh well).
  796. else if ((status == TINFL_STATUS_NEEDS_MORE_INPUT) && (!orig_avail_in))
  797. return MZ_BUF_ERROR; // Signal caller that we can't make forward progress without supplying more input or by setting flush to MZ_FINISH.
  798. else if (flush == MZ_FINISH)
  799. {
  800. // The output buffer MUST be large to hold the remaining uncompressed data when flush==MZ_FINISH.
  801. if (status == TINFL_STATUS_DONE)
  802. return pState->m_dict_avail ? MZ_BUF_ERROR : MZ_STREAM_END;
  803. // 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.
  804. else if (!pStream->avail_out)
  805. return MZ_BUF_ERROR;
  806. }
  807. else if ((status == TINFL_STATUS_DONE) || (!pStream->avail_in) || (!pStream->avail_out) || (pState->m_dict_avail))
  808. break;
  809. }
  810. return ((status == TINFL_STATUS_DONE) && (!pState->m_dict_avail)) ? MZ_STREAM_END : MZ_OK;
  811. }
  812. int mz_inflate(mz_streamp pStream, int flush)
  813. {
  814. return mz_inflate2(pStream, flush, MZ_TRUE);
  815. }
  816. int mz_inflateEnd(mz_streamp pStream)
  817. {
  818. if (!pStream)
  819. return MZ_STREAM_ERROR;
  820. if (pStream->state)
  821. {
  822. pStream->zfree(pStream->opaque, pStream->state);
  823. pStream->state = NULL;
  824. }
  825. return MZ_OK;
  826. }
  827. int mz_uncompress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len)
  828. {
  829. mz_stream stream;
  830. int status;
  831. memset(&stream, 0, sizeof(stream));
  832. // In case mz_ulong is 64-bits (argh I hate longs).
  833. if ((source_len | *pDest_len) > 0xFFFFFFFFU) return MZ_PARAM_ERROR;
  834. stream.next_in = pSource;
  835. stream.avail_in = (mz_uint32)source_len;
  836. stream.next_out = pDest;
  837. stream.avail_out = (mz_uint32)*pDest_len;
  838. status = mz_inflateInit(&stream);
  839. if (status != MZ_OK)
  840. return status;
  841. status = mz_inflate(&stream, MZ_FINISH);
  842. if (status != MZ_STREAM_END)
  843. {
  844. mz_inflateEnd(&stream);
  845. return ((status == MZ_BUF_ERROR) && (!stream.avail_in)) ? MZ_DATA_ERROR : status;
  846. }
  847. *pDest_len = stream.total_out;
  848. return mz_inflateEnd(&stream);
  849. }
  850. const char *mz_error(int err)
  851. {
  852. static struct { int m_err; const char *m_pDesc; } s_error_descs[] =
  853. {
  854. { MZ_OK, "" }, { MZ_STREAM_END, "stream end" }, { MZ_NEED_DICT, "need dictionary" }, { MZ_ERRNO, "file error" }, { MZ_STREAM_ERROR, "stream error" },
  855. { 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" }
  856. };
  857. 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;
  858. return NULL;
  859. }
  860. #endif //MINIZ_NO_ZLIB_APIS
  861. // ------------------- Low-level Decompression (completely independent from all compression API's)
  862. #define TINFL_MEMCPY(d, s, l) memcpy(d, s, l)
  863. #define TINFL_MEMSET(p, c, l) memset(p, c, l)
  864. #define TINFL_CR_BEGIN switch(r->m_state) { case 0:
  865. #define TINFL_CR_RETURN(state_index, result) do { status = result; r->m_state = state_index; goto common_exit; case state_index:; } MZ_MACRO_END
  866. #define TINFL_CR_RETURN_FOREVER(state_index, result) do { for ( ; ; ) { TINFL_CR_RETURN(state_index, result); } } MZ_MACRO_END
  867. #define TINFL_CR_FINISH }
  868. // 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
  869. // reads ahead more than it needs to. Currently TINFL_GET_BYTE() pads the end of the stream with 0's in this scenario.
  870. #define TINFL_GET_BYTE(state_index, c) do { \
  871. if (pIn_buf_cur >= pIn_buf_end) { \
  872. for ( ; ; ) { \
  873. if (decomp_flags & TINFL_FLAG_HAS_MORE_INPUT) { \
  874. TINFL_CR_RETURN(state_index, TINFL_STATUS_NEEDS_MORE_INPUT); \
  875. if (pIn_buf_cur < pIn_buf_end) { \
  876. c = *pIn_buf_cur++; \
  877. break; \
  878. } \
  879. } else { \
  880. c = 0; \
  881. break; \
  882. } \
  883. } \
  884. } else c = *pIn_buf_cur++; } MZ_MACRO_END
  885. #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))
  886. #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
  887. #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
  888. // TINFL_HUFF_BITBUF_FILL() is only used rarely, when the number of bytes remaining in the input buffer falls below 2.
  889. // 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
  890. // 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
  891. // bit buffer contains >=15 bits (deflate's max. Huffman code size).
  892. #define TINFL_HUFF_BITBUF_FILL(state_index, pHuff) \
  893. do { \
  894. temp = (pHuff)->m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]; \
  895. if (temp >= 0) { \
  896. code_len = temp >> 9; \
  897. if ((code_len) && (num_bits >= code_len)) \
  898. break; \
  899. } else if (num_bits > TINFL_FAST_LOOKUP_BITS) { \
  900. code_len = TINFL_FAST_LOOKUP_BITS; \
  901. do { \
  902. temp = (pHuff)->m_tree[~temp + ((bit_buf >> code_len++) & 1)]; \
  903. } while ((temp < 0) && (num_bits >= (code_len + 1))); if (temp >= 0) break; \
  904. } TINFL_GET_BYTE(state_index, c); bit_buf |= (((tinfl_bit_buf_t)c) << num_bits); num_bits += 8; \
  905. } while (num_bits < 15);
  906. // 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
  907. // 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
  908. // 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.
  909. // The slow path is only executed at the very end of the input buffer.
  910. #define TINFL_HUFF_DECODE(state_index, sym, pHuff) do { \
  911. int temp; mz_uint code_len, c; \
  912. if (num_bits < 15) { \
  913. if ((pIn_buf_end - pIn_buf_cur) < 2) { \
  914. TINFL_HUFF_BITBUF_FILL(state_index, pHuff); \
  915. } else { \
  916. 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; \
  917. } \
  918. } \
  919. if ((temp = (pHuff)->m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0) \
  920. code_len = temp >> 9, temp &= 511; \
  921. else { \
  922. code_len = TINFL_FAST_LOOKUP_BITS; do { temp = (pHuff)->m_tree[~temp + ((bit_buf >> code_len++) & 1)]; } while (temp < 0); \
  923. } sym = temp; bit_buf >>= code_len; num_bits -= code_len; } MZ_MACRO_END
  924. 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)
  925. {
  926. 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 };
  927. 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 };
  928. 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};
  929. 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};
  930. 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 };
  931. static const int s_min_table_sizes[3] = { 257, 1, 4 };
  932. tinfl_status status = TINFL_STATUS_FAILED; mz_uint32 num_bits, dist, counter, num_extra; tinfl_bit_buf_t bit_buf;
  933. const mz_uint8 *pIn_buf_cur = pIn_buf_next, *const pIn_buf_end = pIn_buf_next + *pIn_buf_size;
  934. mz_uint8 *pOut_buf_cur = pOut_buf_next, *const pOut_buf_end = pOut_buf_next + *pOut_buf_size;
  935. 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;
  936. // 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).
  937. 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; }
  938. 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;
  939. TINFL_CR_BEGIN
  940. bit_buf = num_bits = dist = counter = num_extra = r->m_zhdr0 = r->m_zhdr1 = 0; r->m_z_adler32 = r->m_check_adler32 = 1;
  941. if (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER)
  942. {
  943. TINFL_GET_BYTE(1, r->m_zhdr0); TINFL_GET_BYTE(2, r->m_zhdr1);
  944. counter = (((r->m_zhdr0 * 256 + r->m_zhdr1) % 31 != 0) || (r->m_zhdr1 & 32) || ((r->m_zhdr0 & 15) != 8));
  945. 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)(1ULL << (8U + (r->m_zhdr0 >> 4)))));
  946. if (counter) { TINFL_CR_RETURN_FOREVER(36, TINFL_STATUS_FAILED); }
  947. }
  948. do
  949. {
  950. TINFL_GET_BITS(3, r->m_final, 3); r->m_type = r->m_final >> 1;
  951. if (r->m_type == 0)
  952. {
  953. TINFL_SKIP_BITS(5, num_bits & 7);
  954. 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]); }
  955. 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); }
  956. while ((counter) && (num_bits))
  957. {
  958. TINFL_GET_BITS(51, dist, 8);
  959. while (pOut_buf_cur >= pOut_buf_end) { TINFL_CR_RETURN(52, TINFL_STATUS_HAS_MORE_OUTPUT); }
  960. *pOut_buf_cur++ = (mz_uint8)dist;
  961. counter--;
  962. }
  963. while (counter)
  964. {
  965. size_t n; while (pOut_buf_cur >= pOut_buf_end) { TINFL_CR_RETURN(9, TINFL_STATUS_HAS_MORE_OUTPUT); }
  966. while (pIn_buf_cur >= pIn_buf_end)
  967. {
  968. if (decomp_flags & TINFL_FLAG_HAS_MORE_INPUT)
  969. {
  970. TINFL_CR_RETURN(38, TINFL_STATUS_NEEDS_MORE_INPUT);
  971. }
  972. else
  973. {
  974. TINFL_CR_RETURN_FOREVER(40, TINFL_STATUS_FAILED);
  975. }
  976. }
  977. n = MZ_MIN(MZ_MIN((size_t)(pOut_buf_end - pOut_buf_cur), (size_t)(pIn_buf_end - pIn_buf_cur)), counter);
  978. TINFL_MEMCPY(pOut_buf_cur, pIn_buf_cur, n); pIn_buf_cur += n; pOut_buf_cur += n; counter -= (mz_uint)n;
  979. }
  980. }
  981. else if (r->m_type == 3)
  982. {
  983. TINFL_CR_RETURN_FOREVER(10, TINFL_STATUS_FAILED);
  984. }
  985. else
  986. {
  987. if (r->m_type == 1)
  988. {
  989. mz_uint8 *p = r->m_tables[0].m_code_size; mz_uint i;
  990. r->m_table_sizes[0] = 288; r->m_table_sizes[1] = 32; TINFL_MEMSET(r->m_tables[1].m_code_size, 5, 32);
  991. 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;
  992. }
  993. else
  994. {
  995. 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]; }
  996. 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; }
  997. r->m_table_sizes[2] = 19;
  998. }
  999. for ( ; (int)r->m_type >= 0; r->m_type--)
  1000. {
  1001. int tree_next, tree_cur; tinfl_huff_table *pTable;
  1002. 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);
  1003. for (i = 0; i < r->m_table_sizes[r->m_type]; ++i) total_syms[pTable->m_code_size[i]]++;
  1004. used_syms = 0, total = 0; next_code[0] = next_code[1] = 0;
  1005. for (i = 1; i <= 15; ++i) { used_syms += total_syms[i]; next_code[i + 1] = (total = ((total + total_syms[i]) << 1)); }
  1006. if ((65536 != total) && (used_syms > 1))
  1007. {
  1008. TINFL_CR_RETURN_FOREVER(35, TINFL_STATUS_FAILED);
  1009. }
  1010. for (tree_next = -1, sym_index = 0; sym_index < r->m_table_sizes[r->m_type]; ++sym_index)
  1011. {
  1012. mz_uint rev_code = 0, l, cur_code, code_size = pTable->m_code_size[sym_index]; if (!code_size) continue;
  1013. cur_code = next_code[code_size]++; for (l = code_size; l > 0; l--, cur_code >>= 1) rev_code = (rev_code << 1) | (cur_code & 1);
  1014. 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; }
  1015. 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; }
  1016. rev_code >>= (TINFL_FAST_LOOKUP_BITS - 1);
  1017. for (j = code_size; j > (TINFL_FAST_LOOKUP_BITS + 1); j--)
  1018. {
  1019. tree_cur -= ((rev_code >>= 1) & 1);
  1020. if (!pTable->m_tree[-tree_cur - 1]) { pTable->m_tree[-tree_cur - 1] = (mz_int16)tree_next; tree_cur = tree_next; tree_next -= 2; } else tree_cur = pTable->m_tree[-tree_cur - 1];
  1021. }
  1022. tree_cur -= ((rev_code >>= 1) & 1); pTable->m_tree[-tree_cur - 1] = (mz_int16)sym_index;
  1023. }
  1024. if (r->m_type == 2)
  1025. {
  1026. for (counter = 0; counter < (r->m_table_sizes[0] + r->m_table_sizes[1]); )
  1027. {
  1028. mz_uint s; TINFL_HUFF_DECODE(16, dist, &r->m_tables[2]); if (dist < 16) { r->m_len_codes[counter++] = (mz_uint8)dist; continue; }
  1029. if ((dist == 16) && (!counter))
  1030. {
  1031. TINFL_CR_RETURN_FOREVER(17, TINFL_STATUS_FAILED);
  1032. }
  1033. num_extra = "\02\03\07"[dist - 16]; TINFL_GET_BITS(18, s, num_extra); s += "\03\03\013"[dist - 16];
  1034. TINFL_MEMSET(r->m_len_codes + counter, (dist == 16) ? r->m_len_codes[counter - 1] : 0, s); counter += s;
  1035. }
  1036. if ((r->m_table_sizes[0] + r->m_table_sizes[1]) != counter)
  1037. {
  1038. TINFL_CR_RETURN_FOREVER(21, TINFL_STATUS_FAILED);
  1039. }
  1040. 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]);
  1041. }
  1042. }
  1043. for ( ; ; )
  1044. {
  1045. mz_uint8 *pSrc;
  1046. for ( ; ; )
  1047. {
  1048. if (((pIn_buf_end - pIn_buf_cur) < 4) || ((pOut_buf_end - pOut_buf_cur) < 2))
  1049. {
  1050. TINFL_HUFF_DECODE(23, counter, &r->m_tables[0]);
  1051. if (counter >= 256)
  1052. break;
  1053. while (pOut_buf_cur >= pOut_buf_end) { TINFL_CR_RETURN(24, TINFL_STATUS_HAS_MORE_OUTPUT); }
  1054. *pOut_buf_cur++ = (mz_uint8)counter;
  1055. }
  1056. else
  1057. {
  1058. int sym2; mz_uint code_len;
  1059. #if TINFL_USE_64BIT_BITBUF
  1060. 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; }
  1061. #else
  1062. 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; }
  1063. #endif
  1064. if ((sym2 = r->m_tables[0].m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0)
  1065. code_len = sym2 >> 9;
  1066. else
  1067. {
  1068. code_len = TINFL_FAST_LOOKUP_BITS; do { sym2 = r->m_tables[0].m_tree[~sym2 + ((bit_buf >> code_len++) & 1)]; } while (sym2 < 0);
  1069. }
  1070. counter = sym2; bit_buf >>= code_len; num_bits -= code_len;
  1071. if (counter & 256)
  1072. break;
  1073. #if !TINFL_USE_64BIT_BITBUF
  1074. 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; }
  1075. #endif
  1076. if ((sym2 = r->m_tables[0].m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0)
  1077. code_len = sym2 >> 9;
  1078. else
  1079. {
  1080. code_len = TINFL_FAST_LOOKUP_BITS; do { sym2 = r->m_tables[0].m_tree[~sym2 + ((bit_buf >> code_len++) & 1)]; } while (sym2 < 0);
  1081. }
  1082. bit_buf >>= code_len; num_bits -= code_len;
  1083. pOut_buf_cur[0] = (mz_uint8)counter;
  1084. if (sym2 & 256)
  1085. {
  1086. pOut_buf_cur++;
  1087. counter = sym2;
  1088. break;
  1089. }
  1090. pOut_buf_cur[1] = (mz_uint8)sym2;
  1091. pOut_buf_cur += 2;
  1092. }
  1093. }
  1094. if ((counter &= 511) == 256) break;
  1095. num_extra = s_length_extra[counter - 257]; counter = s_length_base[counter - 257];
  1096. if (num_extra) { mz_uint extra_bits; TINFL_GET_BITS(25, extra_bits, num_extra); counter += extra_bits; }
  1097. TINFL_HUFF_DECODE(26, dist, &r->m_tables[1]);
  1098. num_extra = s_dist_extra[dist]; dist = s_dist_base[dist];
  1099. if (num_extra) { mz_uint extra_bits; TINFL_GET_BITS(27, extra_bits, num_extra); dist += extra_bits; }
  1100. dist_from_out_buf_start = pOut_buf_cur - pOut_buf_start;
  1101. if ((dist > dist_from_out_buf_start) && (decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF))
  1102. {
  1103. TINFL_CR_RETURN_FOREVER(37, TINFL_STATUS_FAILED);
  1104. }
  1105. pSrc = pOut_buf_start + ((dist_from_out_buf_start - dist) & out_buf_size_mask);
  1106. if ((MZ_MAX(pOut_buf_cur, pSrc) + counter) > pOut_buf_end)
  1107. {
  1108. while (counter--)
  1109. {
  1110. while (pOut_buf_cur >= pOut_buf_end) { TINFL_CR_RETURN(53, TINFL_STATUS_HAS_MORE_OUTPUT); }
  1111. *pOut_buf_cur++ = pOut_buf_start[(dist_from_out_buf_start++ - dist) & out_buf_size_mask];
  1112. }
  1113. continue;
  1114. }
  1115. #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES
  1116. else if ((counter >= 9) && (counter <= dist))
  1117. {
  1118. const mz_uint8 *pSrc_end = pSrc + (counter & ~7);
  1119. do
  1120. {
  1121. ((mz_uint32 *)pOut_buf_cur)[0] = ((const mz_uint32 *)pSrc)[0];
  1122. ((mz_uint32 *)pOut_buf_cur)[1] = ((const mz_uint32 *)pSrc)[1];
  1123. pOut_buf_cur += 8;
  1124. } while ((pSrc += 8) < pSrc_end);
  1125. if ((counter &= 7) < 3)
  1126. {
  1127. if (counter)
  1128. {
  1129. pOut_buf_cur[0] = pSrc[0];
  1130. if (counter > 1)
  1131. pOut_buf_cur[1] = pSrc[1];
  1132. pOut_buf_cur += counter;
  1133. }
  1134. continue;
  1135. }
  1136. }
  1137. #endif
  1138. do
  1139. {
  1140. pOut_buf_cur[0] = pSrc[0];
  1141. pOut_buf_cur[1] = pSrc[1];
  1142. pOut_buf_cur[2] = pSrc[2];
  1143. pOut_buf_cur += 3; pSrc += 3;
  1144. } while ((int)(counter -= 3) > 2);
  1145. if ((int)counter > 0)
  1146. {
  1147. pOut_buf_cur[0] = pSrc[0];
  1148. if ((int)counter > 1)
  1149. pOut_buf_cur[1] = pSrc[1];
  1150. pOut_buf_cur += counter;
  1151. }
  1152. }
  1153. }
  1154. } while (!(r->m_final & 1));
  1155. if (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER)
  1156. {
  1157. 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; }
  1158. }
  1159. TINFL_CR_RETURN_FOREVER(34, TINFL_STATUS_DONE);
  1160. TINFL_CR_FINISH
  1161. common_exit:
  1162. 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;
  1163. *pIn_buf_size = pIn_buf_cur - pIn_buf_next; *pOut_buf_size = pOut_buf_cur - pOut_buf_next;
  1164. //if ((decomp_flags & (TINFL_FLAG_PARSE_ZLIB_HEADER | TINFL_FLAG_COMPUTE_ADLER32)) && (status >= 0))
  1165. if ((decomp_flags & TINFL_FLAG_COMPUTE_ADLER32) && (status >= 0))
  1166. {
  1167. const mz_uint8 *ptr = pOut_buf_next; size_t buf_len = *pOut_buf_size;
  1168. mz_uint32 i, s1 = r->m_check_adler32 & 0xffff, s2 = r->m_check_adler32 >> 16; size_t block_len = buf_len % 5552;
  1169. while (buf_len)
  1170. {
  1171. for (i = 0; i + 7 < block_len; i += 8, ptr += 8)
  1172. {
  1173. s1 += ptr[0], s2 += s1; s1 += ptr[1], s2 += s1; s1 += ptr[2], s2 += s1; s1 += ptr[3], s2 += s1;
  1174. s1 += ptr[4], s2 += s1; s1 += ptr[5], s2 += s1; s1 += ptr[6], s2 += s1; s1 += ptr[7], s2 += s1;
  1175. }
  1176. for ( ; i < block_len; ++i) s1 += *ptr++, s2 += s1;
  1177. s1 %= 65521U, s2 %= 65521U; buf_len -= block_len; block_len = 5552;
  1178. }
  1179. r->m_check_adler32 = (s2 << 16) + s1;
  1180. if ((status == TINFL_STATUS_DONE) && (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) && (r->m_check_adler32 != r->m_z_adler32))
  1181. status = TINFL_STATUS_ADLER32_MISMATCH;
  1182. }
  1183. return status;
  1184. }
  1185. // Higher level helper functions.
  1186. void *tinfl_decompress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags)
  1187. {
  1188. tinfl_decompressor decomp; void *pBuf = NULL, *pNew_buf; size_t src_buf_ofs = 0, out_buf_capacity = 0;
  1189. *pOut_len = 0;
  1190. tinfl_init(&decomp);
  1191. for ( ; ; )
  1192. {
  1193. size_t src_buf_size = src_buf_len - src_buf_ofs, dst_buf_size = out_buf_capacity - *pOut_len, new_out_buf_capacity;
  1194. 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,
  1195. (flags & ~TINFL_FLAG_HAS_MORE_INPUT) | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF);
  1196. if ((status < 0) || (status == TINFL_STATUS_NEEDS_MORE_INPUT))
  1197. {
  1198. MZ_FREE(pBuf); *pOut_len = 0; return NULL;
  1199. }
  1200. src_buf_ofs += src_buf_size;
  1201. *pOut_len += dst_buf_size;
  1202. if (status == TINFL_STATUS_DONE) break;
  1203. new_out_buf_capacity = out_buf_capacity * 2; if (new_out_buf_capacity < 128) new_out_buf_capacity = 128;
  1204. pNew_buf = MZ_REALLOC(pBuf, new_out_buf_capacity);
  1205. if (!pNew_buf)
  1206. {
  1207. MZ_FREE(pBuf); *pOut_len = 0; return NULL;
  1208. }
  1209. pBuf = pNew_buf; out_buf_capacity = new_out_buf_capacity;
  1210. }
  1211. return pBuf;
  1212. }
  1213. 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)
  1214. {
  1215. tinfl_decompressor decomp; tinfl_status status; tinfl_init(&decomp);
  1216. 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);
  1217. return (status != TINFL_STATUS_DONE) ? TINFL_DECOMPRESS_MEM_TO_MEM_FAILED : out_buf_len;
  1218. }
  1219. 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)
  1220. {
  1221. int result = 0;
  1222. tinfl_decompressor decomp;
  1223. mz_uint8 *pDict = (mz_uint8*)MZ_MALLOC(TINFL_LZ_DICT_SIZE); size_t in_buf_ofs = 0, dict_ofs = 0;
  1224. if (!pDict)
  1225. return TINFL_STATUS_FAILED;
  1226. tinfl_init(&decomp);
  1227. for ( ; ; )
  1228. {
  1229. size_t in_buf_size = *pIn_buf_size - in_buf_ofs, dst_buf_size = TINFL_LZ_DICT_SIZE - dict_ofs;
  1230. tinfl_status status = tinfl_decompress(&decomp, (const mz_uint8*)pIn_buf + in_buf_ofs, &in_buf_size, pDict, pDict + dict_ofs, &dst_buf_size,
  1231. (flags & ~(TINFL_FLAG_HAS_MORE_INPUT | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)));
  1232. in_buf_ofs += in_buf_size;
  1233. if ((dst_buf_size) && (!(*pPut_buf_func)(pDict + dict_ofs, (int)dst_buf_size, pPut_buf_user)))
  1234. break;
  1235. if (status != TINFL_STATUS_HAS_MORE_OUTPUT)
  1236. {
  1237. result = (status == TINFL_STATUS_DONE);
  1238. break;
  1239. }
  1240. dict_ofs = (dict_ofs + dst_buf_size) & (TINFL_LZ_DICT_SIZE - 1);
  1241. }
  1242. MZ_FREE(pDict);
  1243. *pIn_buf_size = in_buf_ofs;
  1244. return result;
  1245. }
  1246. // ------------------- Low-level Compression (independent from all decompression API's)
  1247. // Purposely making these tables static for faster init and thread safety.
  1248. static const mz_uint16 s_tdefl_len_sym[256] = {
  1249. 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,
  1250. 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,
  1251. 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,
  1252. 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,
  1253. 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,
  1254. 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,
  1255. 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,
  1256. 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 };
  1257. static const mz_uint8 s_tdefl_len_extra[256] = {
  1258. 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,
  1259. 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,
  1260. 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,
  1261. 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 };
  1262. static const mz_uint8 s_tdefl_small_dist_sym[512] = {
  1263. 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,
  1264. 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,
  1265. 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,
  1266. 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,
  1267. 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,
  1268. 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,
  1269. 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,
  1270. 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,
  1271. 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,
  1272. 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,
  1273. 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,
  1274. 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 };
  1275. static const mz_uint8 s_tdefl_small_dist_extra[512] = {
  1276. 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,
  1277. 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,
  1278. 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,
  1279. 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,
  1280. 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,
  1281. 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,
  1282. 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,
  1283. 7,7,7,7,7,7,7,7 };
  1284. static const mz_uint8 s_tdefl_large_dist_sym[128] = {
  1285. 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,
  1286. 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,
  1287. 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 };
  1288. static const mz_uint8 s_tdefl_large_dist_extra[128] = {
  1289. 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,
  1290. 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,
  1291. 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 };
  1292. // Radix sorts tdefl_sym_freq[] array by 16-bit key m_key. Returns ptr to sorted values.
  1293. typedef struct { mz_uint16 m_key, m_sym_index; } tdefl_sym_freq;
  1294. static tdefl_sym_freq* tdefl_radix_sort_syms(mz_uint num_syms, tdefl_sym_freq* pSyms0, tdefl_sym_freq* pSyms1)
  1295. {
  1296. 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);
  1297. for (i = 0; i < num_syms; i++) { mz_uint freq = pSyms0[i].m_key; hist[freq & 0xFF]++; hist[256 + ((freq >> 8) & 0xFF)]++; }
  1298. while ((total_passes > 1) && (num_syms == hist[(total_passes - 1) * 256])) total_passes--;
  1299. for (pass_shift = 0, pass = 0; pass < total_passes; pass++, pass_shift += 8)
  1300. {
  1301. const mz_uint32* pHist = &hist[pass << 8];
  1302. mz_uint offsets[256], cur_ofs = 0;
  1303. for (i = 0; i < 256; i++) { offsets[i] = cur_ofs; cur_ofs += pHist[i]; }
  1304. for (i = 0; i < num_syms; i++) pNew_syms[offsets[(pCur_syms[i].m_key >> pass_shift) & 0xFF]++] = pCur_syms[i];
  1305. { tdefl_sym_freq* t = pCur_syms; pCur_syms = pNew_syms; pNew_syms = t; }
  1306. }
  1307. return pCur_syms;
  1308. }
  1309. // tdefl_calculate_minimum_redundancy() originally written by: Alistair Moffat, [email protected], Jyrki Katajainen, [email protected], November 1996.
  1310. static void tdefl_calculate_minimum_redundancy(tdefl_sym_freq *A, int n)
  1311. {
  1312. int root, leaf, next, avbl, used, dpth;
  1313. if (n==0) return; else if (n==1) { A[0].m_key = 1; return; }
  1314. A[0].m_key += A[1].m_key; root = 0; leaf = 2;
  1315. for (next=1; next < n-1; next++)
  1316. {
  1317. 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; } else A[next].m_key = A[leaf++].m_key;
  1318. 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; } else A[next].m_key = (mz_uint16)(A[next].m_key + A[leaf++].m_key);
  1319. }
  1320. 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;
  1321. avbl = 1; used = dpth = 0; root = n-2; next = n-1;
  1322. while (avbl>0)
  1323. {
  1324. while (root>=0 && (int)A[root].m_key==dpth) { used++; root--; }
  1325. while (avbl>used) { A[next--].m_key = (mz_uint16)(dpth); avbl--; }
  1326. avbl = 2*used; dpth++; used = 0;
  1327. }
  1328. }
  1329. // Limits canonical Huffman code table's max code size.
  1330. enum { TDEFL_MAX_SUPPORTED_HUFF_CODESIZE = 32 };
  1331. static void tdefl_huffman_enforce_max_code_size(int *pNum_codes, int code_list_len, int max_code_size)
  1332. {
  1333. int i; mz_uint32 total = 0; if (code_list_len <= 1) return;
  1334. for (i = max_code_size + 1; i <= TDEFL_MAX_SUPPORTED_HUFF_CODESIZE; i++) pNum_codes[max_code_size] += pNum_codes[i];
  1335. for (i = max_code_size; i > 0; i--) total += (((mz_uint32)pNum_codes[i]) << (max_code_size - i));
  1336. while (total != (1UL << max_code_size))
  1337. {
  1338. pNum_codes[max_code_size]--;
  1339. for (i = max_code_size - 1; i > 0; i--) if (pNum_codes[i]) { pNum_codes[i]--; pNum_codes[i + 1] += 2; break; }
  1340. total--;
  1341. }
  1342. }
  1343. static void tdefl_optimize_huffman_table(tdefl_compressor *d, int table_num, int table_len, int code_size_limit, int static_table)
  1344. {
  1345. 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);
  1346. if (static_table)
  1347. {
  1348. for (i = 0; i < table_len; i++) num_codes[d->m_huff_code_sizes[table_num][i]]++;
  1349. }
  1350. else
  1351. {
  1352. tdefl_sym_freq syms0[TDEFL_MAX_HUFF_SYMBOLS], syms1[TDEFL_MAX_HUFF_SYMBOLS], *pSyms;
  1353. int num_used_syms = 0;
  1354. const mz_uint16 *pSym_count = &d->m_huff_count[table_num][0];
  1355. 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; }
  1356. pSyms = tdefl_radix_sort_syms(num_used_syms, syms0, syms1); tdefl_calculate_minimum_redundancy(pSyms, num_used_syms);
  1357. for (i = 0; i < num_used_syms; i++) num_codes[pSyms[i].m_key]++;
  1358. tdefl_huffman_enforce_max_code_size(num_codes, num_used_syms, code_size_limit);
  1359. MZ_CLEAR_OBJ(d->m_huff_code_sizes[table_num]); MZ_CLEAR_OBJ(d->m_huff_codes[table_num]);
  1360. for (i = 1, j = num_used_syms; i <= code_size_limit; i++)
  1361. for (l = num_codes[i]; l > 0; l--) d->m_huff_code_sizes[table_num][pSyms[--j].m_sym_index] = (mz_uint8)(i);
  1362. }
  1363. next_code[1] = 0; for (j = 0, i = 2; i <= code_size_limit; i++) next_code[i] = j = ((j + num_codes[i - 1]) << 1);
  1364. for (i = 0; i < table_len; i++)
  1365. {
  1366. mz_uint rev_code = 0, code, code_size; if ((code_size = d->m_huff_code_sizes[table_num][i]) == 0) continue;
  1367. code = next_code[code_size]++; for (l = code_size; l > 0; l--, code >>= 1) rev_code = (rev_code << 1) | (code & 1);
  1368. d->m_huff_codes[table_num][i] = (mz_uint16)rev_code;
  1369. }
  1370. }
  1371. #define TDEFL_PUT_BITS(b, l) do { \
  1372. mz_uint bits = b; mz_uint len = l; MZ_ASSERT(bits <= ((1U << len) - 1U)); \
  1373. d->m_bit_buffer |= (bits << d->m_bits_in); d->m_bits_in += len; \
  1374. while (d->m_bits_in >= 8) { \
  1375. if (d->m_pOutput_buf < d->m_pOutput_buf_end) \
  1376. *d->m_pOutput_buf++ = (mz_uint8)(d->m_bit_buffer); \
  1377. d->m_bit_buffer >>= 8; \
  1378. d->m_bits_in -= 8; \
  1379. } \
  1380. } MZ_MACRO_END
  1381. #define TDEFL_RLE_PREV_CODE_SIZE() { if (rle_repeat_count) { \
  1382. if (rle_repeat_count < 3) { \
  1383. d->m_huff_count[2][prev_code_size] = (mz_uint16)(d->m_huff_count[2][prev_code_size] + rle_repeat_count); \
  1384. while (rle_repeat_count--) packed_code_sizes[num_packed_code_sizes++] = prev_code_size; \
  1385. } else { \
  1386. 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); \
  1387. } rle_repeat_count = 0; } }
  1388. #define TDEFL_RLE_ZERO_CODE_SIZE() { if (rle_z_count) { \
  1389. if (rle_z_count < 3) { \
  1390. 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; \
  1391. } else if (rle_z_count <= 10) { \
  1392. 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); \
  1393. } else { \
  1394. 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); \
  1395. } rle_z_count = 0; } }
  1396. 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 };
  1397. static void tdefl_start_dynamic_block(tdefl_compressor *d)
  1398. {
  1399. 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;
  1400. 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;
  1401. d->m_huff_count[0][256] = 1;
  1402. tdefl_optimize_huffman_table(d, 0, TDEFL_MAX_HUFF_SYMBOLS_0, 15, MZ_FALSE);
  1403. tdefl_optimize_huffman_table(d, 1, TDEFL_MAX_HUFF_SYMBOLS_1, 15, MZ_FALSE);
  1404. for (num_lit_codes = 286; num_lit_codes > 257; num_lit_codes--) if (d->m_huff_code_sizes[0][num_lit_codes - 1]) break;
  1405. for (num_dist_codes = 30; num_dist_codes > 1; num_dist_codes--) if (d->m_huff_code_sizes[1][num_dist_codes - 1]) break;
  1406. memcpy(code_sizes_to_pack, &d->m_huff_code_sizes[0][0], num_lit_codes);
  1407. memcpy(code_sizes_to_pack + num_lit_codes, &d->m_huff_code_sizes[1][0], num_dist_codes);
  1408. total_code_sizes_to_pack = num_lit_codes + num_dist_codes; num_packed_code_sizes = 0; rle_z_count = 0; rle_repeat_count = 0;
  1409. memset(&d->m_huff_count[2][0], 0, sizeof(d->m_huff_count[2][0]) * TDEFL_MAX_HUFF_SYMBOLS_2);
  1410. for (i = 0; i < total_code_sizes_to_pack; i++)
  1411. {
  1412. mz_uint8 code_size = code_sizes_to_pack[i];
  1413. if (!code_size)
  1414. {
  1415. TDEFL_RLE_PREV_CODE_SIZE();
  1416. if (++rle_z_count == 138) { TDEFL_RLE_ZERO_CODE_SIZE(); }
  1417. }
  1418. else
  1419. {
  1420. TDEFL_RLE_ZERO_CODE_SIZE();
  1421. if (code_size != prev_code_size)
  1422. {
  1423. TDEFL_RLE_PREV_CODE_SIZE();
  1424. 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;
  1425. }
  1426. else if (++rle_repeat_count == 6)
  1427. {
  1428. TDEFL_RLE_PREV_CODE_SIZE();
  1429. }
  1430. }
  1431. prev_code_size = code_size;
  1432. }
  1433. if (rle_repeat_count) { TDEFL_RLE_PREV_CODE_SIZE(); } else { TDEFL_RLE_ZERO_CODE_SIZE(); }
  1434. tdefl_optimize_huffman_table(d, 2, TDEFL_MAX_HUFF_SYMBOLS_2, 7, MZ_FALSE);
  1435. TDEFL_PUT_BITS(2, 2);
  1436. TDEFL_PUT_BITS(num_lit_codes - 257, 5);
  1437. TDEFL_PUT_BITS(num_dist_codes - 1, 5);
  1438. 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;
  1439. num_bit_lengths = MZ_MAX(4, (num_bit_lengths + 1)); TDEFL_PUT_BITS(num_bit_lengths - 4, 4);
  1440. 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);
  1441. for (packed_code_sizes_index = 0; packed_code_sizes_index < num_packed_code_sizes; )
  1442. {
  1443. mz_uint code = packed_code_sizes[packed_code_sizes_index++]; MZ_ASSERT(code < TDEFL_MAX_HUFF_SYMBOLS_2);
  1444. TDEFL_PUT_BITS(d->m_huff_codes[2][code], d->m_huff_code_sizes[2][code]);
  1445. if (code >= 16) TDEFL_PUT_BITS(packed_code_sizes[packed_code_sizes_index++], "\02\03\07"[code - 16]);
  1446. }
  1447. }
  1448. static void tdefl_start_static_block(tdefl_compressor *d)
  1449. {
  1450. mz_uint i;
  1451. mz_uint8 *p = &d->m_huff_code_sizes[0][0];
  1452. for (i = 0; i <= 143; ++i) *p++ = 8;
  1453. for ( ; i <= 255; ++i) *p++ = 9;
  1454. for ( ; i <= 279; ++i) *p++ = 7;
  1455. for ( ; i <= 287; ++i) *p++ = 8;
  1456. memset(d->m_huff_code_sizes[1], 5, 32);
  1457. tdefl_optimize_huffman_table(d, 0, 288, 15, MZ_TRUE);
  1458. tdefl_optimize_huffman_table(d, 1, 32, 15, MZ_TRUE);
  1459. TDEFL_PUT_BITS(1, 2);
  1460. }
  1461. static const mz_uint mz_bitmasks[17] = { 0x0000, 0x0001, 0x0003, 0x0007, 0x000F, 0x001F, 0x003F, 0x007F, 0x00FF, 0x01FF, 0x03FF, 0x07FF, 0x0FFF, 0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF };
  1462. #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN && MINIZ_HAS_64BIT_REGISTERS
  1463. static mz_bool tdefl_compress_lz_codes(tdefl_compressor *d)
  1464. {
  1465. mz_uint flags;
  1466. mz_uint8 *pLZ_codes;
  1467. mz_uint8 *pOutput_buf = d->m_pOutput_buf;
  1468. mz_uint8 *pLZ_code_buf_end = d->m_pLZ_code_buf;
  1469. mz_uint64 bit_buffer = d->m_bit_buffer;
  1470. mz_uint bits_in = d->m_bits_in;
  1471. #define TDEFL_PUT_BITS_FAST(b, l) { bit_buffer |= (((mz_uint64)(b)) << bits_in); bits_in += (l); }
  1472. flags = 1;
  1473. for (pLZ_codes = d->m_lz_code_buf; pLZ_codes < pLZ_code_buf_end; flags >>= 1)
  1474. {
  1475. if (flags == 1)
  1476. flags = *pLZ_codes++ | 0x100;
  1477. if (flags & 1)
  1478. {
  1479. mz_uint s0, s1, n0, n1, sym, num_extra_bits;
  1480. mz_uint match_len = pLZ_codes[0], match_dist = *(const mz_uint16 *)(pLZ_codes + 1); pLZ_codes += 3;
  1481. MZ_ASSERT(d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]);
  1482. 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]]);
  1483. TDEFL_PUT_BITS_FAST(match_len & mz_bitmasks[s_tdefl_len_extra[match_len]], s_tdefl_len_extra[match_len]);
  1484. // This sequence coaxes MSVC into using cmov's vs. jmp's.
  1485. s0 = s_tdefl_small_dist_sym[match_dist & 511];
  1486. n0 = s_tdefl_small_dist_extra[match_dist & 511];
  1487. s1 = s_tdefl_large_dist_sym[match_dist >> 8];
  1488. n1 = s_tdefl_large_dist_extra[match_dist >> 8];
  1489. sym = (match_dist < 512) ? s0 : s1;
  1490. num_extra_bits = (match_dist < 512) ? n0 : n1;
  1491. MZ_ASSERT(d->m_huff_code_sizes[1][sym]);
  1492. TDEFL_PUT_BITS_FAST(d->m_huff_codes[1][sym], d->m_huff_code_sizes[1][sym]);
  1493. TDEFL_PUT_BITS_FAST(match_dist & mz_bitmasks[num_extra_bits], num_extra_bits);
  1494. }
  1495. else
  1496. {
  1497. mz_uint lit = *pLZ_codes++;
  1498. MZ_ASSERT(d->m_huff_code_sizes[0][lit]);
  1499. TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]);
  1500. if (((flags & 2) == 0) && (pLZ_codes < pLZ_code_buf_end))
  1501. {
  1502. flags >>= 1;
  1503. lit = *pLZ_codes++;
  1504. MZ_ASSERT(d->m_huff_code_sizes[0][lit]);
  1505. TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]);
  1506. if (((flags & 2) == 0) && (pLZ_codes < pLZ_code_buf_end))
  1507. {
  1508. flags >>= 1;
  1509. lit = *pLZ_codes++;
  1510. MZ_ASSERT(d->m_huff_code_sizes[0][lit]);
  1511. TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]);
  1512. }
  1513. }
  1514. }
  1515. if (pOutput_buf >= d->m_pOutput_buf_end)
  1516. return MZ_FALSE;
  1517. *(mz_uint64*)pOutput_buf = bit_buffer;
  1518. pOutput_buf += (bits_in >> 3);
  1519. bit_buffer >>= (bits_in & ~7);
  1520. bits_in &= 7;
  1521. }
  1522. #undef TDEFL_PUT_BITS_FAST
  1523. d->m_pOutput_buf = pOutput_buf;
  1524. d->m_bits_in = 0;
  1525. d->m_bit_buffer = 0;
  1526. while (bits_in)
  1527. {
  1528. mz_uint32 n = MZ_MIN(bits_in, 16);
  1529. TDEFL_PUT_BITS((mz_uint)bit_buffer & mz_bitmasks[n], n);
  1530. bit_buffer >>= n;
  1531. bits_in -= n;
  1532. }
  1533. TDEFL_PUT_BITS(d->m_huff_codes[0][256], d->m_huff_code_sizes[0][256]);
  1534. return (d->m_pOutput_buf < d->m_pOutput_buf_end);
  1535. }
  1536. #else
  1537. static mz_bool tdefl_compress_lz_codes(tdefl_compressor *d)
  1538. {
  1539. mz_uint flags;
  1540. mz_uint8 *pLZ_codes;
  1541. flags = 1;
  1542. for (pLZ_codes = d->m_lz_code_buf; pLZ_codes < d->m_pLZ_code_buf; flags >>= 1)
  1543. {
  1544. if (flags == 1)
  1545. flags = *pLZ_codes++ | 0x100;
  1546. if (flags & 1)
  1547. {
  1548. mz_uint sym, num_extra_bits;
  1549. mz_uint match_len = pLZ_codes[0], match_dist = (pLZ_codes[1] | (pLZ_codes[2] << 8)); pLZ_codes += 3;
  1550. MZ_ASSERT(d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]);
  1551. 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]]);
  1552. TDEFL_PUT_BITS(match_len & mz_bitmasks[s_tdefl_len_extra[match_len]], s_tdefl_len_extra[match_len]);
  1553. if (match_dist < 512)
  1554. {
  1555. sym = s_tdefl_small_dist_sym[match_dist]; num_extra_bits = s_tdefl_small_dist_extra[match_dist];
  1556. }
  1557. else
  1558. {
  1559. sym = s_tdefl_large_dist_sym[match_dist >> 8]; num_extra_bits = s_tdefl_large_dist_extra[match_dist >> 8];
  1560. }
  1561. MZ_ASSERT(d->m_huff_code_sizes[1][sym]);
  1562. TDEFL_PUT_BITS(d->m_huff_codes[1][sym], d->m_huff_code_sizes[1][sym]);
  1563. TDEFL_PUT_BITS(match_dist & mz_bitmasks[num_extra_bits], num_extra_bits);
  1564. }
  1565. else
  1566. {
  1567. mz_uint lit = *pLZ_codes++;
  1568. MZ_ASSERT(d->m_huff_code_sizes[0][lit]);
  1569. TDEFL_PUT_BITS(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]);
  1570. }
  1571. }
  1572. TDEFL_PUT_BITS(d->m_huff_codes[0][256], d->m_huff_code_sizes[0][256]);
  1573. return (d->m_pOutput_buf < d->m_pOutput_buf_end);
  1574. }
  1575. #endif // MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN && MINIZ_HAS_64BIT_REGISTERS
  1576. static mz_bool tdefl_compress_block(tdefl_compressor *d, mz_bool static_block)
  1577. {
  1578. if (static_block)
  1579. tdefl_start_static_block(d);
  1580. else
  1581. tdefl_start_dynamic_block(d);
  1582. return tdefl_compress_lz_codes(d);
  1583. }
  1584. static int tdefl_flush_block(tdefl_compressor *d, int flush)
  1585. {
  1586. mz_uint saved_bit_buf, saved_bits_in;
  1587. mz_uint8 *pSaved_output_buf;
  1588. mz_bool comp_block_succeeded = MZ_FALSE;
  1589. 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;
  1590. 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;
  1591. d->m_pOutput_buf = pOutput_buf_start;
  1592. d->m_pOutput_buf_end = d->m_pOutput_buf + TDEFL_OUT_BUF_SIZE - 16;
  1593. MZ_ASSERT(!d->m_output_flush_remaining);
  1594. d->m_output_flush_ofs = 0;
  1595. d->m_output_flush_remaining = 0;
  1596. *d->m_pLZ_flags = (mz_uint8)(*d->m_pLZ_flags >> d->m_num_flags_left);
  1597. d->m_pLZ_code_buf -= (d->m_num_flags_left == 8);
  1598. if ((d->m_flags & TDEFL_WRITE_ZLIB_HEADER) && (!d->m_block_index))
  1599. {
  1600. TDEFL_PUT_BITS(0x78, 8); TDEFL_PUT_BITS(0x01, 8);
  1601. }
  1602. TDEFL_PUT_BITS(flush == TDEFL_FINISH, 1);
  1603. pSaved_output_buf = d->m_pOutput_buf; saved_bit_buf = d->m_bit_buffer; saved_bits_in = d->m_bits_in;
  1604. if (!use_raw_block)
  1605. comp_block_succeeded = tdefl_compress_block(d, (d->m_flags & TDEFL_FORCE_ALL_STATIC_BLOCKS) || (d->m_total_lz_bytes < 48));
  1606. // If the block gets expanded, forget the current contents of the output buffer and send a raw block instead.
  1607. if ( ((use_raw_block) || ((d->m_total_lz_bytes) && ((d->m_pOutput_buf - pSaved_output_buf + 1U) >= d->m_total_lz_bytes))) &&
  1608. ((d->m_lookahead_pos - d->m_lz_code_buf_dict_pos) <= d->m_dict_size) )
  1609. {
  1610. mz_uint i; d->m_pOutput_buf = pSaved_output_buf; d->m_bit_buffer = saved_bit_buf, d->m_bits_in = saved_bits_in;
  1611. TDEFL_PUT_BITS(0, 2);
  1612. if (d->m_bits_in) { TDEFL_PUT_BITS(0, 8 - d->m_bits_in); }
  1613. for (i = 2; i; --i, d->m_total_lz_bytes ^= 0xFFFF)
  1614. {
  1615. TDEFL_PUT_BITS(d->m_total_lz_bytes & 0xFFFF, 16);
  1616. }
  1617. for (i = 0; i < d->m_total_lz_bytes; ++i)
  1618. {
  1619. TDEFL_PUT_BITS(d->m_dict[(d->m_lz_code_buf_dict_pos + i) & TDEFL_LZ_DICT_SIZE_MASK], 8);
  1620. }
  1621. }
  1622. // Check for the extremely unlikely (if not impossible) case of the compressed block not fitting into the output buffer when using dynamic codes.
  1623. else if (!comp_block_succeeded)
  1624. {
  1625. d->m_pOutput_buf = pSaved_output_buf; d->m_bit_buffer = saved_bit_buf, d->m_bits_in = saved_bits_in;
  1626. tdefl_compress_block(d, MZ_TRUE);
  1627. }
  1628. if (flush)
  1629. {
  1630. if (flush == TDEFL_FINISH)
  1631. {
  1632. if (d->m_bits_in) { TDEFL_PUT_BITS(0, 8 - d->m_bits_in); }
  1633. 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; } }
  1634. }
  1635. else
  1636. {
  1637. 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); }
  1638. }
  1639. }
  1640. MZ_ASSERT(d->m_pOutput_buf < d->m_pOutput_buf_end);
  1641. memset(&d->m_huff_count[0][0], 0, sizeof(d->m_huff_count[0][0]) * TDEFL_MAX_HUFF_SYMBOLS_0);
  1642. memset(&d->m_huff_count[1][0], 0, sizeof(d->m_huff_count[1][0]) * TDEFL_MAX_HUFF_SYMBOLS_1);
  1643. 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++;
  1644. if ((n = (int)(d->m_pOutput_buf - pOutput_buf_start)) != 0)
  1645. {
  1646. if (d->m_pPut_buf_func)
  1647. {
  1648. *d->m_pIn_buf_size = d->m_pSrc - (const mz_uint8 *)d->m_pIn_buf;
  1649. if (!(*d->m_pPut_buf_func)(d->m_output_buf, n, d->m_pPut_buf_user))
  1650. return (d->m_prev_return_status = TDEFL_STATUS_PUT_BUF_FAILED);
  1651. }
  1652. else if (pOutput_buf_start == d->m_output_buf)
  1653. {
  1654. int bytes_to_copy = (int)MZ_MIN((size_t)n, (size_t)(*d->m_pOut_buf_size - d->m_out_buf_ofs));
  1655. memcpy((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs, d->m_output_buf, bytes_to_copy);
  1656. d->m_out_buf_ofs += bytes_to_copy;
  1657. if ((n -= bytes_to_copy) != 0)
  1658. {
  1659. d->m_output_flush_ofs = bytes_to_copy;
  1660. d->m_output_flush_remaining = n;
  1661. }
  1662. }
  1663. else
  1664. {
  1665. d->m_out_buf_ofs += n;
  1666. }
  1667. }
  1668. return d->m_output_flush_remaining;
  1669. }
  1670. #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES
  1671. #define TDEFL_READ_UNALIGNED_WORD(p) *(const mz_uint16*)(p)
  1672. 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)
  1673. {
  1674. mz_uint dist, pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK, match_len = *pMatch_len, probe_pos = pos, next_probe_pos, probe_len;
  1675. mz_uint num_probes_left = d->m_max_probes[match_len >= 32];
  1676. const mz_uint16 *s = (const mz_uint16*)(d->m_dict + pos), *p, *q;
  1677. mz_uint16 c01 = TDEFL_READ_UNALIGNED_WORD(&d->m_dict[pos + match_len - 1]), s01 = TDEFL_READ_UNALIGNED_WORD(s);
  1678. MZ_ASSERT(max_match_len <= TDEFL_MAX_MATCH_LEN); if (max_match_len <= match_len) return;
  1679. for ( ; ; )
  1680. {
  1681. for ( ; ; )
  1682. {
  1683. if (--num_probes_left == 0) return;
  1684. #define TDEFL_PROBE \
  1685. next_probe_pos = d->m_next[probe_pos]; \
  1686. if ((!next_probe_pos) || ((dist = (mz_uint16)(lookahead_pos - next_probe_pos)) > max_dist)) return; \
  1687. probe_pos = next_probe_pos & TDEFL_LZ_DICT_SIZE_MASK; \
  1688. if (TDEFL_READ_UNALIGNED_WORD(&d->m_dict[probe_pos + match_len - 1]) == c01) break;
  1689. TDEFL_PROBE; TDEFL_PROBE; TDEFL_PROBE;
  1690. }
  1691. 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;
  1692. do { } while ( (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) &&
  1693. (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (--probe_len > 0) );
  1694. if (!probe_len)
  1695. {
  1696. *pMatch_dist = dist; *pMatch_len = MZ_MIN(max_match_len, TDEFL_MAX_MATCH_LEN); break;
  1697. }
  1698. else if ((probe_len = ((mz_uint)(p - s) * 2) + (mz_uint)(*(const mz_uint8*)p == *(const mz_uint8*)q)) > match_len)
  1699. {
  1700. *pMatch_dist = dist; if ((*pMatch_len = match_len = MZ_MIN(max_match_len, probe_len)) == max_match_len) break;
  1701. c01 = TDEFL_READ_UNALIGNED_WORD(&d->m_dict[pos + match_len - 1]);
  1702. }
  1703. }
  1704. }
  1705. #else
  1706. 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)
  1707. {
  1708. mz_uint dist, pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK, match_len = *pMatch_len, probe_pos = pos, next_probe_pos, probe_len;
  1709. mz_uint num_probes_left = d->m_max_probes[match_len >= 32];
  1710. const mz_uint8 *s = d->m_dict + pos, *p, *q;
  1711. mz_uint8 c0 = d->m_dict[pos + match_len], c1 = d->m_dict[pos + match_len - 1];
  1712. MZ_ASSERT(max_match_len <= TDEFL_MAX_MATCH_LEN); if (max_match_len <= match_len) return;
  1713. for ( ; ; )
  1714. {
  1715. for ( ; ; )
  1716. {
  1717. if (--num_probes_left == 0) return;
  1718. #define TDEFL_PROBE \
  1719. next_probe_pos = d->m_next[probe_pos]; \
  1720. if ((!next_probe_pos) || ((dist = (mz_uint16)(lookahead_pos - next_probe_pos)) > max_dist)) return; \
  1721. probe_pos = next_probe_pos & TDEFL_LZ_DICT_SIZE_MASK; \
  1722. if ((d->m_dict[probe_pos + match_len] == c0) && (d->m_dict[probe_pos + match_len - 1] == c1)) break;
  1723. TDEFL_PROBE; TDEFL_PROBE; TDEFL_PROBE;
  1724. }
  1725. 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;
  1726. if (probe_len > match_len)
  1727. {
  1728. *pMatch_dist = dist; if ((*pMatch_len = match_len = probe_len) == max_match_len) return;
  1729. c0 = d->m_dict[pos + match_len]; c1 = d->m_dict[pos + match_len - 1];
  1730. }
  1731. }
  1732. }
  1733. #endif // #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES
  1734. #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN
  1735. static mz_bool tdefl_compress_fast(tdefl_compressor *d)
  1736. {
  1737. // Faster, minimally featured LZRW1-style match+parse loop with better register utilization. Intended for applications where raw throughput is valued more highly than ratio.
  1738. 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;
  1739. mz_uint8 *pLZ_code_buf = d->m_pLZ_code_buf, *pLZ_flags = d->m_pLZ_flags;
  1740. mz_uint cur_pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK;
  1741. while ((d->m_src_buf_left) || ((d->m_flush) && (lookahead_size)))
  1742. {
  1743. const mz_uint TDEFL_COMP_FAST_LOOKAHEAD_SIZE = 4096;
  1744. mz_uint dst_pos = (lookahead_pos + lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK;
  1745. mz_uint num_bytes_to_process = (mz_uint)MZ_MIN(d->m_src_buf_left, TDEFL_COMP_FAST_LOOKAHEAD_SIZE - lookahead_size);
  1746. d->m_src_buf_left -= num_bytes_to_process;
  1747. lookahead_size += num_bytes_to_process;
  1748. while (num_bytes_to_process)
  1749. {
  1750. mz_uint32 n = MZ_MIN(TDEFL_LZ_DICT_SIZE - dst_pos, num_bytes_to_process);
  1751. memcpy(d->m_dict + dst_pos, d->m_pSrc, n);
  1752. if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1))
  1753. memcpy(d->m_dict + TDEFL_LZ_DICT_SIZE + dst_pos, d->m_pSrc, MZ_MIN(n, (TDEFL_MAX_MATCH_LEN - 1) - dst_pos));
  1754. d->m_pSrc += n;
  1755. dst_pos = (dst_pos + n) & TDEFL_LZ_DICT_SIZE_MASK;
  1756. num_bytes_to_process -= n;
  1757. }
  1758. dict_size = MZ_MIN(TDEFL_LZ_DICT_SIZE - lookahead_size, dict_size);
  1759. if ((!d->m_flush) && (lookahead_size < TDEFL_COMP_FAST_LOOKAHEAD_SIZE)) break;
  1760. while (lookahead_size >= 4)
  1761. {
  1762. mz_uint cur_match_dist, cur_match_len = 1;
  1763. mz_uint8 *pCur_dict = d->m_dict + cur_pos;
  1764. mz_uint first_trigram = (*(const mz_uint32 *)pCur_dict) & 0xFFFFFF;
  1765. mz_uint hash = (first_trigram ^ (first_trigram >> (24 - (TDEFL_LZ_HASH_BITS - 8)))) & TDEFL_LEVEL1_HASH_SIZE_MASK;
  1766. mz_uint probe_pos = d->m_hash[hash];
  1767. d->m_hash[hash] = (mz_uint16)lookahead_pos;
  1768. 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))
  1769. {
  1770. const mz_uint16 *p = (const mz_uint16 *)pCur_dict;
  1771. const mz_uint16 *q = (const mz_uint16 *)(d->m_dict + probe_pos);
  1772. mz_uint32 probe_len = 32;
  1773. do { } while ( (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) &&
  1774. (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (--probe_len > 0) );
  1775. cur_match_len = ((mz_uint)(p - (const mz_uint16 *)pCur_dict) * 2) + (mz_uint)(*(const mz_uint8 *)p == *(const mz_uint8 *)q);
  1776. if (!probe_len)
  1777. cur_match_len = cur_match_dist ? TDEFL_MAX_MATCH_LEN : 0;
  1778. if ((cur_match_len < TDEFL_MIN_MATCH_LEN) || ((cur_match_len == TDEFL_MIN_MATCH_LEN) && (cur_match_dist >= 8U*1024U)))
  1779. {
  1780. cur_match_len = 1;
  1781. *pLZ_code_buf++ = (mz_uint8)first_trigram;
  1782. *pLZ_flags = (mz_uint8)(*pLZ_flags >> 1);
  1783. d->m_huff_count[0][(mz_uint8)first_trigram]++;
  1784. }
  1785. else
  1786. {
  1787. mz_uint32 s0, s1;
  1788. cur_match_len = MZ_MIN(cur_match_len, lookahead_size);
  1789. MZ_ASSERT((cur_match_len >= TDEFL_MIN_MATCH_LEN) && (cur_match_dist >= 1) && (cur_match_dist <= TDEFL_LZ_DICT_SIZE));
  1790. cur_match_dist--;
  1791. pLZ_code_buf[0] = (mz_uint8)(cur_match_len - TDEFL_MIN_MATCH_LEN);
  1792. *(mz_uint16 *)(&pLZ_code_buf[1]) = (mz_uint16)cur_match_dist;
  1793. pLZ_code_buf += 3;
  1794. *pLZ_flags = (mz_uint8)((*pLZ_flags >> 1) | 0x80);
  1795. s0 = s_tdefl_small_dist_sym[cur_match_dist & 511];
  1796. s1 = s_tdefl_large_dist_sym[cur_match_dist >> 8];
  1797. d->m_huff_count[1][(cur_match_dist < 512) ? s0 : s1]++;
  1798. d->m_huff_count[0][s_tdefl_len_sym[cur_match_len - TDEFL_MIN_MATCH_LEN]]++;
  1799. }
  1800. }
  1801. else
  1802. {
  1803. *pLZ_code_buf++ = (mz_uint8)first_trigram;
  1804. *pLZ_flags = (mz_uint8)(*pLZ_flags >> 1);
  1805. d->m_huff_count[0][(mz_uint8)first_trigram]++;
  1806. }
  1807. if (--num_flags_left == 0) { num_flags_left = 8; pLZ_flags = pLZ_code_buf++; }
  1808. total_lz_bytes += cur_match_len;
  1809. lookahead_pos += cur_match_len;
  1810. dict_size = MZ_MIN(dict_size + cur_match_len, TDEFL_LZ_DICT_SIZE);
  1811. cur_pos = (cur_pos + cur_match_len) & TDEFL_LZ_DICT_SIZE_MASK;
  1812. MZ_ASSERT(lookahead_size >= cur_match_len);
  1813. lookahead_size -= cur_match_len;
  1814. if (pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8])
  1815. {
  1816. int n;
  1817. d->m_lookahead_pos = lookahead_pos; d->m_lookahead_size = lookahead_size; d->m_dict_size = dict_size;
  1818. 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;
  1819. if ((n = tdefl_flush_block(d, 0)) != 0)
  1820. return (n < 0) ? MZ_FALSE : MZ_TRUE;
  1821. 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;
  1822. }
  1823. }
  1824. while (lookahead_size)
  1825. {
  1826. mz_uint8 lit = d->m_dict[cur_pos];
  1827. total_lz_bytes++;
  1828. *pLZ_code_buf++ = lit;
  1829. *pLZ_flags = (mz_uint8)(*pLZ_flags >> 1);
  1830. if (--num_flags_left == 0) { num_flags_left = 8; pLZ_flags = pLZ_code_buf++; }
  1831. d->m_huff_count[0][lit]++;
  1832. lookahead_pos++;
  1833. dict_size = MZ_MIN(dict_size + 1, TDEFL_LZ_DICT_SIZE);
  1834. cur_pos = (cur_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK;
  1835. lookahead_size--;
  1836. if (pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8])
  1837. {
  1838. int n;
  1839. d->m_lookahead_pos = lookahead_pos; d->m_lookahead_size = lookahead_size; d->m_dict_size = dict_size;
  1840. 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;
  1841. if ((n = tdefl_flush_block(d, 0)) != 0)
  1842. return (n < 0) ? MZ_FALSE : MZ_TRUE;
  1843. 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;
  1844. }
  1845. }
  1846. }
  1847. d->m_lookahead_pos = lookahead_pos; d->m_lookahead_size = lookahead_size; d->m_dict_size = dict_size;
  1848. 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;
  1849. return MZ_TRUE;
  1850. }
  1851. #endif // MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN
  1852. static MZ_FORCEINLINE void tdefl_record_literal(tdefl_compressor *d, mz_uint8 lit)
  1853. {
  1854. d->m_total_lz_bytes++;
  1855. *d->m_pLZ_code_buf++ = lit;
  1856. *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++; }
  1857. d->m_huff_count[0][lit]++;
  1858. }
  1859. static MZ_FORCEINLINE void tdefl_record_match(tdefl_compressor *d, mz_uint match_len, mz_uint match_dist)
  1860. {
  1861. mz_uint32 s0, s1;
  1862. MZ_ASSERT((match_len >= TDEFL_MIN_MATCH_LEN) && (match_dist >= 1) && (match_dist <= TDEFL_LZ_DICT_SIZE));
  1863. d->m_total_lz_bytes += match_len;
  1864. d->m_pLZ_code_buf[0] = (mz_uint8)(match_len - TDEFL_MIN_MATCH_LEN);
  1865. match_dist -= 1;
  1866. d->m_pLZ_code_buf[1] = (mz_uint8)(match_dist & 0xFF);
  1867. d->m_pLZ_code_buf[2] = (mz_uint8)(match_dist >> 8); d->m_pLZ_code_buf += 3;
  1868. *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++; }
  1869. s0 = s_tdefl_small_dist_sym[match_dist & 511]; s1 = s_tdefl_large_dist_sym[(match_dist >> 8) & 127];
  1870. d->m_huff_count[1][(match_dist < 512) ? s0 : s1]++;
  1871. if (match_len >= TDEFL_MIN_MATCH_LEN) d->m_huff_count[0][s_tdefl_len_sym[match_len - TDEFL_MIN_MATCH_LEN]]++;
  1872. }
  1873. static mz_bool tdefl_compress_normal(tdefl_compressor *d)
  1874. {
  1875. const mz_uint8 *pSrc = d->m_pSrc; size_t src_buf_left = d->m_src_buf_left;
  1876. tdefl_flush flush = d->m_flush;
  1877. while ((src_buf_left) || ((flush) && (d->m_lookahead_size)))
  1878. {
  1879. mz_uint len_to_move, cur_match_dist, cur_match_len, cur_pos;
  1880. // Update dictionary and hash chains. Keeps the lookahead size equal to TDEFL_MAX_MATCH_LEN.
  1881. if ((d->m_lookahead_size + d->m_dict_size) >= (TDEFL_MIN_MATCH_LEN - 1))
  1882. {
  1883. 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;
  1884. 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];
  1885. mz_uint num_bytes_to_process = (mz_uint)MZ_MIN(src_buf_left, TDEFL_MAX_MATCH_LEN - d->m_lookahead_size);
  1886. const mz_uint8 *pSrc_end = pSrc + num_bytes_to_process;
  1887. src_buf_left -= num_bytes_to_process;
  1888. d->m_lookahead_size += num_bytes_to_process;
  1889. while (pSrc != pSrc_end)
  1890. {
  1891. 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;
  1892. hash = ((hash << TDEFL_LZ_HASH_SHIFT) ^ c) & (TDEFL_LZ_HASH_SIZE - 1);
  1893. d->m_next[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] = d->m_hash[hash]; d->m_hash[hash] = (mz_uint16)(ins_pos);
  1894. dst_pos = (dst_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK; ins_pos++;
  1895. }
  1896. }
  1897. else
  1898. {
  1899. while ((src_buf_left) && (d->m_lookahead_size < TDEFL_MAX_MATCH_LEN))
  1900. {
  1901. mz_uint8 c = *pSrc++;
  1902. mz_uint dst_pos = (d->m_lookahead_pos + d->m_lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK;
  1903. src_buf_left--;
  1904. d->m_dict[dst_pos] = c;
  1905. if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1))
  1906. d->m_dict[TDEFL_LZ_DICT_SIZE + dst_pos] = c;
  1907. if ((++d->m_lookahead_size + d->m_dict_size) >= TDEFL_MIN_MATCH_LEN)
  1908. {
  1909. mz_uint ins_pos = d->m_lookahead_pos + (d->m_lookahead_size - 1) - 2;
  1910. 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);
  1911. d->m_next[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] = d->m_hash[hash]; d->m_hash[hash] = (mz_uint16)(ins_pos);
  1912. }
  1913. }
  1914. }
  1915. d->m_dict_size = MZ_MIN(TDEFL_LZ_DICT_SIZE - d->m_lookahead_size, d->m_dict_size);
  1916. if ((!flush) && (d->m_lookahead_size < TDEFL_MAX_MATCH_LEN))
  1917. break;
  1918. // Simple lazy/greedy parsing state machine.
  1919. 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;
  1920. if (d->m_flags & (TDEFL_RLE_MATCHES | TDEFL_FORCE_ALL_RAW_BLOCKS))
  1921. {
  1922. if ((d->m_dict_size) && (!(d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS)))
  1923. {
  1924. mz_uint8 c = d->m_dict[(cur_pos - 1) & TDEFL_LZ_DICT_SIZE_MASK];
  1925. 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++; }
  1926. if (cur_match_len < TDEFL_MIN_MATCH_LEN) cur_match_len = 0; else cur_match_dist = 1;
  1927. }
  1928. }
  1929. else
  1930. {
  1931. tdefl_find_match(d, d->m_lookahead_pos, d->m_dict_size, d->m_lookahead_size, &cur_match_dist, &cur_match_len);
  1932. }
  1933. 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)))
  1934. {
  1935. cur_match_dist = cur_match_len = 0;
  1936. }
  1937. if (d->m_saved_match_len)
  1938. {
  1939. if (cur_match_len > d->m_saved_match_len)
  1940. {
  1941. tdefl_record_literal(d, (mz_uint8)d->m_saved_lit);
  1942. if (cur_match_len >= 128)
  1943. {
  1944. tdefl_record_match(d, cur_match_len, cur_match_dist);
  1945. d->m_saved_match_len = 0; len_to_move = cur_match_len;
  1946. }
  1947. else
  1948. {
  1949. 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;
  1950. }
  1951. }
  1952. else
  1953. {
  1954. tdefl_record_match(d, d->m_saved_match_len, d->m_saved_match_dist);
  1955. len_to_move = d->m_saved_match_len - 1; d->m_saved_match_len = 0;
  1956. }
  1957. }
  1958. else if (!cur_match_dist)
  1959. tdefl_record_literal(d, d->m_dict[MZ_MIN(cur_pos, sizeof(d->m_dict) - 1)]);
  1960. else if ((d->m_greedy_parsing) || (d->m_flags & TDEFL_RLE_MATCHES) || (cur_match_len >= 128))
  1961. {
  1962. tdefl_record_match(d, cur_match_len, cur_match_dist);
  1963. len_to_move = cur_match_len;
  1964. }
  1965. else
  1966. {
  1967. 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;
  1968. }
  1969. // Move the lookahead forward by len_to_move bytes.
  1970. d->m_lookahead_pos += len_to_move;
  1971. MZ_ASSERT(d->m_lookahead_size >= len_to_move);
  1972. d->m_lookahead_size -= len_to_move;
  1973. d->m_dict_size = MZ_MIN(d->m_dict_size + len_to_move, TDEFL_LZ_DICT_SIZE);
  1974. // Check if it's time to flush the current LZ codes to the internal output buffer.
  1975. if ( (d->m_pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) ||
  1976. ( (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))) )
  1977. {
  1978. int n;
  1979. d->m_pSrc = pSrc; d->m_src_buf_left = src_buf_left;
  1980. if ((n = tdefl_flush_block(d, 0)) != 0)
  1981. return (n < 0) ? MZ_FALSE : MZ_TRUE;
  1982. }
  1983. }
  1984. d->m_pSrc = pSrc; d->m_src_buf_left = src_buf_left;
  1985. return MZ_TRUE;
  1986. }
  1987. static tdefl_status tdefl_flush_output_buffer(tdefl_compressor *d)
  1988. {
  1989. if (d->m_pIn_buf_size)
  1990. {
  1991. *d->m_pIn_buf_size = d->m_pSrc - (const mz_uint8 *)d->m_pIn_buf;
  1992. }
  1993. if (d->m_pOut_buf_size)
  1994. {
  1995. size_t n = MZ_MIN(*d->m_pOut_buf_size - d->m_out_buf_ofs, d->m_output_flush_remaining);
  1996. memcpy((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs, d->m_output_buf + d->m_output_flush_ofs, n);
  1997. d->m_output_flush_ofs += (mz_uint)n;
  1998. d->m_output_flush_remaining -= (mz_uint)n;
  1999. d->m_out_buf_ofs += n;
  2000. *d->m_pOut_buf_size = d->m_out_buf_ofs;
  2001. }
  2002. return (d->m_finished && !d->m_output_flush_remaining) ? TDEFL_STATUS_DONE : TDEFL_STATUS_OKAY;
  2003. }
  2004. 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)
  2005. {
  2006. if (!d)
  2007. {
  2008. if (pIn_buf_size) *pIn_buf_size = 0;
  2009. if (pOut_buf_size) *pOut_buf_size = 0;
  2010. return TDEFL_STATUS_BAD_PARAM;
  2011. }
  2012. d->m_pIn_buf = pIn_buf; d->m_pIn_buf_size = pIn_buf_size;
  2013. d->m_pOut_buf = pOut_buf; d->m_pOut_buf_size = pOut_buf_size;
  2014. d->m_pSrc = (const mz_uint8 *)(pIn_buf); d->m_src_buf_left = pIn_buf_size ? *pIn_buf_size : 0;
  2015. d->m_out_buf_ofs = 0;
  2016. d->m_flush = flush;
  2017. if ( ((d->m_pPut_buf_func != NULL) == ((pOut_buf != NULL) || (pOut_buf_size != NULL))) || (d->m_prev_return_status != TDEFL_STATUS_OKAY) ||
  2018. (d->m_wants_to_finish && (flush != TDEFL_FINISH)) || (pIn_buf_size && *pIn_buf_size && !pIn_buf) || (pOut_buf_size && *pOut_buf_size && !pOut_buf) )
  2019. {
  2020. if (pIn_buf_size) *pIn_buf_size = 0;
  2021. if (pOut_buf_size) *pOut_buf_size = 0;
  2022. return (d->m_prev_return_status = TDEFL_STATUS_BAD_PARAM);
  2023. }
  2024. d->m_wants_to_finish |= (flush == TDEFL_FINISH);
  2025. if ((d->m_output_flush_remaining) || (d->m_finished))
  2026. return (d->m_prev_return_status = tdefl_flush_output_buffer(d));
  2027. #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN
  2028. if (((d->m_flags & TDEFL_MAX_PROBES_MASK) == 1) &&
  2029. ((d->m_flags & TDEFL_GREEDY_PARSING_FLAG) != 0) &&
  2030. ((d->m_flags & (TDEFL_FILTER_MATCHES | TDEFL_FORCE_ALL_RAW_BLOCKS | TDEFL_RLE_MATCHES)) == 0))
  2031. {
  2032. if (!tdefl_compress_fast(d))
  2033. return d->m_prev_return_status;
  2034. }
  2035. else
  2036. #endif // #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN
  2037. {
  2038. if (!tdefl_compress_normal(d))
  2039. return d->m_prev_return_status;
  2040. }
  2041. if ((d->m_flags & (TDEFL_WRITE_ZLIB_HEADER | TDEFL_COMPUTE_ADLER32)) && (pIn_buf))
  2042. d->m_adler32 = (mz_uint32)mz_adler32(d->m_adler32, (const mz_uint8 *)pIn_buf, d->m_pSrc - (const mz_uint8 *)pIn_buf);
  2043. if ((flush) && (!d->m_lookahead_size) && (!d->m_src_buf_left) && (!d->m_output_flush_remaining))
  2044. {
  2045. if (tdefl_flush_block(d, flush) < 0)
  2046. return d->m_prev_return_status;
  2047. d->m_finished = (flush == TDEFL_FINISH);
  2048. if (flush == TDEFL_FULL_FLUSH) { MZ_CLEAR_OBJ(d->m_hash); MZ_CLEAR_OBJ(d->m_next); d->m_dict_size = 0; }
  2049. }
  2050. return (d->m_prev_return_status = tdefl_flush_output_buffer(d));
  2051. }
  2052. tdefl_status tdefl_compress_buffer(tdefl_compressor *d, const void *pIn_buf, size_t in_buf_size, tdefl_flush flush)
  2053. {
  2054. MZ_ASSERT(d->m_pPut_buf_func); return tdefl_compress(d, pIn_buf, &in_buf_size, NULL, NULL, flush);
  2055. }
  2056. tdefl_status tdefl_init(tdefl_compressor *d, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags)
  2057. {
  2058. d->m_pPut_buf_func = pPut_buf_func; d->m_pPut_buf_user = pPut_buf_user;
  2059. 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;
  2060. d->m_max_probes[1] = 1 + (((flags & 0xFFF) >> 2) + 2) / 3;
  2061. if (!(flags & TDEFL_NONDETERMINISTIC_PARSING_FLAG)) MZ_CLEAR_OBJ(d->m_hash);
  2062. 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;
  2063. 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;
  2064. 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;
  2065. 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;
  2066. d->m_saved_match_dist = d->m_saved_match_len = d->m_saved_lit = 0; d->m_adler32 = 1;
  2067. d->m_pIn_buf = NULL; d->m_pOut_buf = NULL;
  2068. d->m_pIn_buf_size = NULL; d->m_pOut_buf_size = NULL;
  2069. d->m_flush = TDEFL_NO_FLUSH; d->m_pSrc = NULL; d->m_src_buf_left = 0; d->m_out_buf_ofs = 0;
  2070. memset(&d->m_huff_count[0][0], 0, sizeof(d->m_huff_count[0][0]) * TDEFL_MAX_HUFF_SYMBOLS_0);
  2071. memset(&d->m_huff_count[1][0], 0, sizeof(d->m_huff_count[1][0]) * TDEFL_MAX_HUFF_SYMBOLS_1);
  2072. return TDEFL_STATUS_OKAY;
  2073. }
  2074. tdefl_status tdefl_get_prev_return_status(tdefl_compressor *d)
  2075. {
  2076. return d->m_prev_return_status;
  2077. }
  2078. mz_uint32 tdefl_get_adler32(tdefl_compressor *d)
  2079. {
  2080. return d->m_adler32;
  2081. }
  2082. 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)
  2083. {
  2084. tdefl_compressor *pComp; mz_bool succeeded; if (((buf_len) && (!pBuf)) || (!pPut_buf_func)) return MZ_FALSE;
  2085. pComp = (tdefl_compressor*)MZ_MALLOC(sizeof(tdefl_compressor)); if (!pComp) return MZ_FALSE;
  2086. succeeded = (tdefl_init(pComp, pPut_buf_func, pPut_buf_user, flags) == TDEFL_STATUS_OKAY);
  2087. succeeded = succeeded && (tdefl_compress_buffer(pComp, pBuf, buf_len, TDEFL_FINISH) == TDEFL_STATUS_DONE);
  2088. MZ_FREE(pComp); return succeeded;
  2089. }
  2090. typedef struct
  2091. {
  2092. size_t m_size, m_capacity;
  2093. mz_uint8 *m_pBuf;
  2094. mz_bool m_expandable;
  2095. } tdefl_output_buffer;
  2096. static mz_bool tdefl_output_buffer_putter(const void *pBuf, int len, void *pUser)
  2097. {
  2098. tdefl_output_buffer *p = (tdefl_output_buffer *)pUser;
  2099. size_t new_size = p->m_size + len;
  2100. if (new_size > p->m_capacity)
  2101. {
  2102. size_t new_capacity = p->m_capacity; mz_uint8 *pNew_buf; if (!p->m_expandable) return MZ_FALSE;
  2103. do { new_capacity = MZ_MAX(128U, new_capacity << 1U); } while (new_size > new_capacity);
  2104. pNew_buf = (mz_uint8*)MZ_REALLOC(p->m_pBuf, new_capacity); if (!pNew_buf) return MZ_FALSE;
  2105. p->m_pBuf = pNew_buf; p->m_capacity = new_capacity;
  2106. }
  2107. memcpy((mz_uint8*)p->m_pBuf + p->m_size, pBuf, len); p->m_size = new_size;
  2108. return MZ_TRUE;
  2109. }
  2110. void *tdefl_compress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags)
  2111. {
  2112. tdefl_output_buffer out_buf; MZ_CLEAR_OBJ(out_buf);
  2113. if (!pOut_len) return MZ_FALSE; else *pOut_len = 0;
  2114. out_buf.m_expandable = MZ_TRUE;
  2115. if (!tdefl_compress_mem_to_output(pSrc_buf, src_buf_len, tdefl_output_buffer_putter, &out_buf, flags)) return NULL;
  2116. *pOut_len = out_buf.m_size; return out_buf.m_pBuf;
  2117. }
  2118. 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)
  2119. {
  2120. tdefl_output_buffer out_buf; MZ_CLEAR_OBJ(out_buf);
  2121. if (!pOut_buf) return 0;
  2122. out_buf.m_pBuf = (mz_uint8*)pOut_buf; out_buf.m_capacity = out_buf_len;
  2123. if (!tdefl_compress_mem_to_output(pSrc_buf, src_buf_len, tdefl_output_buffer_putter, &out_buf, flags)) return 0;
  2124. return out_buf.m_size;
  2125. }
  2126. #ifndef MINIZ_NO_ZLIB_APIS
  2127. static const mz_uint s_tdefl_num_probes[11] = { 0, 1, 6, 32, 16, 32, 128, 256, 512, 768, 1500 };
  2128. // 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).
  2129. mz_uint tdefl_create_comp_flags_from_zip_params(int level, int window_bits, int strategy)
  2130. {
  2131. mz_uint comp_flags = s_tdefl_num_probes[(level >= 0) ? MZ_MIN(10, level) : MZ_DEFAULT_LEVEL] | ((level <= 3) ? TDEFL_GREEDY_PARSING_FLAG : 0);
  2132. if (window_bits > 0) comp_flags |= TDEFL_WRITE_ZLIB_HEADER;
  2133. if (!level) comp_flags |= TDEFL_FORCE_ALL_RAW_BLOCKS;
  2134. else if (strategy == MZ_FILTERED) comp_flags |= TDEFL_FILTER_MATCHES;
  2135. else if (strategy == MZ_HUFFMAN_ONLY) comp_flags &= ~TDEFL_MAX_PROBES_MASK;
  2136. else if (strategy == MZ_FIXED) comp_flags |= TDEFL_FORCE_ALL_STATIC_BLOCKS;
  2137. else if (strategy == MZ_RLE) comp_flags |= TDEFL_RLE_MATCHES;
  2138. return comp_flags;
  2139. }
  2140. #endif //MINIZ_NO_ZLIB_APIS
  2141. #ifdef _MSC_VER
  2142. #pragma warning (push)
  2143. #pragma warning (disable:4204) // nonstandard extension used : non-constant aggregate initializer (also supported by GNU C and C99, so no big deal)
  2144. #endif
  2145. // Simple PNG writer function by Alex Evans, 2011. Released into the public domain: https://gist.github.com/908299, more context at
  2146. // http://altdevblogaday.org/2011/04/06/a-smaller-jpg-encoder/.
  2147. // This is actually a modification of Alex's original code so PNG files generated by this function pass pngcheck.
  2148. 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)
  2149. {
  2150. // Using a local copy of this array here in case MINIZ_NO_ZLIB_APIS was defined.
  2151. static const mz_uint s_tdefl_png_num_probes[11] = { 0, 1, 6, 32, 16, 32, 128, 256, 512, 768, 1500 };
  2152. 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;
  2153. if (!pComp) return NULL;
  2154. 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; }
  2155. // write dummy header
  2156. for (z = 41; z; --z) tdefl_output_buffer_putter(&z, 1, &out_buf);
  2157. // compress image data
  2158. tdefl_init(pComp, tdefl_output_buffer_putter, &out_buf, s_tdefl_png_num_probes[MZ_MIN(10, level)] | TDEFL_WRITE_ZLIB_HEADER | (level <= 3 ? TDEFL_GREEDY_PARSING_FLAG : 0));
  2159. 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); }
  2160. if (tdefl_compress_buffer(pComp, NULL, 0, TDEFL_FINISH) != TDEFL_STATUS_DONE) { MZ_FREE(pComp); MZ_FREE(out_buf.m_pBuf); return NULL; }
  2161. // write real header
  2162. *pLen_out = out_buf.m_size-41;
  2163. {
  2164. static const mz_uint8 chans[] = {0x00, 0x00, 0x04, 0x02, 0x06};
  2165. mz_uint8 pnghdr[41]={0x89,0x50,0x4e,0x47,0x0d,0x0a,0x1a,0x0a,0x00,0x00,0x00,0x0d,0x49,0x48,0x44,0x52,
  2166. 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,
  2167. (mz_uint8)(*pLen_out>>24),(mz_uint8)(*pLen_out>>16),(mz_uint8)(*pLen_out>>8),(mz_uint8)*pLen_out,0x49,0x44,0x41,0x54};
  2168. 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);
  2169. memcpy(out_buf.m_pBuf, pnghdr, 41);
  2170. }
  2171. // write footer (IDAT CRC-32, followed by IEND chunk)
  2172. 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; }
  2173. 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);
  2174. // compute final size of file, grab compressed data buffer and return
  2175. *pLen_out += 57; MZ_FREE(pComp); return out_buf.m_pBuf;
  2176. }
  2177. void *tdefl_write_image_to_png_file_in_memory(const void *pImage, int w, int h, int num_chans, size_t *pLen_out)
  2178. {
  2179. // 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)
  2180. return tdefl_write_image_to_png_file_in_memory_ex(pImage, w, h, num_chans, pLen_out, 6, MZ_FALSE);
  2181. }
  2182. #ifdef _MSC_VER
  2183. #pragma warning (pop)
  2184. #endif
  2185. } // namespace buminiz
  2186. #endif // MINIZ_HEADER_FILE_ONLY