]> git.donarmstrong.com Git - samtools.git/blob - bgzf.c
compatible with Windows binary files
[samtools.git] / bgzf.c
1 /*
2  * The Broad Institute
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.
6  *
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,
9  * or functionality.
10  */
11
12 /*
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 */
16
17 #include <stdio.h>
18 #include <stdlib.h>
19 #include <string.h>
20 #include <unistd.h>
21 #include <fcntl.h>
22 #include <sys/types.h>
23 #include <sys/stat.h>
24 #include "bgzf.h"
25
26 #include "khash.h"
27 typedef struct {
28         int size;
29         uint8_t *block;
30         int64_t end_offset;
31 } cache_t;
32 KHASH_MAP_INIT_INT64(cache, cache_t)
33
34 #if defined(_WIN32) || defined(_MSC_VER)
35 #define ftello(fp) ftell(fp)
36 #define fseeko(fp, offset, whence) fseek(fp, offset, whence)
37 #else
38 extern off_t ftello(FILE *stream);
39 extern int fseeko(FILE *stream, off_t offset, int whence);
40 #endif
41
42 typedef int8_t bgzf_byte_t;
43
44 static const int DEFAULT_BLOCK_SIZE = 64 * 1024;
45 static const int MAX_BLOCK_SIZE = 64 * 1024;
46
47 static const int BLOCK_HEADER_LENGTH = 18;
48 static const int BLOCK_FOOTER_LENGTH = 8;
49
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
59
60 static const int GZIP_WINDOW_BITS = -15; // no zlib header
61 static const int Z_DEFAULT_MEM_LEVEL = 8;
62
63
64 inline
65 void
66 packInt16(uint8_t* buffer, uint16_t value)
67 {
68     buffer[0] = value;
69     buffer[1] = value >> 8;
70 }
71
72 inline
73 int
74 unpackInt16(const uint8_t* buffer)
75 {
76     return (buffer[0] | (buffer[1] << 8));
77 }
78
79 inline
80 void
81 packInt32(uint8_t* buffer, uint32_t value)
82 {
83     buffer[0] = value;
84     buffer[1] = value >> 8;
85     buffer[2] = value >> 16;
86     buffer[3] = value >> 24;
87 }
88
89 static inline
90 int
91 bgzf_min(int x, int y)
92 {
93     return (x < y) ? x : y;
94 }
95
96 static
97 void
98 report_error(BGZF* fp, const char* message) {
99     fp->error = message;
100 }
101
102 static BGZF *bgzf_read_init()
103 {
104         BGZF *fp;
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);
110         fp->cache_size = 0;
111         fp->cache = kh_init(cache);
112         return fp;
113 }
114
115 static
116 BGZF*
117 open_read(int fd)
118 {
119 #ifdef _USE_KNETFILE
120     knetFile *file = knet_dopen(fd, "r");
121 #else
122     FILE* file = fdopen(fd, "r");
123 #endif
124     BGZF* fp;
125         if (file == 0) return 0;
126         fp = bgzf_read_init();
127     fp->file_descriptor = fd;
128     fp->open_mode = 'r';
129 #ifdef _USE_KNETFILE
130     fp->x.fpr = file;
131 #else
132     fp->file = file;
133 #endif
134     return fp;
135 }
136
137 static
138 BGZF*
139 open_write(int fd, bool is_uncompressed)
140 {
141     FILE* file = fdopen(fd, "w");
142     BGZF* fp;
143         if (file == 0) return 0;
144         fp = malloc(sizeof(BGZF));
145     fp->file_descriptor = fd;
146     fp->open_mode = 'w';
147     fp->owned_file = 0; fp->is_uncompressed = is_uncompressed;
148 #ifdef _USE_KNETFILE
149     fp->x.fpw = file;
150 #else
151     fp->file = file;
152 #endif
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;
160     fp->error = NULL;
161     return fp;
162 }
163
164 BGZF*
165 bgzf_open(const char* __restrict path, const char* __restrict mode)
166 {
167     BGZF* fp = NULL;
168     if (mode[0] == 'r' || mode[0] == 'R') { /* The reading mode is preferred. */
169 #ifdef _USE_KNETFILE
170                 knetFile *file = knet_open(path, mode);
171                 if (file == 0) return 0;
172                 fp = bgzf_read_init();
173                 fp->file_descriptor = -1;
174                 fp->open_mode = 'r';
175                 fp->x.fpr = file;
176 #else
177                 int fd, oflag = O_RDONLY;
178 #ifdef _WIN32
179                 oflag |= O_BINARY;
180 #endif
181                 fd = open(path, oflag);
182                 if (fd == -1) return 0;
183         fp = open_read(fd);
184 #endif
185     } else if (mode[0] == 'w' || mode[0] == 'W') {
186                 int fd, oflag = O_WRONLY | O_CREAT | O_TRUNC;
187 #ifdef _WIN32
188                 oflag |= O_BINARY;
189 #endif
190                 fd = open(path, oflag, 0644);
191                 if (fd == -1) return 0;
192         fp = open_write(fd, strstr(mode, "u")? 1 : 0);
193     }
194     if (fp != NULL) {
195         fp->owned_file = 1;
196     }
197     return fp;
198 }
199
200 BGZF*
201 bgzf_fdopen(int fd, const char * __restrict mode)
202 {
203         if (fd == -1) return 0;
204     if (mode[0] == 'r' || mode[0] == 'R') {
205         return open_read(fd);
206     } else if (mode[0] == 'w' || mode[0] == 'W') {
207         return open_write(fd, strstr(mode, "u")? 1 : 0);
208     } else {
209         return NULL;
210     }
211 }
212
213 static
214 int
215 deflate_block(BGZF* fp, int block_length)
216 {
217     // Deflate the block in fp->uncompressed_block into fp->compressed_block.
218     // Also adds an extra field that stores the compressed block length.
219
220     bgzf_byte_t* buffer = fp->compressed_block;
221     int buffer_size = fp->compressed_block_size;
222
223     // Init gzip header
224     buffer[0] = GZIP_ID1;
225     buffer[1] = GZIP_ID2;
226     buffer[2] = CM_DEFLATE;
227     buffer[3] = FLG_FEXTRA;
228     buffer[4] = 0; // mtime
229     buffer[5] = 0;
230     buffer[6] = 0;
231     buffer[7] = 0;
232     buffer[8] = 0;
233     buffer[9] = OS_UNKNOWN;
234     buffer[10] = BGZF_XLEN;
235     buffer[11] = 0;
236     buffer[12] = BGZF_ID1;
237     buffer[13] = BGZF_ID2;
238     buffer[14] = BGZF_LEN;
239     buffer[15] = 0;
240     buffer[16] = 0; // placeholder for block length
241     buffer[17] = 0;
242
243     // loop to retry for blocks that do not compress enough
244     int input_length = block_length;
245     int compressed_length = 0;
246     while (1) {
247                 int compress_level = fp->is_uncompressed? 0 : Z_DEFAULT_COMPRESSION;
248         z_stream zs;
249         zs.zalloc = NULL;
250         zs.zfree = NULL;
251         zs.next_in = fp->uncompressed_block;
252         zs.avail_in = input_length;
253         zs.next_out = (void*)&buffer[BLOCK_HEADER_LENGTH];
254         zs.avail_out = buffer_size - BLOCK_HEADER_LENGTH - BLOCK_FOOTER_LENGTH;
255
256         int status = deflateInit2(&zs, compress_level, Z_DEFLATED,
257                                   GZIP_WINDOW_BITS, Z_DEFAULT_MEM_LEVEL, Z_DEFAULT_STRATEGY);
258         if (status != Z_OK) {
259             report_error(fp, "deflate init failed");
260             return -1;
261         }
262         status = deflate(&zs, Z_FINISH);
263         if (status != Z_STREAM_END) {
264             deflateEnd(&zs);
265             if (status == Z_OK) {
266                 // Not enough space in buffer.
267                 // Can happen in the rare case the input doesn't compress enough.
268                 // Reduce the amount of input until it fits.
269                 input_length -= 1024;
270                 if (input_length <= 0) {
271                     // should never happen
272                     report_error(fp, "input reduction failed");
273                     return -1;
274                 }
275                 continue;
276             }
277             report_error(fp, "deflate failed");
278             return -1;
279         }
280         status = deflateEnd(&zs);
281         if (status != Z_OK) {
282             report_error(fp, "deflate end failed");
283             return -1;
284         }
285         compressed_length = zs.total_out;
286         compressed_length += BLOCK_HEADER_LENGTH + BLOCK_FOOTER_LENGTH;
287         if (compressed_length > MAX_BLOCK_SIZE) {
288             // should never happen
289             report_error(fp, "deflate overflow");
290             return -1;
291         }
292         break;
293     }
294
295     packInt16((uint8_t*)&buffer[16], compressed_length-1);
296     uint32_t crc = crc32(0L, NULL, 0L);
297     crc = crc32(crc, fp->uncompressed_block, input_length);
298     packInt32((uint8_t*)&buffer[compressed_length-8], crc);
299     packInt32((uint8_t*)&buffer[compressed_length-4], input_length);
300
301     int remaining = block_length - input_length;
302     if (remaining > 0) {
303         if (remaining > input_length) {
304             // should never happen (check so we can use memcpy)
305             report_error(fp, "remainder too large");
306             return -1;
307         }
308         memcpy(fp->uncompressed_block,
309                fp->uncompressed_block + input_length,
310                remaining);
311     }
312     fp->block_offset = remaining;
313     return compressed_length;
314 }
315
316 static
317 int
318 inflate_block(BGZF* fp, int block_length)
319 {
320     // Inflate the block in fp->compressed_block into fp->uncompressed_block
321
322     z_stream zs;
323     zs.zalloc = NULL;
324     zs.zfree = NULL;
325     zs.next_in = fp->compressed_block + 18;
326     zs.avail_in = block_length - 16;
327     zs.next_out = fp->uncompressed_block;
328     zs.avail_out = fp->uncompressed_block_size;
329
330     int status = inflateInit2(&zs, GZIP_WINDOW_BITS);
331     if (status != Z_OK) {
332         report_error(fp, "inflate init failed");
333         return -1;
334     }
335     status = inflate(&zs, Z_FINISH);
336     if (status != Z_STREAM_END) {
337         inflateEnd(&zs);
338         report_error(fp, "inflate failed");
339         return -1;
340     }
341     status = inflateEnd(&zs);
342     if (status != Z_OK) {
343         report_error(fp, "inflate failed");
344         return -1;
345     }
346     return zs.total_out;
347 }
348
349 static
350 int
351 check_header(const bgzf_byte_t* header)
352 {
353     return (header[0] == GZIP_ID1 &&
354             header[1] == (bgzf_byte_t) GZIP_ID2 &&
355             header[2] == Z_DEFLATED &&
356             (header[3] & FLG_FEXTRA) != 0 &&
357             unpackInt16((uint8_t*)&header[10]) == BGZF_XLEN &&
358             header[12] == BGZF_ID1 &&
359             header[13] == BGZF_ID2 &&
360             unpackInt16((uint8_t*)&header[14]) == BGZF_LEN);
361 }
362
363 static void free_cache(BGZF *fp)
364 {
365         khint_t k;
366         khash_t(cache) *h = (khash_t(cache)*)fp->cache;
367         if (fp->open_mode != 'r') return;
368         for (k = kh_begin(h); k < kh_end(h); ++k)
369                 if (kh_exist(h, k)) free(kh_val(h, k).block);
370         kh_destroy(cache, h);
371 }
372
373 static int load_block_from_cache(BGZF *fp, int64_t block_address)
374 {
375         khint_t k;
376         cache_t *p;
377         khash_t(cache) *h = (khash_t(cache)*)fp->cache;
378         k = kh_get(cache, h, block_address);
379         if (k == kh_end(h)) return 0;
380         p = &kh_val(h, k);
381         if (fp->block_length != 0) fp->block_offset = 0;
382         fp->block_address = block_address;
383         fp->block_length = p->size;
384         memcpy(fp->uncompressed_block, p->block, MAX_BLOCK_SIZE);
385 #ifdef _USE_KNETFILE
386         knet_seek(fp->x.fpr, p->end_offset, SEEK_SET);
387 #else
388         fseeko(fp->file, p->end_offset, SEEK_SET);
389 #endif
390         return p->size;
391 }
392
393 static void cache_block(BGZF *fp, int size)
394 {
395         int ret;
396         khint_t k;
397         cache_t *p;
398         khash_t(cache) *h = (khash_t(cache)*)fp->cache;
399         if (MAX_BLOCK_SIZE >= fp->cache_size) return;
400         if ((kh_size(h) + 1) * MAX_BLOCK_SIZE > fp->cache_size) {
401                 /* A better way would be to remove the oldest block in the
402                  * cache, but here we remove a random one for simplicity. This
403                  * should not have a big impact on performance. */
404                 for (k = kh_begin(h); k < kh_end(h); ++k)
405                         if (kh_exist(h, k)) break;
406                 if (k < kh_end(h)) {
407                         free(kh_val(h, k).block);
408                         kh_del(cache, h, k);
409                 }
410         }
411         k = kh_put(cache, h, fp->block_address, &ret);
412         if (ret == 0) return; // if this happens, a bug!
413         p = &kh_val(h, k);
414         p->size = fp->block_length;
415         p->end_offset = fp->block_address + size;
416         p->block = malloc(MAX_BLOCK_SIZE);
417         memcpy(kh_val(h, k).block, fp->uncompressed_block, MAX_BLOCK_SIZE);
418 }
419
420 static
421 int
422 read_block(BGZF* fp)
423 {
424     bgzf_byte_t header[BLOCK_HEADER_LENGTH];
425         int size = 0;
426 #ifdef _USE_KNETFILE
427     int64_t block_address = knet_tell(fp->x.fpr);
428         if (load_block_from_cache(fp, block_address)) return 0;
429     int count = knet_read(fp->x.fpr, header, sizeof(header));
430 #else
431     int64_t block_address = ftello(fp->file);
432         if (load_block_from_cache(fp, block_address)) return 0;
433     int count = fread(header, 1, sizeof(header), fp->file);
434 #endif
435     if (count == 0) {
436         fp->block_length = 0;
437         return 0;
438     }
439         size = count;
440     if (count != sizeof(header)) {
441         report_error(fp, "read failed");
442         return -1;
443     }
444     if (!check_header(header)) {
445         report_error(fp, "invalid block header");
446         return -1;
447     }
448     int block_length = unpackInt16((uint8_t*)&header[16]) + 1;
449     bgzf_byte_t* compressed_block = (bgzf_byte_t*) fp->compressed_block;
450     memcpy(compressed_block, header, BLOCK_HEADER_LENGTH);
451     int remaining = block_length - BLOCK_HEADER_LENGTH;
452 #ifdef _USE_KNETFILE
453     count = knet_read(fp->x.fpr, &compressed_block[BLOCK_HEADER_LENGTH], remaining);
454 #else
455     count = fread(&compressed_block[BLOCK_HEADER_LENGTH], 1, remaining, fp->file);
456 #endif
457     if (count != remaining) {
458         report_error(fp, "read failed");
459         return -1;
460     }
461         size += count;
462     count = inflate_block(fp, block_length);
463     if (count < 0) {
464         return -1;
465     }
466     if (fp->block_length != 0) {
467         // Do not reset offset if this read follows a seek.
468         fp->block_offset = 0;
469     }
470     fp->block_address = block_address;
471     fp->block_length = count;
472         cache_block(fp, size);
473     return 0;
474 }
475
476 int
477 bgzf_read(BGZF* fp, void* data, int length)
478 {
479     if (length <= 0) {
480         return 0;
481     }
482     if (fp->open_mode != 'r') {
483         report_error(fp, "file not open for reading");
484         return -1;
485     }
486
487     int bytes_read = 0;
488     bgzf_byte_t* output = data;
489     while (bytes_read < length) {
490         int available = fp->block_length - fp->block_offset;
491         if (available <= 0) {
492             if (read_block(fp) != 0) {
493                 return -1;
494             }
495             available = fp->block_length - fp->block_offset;
496             if (available <= 0) {
497                 break;
498             }
499         }
500         int copy_length = bgzf_min(length-bytes_read, available);
501         bgzf_byte_t* buffer = fp->uncompressed_block;
502         memcpy(output, buffer + fp->block_offset, copy_length);
503         fp->block_offset += copy_length;
504         output += copy_length;
505         bytes_read += copy_length;
506     }
507     if (fp->block_offset == fp->block_length) {
508 #ifdef _USE_KNETFILE
509         fp->block_address = knet_tell(fp->x.fpr);
510 #else
511         fp->block_address = ftello(fp->file);
512 #endif
513         fp->block_offset = 0;
514         fp->block_length = 0;
515     }
516     return bytes_read;
517 }
518
519 static
520 int
521 flush_block(BGZF* fp)
522 {
523     while (fp->block_offset > 0) {
524         int block_length = deflate_block(fp, fp->block_offset);
525         if (block_length < 0) {
526             return -1;
527         }
528 #ifdef _USE_KNETFILE
529         int count = fwrite(fp->compressed_block, 1, block_length, fp->x.fpw);
530 #else
531         int count = fwrite(fp->compressed_block, 1, block_length, fp->file);
532 #endif
533         if (count != block_length) {
534             report_error(fp, "write failed");
535             return -1;
536         }
537         fp->block_address += block_length;
538     }
539     return 0;
540 }
541
542 int
543 bgzf_write(BGZF* fp, const void* data, int length)
544 {
545     if (fp->open_mode != 'w') {
546         report_error(fp, "file not open for writing");
547         return -1;
548     }
549
550     if (fp->uncompressed_block == NULL) {
551         fp->uncompressed_block = malloc(fp->uncompressed_block_size);
552     }
553
554     const bgzf_byte_t* input = data;
555     int block_length = fp->uncompressed_block_size;
556     int bytes_written = 0;
557     while (bytes_written < length) {
558         int copy_length = bgzf_min(block_length - fp->block_offset, length - bytes_written);
559         bgzf_byte_t* buffer = fp->uncompressed_block;
560         memcpy(buffer + fp->block_offset, input, copy_length);
561         fp->block_offset += copy_length;
562         input += copy_length;
563         bytes_written += copy_length;
564         if (fp->block_offset == block_length) {
565             if (flush_block(fp) != 0) {
566                 break;
567             }
568         }
569     }
570     return bytes_written;
571 }
572
573 int
574 bgzf_close(BGZF* fp)
575 {
576     if (fp->open_mode == 'w') {
577         if (flush_block(fp) != 0) {
578             return -1;
579         }
580                 { // add an empty block
581                         int count, block_length = deflate_block(fp, 0);
582 #ifdef _USE_KNETFILE
583                         count = fwrite(fp->compressed_block, 1, block_length, fp->x.fpw);
584 #else
585                         count = fwrite(fp->compressed_block, 1, block_length, fp->file);
586 #endif
587                 }
588 #ifdef _USE_KNETFILE
589         if (fflush(fp->x.fpw) != 0) {
590 #else
591         if (fflush(fp->file) != 0) {
592 #endif
593             report_error(fp, "flush failed");
594             return -1;
595         }
596     }
597     if (fp->owned_file) {
598 #ifdef _USE_KNETFILE
599                 int ret;
600                 if (fp->open_mode == 'w') ret = fclose(fp->x.fpw);
601                 else ret = knet_close(fp->x.fpr);
602         if (ret != 0) return -1;
603 #else
604         if (fclose(fp->file) != 0) {
605             return -1;
606         }
607 #endif
608     }
609     free(fp->uncompressed_block);
610     free(fp->compressed_block);
611         free_cache(fp);
612     free(fp);
613     return 0;
614 }
615
616 int64_t
617 bgzf_tell(BGZF* fp)
618 {
619     return ((fp->block_address << 16) | (fp->block_offset & 0xFFFF));
620 }
621
622 void bgzf_set_cache_size(BGZF *fp, int cache_size)
623 {
624         if (fp) fp->cache_size = cache_size;
625 }
626
627 int bgzf_check_EOF(BGZF *fp)
628 {
629         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";
630         uint8_t buf[28];
631         off_t offset;
632 #ifdef _USE_KNETFILE
633         offset = knet_tell(fp->x.fpr);
634         if (knet_seek(fp->x.fpr, -28, SEEK_END) != 0) return -1;
635         knet_read(fp->x.fpr, buf, 28);
636         knet_seek(fp->x.fpr, offset, SEEK_SET);
637 #else
638         offset = ftello(fp->file);
639         if (fseeko(fp->file, -28, SEEK_END) != 0) return -1;
640         fread(buf, 1, 28, fp->file);
641         fseeko(fp->file, offset, SEEK_SET);
642 #endif
643         return (memcmp(magic, buf, 28) == 0)? 1 : 0;
644 }
645
646 int64_t
647 bgzf_seek(BGZF* fp, int64_t pos, int where)
648 {
649     if (fp->open_mode != 'r') {
650         report_error(fp, "file not open for read");
651         return -1;
652     }
653     if (where != SEEK_SET) {
654         report_error(fp, "unimplemented seek option");
655         return -1;
656     }
657     int block_offset = pos & 0xFFFF;
658     int64_t block_address = (pos >> 16) & 0xFFFFFFFFFFFFLL;
659 #ifdef _USE_KNETFILE
660     if (knet_seek(fp->x.fpr, block_address, SEEK_SET) != 0) {
661 #else
662     if (fseeko(fp->file, block_address, SEEK_SET) != 0) {
663 #endif
664         report_error(fp, "seek failed");
665         return -1;
666     }
667     fp->block_length = 0;  // indicates current block is not loaded
668     fp->block_address = block_address;
669     fp->block_offset = block_offset;
670     return 0;
671 }