Skip to content
Snippets Groups Projects
miniz_tester.cpp 52.4 KiB
Newer Older
Andre Maroneze's avatar
Andre Maroneze committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000
// miniz_tester.cpp
// Note: This module is not intended to make a good example, or be used for anything other than testing.
// It's something quick I put together last year to help regression test miniz/tinfl under Linux/Win32/Mac. It's derived from LZHAM's test module.
#ifdef _MSC_VER
#pragma warning (disable:4127) //  warning C4127: conditional expression is constant
#endif

#if defined(__GNUC__)
  // Ensure we get the 64-bit variants of the CRT's file I/O calls
  #ifndef _FILE_OFFSET_BITS
    #define _FILE_OFFSET_BITS 64
  #endif
  #ifndef _LARGEFILE64_SOURCE
    #define _LARGEFILE64_SOURCE 1
  #endif
#endif

#include "miniz.h"
#include "miniz_zip.h"

#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
#include <memory.h>
#include <stdarg.h>
#include <malloc.h>
#include <vector>
#include <string>
#include <limits.h>
#include <sys/stat.h>

#include "timer.h"

#define my_max(a,b) (((a) > (b)) ? (a) : (b))
#define my_min(a,b) (((a) < (b)) ? (a) : (b))

typedef unsigned char uint8;
typedef unsigned short uint16;
typedef unsigned int uint;

#define TDEFL_PRINT_OUTPUT_PROGRESS

#if defined(WIN32)
   #define WIN32_LEAN_AND_MEAN
   #include <windows.h>
   #define FILE_STAT_STRUCT _stat
   #define FILE_STAT _stat
#else
   #include <unistd.h>
   #define Sleep(ms) usleep(ms*1000)
   #define _aligned_malloc(size, alignment) memalign(alignment, size)
   #define _aligned_free free
   #define fopen fopen64
   #define _fseeki64 fseeko64
   #define _ftelli64 ftello64
   #define _stricmp strcasecmp
   #define FILE_STAT_STRUCT stat64
   #define FILE_STAT stat64
#endif

#ifdef WIN32
#define QUAD_INT_FMT "%I64u"
#else
#define QUAD_INT_FMT "%llu"
#endif

#ifdef _DEBUG
const bool g_is_debug = true;
#else
const bool g_is_debug = false;
#endif

typedef unsigned char uint8;
typedef unsigned int uint;
typedef unsigned int uint32;
typedef unsigned long long uint64;
typedef long long int64;

#define TDEFLTEST_COMP_INPUT_BUFFER_SIZE 1024*1024*2
#define TDEFLTEST_COMP_OUTPUT_BUFFER_SIZE 1024*1024*2
#define TDEFLTEST_DECOMP_INPUT_BUFFER_SIZE 1024*1024*2

static float s_max_small_comp_ratio, s_max_large_comp_ratio;

struct comp_options
{
  comp_options() :
    m_level(7),
    m_unbuffered_decompression(false),
    m_verify_compressed_data(false),
    m_randomize_params(false),
    m_randomize_buffer_sizes(false),
    m_z_strat(Z_DEFAULT_STRATEGY),
    m_random_z_flushing(false),
    m_write_zlib_header(true),
    m_archive_test(false),
    m_write_archives(false)
  {
  }

  void print()
  {
    printf("Level: %u\n", m_level);
    printf("Write zlib header: %u\n", (uint)m_write_zlib_header);
    printf("Unbuffered decompression: %u\n", (uint)m_unbuffered_decompression);
    printf("Verify compressed data: %u\n", (uint)m_verify_compressed_data);
    printf("Randomize parameters: %u\n", m_randomize_params);
    printf("Randomize buffer sizes: %u\n", m_randomize_buffer_sizes);
    printf("Deflate strategy: %u\n", m_z_strat);
    printf("Random Z stream flushing: %u\n", m_random_z_flushing);
    printf("Archive test: %u\n", m_archive_test);
    printf("Write archives: %u\n", m_write_archives);
  }

  uint m_level;
  bool m_unbuffered_decompression;
  bool m_verify_compressed_data;
  bool m_randomize_params;
  bool m_randomize_buffer_sizes;
  uint m_z_strat;
  bool m_random_z_flushing;
  bool m_write_zlib_header;
  bool m_archive_test;
  bool m_write_archives;
};

#define RND_SHR3(x)  (x ^= (x << 17), x ^= (x >> 13), x ^= (x << 5))

#if 0
static void random_fill(uint8 *pDst, size_t len, uint32 x)
{
  x ^= (x << 16);
  if (!x) x++;

  while (len)
  {
    RND_SHR3(x); uint64 l0 = x & 0xFFF;
    RND_SHR3(x); uint64 l1 = x & 0xFFF;
    RND_SHR3(x); uint64 l2 = x & 0xFFF;
    RND_SHR3(x); uint c = x;

    uint l = (uint)(((l0*l1*l2)/(16769025ULL) * 32) / 4095);
    l = (uint)my_max(1,my_min(l, len));
    len -= l;

    while (l--)
    {
      *pDst++ = (uint8)c;
    }

    if (((int)x < 0) && len)
    {
      *pDst++ = 0;
      len--;
    }
  }
}
#endif

static void print_usage()
{
  printf("Usage: [options] [mode] inpath/infile [outfile]\n");
  printf("\n");
  printf("Modes:\n");
  printf("c - Compress \"infile\" to \"outfile\"\n");
  printf("d - Decompress \"infile\" to \"outfile\"\n");
  printf("a - Recursively compress all files under \"inpath\"\n");
  printf("r - Archive decompression test\n");
  printf("\n");
  printf("Options:\n");
  printf("-m[0-10] - Compression level: 0=fastest (Huffman only), 9=best (10=uber)\n");
  printf("-u - Use unbuffered decompression on files that can fit into memory.\n");
  printf("     Unbuffered decompression is faster, but may have more I/O overhead.\n");
  printf("-v - Immediately decompress compressed file after compression for verification.\n");
  printf("-z - Do not write zlib header\n");
  printf("-r - Randomize parameters during recursive testing\n");
  printf("-b - Randomize input/output buffer sizes\n");
  printf("-h - Use random z_flushing\n");
  printf("-x# - Set rand() seed to value\n");
  printf("-t# - Set z_strategy to value [0-4]\n");
  printf("-a - Create single-file archives instead of files during testing\n");
  printf("-w - Test archive cloning\n");
}

static void print_error(const char *pMsg, ...)
{
  char buf[1024];

  va_list args;
  va_start(args, pMsg);
  vsnprintf(buf, sizeof(buf), pMsg, args);
  va_end(args);

  buf[sizeof(buf) - 1] = '\0';

  fprintf(stderr, "Error: %s", buf);
}

static FILE* open_file_with_retries(const char *pFilename, const char* pMode)
{
  const uint cNumRetries = 8;
  for (uint i = 0; i < cNumRetries; i++)
  {
    FILE* pFile = fopen(pFilename, pMode);
    if (pFile)
      return pFile;
    Sleep(250);
  }
  return NULL;
}

static bool ensure_file_exists_and_is_readable(const char *pFilename)
{
  FILE *p = fopen(pFilename, "rb");
  if (!p)
    return false;

  _fseeki64(p, 0, SEEK_END);
  uint64 src_file_size = _ftelli64(p);
  _fseeki64(p, 0, SEEK_SET);

  if (src_file_size)
  {
    char buf[1];
    if (fread(buf, 1, 1, p) != 1)
    {
      fclose(p);
      return false;
    }
  }
  fclose(p);
  return true;
}

static bool ensure_file_is_writable(const char *pFilename)
{
  const int cNumRetries = 8;
  for (int i = 0; i < cNumRetries; i++)
  {
    FILE *pFile = fopen(pFilename, "wb");
    if (pFile)
    {
      fclose(pFile);
      return true;
    }
    Sleep(250);
  }
  return false;
}

static int simple_test1(const comp_options &options)
{
  (void)options;

  size_t cmp_len = 0;

  const char *p = "This is a test.This is a test.This is a test.1234567This is a test.This is a test.123456";
  size_t uncomp_len = strlen(p);

  void *pComp_data = tdefl_compress_mem_to_heap(p, uncomp_len, &cmp_len, TDEFL_WRITE_ZLIB_HEADER);
  if (!pComp_data)
  {
    free(pComp_data);
    print_error("Compression test failed!\n");
    return EXIT_FAILURE;
  }

  printf("Uncompressed size: %u\nCompressed size: %u\n", (uint)uncomp_len, (uint)cmp_len);

  size_t decomp_len = 0;
  void *pDecomp_data = tinfl_decompress_mem_to_heap(pComp_data, cmp_len, &decomp_len, TINFL_FLAG_PARSE_ZLIB_HEADER);

  if ((!pDecomp_data) || (decomp_len != uncomp_len) || (memcmp(pDecomp_data, p, uncomp_len)))
  {
    free(pComp_data);
    free(pDecomp_data);
    print_error("Compression test failed!\n");
    return EXIT_FAILURE;
  }

  printf("Low-level API compression test succeeded.\n");

  free(pComp_data);
  free(pDecomp_data);

  return EXIT_SUCCESS;
}

static int simple_test2(const comp_options &options)
{
  (void)options;

  uint8 cmp_buf[1024], decomp_buf[1024];
  uLong cmp_len = sizeof(cmp_buf);

  const char *p = "This is a test.This is a test.This is a test.1234567This is a test.This is a test.123456";
  uLong uncomp_len = (uLong)strlen(p);

  int status = compress(cmp_buf, &cmp_len, (const uint8*)p, uncomp_len);
  if (status != Z_OK)
  {
    print_error("Compression test failed!\n");
    return EXIT_FAILURE;
  }

  printf("Uncompressed size: %u\nCompressed size: %u\n", (uint)uncomp_len, (uint)cmp_len);

  if (cmp_len > compressBound(uncomp_len))
  {
    print_error("compressBound() returned bogus result\n");
    return EXIT_FAILURE;
  }

  uLong decomp_len = sizeof(decomp_buf);
  status = uncompress(decomp_buf, &decomp_len, cmp_buf, cmp_len);;

  if ((status != Z_OK) || (decomp_len != uncomp_len) || (memcmp(decomp_buf, p, uncomp_len)))
  {
    print_error("Compression test failed!\n");
    return EXIT_FAILURE;
  }

  printf("zlib API compression test succeeded.\n");

  return EXIT_SUCCESS;
}

static bool compress_file_zlib(const char* pSrc_filename, const char *pDst_filename, const comp_options &options)
{
  printf("Testing: Streaming zlib compression\n");

  FILE *pInFile = fopen(pSrc_filename, "rb");
  if (!pInFile)
  {
    print_error("Unable to read file: %s\n", pSrc_filename);
    return false;
  }

  FILE *pOutFile = fopen(pDst_filename, "wb");
  if (!pOutFile)
  {
    print_error("Unable to create file: %s\n", pDst_filename);
    return false;
  }

  _fseeki64(pInFile, 0, SEEK_END);
  uint64 src_file_size = _ftelli64(pInFile);
  _fseeki64(pInFile, 0, SEEK_SET);

  fputc('D', pOutFile); fputc('E', pOutFile); fputc('F', pOutFile); fputc('0', pOutFile);
  fputc(options.m_write_zlib_header, pOutFile);

  for (uint i = 0; i < 8; i++)
    fputc(static_cast<int>((src_file_size >> (i * 8)) & 0xFF), pOutFile);

  uint cInBufSize = TDEFLTEST_COMP_INPUT_BUFFER_SIZE;
  uint cOutBufSize = TDEFLTEST_COMP_OUTPUT_BUFFER_SIZE;
  if (options.m_randomize_buffer_sizes)
  {
    cInBufSize = 1 + (rand() % 4096);
    cOutBufSize = 1 + (rand() % 4096);
  }
  printf("Input buffer size: %u, Output buffer size: %u\n", cInBufSize, cOutBufSize);

  uint8 *in_file_buf = static_cast<uint8*>(_aligned_malloc(cInBufSize, 16));
  uint8 *out_file_buf = static_cast<uint8*>(_aligned_malloc(cOutBufSize, 16));
  if ((!in_file_buf) || (!out_file_buf))
  {
    print_error("Out of memory!\n");
    _aligned_free(in_file_buf);
    _aligned_free(out_file_buf);
    fclose(pInFile);
    fclose(pOutFile);
    return false;
  }

  uint64 src_bytes_left = src_file_size;

  uint in_file_buf_size = 0;
  uint in_file_buf_ofs = 0;

  uint64 total_output_bytes = 0;

  timer_ticks start_time = timer::get_ticks();

  z_stream zstream;
  memset(&zstream, 0, sizeof(zstream));

  timer_ticks init_start_time = timer::get_ticks();
  int status = deflateInit2(&zstream, options.m_level, Z_DEFLATED, options.m_write_zlib_header ? Z_DEFAULT_WINDOW_BITS : -Z_DEFAULT_WINDOW_BITS, 9, options.m_z_strat);
  timer_ticks total_init_time = timer::get_ticks() - init_start_time;

  if (status != Z_OK)
  {
    print_error("Failed initializing compressor!\n");
    _aligned_free(in_file_buf);
    _aligned_free(out_file_buf);
    fclose(pInFile);
    fclose(pOutFile);
    return false;
  }

  printf("deflateInit2() took %3.3fms\n", timer::ticks_to_secs(total_init_time)*1000.0f);

  uint32 x = my_max(1, (uint32)(src_file_size ^ (src_file_size >> 32)));

  for ( ; ; )
  {
    if (src_file_size)
    {
      double total_elapsed_time = timer::ticks_to_secs(timer::get_ticks() - start_time);
      double total_bytes_processed = static_cast<double>(src_file_size - src_bytes_left);
      double comp_rate = (total_elapsed_time > 0.0f) ? total_bytes_processed / total_elapsed_time : 0.0f;

#ifdef TDEFL_PRINT_OUTPUT_PROGRESS
      for (int i = 0; i < 15; i++)
        printf("\b\b\b\b");
      printf("Progress: %3.1f%%, Bytes Remaining: %3.1fMB, %3.3fMB/sec", (1.0f - (static_cast<float>(src_bytes_left) / src_file_size)) * 100.0f, src_bytes_left / 1048576.0f, comp_rate / (1024.0f * 1024.0f));
      printf("                \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b");
#endif
    }

    if (in_file_buf_ofs == in_file_buf_size)
    {
      in_file_buf_size = static_cast<uint>(my_min(cInBufSize, src_bytes_left));

      if (fread(in_file_buf, 1, in_file_buf_size, pInFile) != in_file_buf_size)
      {
        printf("\n");
        print_error("Failure reading from source file!\n");
        _aligned_free(in_file_buf);
        _aligned_free(out_file_buf);
        fclose(pInFile);
        fclose(pOutFile);
        deflateEnd(&zstream);
        return false;
      }

      src_bytes_left -= in_file_buf_size;

      in_file_buf_ofs = 0;
    }

    zstream.next_in = &in_file_buf[in_file_buf_ofs];
    zstream.avail_in = in_file_buf_size - in_file_buf_ofs;
    zstream.next_out = out_file_buf;
    zstream.avail_out = cOutBufSize;

    int flush = !src_bytes_left ? Z_FINISH : Z_NO_FLUSH;
    if ((flush == Z_NO_FLUSH) && (options.m_random_z_flushing))
    {
      RND_SHR3(x);
      if ((x & 15) == 0)
      {
        RND_SHR3(x);
        flush = (x & 31) ? Z_SYNC_FLUSH : Z_FULL_FLUSH;
      }
    }
    status = deflate(&zstream, flush);

    uint num_in_bytes = (in_file_buf_size - in_file_buf_ofs) - zstream.avail_in;
    uint num_out_bytes = cOutBufSize - zstream.avail_out;
    if (num_in_bytes)
    {
      in_file_buf_ofs += (uint)num_in_bytes;
      assert(in_file_buf_ofs <= in_file_buf_size);
    }

    if (num_out_bytes)
    {
      if (fwrite(out_file_buf, 1, static_cast<uint>(num_out_bytes), pOutFile) != num_out_bytes)
      {
        printf("\n");
        print_error("Failure writing to destination file!\n");
        _aligned_free(in_file_buf);
        _aligned_free(out_file_buf);
        fclose(pInFile);
        fclose(pOutFile);
        deflateEnd(&zstream);
        return false;
      }

      total_output_bytes += num_out_bytes;
    }

    if (status != Z_OK)
      break;
  }

#ifdef TDEFL_PRINT_OUTPUT_PROGRESS
  for (int i = 0; i < 15; i++)
  {
    printf("\b\b\b\b    \b\b\b\b");
  }
#endif

  src_bytes_left += (in_file_buf_size - in_file_buf_ofs);

  uint32 adler32 = zstream.adler;
  deflateEnd(&zstream);

  timer_ticks end_time = timer::get_ticks();
  double total_time = timer::ticks_to_secs(my_max(1, end_time - start_time));

  uint64 cmp_file_size = _ftelli64(pOutFile);

  _aligned_free(in_file_buf);
  in_file_buf = NULL;
  _aligned_free(out_file_buf);
  out_file_buf = NULL;

  fclose(pInFile);
  pInFile = NULL;
  fclose(pOutFile);
  pOutFile = NULL;

  if (status != Z_STREAM_END)
  {
    print_error("Compression failed with status %i\n", status);
    return false;
  }

  if (src_bytes_left)
  {
    print_error("Compressor failed to consume entire input file!\n");
    return false;
  }

  printf("Success\n");
  printf("Input file size: " QUAD_INT_FMT ", Compressed file size: " QUAD_INT_FMT ", Ratio: %3.2f%%\n", src_file_size, cmp_file_size, src_file_size ? ((1.0f - (static_cast<float>(cmp_file_size) / src_file_size)) * 100.0f) : 0.0f);
  printf("Compression time: %3.6f\nConsumption rate: %9.1f bytes/sec, Emission rate: %9.1f bytes/sec\n", total_time, src_file_size / total_time, cmp_file_size / total_time);
  printf("Input file adler32: 0x%08X\n", adler32);
  if (src_file_size)
  {
    if (src_file_size >= 256)
      s_max_large_comp_ratio = my_max(s_max_large_comp_ratio, cmp_file_size / (float)src_file_size);
    else
      s_max_small_comp_ratio = my_max(s_max_small_comp_ratio, cmp_file_size / (float)src_file_size);
  }
  //printf("Max small comp ratio: %f, Max large comp ratio: %f\n", s_max_small_comp_ratio, s_max_large_comp_ratio);

  return true;
}

static bool decompress_file_zlib(const char* pSrc_filename, const char *pDst_filename, comp_options options)
{
  FILE *pInFile = fopen(pSrc_filename, "rb");
  if (!pInFile)
  {
    print_error("Unable to read file: %s\n", pSrc_filename);
    return false;
  }

  _fseeki64(pInFile, 0, SEEK_END);
  uint64 src_file_size = _ftelli64(pInFile);
  _fseeki64(pInFile, 0, SEEK_SET);
  if (src_file_size < (5+9))
  {
    print_error("Compressed file is too small!\n");
    fclose(pInFile);
    return false;
  }

  int h0 = fgetc(pInFile);
  int h1 = fgetc(pInFile);
  int h2 = fgetc(pInFile);
  int h3 = fgetc(pInFile);
  int zlib_header = fgetc(pInFile);
  if ((h0 != 'D') | (h1 != 'E') || (h2 != 'F') || (h3 != '0'))
  {
    print_error("Unrecognized/invalid header in file: %s\n", pSrc_filename);
    fclose(pInFile);
    return false;
  }

  FILE *pOutFile = fopen(pDst_filename, "wb");
  if (!pOutFile)
  {
    print_error("Unable to create file: %s\n", pDst_filename);
    fclose(pInFile);
    return false;
  }

  uint64 orig_file_size = 0;
  for (uint i = 0; i < 8; i++)
    orig_file_size |= (static_cast<uint64>(fgetc(pInFile)) << (i * 8));

  int total_header_bytes = ftell(pInFile);

  // Avoid running out of memory on large files when using unbuffered decompression.
  if ((options.m_unbuffered_decompression) && (orig_file_size > 768*1024*1024))
  {
    printf("Output file is too large for unbuffered decompression - switching to streaming decompression.\n");
    options.m_unbuffered_decompression = false;
  }

  if (options.m_unbuffered_decompression)
    printf("Testing: Unbuffered decompression\n");
  else
    printf("Testing: Streaming decompression\n");

  uint cInBufSize = options.m_unbuffered_decompression ? static_cast<uint>(src_file_size) : TDEFLTEST_DECOMP_INPUT_BUFFER_SIZE;
  uint out_buf_size = options.m_unbuffered_decompression ? static_cast<uint>(orig_file_size) : TINFL_LZ_DICT_SIZE;

  if ((options.m_randomize_buffer_sizes) && (!options.m_unbuffered_decompression))
  {
    cInBufSize = 1 + (rand() % 4096);
  }

  printf("Input buffer size: %u, Output buffer size: %u\n", cInBufSize, out_buf_size);

  uint8 *in_file_buf = static_cast<uint8*>(_aligned_malloc(cInBufSize, 16));
  uint8 *out_file_buf = static_cast<uint8*>(_aligned_malloc(out_buf_size, 16));
  if ((!in_file_buf) || (!out_file_buf))
  {
    print_error("Failed allocating output buffer!\n");
    _aligned_free(in_file_buf);
    fclose(pInFile);
    fclose(pOutFile);
    return false;
  }

  uint64 src_bytes_left = src_file_size - total_header_bytes;
  uint64 dst_bytes_left = orig_file_size;

  uint in_file_buf_size = 0;
  uint in_file_buf_ofs = 0;
  uint out_file_buf_ofs = 0;

  timer_ticks start_time = timer::get_ticks();
  double decomp_only_time = 0;

  z_stream zstream;
  memset(&zstream, 0, sizeof(zstream));

  timer_ticks init_start_time = timer::get_ticks();
  int status = zlib_header ? inflateInit(&zstream) : inflateInit2(&zstream, -Z_DEFAULT_WINDOW_BITS);
  timer_ticks total_init_time = timer::get_ticks() - init_start_time;
  if (status != Z_OK)
  {
    print_error("Failed initializing decompressor!\n");
    _aligned_free(in_file_buf);
    _aligned_free(out_file_buf);
    fclose(pInFile);
    fclose(pOutFile);
    return false;
  }

  printf("inflateInit() took %3.3fms\n", timer::ticks_to_secs(total_init_time)*1000.0f);

  for ( ; ; )
  {
    if (in_file_buf_ofs == in_file_buf_size)
    {
      in_file_buf_size = static_cast<uint>(my_min(cInBufSize, src_bytes_left));

      if (fread(in_file_buf, 1, in_file_buf_size, pInFile) != in_file_buf_size)
      {
        print_error("Failure reading from source file!\n");
        _aligned_free(in_file_buf);
        _aligned_free(out_file_buf);
        deflateEnd(&zstream);
        fclose(pInFile);
        fclose(pOutFile);
        return false;
      }

      src_bytes_left -= in_file_buf_size;

      in_file_buf_ofs = 0;
    }

    uint num_in_bytes = (in_file_buf_size - in_file_buf_ofs);
    uint num_out_bytes = (out_buf_size - out_file_buf_ofs);
    zstream.next_in = in_file_buf + in_file_buf_ofs;
    zstream.avail_in = num_in_bytes;
    zstream.next_out = out_file_buf + out_file_buf_ofs;
    zstream.avail_out = num_out_bytes;

    {
      timer decomp_only_timer;
      decomp_only_timer.start();
      status = inflate(&zstream, options.m_unbuffered_decompression ? Z_FINISH : Z_SYNC_FLUSH);
      decomp_only_time += decomp_only_timer.get_elapsed_secs();
    }
    num_in_bytes -= zstream.avail_in;
    num_out_bytes -= zstream.avail_out;

    if (num_in_bytes)
    {
      in_file_buf_ofs += (uint)num_in_bytes;
      assert(in_file_buf_ofs <= in_file_buf_size);
    }

    out_file_buf_ofs += (uint)num_out_bytes;

    if ((out_file_buf_ofs == out_buf_size) || (status == Z_STREAM_END))
    {
      if (fwrite(out_file_buf, 1, static_cast<uint>(out_file_buf_ofs), pOutFile) != out_file_buf_ofs)
      {
        print_error("Failure writing to destination file!\n");
        _aligned_free(in_file_buf);
        _aligned_free(out_file_buf);
        inflateEnd(&zstream);
        fclose(pInFile);
        fclose(pOutFile);
        return false;
      }
      out_file_buf_ofs = 0;
    }

    if (num_out_bytes > dst_bytes_left)
    {
      print_error("Decompressor wrote too many bytes to destination file!\n");
      _aligned_free(in_file_buf);
      _aligned_free(out_file_buf);
      inflateEnd(&zstream);
      fclose(pInFile);
      fclose(pOutFile);
      return false;
    }
    dst_bytes_left -= num_out_bytes;

    if (status != Z_OK)
      break;
  }
  _aligned_free(in_file_buf);
  in_file_buf = NULL;

  _aligned_free(out_file_buf);
  out_file_buf = NULL;

  src_bytes_left += (in_file_buf_size - in_file_buf_ofs);

  uint32 adler32 = zstream.adler;
  inflateEnd(&zstream);

  timer_ticks end_time = timer::get_ticks();
  double total_time = timer::ticks_to_secs(my_max(1, end_time - start_time));

  fclose(pInFile);
  pInFile = NULL;

  fclose(pOutFile);
  pOutFile = NULL;

  if (status != Z_STREAM_END)
  {
    print_error("Decompression FAILED with status %i\n", status);
    return false;
  }

  if ((src_file_size < UINT_MAX) && (orig_file_size < UINT_MAX))
  {
    if ((((size_t)zstream.total_in + total_header_bytes) != src_file_size) || (zstream.total_out != orig_file_size))
    {
      print_error("Decompression FAILED to consume all input or write all expected output!\n");
      return false;
    }
  }

  if (dst_bytes_left)
  {
    print_error("Decompressor FAILED to output the entire output file!\n");
    return false;
  }

  if (src_bytes_left)
  {
    print_error("Decompressor FAILED to read " QUAD_INT_FMT " bytes from input buffer\n", src_bytes_left);
  }

  printf("Success\n");
  printf("Source file size: " QUAD_INT_FMT ", Decompressed file size: " QUAD_INT_FMT "\n", src_file_size, orig_file_size);
  if (zlib_header) printf("Decompressed adler32: 0x%08X\n", adler32);
  printf("Overall decompression time (decompression init+I/O+decompression): %3.6f\n  Consumption rate: %9.1f bytes/sec, Decompression rate: %9.1f bytes/sec\n", total_time, src_file_size / total_time, orig_file_size / total_time);
  printf("Decompression only time (not counting decompression init or I/O): %3.6f\n  Consumption rate: %9.1f bytes/sec, Decompression rate: %9.1f bytes/sec\n", decomp_only_time, src_file_size / decomp_only_time, orig_file_size / decomp_only_time);

  return true;
}

static bool compare_files(const char *pFilename1, const char* pFilename2)
{
  FILE* pFile1 = open_file_with_retries(pFilename1, "rb");
  if (!pFile1)
  {
    print_error("Failed opening file: %s\n", pFilename1);
    return false;
  }

  FILE* pFile2 = open_file_with_retries(pFilename2, "rb");
  if (!pFile2)
  {
    print_error("Failed opening file: %s\n", pFilename2);
    fclose(pFile1);
    return false;
  }

  _fseeki64(pFile1, 0, SEEK_END);
  int64 fileSize1 = _ftelli64(pFile1);
  _fseeki64(pFile1, 0, SEEK_SET);

  _fseeki64(pFile2, 0, SEEK_END);
  int64 fileSize2 = _ftelli64(pFile2);
  _fseeki64(pFile2, 0, SEEK_SET);

  if (fileSize1 != fileSize2)
  {
    print_error("Files to compare are not the same size: %I64i vs. %I64i.\n", fileSize1, fileSize2);
    fclose(pFile1);
    fclose(pFile2);
    return false;
  }

  const uint cBufSize = 1024 * 1024;
  std::vector<uint8> buf1(cBufSize);
  std::vector<uint8> buf2(cBufSize);

  int64 bytes_remaining = fileSize1;
  while (bytes_remaining)
  {
    const uint bytes_to_read = static_cast<uint>(my_min(cBufSize, bytes_remaining));

    if (fread(&buf1.front(), bytes_to_read, 1, pFile1) != 1)
    {
      print_error("Failed reading from file: %s\n", pFilename1);
      fclose(pFile1);
      fclose(pFile2);
      return false;
    }

    if (fread(&buf2.front(), bytes_to_read, 1, pFile2) != 1)
    {
      print_error("Failed reading from file: %s\n", pFilename2);
      fclose(pFile1);
      fclose(pFile2);
      return false;
    }

    if (memcmp(&buf1.front(), &buf2.front(), bytes_to_read) != 0)
    {
      print_error("File data comparison failed!\n");
      fclose(pFile1);
      fclose(pFile2);
      return false;
    }

    bytes_remaining -= bytes_to_read;
  }

  fclose(pFile1);
  fclose(pFile2);
  return true;
}

static bool zip_create(const char *pZip_filename, const char *pSrc_filename)
{
  mz_zip_archive zip;
  memset(&zip, 0, sizeof(zip));
  if ((rand() % 100) >= 10)
    zip.m_file_offset_alignment = 1 << (rand() & 15);
  if (!mz_zip_writer_init_file(&zip, pZip_filename, 65537))
  {
    print_error("Failed creating zip archive \"%s\" (1)!\n", pZip_filename);
    return false;
  }

  mz_bool success = MZ_TRUE;

  const char *pStr = "This is a test!This is a test!This is a test!\n";
  size_t comp_size;
  void *pComp_data = tdefl_compress_mem_to_heap(pStr, strlen(pStr), &comp_size, 256);
  success &= mz_zip_writer_add_mem_ex(&zip, "precomp.txt", pComp_data, comp_size, "Comment", (uint16)strlen("Comment"), MZ_ZIP_FLAG_COMPRESSED_DATA, strlen(pStr), mz_crc32(MZ_CRC32_INIT, (const uint8 *)pStr, strlen(pStr)));

  success &= mz_zip_writer_add_mem(&zip, "cool/", NULL, 0, 0);

  success &= mz_zip_writer_add_mem(&zip, "1.txt", pStr, strlen(pStr), 9);
  int n = rand() & 4095;
  for (int i = 0; i < n; i++)
  {
    char name[256], buf[256], comment[256];
    sprintf(name, "t%u.txt", i);
    sprintf(buf, "%u\n", i*5377);
    sprintf(comment, "comment: %u\n", i);
    success &= mz_zip_writer_add_mem_ex(&zip, name, buf, strlen(buf), comment, (uint16)strlen(comment), i % 10, 0, 0);
  }

  const char *pTestComment = "test comment";
  success &= mz_zip_writer_add_file(&zip, "test.bin", pSrc_filename, pTestComment, (uint16)strlen(pTestComment), 9);

  if (ensure_file_exists_and_is_readable("changelog.txt"))
    success &= mz_zip_writer_add_file(&zip, "changelog.txt", "changelog.txt", "This is a comment", (uint16)strlen("This is a comment"), 9);

  if (!success)
  {
    mz_zip_writer_end(&zip);
    remove(pZip_filename);
    print_error("Failed creating zip archive \"%s\" (2)!\n", pZip_filename);
    return false;
  }

  if (!mz_zip_writer_finalize_archive(&zip))
  {
    mz_zip_writer_end(&zip);
    remove(pZip_filename);
    print_error("Failed creating zip archive \"%s\" (3)!\n", pZip_filename);
    return false;
  }

  mz_zip_writer_end(&zip);

  struct FILE_STAT_STRUCT stat_buf;
  FILE_STAT(pZip_filename, &stat_buf);
  uint64 actual_file_size = stat_buf.st_size;
  if (zip.m_archive_size != actual_file_size)
  {
    print_error("Archive's actual size and zip archive object's size differ for file \"%s\"!\n", pZip_filename);
    return false;
  }

  printf("Created zip file \"%s\", file size: " QUAD_INT_FMT "\n", pZip_filename, zip.m_archive_size);
  return true;
}

static size_t zip_write_callback(void *pOpaque, mz_uint64 ofs, const void *pBuf, size_t n)
{
  (void)pOpaque, (void)ofs, (void)pBuf, (void)n;
  return n;
}

static bool zip_extract(const char *pZip_filename, const char *pDst_filename)
{
  mz_zip_archive zip;
  memset(&zip, 0, sizeof(zip));
  if (!mz_zip_reader_init_file(&zip, pZip_filename, 0))
  {
    print_error("Failed opening zip archive \"%s\"!\n", pZip_filename);
    return false;
  }

  int file_index = mz_zip_reader_locate_file(&zip, "test.bin", "test Comment", 0);
  int alt_file_index = mz_zip_reader_locate_file(&zip, "test.bin", "test Comment e", 0);
  if ((file_index < 0) || (alt_file_index >= 0))
  {
    print_error("Archive \"%s\" is missing test.bin file!\n", pZip_filename);
    mz_zip_reader_end(&zip);
    return false;
  }

  alt_file_index = mz_zip_reader_locate_file(&zip, "test.bin", NULL, 0);
  if (alt_file_index != file_index)
  {
    print_error("mz_zip_reader_locate_file() failed!\n", pZip_filename);
    mz_zip_reader_end(&zip);
    return false;
  }

  if (!mz_zip_reader_extract_to_file(&zip, file_index, pDst_filename, 0))
  {
    print_error("Failed extracting test.bin from archive \"%s\" err: %s!\n", pZip_filename, mz_zip_get_error_string(mz_zip_get_last_error(&zip)));
    mz_zip_reader_end(&zip);
    return false;
  }

  for (uint i = 0; i < mz_zip_reader_get_num_files(&zip); i++)
  {
    mz_zip_archive_file_stat stat;
    if (!mz_zip_reader_file_stat(&zip, i, &stat))
    {
      print_error("Failed testing archive -1 \"%s\" err: %s!\n", pZip_filename, mz_zip_get_error_string(mz_zip_get_last_error(&zip)));
      mz_zip_reader_end(&zip);
      return false;
    }
    //printf("\"%s\" %I64u %I64u\n", stat.m_filename, stat.m_comp_size, stat.m_uncomp_size);
    size_t size = 0;

    mz_bool status = mz_zip_reader_extract_to_callback(&zip, i, zip_write_callback, NULL, 0);
    if (!status)
    {
      print_error("Failed testing archive -2 \"%s\" err: %s!\n", pZip_filename, mz_zip_get_error_string(mz_zip_get_last_error(&zip)));
      mz_zip_reader_end(&zip);
      return false;
    }

    if (stat.m_uncomp_size<100*1024*1024)
    {
        void *p = mz_zip_reader_extract_to_heap(&zip, i, &size, 0);
        if (!p)
        {
            print_error("Failed testing archive -3 \"%s\" err: %s!\n", pZip_filename, mz_zip_get_error_string(mz_zip_get_last_error(&zip)));
            mz_zip_reader_end(&zip);
            return false;
        }
        free(p);
    }

    if (stat.m_uncomp_size<100*1024*1024)
    {
        /* Use iterative reader to read onto heap in one big chunk */
        mz_zip_reader_extract_iter_state *pIter = mz_zip_reader_extract_iter_new(&zip, i, 0);