compression.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  1. /**************************************************************************/
  2. /* compression.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. #include "compression.h"
  31. #include "core/config/project_settings.h"
  32. #include "core/io/zip_io.h"
  33. #include "thirdparty/misc/fastlz.h"
  34. #include <zlib.h>
  35. #include <zstd.h>
  36. #ifdef BROTLI_ENABLED
  37. #include <brotli/decode.h>
  38. #endif
  39. int Compression::compress(uint8_t *p_dst, const uint8_t *p_src, int p_src_size, Mode p_mode) {
  40. switch (p_mode) {
  41. case MODE_BROTLI: {
  42. ERR_FAIL_V_MSG(-1, "Only brotli decompression is supported.");
  43. } break;
  44. case MODE_FASTLZ: {
  45. if (p_src_size < 16) {
  46. uint8_t src[16];
  47. memset(&src[p_src_size], 0, 16 - p_src_size);
  48. memcpy(src, p_src, p_src_size);
  49. return fastlz_compress(src, 16, p_dst);
  50. } else {
  51. return fastlz_compress(p_src, p_src_size, p_dst);
  52. }
  53. } break;
  54. case MODE_DEFLATE:
  55. case MODE_GZIP: {
  56. int window_bits = p_mode == MODE_DEFLATE ? 15 : 15 + 16;
  57. z_stream strm;
  58. strm.zalloc = zipio_alloc;
  59. strm.zfree = zipio_free;
  60. strm.opaque = Z_NULL;
  61. int level = p_mode == MODE_DEFLATE ? zlib_level : gzip_level;
  62. int err = deflateInit2(&strm, level, Z_DEFLATED, window_bits, 8, Z_DEFAULT_STRATEGY);
  63. if (err != Z_OK) {
  64. return -1;
  65. }
  66. strm.avail_in = p_src_size;
  67. int aout = deflateBound(&strm, p_src_size);
  68. strm.avail_out = aout;
  69. strm.next_in = (Bytef *)p_src;
  70. strm.next_out = p_dst;
  71. deflate(&strm, Z_FINISH);
  72. aout = aout - strm.avail_out;
  73. deflateEnd(&strm);
  74. return aout;
  75. } break;
  76. case MODE_ZSTD: {
  77. ZSTD_CCtx *cctx = ZSTD_createCCtx();
  78. ZSTD_CCtx_setParameter(cctx, ZSTD_c_compressionLevel, zstd_level);
  79. if (zstd_long_distance_matching) {
  80. ZSTD_CCtx_setParameter(cctx, ZSTD_c_enableLongDistanceMatching, 1);
  81. ZSTD_CCtx_setParameter(cctx, ZSTD_c_windowLog, zstd_window_log_size);
  82. }
  83. int max_dst_size = get_max_compressed_buffer_size(p_src_size, MODE_ZSTD);
  84. int ret = ZSTD_compressCCtx(cctx, p_dst, max_dst_size, p_src, p_src_size, zstd_level);
  85. ZSTD_freeCCtx(cctx);
  86. return ret;
  87. } break;
  88. }
  89. ERR_FAIL_V(-1);
  90. }
  91. int Compression::get_max_compressed_buffer_size(int p_src_size, Mode p_mode) {
  92. switch (p_mode) {
  93. case MODE_BROTLI: {
  94. ERR_FAIL_V_MSG(-1, "Only brotli decompression is supported.");
  95. } break;
  96. case MODE_FASTLZ: {
  97. int ss = p_src_size + p_src_size * 6 / 100;
  98. if (ss < 66) {
  99. ss = 66;
  100. }
  101. return ss;
  102. } break;
  103. case MODE_DEFLATE:
  104. case MODE_GZIP: {
  105. int window_bits = p_mode == MODE_DEFLATE ? 15 : 15 + 16;
  106. z_stream strm;
  107. strm.zalloc = zipio_alloc;
  108. strm.zfree = zipio_free;
  109. strm.opaque = Z_NULL;
  110. int err = deflateInit2(&strm, Z_DEFAULT_COMPRESSION, Z_DEFLATED, window_bits, 8, Z_DEFAULT_STRATEGY);
  111. if (err != Z_OK) {
  112. return -1;
  113. }
  114. int aout = deflateBound(&strm, p_src_size);
  115. deflateEnd(&strm);
  116. return aout;
  117. } break;
  118. case MODE_ZSTD: {
  119. return ZSTD_compressBound(p_src_size);
  120. } break;
  121. }
  122. ERR_FAIL_V(-1);
  123. }
  124. int Compression::decompress(uint8_t *p_dst, int p_dst_max_size, const uint8_t *p_src, int p_src_size, Mode p_mode) {
  125. switch (p_mode) {
  126. case MODE_BROTLI: {
  127. #ifdef BROTLI_ENABLED
  128. size_t ret_size = p_dst_max_size;
  129. BrotliDecoderResult res = BrotliDecoderDecompress(p_src_size, p_src, &ret_size, p_dst);
  130. ERR_FAIL_COND_V(res != BROTLI_DECODER_RESULT_SUCCESS, -1);
  131. return ret_size;
  132. #else
  133. ERR_FAIL_V_MSG(-1, "Godot was compiled without brotli support.");
  134. #endif
  135. } break;
  136. case MODE_FASTLZ: {
  137. int ret_size = 0;
  138. if (p_dst_max_size < 16) {
  139. uint8_t dst[16];
  140. fastlz_decompress(p_src, p_src_size, dst, 16);
  141. memcpy(p_dst, dst, p_dst_max_size);
  142. ret_size = p_dst_max_size;
  143. } else {
  144. ret_size = fastlz_decompress(p_src, p_src_size, p_dst, p_dst_max_size);
  145. }
  146. return ret_size;
  147. } break;
  148. case MODE_DEFLATE:
  149. case MODE_GZIP: {
  150. int window_bits = p_mode == MODE_DEFLATE ? 15 : 15 + 16;
  151. z_stream strm;
  152. strm.zalloc = zipio_alloc;
  153. strm.zfree = zipio_free;
  154. strm.opaque = Z_NULL;
  155. strm.avail_in = 0;
  156. strm.next_in = Z_NULL;
  157. int err = inflateInit2(&strm, window_bits);
  158. ERR_FAIL_COND_V(err != Z_OK, -1);
  159. strm.avail_in = p_src_size;
  160. strm.avail_out = p_dst_max_size;
  161. strm.next_in = (Bytef *)p_src;
  162. strm.next_out = p_dst;
  163. err = inflate(&strm, Z_FINISH);
  164. int total = strm.total_out;
  165. inflateEnd(&strm);
  166. ERR_FAIL_COND_V(err != Z_STREAM_END, -1);
  167. return total;
  168. } break;
  169. case MODE_ZSTD: {
  170. ZSTD_DCtx *dctx = ZSTD_createDCtx();
  171. if (zstd_long_distance_matching) {
  172. ZSTD_DCtx_setParameter(dctx, ZSTD_d_windowLogMax, zstd_window_log_size);
  173. }
  174. int ret = ZSTD_decompressDCtx(dctx, p_dst, p_dst_max_size, p_src, p_src_size);
  175. ZSTD_freeDCtx(dctx);
  176. return ret;
  177. } break;
  178. }
  179. ERR_FAIL_V(-1);
  180. }
  181. /**
  182. This will handle both Gzip and Deflate streams. It will automatically allocate the output buffer into the provided p_dst_vect Vector.
  183. This is required for compressed data whose final uncompressed size is unknown, as is the case for HTTP response bodies.
  184. This is much slower however than using Compression::decompress because it may result in multiple full copies of the output buffer.
  185. */
  186. int Compression::decompress_dynamic(Vector<uint8_t> *p_dst_vect, int p_max_dst_size, const uint8_t *p_src, int p_src_size, Mode p_mode) {
  187. uint8_t *dst = nullptr;
  188. int out_mark = 0;
  189. ERR_FAIL_COND_V(p_src_size <= 0, Z_DATA_ERROR);
  190. if (p_mode == MODE_BROTLI) {
  191. #ifdef BROTLI_ENABLED
  192. BrotliDecoderResult ret;
  193. BrotliDecoderState *state = BrotliDecoderCreateInstance(nullptr, nullptr, nullptr);
  194. ERR_FAIL_NULL_V(state, Z_DATA_ERROR);
  195. // Setup the stream inputs.
  196. const uint8_t *next_in = p_src;
  197. size_t avail_in = p_src_size;
  198. uint8_t *next_out = nullptr;
  199. size_t avail_out = 0;
  200. size_t total_out = 0;
  201. // Ensure the destination buffer is empty.
  202. p_dst_vect->clear();
  203. // Decompress until stream ends or end of file.
  204. do {
  205. // Add another chunk size to the output buffer.
  206. // This forces a copy of the whole buffer.
  207. p_dst_vect->resize(p_dst_vect->size() + gzip_chunk);
  208. // Get pointer to the actual output buffer.
  209. dst = p_dst_vect->ptrw();
  210. // Set the stream to the new output stream.
  211. // Since it was copied, we need to reset the stream to the new buffer.
  212. next_out = &(dst[out_mark]);
  213. avail_out += gzip_chunk;
  214. ret = BrotliDecoderDecompressStream(state, &avail_in, &next_in, &avail_out, &next_out, &total_out);
  215. if (ret == BROTLI_DECODER_RESULT_ERROR) {
  216. WARN_PRINT(BrotliDecoderErrorString(BrotliDecoderGetErrorCode(state)));
  217. BrotliDecoderDestroyInstance(state);
  218. p_dst_vect->clear();
  219. return Z_DATA_ERROR;
  220. }
  221. out_mark += gzip_chunk - avail_out;
  222. // Enforce max output size.
  223. if (p_max_dst_size > -1 && total_out > (uint64_t)p_max_dst_size) {
  224. BrotliDecoderDestroyInstance(state);
  225. p_dst_vect->clear();
  226. return Z_BUF_ERROR;
  227. }
  228. } while (ret != BROTLI_DECODER_RESULT_SUCCESS);
  229. // If all done successfully, resize the output if it's larger than the actual output.
  230. if ((unsigned long)p_dst_vect->size() > total_out) {
  231. p_dst_vect->resize(total_out);
  232. }
  233. // Clean up and return.
  234. BrotliDecoderDestroyInstance(state);
  235. return Z_OK;
  236. #else
  237. ERR_FAIL_V_MSG(Z_ERRNO, "Godot was compiled without brotli support.");
  238. #endif
  239. } else {
  240. // This function only supports GZip and Deflate.
  241. ERR_FAIL_COND_V(p_mode != MODE_DEFLATE && p_mode != MODE_GZIP, Z_ERRNO);
  242. int ret;
  243. z_stream strm;
  244. int window_bits = p_mode == MODE_DEFLATE ? 15 : 15 + 16;
  245. // Initialize the stream.
  246. strm.zalloc = Z_NULL;
  247. strm.zfree = Z_NULL;
  248. strm.opaque = Z_NULL;
  249. strm.avail_in = 0;
  250. strm.next_in = Z_NULL;
  251. int err = inflateInit2(&strm, window_bits);
  252. ERR_FAIL_COND_V(err != Z_OK, -1);
  253. // Setup the stream inputs.
  254. strm.next_in = (Bytef *)p_src;
  255. strm.avail_in = p_src_size;
  256. // Ensure the destination buffer is empty.
  257. p_dst_vect->clear();
  258. // Decompress until deflate stream ends or end of file.
  259. do {
  260. // Add another chunk size to the output buffer.
  261. // This forces a copy of the whole buffer.
  262. p_dst_vect->resize(p_dst_vect->size() + gzip_chunk);
  263. // Get pointer to the actual output buffer.
  264. dst = p_dst_vect->ptrw();
  265. // Set the stream to the new output stream.
  266. // Since it was copied, we need to reset the stream to the new buffer.
  267. strm.next_out = &(dst[out_mark]);
  268. strm.avail_out = gzip_chunk;
  269. // Run inflate() on input until output buffer is full and needs to be resized or input runs out.
  270. do {
  271. ret = inflate(&strm, Z_SYNC_FLUSH);
  272. switch (ret) {
  273. case Z_NEED_DICT:
  274. ret = Z_DATA_ERROR;
  275. [[fallthrough]];
  276. case Z_DATA_ERROR:
  277. case Z_MEM_ERROR:
  278. case Z_STREAM_ERROR:
  279. case Z_BUF_ERROR:
  280. if (strm.msg) {
  281. WARN_PRINT(strm.msg);
  282. }
  283. (void)inflateEnd(&strm);
  284. p_dst_vect->clear();
  285. return ret;
  286. }
  287. } while (strm.avail_out > 0 && strm.avail_in > 0);
  288. out_mark += gzip_chunk;
  289. // Enforce max output size.
  290. if (p_max_dst_size > -1 && strm.total_out > (uint64_t)p_max_dst_size) {
  291. (void)inflateEnd(&strm);
  292. p_dst_vect->clear();
  293. return Z_BUF_ERROR;
  294. }
  295. } while (ret != Z_STREAM_END);
  296. // If all done successfully, resize the output if it's larger than the actual output.
  297. if ((unsigned long)p_dst_vect->size() > strm.total_out) {
  298. p_dst_vect->resize(strm.total_out);
  299. }
  300. // Clean up and return.
  301. (void)inflateEnd(&strm);
  302. return Z_OK;
  303. }
  304. }
  305. int Compression::zlib_level = Z_DEFAULT_COMPRESSION;
  306. int Compression::gzip_level = Z_DEFAULT_COMPRESSION;
  307. int Compression::zstd_level = 3;
  308. bool Compression::zstd_long_distance_matching = false;
  309. int Compression::zstd_window_log_size = 27; // ZSTD_WINDOWLOG_LIMIT_DEFAULT
  310. int Compression::gzip_chunk = 16384;