3 * SOFTWARE COPYRIGHT NOTICE AGREEMENT
4 * This software and its documentation are copyright 2008 by the
5 * Broad Institute/Massachusetts Institute of Technology. All rights are reserved.
7 * This software is supplied without any warranty or guaranteed support whatsoever.
8 * Neither the Broad Institute nor MIT can be responsible for its use, misuse,
13 2009-06-29 by lh3: cache recent uncompressed blocks.
14 2009-06-25 by lh3: optionally use my knetfile library to access file on a FTP.
15 2009-06-12 by lh3: support a mode string like "wu" where 'u' for uncompressed output */
22 #include <sys/types.h>
32 KHASH_MAP_INIT_INT64(cache, cache_t)
35 #define ftello(fp) ftell(fp)
36 #define fseeko(fp, offset, whence) fseek(fp, offset, whence)
38 extern off_t ftello(FILE *stream);
39 extern int fseeko(FILE *stream, off_t offset, int whence);
42 typedef int8_t bgzf_byte_t;
44 static const int DEFAULT_BLOCK_SIZE = 64 * 1024;
45 static const int MAX_BLOCK_SIZE = 64 * 1024;
47 static const int BLOCK_HEADER_LENGTH = 18;
48 static const int BLOCK_FOOTER_LENGTH = 8;
50 static const int GZIP_ID1 = 31;
51 static const int GZIP_ID2 = 139;
52 static const int CM_DEFLATE = 8;
53 static const int FLG_FEXTRA = 4;
54 static const int OS_UNKNOWN = 255;
55 static const int BGZF_ID1 = 66; // 'B'
56 static const int BGZF_ID2 = 67; // 'C'
57 static const int BGZF_LEN = 2;
58 static const int BGZF_XLEN = 6; // BGZF_LEN+4
60 static const int GZIP_WINDOW_BITS = -15; // no zlib header
61 static const int Z_DEFAULT_MEM_LEVEL = 8;
66 packInt16(uint8_t* buffer, uint16_t value)
69 buffer[1] = value >> 8;
74 unpackInt16(const uint8_t* buffer)
76 return (buffer[0] | (buffer[1] << 8));
81 packInt32(uint8_t* buffer, uint32_t value)
84 buffer[1] = value >> 8;
85 buffer[2] = value >> 16;
86 buffer[3] = value >> 24;
91 bgzf_min(int x, int y)
93 return (x < y) ? x : y;
98 report_error(BGZF* fp, const char* message) {
102 static BGZF *bgzf_read_init()
105 fp = calloc(1, sizeof(BGZF));
106 fp->uncompressed_block_size = MAX_BLOCK_SIZE;
107 fp->uncompressed_block = malloc(MAX_BLOCK_SIZE);
108 fp->compressed_block_size = MAX_BLOCK_SIZE;
109 fp->compressed_block = malloc(MAX_BLOCK_SIZE);
111 fp->cache = kh_init(cache);
120 knetFile *file = knet_dopen(fd, "r");
122 FILE* file = fdopen(fd, "r");
125 if (file == 0) return 0;
126 fp = bgzf_read_init();
127 fp->file_descriptor = fd;
139 open_write(int fd, bool is_uncompressed)
141 FILE* file = fdopen(fd, "w");
143 if (file == 0) return 0;
144 fp = malloc(sizeof(BGZF));
145 fp->file_descriptor = fd;
147 fp->owned_file = 0; fp->is_uncompressed = is_uncompressed;
153 fp->uncompressed_block_size = DEFAULT_BLOCK_SIZE;
154 fp->uncompressed_block = NULL;
155 fp->compressed_block_size = MAX_BLOCK_SIZE;
156 fp->compressed_block = malloc(MAX_BLOCK_SIZE);
157 fp->block_address = 0;
158 fp->block_offset = 0;
159 fp->block_length = 0;
165 bgzf_open(const char* __restrict path, const char* __restrict mode)
168 if (mode[0] == 'r' || mode[0] == 'R') { /* The reading mode is preferred. */
170 knetFile *file = knet_open(path, mode);
171 if (file == 0) return 0;
172 fp = bgzf_read_init();
173 fp->file_descriptor = -1;
177 int oflag = O_RDONLY;
178 int fd = open(path, oflag);
179 if (fd == -1) return 0;
182 } else if (mode[0] == 'w' || mode[0] == 'W') {
183 int oflag = O_WRONLY | O_CREAT | O_TRUNC;
184 int fd = open(path, oflag, 0644);
185 if (fd == -1) return 0;
186 fp = open_write(fd, strstr(mode, "u")? 1 : 0);
195 bgzf_fdopen(int fd, const char * __restrict mode)
197 if (fd == -1) return 0;
198 if (mode[0] == 'r' || mode[0] == 'R') {
199 return open_read(fd);
200 } else if (mode[0] == 'w' || mode[0] == 'W') {
201 return open_write(fd, strstr(mode, "u")? 1 : 0);
209 deflate_block(BGZF* fp, int block_length)
211 // Deflate the block in fp->uncompressed_block into fp->compressed_block.
212 // Also adds an extra field that stores the compressed block length.
214 bgzf_byte_t* buffer = fp->compressed_block;
215 int buffer_size = fp->compressed_block_size;
218 buffer[0] = GZIP_ID1;
219 buffer[1] = GZIP_ID2;
220 buffer[2] = CM_DEFLATE;
221 buffer[3] = FLG_FEXTRA;
222 buffer[4] = 0; // mtime
227 buffer[9] = OS_UNKNOWN;
228 buffer[10] = BGZF_XLEN;
230 buffer[12] = BGZF_ID1;
231 buffer[13] = BGZF_ID2;
232 buffer[14] = BGZF_LEN;
234 buffer[16] = 0; // placeholder for block length
237 // loop to retry for blocks that do not compress enough
238 int input_length = block_length;
239 int compressed_length = 0;
241 int compress_level = fp->is_uncompressed? 0 : Z_DEFAULT_COMPRESSION;
245 zs.next_in = fp->uncompressed_block;
246 zs.avail_in = input_length;
247 zs.next_out = (void*)&buffer[BLOCK_HEADER_LENGTH];
248 zs.avail_out = buffer_size - BLOCK_HEADER_LENGTH - BLOCK_FOOTER_LENGTH;
250 int status = deflateInit2(&zs, compress_level, Z_DEFLATED,
251 GZIP_WINDOW_BITS, Z_DEFAULT_MEM_LEVEL, Z_DEFAULT_STRATEGY);
252 if (status != Z_OK) {
253 report_error(fp, "deflate init failed");
256 status = deflate(&zs, Z_FINISH);
257 if (status != Z_STREAM_END) {
259 if (status == Z_OK) {
260 // Not enough space in buffer.
261 // Can happen in the rare case the input doesn't compress enough.
262 // Reduce the amount of input until it fits.
263 input_length -= 1024;
264 if (input_length <= 0) {
265 // should never happen
266 report_error(fp, "input reduction failed");
271 report_error(fp, "deflate failed");
274 status = deflateEnd(&zs);
275 if (status != Z_OK) {
276 report_error(fp, "deflate end failed");
279 compressed_length = zs.total_out;
280 compressed_length += BLOCK_HEADER_LENGTH + BLOCK_FOOTER_LENGTH;
281 if (compressed_length > MAX_BLOCK_SIZE) {
282 // should never happen
283 report_error(fp, "deflate overflow");
289 packInt16((uint8_t*)&buffer[16], compressed_length-1);
290 uint32_t crc = crc32(0L, NULL, 0L);
291 crc = crc32(crc, fp->uncompressed_block, input_length);
292 packInt32((uint8_t*)&buffer[compressed_length-8], crc);
293 packInt32((uint8_t*)&buffer[compressed_length-4], input_length);
295 int remaining = block_length - input_length;
297 if (remaining > input_length) {
298 // should never happen (check so we can use memcpy)
299 report_error(fp, "remainder too large");
302 memcpy(fp->uncompressed_block,
303 fp->uncompressed_block + input_length,
306 fp->block_offset = remaining;
307 return compressed_length;
312 inflate_block(BGZF* fp, int block_length)
314 // Inflate the block in fp->compressed_block into fp->uncompressed_block
319 zs.next_in = fp->compressed_block + 18;
320 zs.avail_in = block_length - 16;
321 zs.next_out = fp->uncompressed_block;
322 zs.avail_out = fp->uncompressed_block_size;
324 int status = inflateInit2(&zs, GZIP_WINDOW_BITS);
325 if (status != Z_OK) {
326 report_error(fp, "inflate init failed");
329 status = inflate(&zs, Z_FINISH);
330 if (status != Z_STREAM_END) {
332 report_error(fp, "inflate failed");
335 status = inflateEnd(&zs);
336 if (status != Z_OK) {
337 report_error(fp, "inflate failed");
345 check_header(const bgzf_byte_t* header)
347 return (header[0] == GZIP_ID1 &&
348 header[1] == (bgzf_byte_t) GZIP_ID2 &&
349 header[2] == Z_DEFLATED &&
350 (header[3] & FLG_FEXTRA) != 0 &&
351 unpackInt16((uint8_t*)&header[10]) == BGZF_XLEN &&
352 header[12] == BGZF_ID1 &&
353 header[13] == BGZF_ID2 &&
354 unpackInt16((uint8_t*)&header[14]) == BGZF_LEN);
357 static void free_cache(BGZF *fp)
360 khash_t(cache) *h = (khash_t(cache)*)fp->cache;
361 if (fp->open_mode != 'r') return;
362 for (k = kh_begin(h); k < kh_end(h); ++k)
363 if (kh_exist(h, k)) free(kh_val(h, k).block);
364 kh_destroy(cache, h);
367 static int load_block_from_cache(BGZF *fp, int64_t block_address)
371 khash_t(cache) *h = (khash_t(cache)*)fp->cache;
372 k = kh_get(cache, h, block_address);
373 if (k == kh_end(h)) return 0;
375 if (fp->block_length != 0) fp->block_offset = 0;
376 fp->block_address = block_address;
377 fp->block_length = p->size;
378 memcpy(fp->uncompressed_block, p->block, MAX_BLOCK_SIZE);
380 knet_seek(fp->x.fpr, p->end_offset, SEEK_SET);
382 fseeko(fp->file, p->end_offset, SEEK_SET);
387 static void cache_block(BGZF *fp, int size)
392 khash_t(cache) *h = (khash_t(cache)*)fp->cache;
393 if (MAX_BLOCK_SIZE >= fp->cache_size) return;
394 if ((kh_size(h) + 1) * MAX_BLOCK_SIZE > fp->cache_size) {
395 /* A better way would be to remove the oldest block in the
396 * cache, but here we remove a random one for simplicity. This
397 * should not have a big impact on performance. */
398 for (k = kh_begin(h); k < kh_end(h); ++k)
399 if (kh_exist(h, k)) break;
401 free(kh_val(h, k).block);
405 k = kh_put(cache, h, fp->block_address, &ret);
406 if (ret == 0) return; // if this happens, a bug!
408 p->size = fp->block_length;
409 p->end_offset = fp->block_address + size;
410 p->block = malloc(MAX_BLOCK_SIZE);
411 memcpy(kh_val(h, k).block, fp->uncompressed_block, MAX_BLOCK_SIZE);
418 bgzf_byte_t header[BLOCK_HEADER_LENGTH];
421 int64_t block_address = knet_tell(fp->x.fpr);
422 if (load_block_from_cache(fp, block_address)) return 0;
423 int count = knet_read(fp->x.fpr, header, sizeof(header));
425 int64_t block_address = ftello(fp->file);
426 if (load_block_from_cache(fp, block_address)) return 0;
427 int count = fread(header, 1, sizeof(header), fp->file);
430 fp->block_length = 0;
434 if (count != sizeof(header)) {
435 report_error(fp, "read failed");
438 if (!check_header(header)) {
439 report_error(fp, "invalid block header");
442 int block_length = unpackInt16((uint8_t*)&header[16]) + 1;
443 bgzf_byte_t* compressed_block = (bgzf_byte_t*) fp->compressed_block;
444 memcpy(compressed_block, header, BLOCK_HEADER_LENGTH);
445 int remaining = block_length - BLOCK_HEADER_LENGTH;
447 count = knet_read(fp->x.fpr, &compressed_block[BLOCK_HEADER_LENGTH], remaining);
449 count = fread(&compressed_block[BLOCK_HEADER_LENGTH], 1, remaining, fp->file);
451 if (count != remaining) {
452 report_error(fp, "read failed");
456 count = inflate_block(fp, block_length);
460 if (fp->block_length != 0) {
461 // Do not reset offset if this read follows a seek.
462 fp->block_offset = 0;
464 fp->block_address = block_address;
465 fp->block_length = count;
466 cache_block(fp, size);
471 bgzf_read(BGZF* fp, void* data, int length)
476 if (fp->open_mode != 'r') {
477 report_error(fp, "file not open for reading");
482 bgzf_byte_t* output = data;
483 while (bytes_read < length) {
484 int available = fp->block_length - fp->block_offset;
485 if (available <= 0) {
486 if (read_block(fp) != 0) {
489 available = fp->block_length - fp->block_offset;
490 if (available <= 0) {
494 int copy_length = bgzf_min(length-bytes_read, available);
495 bgzf_byte_t* buffer = fp->uncompressed_block;
496 memcpy(output, buffer + fp->block_offset, copy_length);
497 fp->block_offset += copy_length;
498 output += copy_length;
499 bytes_read += copy_length;
501 if (fp->block_offset == fp->block_length) {
503 fp->block_address = knet_tell(fp->x.fpr);
505 fp->block_address = ftello(fp->file);
507 fp->block_offset = 0;
508 fp->block_length = 0;
515 flush_block(BGZF* fp)
517 while (fp->block_offset > 0) {
518 int block_length = deflate_block(fp, fp->block_offset);
519 if (block_length < 0) {
523 int count = fwrite(fp->compressed_block, 1, block_length, fp->x.fpw);
525 int count = fwrite(fp->compressed_block, 1, block_length, fp->file);
527 if (count != block_length) {
528 report_error(fp, "write failed");
531 fp->block_address += block_length;
537 bgzf_write(BGZF* fp, const void* data, int length)
539 if (fp->open_mode != 'w') {
540 report_error(fp, "file not open for writing");
544 if (fp->uncompressed_block == NULL) {
545 fp->uncompressed_block = malloc(fp->uncompressed_block_size);
548 const bgzf_byte_t* input = data;
549 int block_length = fp->uncompressed_block_size;
550 int bytes_written = 0;
551 while (bytes_written < length) {
552 int copy_length = bgzf_min(block_length - fp->block_offset, length - bytes_written);
553 bgzf_byte_t* buffer = fp->uncompressed_block;
554 memcpy(buffer + fp->block_offset, input, copy_length);
555 fp->block_offset += copy_length;
556 input += copy_length;
557 bytes_written += copy_length;
558 if (fp->block_offset == block_length) {
559 if (flush_block(fp) != 0) {
564 return bytes_written;
570 if (fp->open_mode == 'w') {
571 if (flush_block(fp) != 0) {
574 { // add an empty block
575 int count, block_length = deflate_block(fp, 0);
577 count = fwrite(fp->compressed_block, 1, block_length, fp->x.fpw);
579 count = fwrite(fp->compressed_block, 1, block_length, fp->file);
583 if (fflush(fp->x.fpw) != 0) {
585 if (fflush(fp->file) != 0) {
587 report_error(fp, "flush failed");
591 if (fp->owned_file) {
594 if (fp->open_mode == 'w') ret = fclose(fp->x.fpw);
595 else ret = knet_close(fp->x.fpr);
596 if (ret != 0) return -1;
598 if (fclose(fp->file) != 0) {
603 free(fp->uncompressed_block);
604 free(fp->compressed_block);
613 return ((fp->block_address << 16) | (fp->block_offset & 0xFFFF));
616 void bgzf_set_cache_size(BGZF *fp, int cache_size)
618 if (fp) fp->cache_size = cache_size;
621 int bgzf_check_EOF(BGZF *fp)
623 static uint8_t magic[28] = "\037\213\010\4\0\0\0\0\0\377\6\0\102\103\2\0\033\0\3\0\0\0\0\0\0\0\0\0";
627 offset = knet_tell(fp->x.fpr);
628 if (knet_seek(fp->x.fpr, -28, SEEK_END) != 0) return -1;
629 knet_read(fp->x.fpr, buf, 28);
630 knet_seek(fp->x.fpr, offset, SEEK_SET);
632 offset = ftello(fp->file);
633 if (fseeko(fp->file, -28, SEEK_END) != 0) return -1;
634 fread(buf, 1, 28, fp->file);
635 fseeko(fp->file, offset, SEEK_SET);
637 return (memcmp(magic, buf, 28) == 0)? 1 : 0;
641 bgzf_seek(BGZF* fp, int64_t pos, int where)
643 if (fp->open_mode != 'r') {
644 report_error(fp, "file not open for read");
647 if (where != SEEK_SET) {
648 report_error(fp, "unimplemented seek option");
651 int block_offset = pos & 0xFFFF;
652 int64_t block_address = (pos >> 16) & 0xFFFFFFFFFFFFLL;
654 if (knet_seek(fp->x.fpr, block_address, SEEK_SET) != 0) {
656 if (fseeko(fp->file, block_address, SEEK_SET) != 0) {
658 report_error(fp, "seek failed");
661 fp->block_length = 0; // indicates current block is not loaded
662 fp->block_address = block_address;
663 fp->block_offset = block_offset;