1 //-----------------------------------------------------------------------------
2 // This code is licensed to you under the terms of the GNU GPL, version 2 or,
3 // at your option, any later version. See the LICENSE.txt file for the text of
5 //-----------------------------------------------------------------------------
6 // Flasher frontend tool
7 //-----------------------------------------------------------------------------
15 #define MAX(a,b) ((a)>(b)?(a):(b))
18 #define COMPRESS_LEVEL 9 // use best possible compression
20 #define FPGA_CONFIG_SIZE 42175
21 static uint8_t fpga_config
[FPGA_CONFIG_SIZE
];
23 static void usage(char *argv0
)
25 fprintf(stderr
, "Usage: %s <infile> <outfile>\n\n", argv0
);
29 static voidpf
fpga_deflate_malloc(voidpf opaque
, uInt items
, uInt size
)
31 fprintf(stderr
, "zlib requested %d bytes\n", items
*size
);
32 return malloc(items
*size
);
36 static void fpga_deflate_free(voidpf opaque
, voidpf address
)
38 fprintf(stderr
, "zlib frees memory\n");
43 int zlib_compress(FILE *infile
, FILE *outfile
)
46 z_stream compressed_fpga_stream
;
48 // read the input file into fpga_config[] and count occurrences of each symbol:
50 while(!feof(infile
)) {
54 if (i
> FPGA_CONFIG_SIZE
+1) {
55 fprintf(stderr
, "Input file too big (> %d bytes). This is probably not a PM3 FPGA config file.", FPGA_CONFIG_SIZE
);
62 // initialize zlib structures
63 compressed_fpga_stream
.next_in
= fpga_config
;
64 compressed_fpga_stream
.avail_in
= i
;
65 compressed_fpga_stream
.zalloc
= fpga_deflate_malloc
;
66 compressed_fpga_stream
.zfree
= fpga_deflate_free
;
68 // estimate the size of the compressed output
69 unsigned int outsize_max
= deflateBound(&compressed_fpga_stream
, compressed_fpga_stream
.avail_in
);
70 uint8_t *outbuf
= malloc(outsize_max
);
71 compressed_fpga_stream
.next_out
= outbuf
;
72 compressed_fpga_stream
.avail_out
= outsize_max
;
73 fprintf(stderr
, "Allocated %d bytes for output file (estimated upper bound)\n", outsize_max
);
75 ret
= deflateInit(&compressed_fpga_stream
, COMPRESS_LEVEL
);
78 ret
= deflate(&compressed_fpga_stream
, Z_FINISH
);
81 fprintf(stderr
, "produced %d bytes of output\n", compressed_fpga_stream
.total_out
);
83 if (ret
!= Z_STREAM_END
) {
84 fprintf(stderr
, "Error in deflate(): %d %s\n", ret
, compressed_fpga_stream
.msg
);
86 deflateEnd(&compressed_fpga_stream
);
92 for (i
= 0; i
< compressed_fpga_stream
.total_out
; i
++) {
93 fputc(outbuf
[i
], outfile
);
97 deflateEnd(&compressed_fpga_stream
);
107 int main(int argc
, char **argv
)
116 infilename
= argv
[1];
117 outfilename
= argv
[2];
120 FILE *infile
= fopen(infilename
, "rb");
121 if (infile
== NULL
) {
122 fprintf(stderr
, "Error. Cannot open input file %s", infilename
);
126 FILE *outfile
= fopen(outfilename
, "wb");
127 if (outfile
== NULL
) {
128 fprintf(stderr
, "Error. Cannot open output file %s", outfilename
);
133 return zlib_compress(infile
, outfile
);