]> git.donarmstrong.com Git - samtools.git/blob - bgzf.c
Create trunk copy
[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 #include <stdio.h>
13 #include <stdlib.h>
14 #include <string.h>
15 #include <unistd.h>
16 #include <fcntl.h>
17 #include <sys/types.h>
18 #include <sys/stat.h>
19 #include "bgzf.h"
20
21 extern off_t ftello(FILE *stream);
22 extern int fseeko(FILE *stream, off_t offset, int whence);
23
24 typedef int8_t byte;
25
26 static const int DEFAULT_BLOCK_SIZE = 64 * 1024;
27 static const int MAX_BLOCK_SIZE = 64 * 1024;
28
29 static const int BLOCK_HEADER_LENGTH = 18;
30 static const int BLOCK_FOOTER_LENGTH = 8;
31
32 static const int GZIP_ID1 = 31;
33 static const int GZIP_ID2 = 139;
34 static const int CM_DEFLATE = 8;
35 static const int FLG_FEXTRA = 4;
36 static const int OS_UNKNOWN = 255;
37 static const int BGZF_ID1 = 66; // 'B'
38 static const int BGZF_ID2 = 67; // 'C'
39 static const int BGZF_LEN = 2;
40 static const int BGZF_XLEN = 6; // BGZF_LEN+4
41
42 static const int GZIP_WINDOW_BITS = -15; // no zlib header
43 static const int Z_DEFAULT_MEM_LEVEL = 8;
44
45
46 inline
47 void
48 packInt16(uint8_t* buffer, uint16_t value)
49 {
50     buffer[0] = value;
51     buffer[1] = value >> 8;
52 }
53
54 inline
55 int
56 unpackInt16(const uint8_t* buffer)
57 {
58     return (buffer[0] | (buffer[1] << 8));
59 }
60
61 inline
62 void
63 packInt32(uint8_t* buffer, uint32_t value)
64 {
65     buffer[0] = value;
66     buffer[1] = value >> 8;
67     buffer[2] = value >> 16;
68     buffer[3] = value >> 24;
69 }
70
71 inline
72 int
73 min(int x, int y)
74 {
75     return (x < y) ? x : y;
76 }
77
78 static
79 void
80 report_error(BGZF* fp, const char* message) {
81     fp->error = message;
82 }
83
84 static
85 BGZF*
86 open_read(int fd)
87 {
88     FILE* file = fdopen(fd, "r");
89     BGZF* fp = malloc(sizeof(BGZF));
90     fp->file_descriptor = fd;
91     fp->open_mode = 'r';
92     fp->owned_file = 0;
93     fp->file = file;
94     fp->uncompressed_block_size = MAX_BLOCK_SIZE;
95     fp->uncompressed_block = malloc(MAX_BLOCK_SIZE);
96     fp->compressed_block_size = MAX_BLOCK_SIZE;
97     fp->compressed_block = malloc(MAX_BLOCK_SIZE);
98     fp->block_address = 0;
99     fp->block_offset = 0;
100     fp->block_length = 0;
101     fp->error = NULL;
102     return fp;
103 }
104
105 static
106 BGZF*
107 open_write(int fd)
108 {
109     FILE* file = fdopen(fd, "w");
110     BGZF* fp = malloc(sizeof(BGZF));
111     fp->file_descriptor = fd;
112     fp->open_mode = 'w';
113     fp->owned_file = 0;
114     fp->file = file;
115     fp->uncompressed_block_size = DEFAULT_BLOCK_SIZE;
116     fp->uncompressed_block = NULL;
117     fp->compressed_block_size = MAX_BLOCK_SIZE;
118     fp->compressed_block = malloc(MAX_BLOCK_SIZE);
119     fp->block_address = 0;
120     fp->block_offset = 0;
121     fp->block_length = 0;
122     fp->error = NULL;
123     return fp;
124 }
125
126 BGZF*
127 bgzf_open(const char* __restrict path, const char* __restrict mode)
128 {
129     BGZF* fp = NULL;
130     if (strcasecmp(mode, "r") == 0) {
131         int oflag = O_RDONLY;
132         int fd = open(path, oflag);
133         fp = open_read(fd);
134     } else if (strcasecmp(mode, "w") == 0) {
135         int oflag = O_WRONLY | O_CREAT | O_TRUNC;
136         int fd = open(path, oflag, 0644);
137         fp = open_write(fd);
138     }
139     if (fp != NULL) {
140         fp->owned_file = 1;
141     }
142     return fp;
143 }
144
145 BGZF*
146 bgzf_fdopen(int fd, const char * __restrict mode)
147 {
148     if (strcasecmp(mode, "r") == 0) {
149         return open_read(fd);
150     } else if (strcasecmp(mode, "w") == 0) {
151         return open_write(fd);
152     } else {
153         return NULL;
154     }
155 }
156
157 static
158 int
159 deflate_block(BGZF* fp, int block_length)
160 {
161     // Deflate the block in fp->uncompressed_block into fp->compressed_block.
162     // Also adds an extra field that stores the compressed block length.
163
164     byte* buffer = fp->compressed_block;
165     int buffer_size = fp->compressed_block_size;
166
167     // Init gzip header
168     buffer[0] = GZIP_ID1;
169     buffer[1] = GZIP_ID2;
170     buffer[2] = CM_DEFLATE;
171     buffer[3] = FLG_FEXTRA;
172     buffer[4] = 0; // mtime
173     buffer[5] = 0;
174     buffer[6] = 0;
175     buffer[7] = 0;
176     buffer[8] = 0;
177     buffer[9] = OS_UNKNOWN;
178     buffer[10] = BGZF_XLEN;
179     buffer[11] = 0;
180     buffer[12] = BGZF_ID1;
181     buffer[13] = BGZF_ID2;
182     buffer[14] = BGZF_LEN;
183     buffer[15] = 0;
184     buffer[16] = 0; // placeholder for block length
185     buffer[17] = 0;
186
187     // loop to retry for blocks that do not compress enough
188     int input_length = block_length;
189     int compressed_length = 0;
190     while (1) {
191
192         z_stream zs;
193         zs.zalloc = NULL;
194         zs.zfree = NULL;
195         zs.next_in = fp->uncompressed_block;
196         zs.avail_in = input_length;
197         zs.next_out = (void*)&buffer[BLOCK_HEADER_LENGTH];
198         zs.avail_out = buffer_size - BLOCK_HEADER_LENGTH - BLOCK_FOOTER_LENGTH;
199
200         int status = deflateInit2(&zs, Z_DEFAULT_COMPRESSION, Z_DEFLATED,
201                                   GZIP_WINDOW_BITS, Z_DEFAULT_MEM_LEVEL, Z_DEFAULT_STRATEGY);
202         if (status != Z_OK) {
203             report_error(fp, "deflate init failed");
204             return -1;
205         }
206         status = deflate(&zs, Z_FINISH);
207         if (status != Z_STREAM_END) {
208             deflateEnd(&zs);
209             if (status == Z_OK) {
210                 // Not enough space in buffer.
211                 // Can happen in the rare case the input doesn't compress enough.
212                 // Reduce the amount of input until it fits.
213                 input_length -= 1024;
214                 if (input_length <= 0) {
215                     // should never happen
216                     report_error(fp, "input reduction failed");
217                     return -1;
218                 }
219                 continue;
220             }
221             report_error(fp, "deflate failed");
222             return -1;
223         }
224         status = deflateEnd(&zs);
225         if (status != Z_OK) {
226             report_error(fp, "deflate end failed");
227             return -1;
228         }
229         compressed_length = zs.total_out;
230         compressed_length += BLOCK_HEADER_LENGTH + BLOCK_FOOTER_LENGTH;
231         if (compressed_length > MAX_BLOCK_SIZE) {
232             // should never happen
233             report_error(fp, "deflate overflow");
234             return -1;
235         }
236         break;
237     }
238
239     packInt16((uint8_t*)&buffer[16], compressed_length-1);
240     uint32_t crc = crc32(0L, NULL, 0L);
241     crc = crc32(crc, fp->uncompressed_block, input_length);
242     packInt32((uint8_t*)&buffer[compressed_length-8], crc);
243     packInt32((uint8_t*)&buffer[compressed_length-4], input_length);
244
245     int remaining = block_length - input_length;
246     if (remaining > 0) {
247         if (remaining > input_length) {
248             // should never happen (check so we can use memcpy)
249             report_error(fp, "remainder too large");
250             return -1;
251         }
252         memcpy(fp->uncompressed_block,
253                fp->uncompressed_block + input_length,
254                remaining);
255     }
256     fp->block_offset = remaining;
257     return compressed_length;
258 }
259
260 static
261 int
262 inflate_block(BGZF* fp, int block_length)
263 {
264     // Inflate the block in fp->compressed_block into fp->uncompressed_block
265
266     z_stream zs;
267     zs.zalloc = NULL;
268     zs.zfree = NULL;
269     zs.next_in = fp->compressed_block + 18;
270     zs.avail_in = block_length - 16;
271     zs.next_out = fp->uncompressed_block;
272     zs.avail_out = fp->uncompressed_block_size;
273
274     int status = inflateInit2(&zs, GZIP_WINDOW_BITS);
275     if (status != Z_OK) {
276         report_error(fp, "inflate init failed");
277         return -1;
278     }
279     status = inflate(&zs, Z_FINISH);
280     if (status != Z_STREAM_END) {
281         inflateEnd(&zs);
282         report_error(fp, "inflate failed");
283         return -1;
284     }
285     status = inflateEnd(&zs);
286     if (status != Z_OK) {
287         report_error(fp, "inflate failed");
288         return -1;
289     }
290     return zs.total_out;
291 }
292
293 static
294 int
295 check_header(const byte* header)
296 {
297     return (header[0] == GZIP_ID1 &&
298             header[1] == (byte) GZIP_ID2 &&
299             header[2] == Z_DEFLATED &&
300             (header[3] & FLG_FEXTRA) != 0 &&
301             unpackInt16((uint8_t*)&header[10]) == BGZF_XLEN &&
302             header[12] == BGZF_ID1 &&
303             header[13] == BGZF_ID2 &&
304             unpackInt16((uint8_t*)&header[14]) == BGZF_LEN);
305 }
306
307 static
308 int
309 read_block(BGZF* fp)
310 {
311     byte header[BLOCK_HEADER_LENGTH];
312     int64_t block_address = ftello(fp->file);
313     int count = fread(header, 1, sizeof(header), fp->file);
314     if (count == 0) {
315         fp->block_length = 0;
316         return 0;
317     }
318     if (count != sizeof(header)) {
319         report_error(fp, "read failed");
320         return -1;
321     }
322     if (!check_header(header)) {
323         report_error(fp, "invalid block header");
324         return -1;
325     }
326     int block_length = unpackInt16((uint8_t*)&header[16]) + 1;
327     byte* compressed_block = (byte*) fp->compressed_block;
328     memcpy(compressed_block, header, BLOCK_HEADER_LENGTH);
329     int remaining = block_length - BLOCK_HEADER_LENGTH;
330     count = fread(&compressed_block[BLOCK_HEADER_LENGTH], 1, remaining, fp->file);
331     if (count != remaining) {
332         report_error(fp, "read failed");
333         return -1;
334     }
335     count = inflate_block(fp, block_length);
336     if (count < 0) {
337         return -1;
338     }
339     if (fp->block_length != 0) {
340         // Do not reset offset if this read follows a seek.
341         fp->block_offset = 0;
342     }
343     fp->block_address = block_address;
344     fp->block_length = count;
345     return 0;
346 }
347
348 int
349 bgzf_read(BGZF* fp, void* data, int length)
350 {
351     if (length <= 0) {
352         return 0;
353     }
354     if (fp->open_mode != 'r') {
355         report_error(fp, "file not open for reading");
356         return -1;
357     }
358
359     int bytes_read = 0;
360     byte* output = data;
361     while (bytes_read < length) {
362         int available = fp->block_length - fp->block_offset;
363         if (available <= 0) {
364             if (read_block(fp) != 0) {
365                 return -1;
366             }
367             available = fp->block_length - fp->block_offset;
368             if (available <= 0) {
369                 break;
370             }
371         }
372         int copy_length = min(length-bytes_read, available);
373         byte* buffer = fp->uncompressed_block;
374         memcpy(output, buffer + fp->block_offset, copy_length);
375         fp->block_offset += copy_length;
376         output += copy_length;
377         bytes_read += copy_length;
378     }
379     if (fp->block_offset == fp->block_length) {
380         fp->block_address = ftello(fp->file);
381         fp->block_offset = 0;
382         fp->block_length = 0;
383     }
384     return bytes_read;
385 }
386
387 static
388 int
389 flush_block(BGZF* fp)
390 {
391     while (fp->block_offset > 0) {
392         int block_length = deflate_block(fp, fp->block_offset);
393         if (block_length < 0) {
394             return -1;
395         }
396         int count = fwrite(fp->compressed_block, 1, block_length, fp->file);
397         if (count != block_length) {
398             report_error(fp, "write failed");
399             return -1;
400         }
401         fp->block_address += block_length;
402     }
403     return 0;
404 }
405
406 int
407 bgzf_write(BGZF* fp, const void* data, int length)
408 {
409     if (fp->open_mode != 'w') {
410         report_error(fp, "file not open for writing");
411         return -1;
412     }
413
414     if (fp->uncompressed_block == NULL) {
415         fp->uncompressed_block = malloc(fp->uncompressed_block_size);
416     }
417
418     const byte* input = data;
419     int block_length = fp->uncompressed_block_size;
420     int bytes_written = 0;
421     while (bytes_written < length) {
422         int copy_length = min(block_length - fp->block_offset, length - bytes_written);
423         byte* buffer = fp->uncompressed_block;
424         memcpy(buffer + fp->block_offset, input, copy_length);
425         fp->block_offset += copy_length;
426         input += copy_length;
427         bytes_written += copy_length;
428         if (fp->block_offset == block_length) {
429             if (flush_block(fp) != 0) {
430                 break;
431             }
432         }
433     }
434     return bytes_written;
435 }
436
437 int
438 bgzf_close(BGZF* fp)
439 {
440     if (fp->open_mode == 'w') {
441         if (flush_block(fp) != 0) {
442             return -1;
443         }
444         if (fflush(fp->file) != 0) {
445             report_error(fp, "flush failed");
446             return -1;
447         }
448     }
449     if (fp->owned_file) {
450         if (fclose(fp->file) != 0) {
451             return -1;
452         }
453     }
454     free(fp->uncompressed_block);
455     free(fp->compressed_block);
456     free(fp);
457     return 0;
458 }
459
460 int64_t
461 bgzf_tell(BGZF* fp)
462 {
463     return ((fp->block_address << 16) | (fp->block_offset & 0xFFFF));
464 }
465
466 int64_t
467 bgzf_seek(BGZF* fp, int64_t pos, int where)
468 {
469     if (fp->open_mode != 'r') {
470         report_error(fp, "file not open for read");
471         return -1;
472     }
473     if (where != SEEK_SET) {
474         report_error(fp, "unimplemented seek option");
475         return -1;
476     }
477     int block_offset = pos & 0xFFFF;
478     int64_t block_address = (pos >> 16) & 0xFFFFFFFFFFFFLL;
479     if (fseeko(fp->file, block_address, SEEK_SET) != 0) {
480         report_error(fp, "seek failed");
481         return -1;
482     }
483     fp->block_length = 0;  // indicates current block is not loaded
484     fp->block_address = block_address;
485     fp->block_offset = block_offset;
486     return 0;
487 }
488