+
+static int get_from_fpga_stream(z_streamp compressed_fpga_stream, uint8_t *output_buffer)
+{
+ if (fpga_image_ptr == compressed_fpga_stream->next_out) { // need more data
+ compressed_fpga_stream->next_out = output_buffer;
+ compressed_fpga_stream->avail_out = OUTPUT_BUFFER_LEN;
+ fpga_image_ptr = output_buffer;
+ int res = inflate(compressed_fpga_stream, Z_SYNC_FLUSH);
+ if (res != Z_OK) {
+ Dbprintf("inflate returned: %d, %s", res, compressed_fpga_stream->msg);
+ }
+ if (res < 0) {
+ return res;
+ }
+ }
+
+ return *fpga_image_ptr++;
+}
+
+
+static voidpf fpga_inflate_malloc(voidpf opaque, uInt items, uInt size)
+{
+ Dbprintf("zlib requested %d bytes", items*size);
+ return BigBuf_malloc(items*size);
+}
+
+
+static void fpga_inflate_free(voidpf opaque, voidpf address)
+{
+ Dbprintf("zlib frees memory");
+ BigBuf_free_keep_EM();
+}
+
+
+static bool reset_fpga_stream(int bitstream_version, z_streamp compressed_fpga_stream, uint8_t *output_buffer)
+{
+ uint8_t header[FPGA_BITSTREAM_FIXED_HEADER_SIZE];
+ uint8_t *fpga_image_start;
+ uint32_t fpga_image_size;
+
+ if (bitstream_version == FPGA_BITSTREAM_LF) {
+ fpga_image_start = &_binary_fpga_lf_bit_start;
+ fpga_image_size = (uint32_t)&_binary_fpga_lf_bit_end - (uint32_t)&_binary_fpga_lf_bit_start;
+ } else if (bitstream_version == FPGA_BITSTREAM_HF) {
+ fpga_image_start = &_binary_fpga_hf_bit_start;
+ fpga_image_size = (uint32_t)&_binary_fpga_hf_bit_end - (uint32_t)&_binary_fpga_hf_bit_start;
+ } else {
+ return false;
+ }
+
+ // initialize z_stream structure for inflate:
+ compressed_fpga_stream->next_in = fpga_image_start;
+ compressed_fpga_stream->avail_in = fpga_image_size;
+ compressed_fpga_stream->next_out = output_buffer;
+ compressed_fpga_stream->avail_out = OUTPUT_BUFFER_LEN;
+ compressed_fpga_stream->zalloc = &fpga_inflate_malloc;
+ compressed_fpga_stream->zfree = &fpga_inflate_free;
+
+ inflateInit2(compressed_fpga_stream, 15);
+
+ fpga_image_ptr = output_buffer;
+
+ for (uint16_t i = 0; i < FPGA_BITSTREAM_FIXED_HEADER_SIZE; i++) {
+ header[i] = get_from_fpga_stream(compressed_fpga_stream, output_buffer);
+ }
+
+ // Check for a valid .bit file (starts with _bitparse_fixed_header)
+ if(memcmp(_bitparse_fixed_header, header, FPGA_BITSTREAM_FIXED_HEADER_SIZE) == 0) {
+ return true;
+ } else {
+ return false;
+ }
+}
+
+