-
Notifications
You must be signed in to change notification settings - Fork 446
/
bgzf.c
2570 lines (2248 loc) · 79.8 KB
/
bgzf.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* The MIT License
Copyright (c) 2008 Broad Institute / Massachusetts Institute of Technology
2011, 2012 Attractive Chaos <attractor@live.co.uk>
Copyright (C) 2009, 2013-2021 Genome Research Ltd
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#define HTS_BUILDING_LIBRARY // Enables HTSLIB_EXPORT, see htslib/hts_defs.h
#include <config.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <assert.h>
#include <pthread.h>
#include <sys/types.h>
#include <inttypes.h>
#include <zlib.h>
#ifdef HAVE_LIBDEFLATE
#include <libdeflate.h>
#endif
#include "htslib/hts.h"
#include "htslib/bgzf.h"
#include "htslib/hfile.h"
#include "htslib/thread_pool.h"
#include "htslib/hts_endian.h"
#include "cram/pooled_alloc.h"
#include "hts_internal.h"
#ifndef EFTYPE
#define EFTYPE ENOEXEC
#endif
#define BGZF_CACHE
#define BGZF_MT
#define BLOCK_HEADER_LENGTH 18
#define BLOCK_FOOTER_LENGTH 8
/* BGZF/GZIP header (specialized from RFC 1952; little endian):
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
| 31|139| 8| 4| 0| 0|255| 6| 66| 67| 2|BLK_LEN|
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
BGZF extension:
^ ^ ^ ^
| | | |
FLG.EXTRA XLEN B C
BGZF format is compatible with GZIP. It limits the size of each compressed
block to 2^16 bytes and adds and an extra "BC" field in the gzip header which
records the size.
*/
static const uint8_t g_magic[19] = "\037\213\010\4\0\0\0\0\0\377\6\0\102\103\2\0\0\0";
#ifdef BGZF_CACHE
typedef struct {
int size;
uint8_t *block;
int64_t end_offset;
} cache_t;
#include "htslib/khash.h"
KHASH_MAP_INIT_INT64(cache, cache_t)
#endif
struct bgzf_cache_t {
khash_t(cache) *h;
khint_t last_pos;
};
#ifdef BGZF_MT
typedef struct bgzf_job {
BGZF *fp;
unsigned char comp_data[BGZF_MAX_BLOCK_SIZE];
size_t comp_len;
unsigned char uncomp_data[BGZF_MAX_BLOCK_SIZE];
size_t uncomp_len;
int errcode;
int64_t block_address;
int hit_eof;
} bgzf_job;
enum mtaux_cmd {
NONE = 0,
SEEK,
SEEK_DONE,
HAS_EOF,
HAS_EOF_DONE,
CLOSE,
};
// When multi-threaded bgzf_tell won't work, so we delay the hts_idx_push
// until we've written the last block.
typedef struct {
hts_pos_t beg, end;
int tid, is_mapped; // args for hts_idx_push
uint64_t offset, block_number;
} hts_idx_cache_entry;
typedef struct {
int nentries, mentries; // used and allocated
hts_idx_cache_entry *e; // hts_idx elements
} hts_idx_cache_t;
typedef struct bgzf_mtaux_t {
// Memory pool for bgzf_job structs, to avoid many malloc/free
pool_alloc_t *job_pool;
bgzf_job *curr_job;
// Thread pool
int n_threads;
int own_pool;
hts_tpool *pool;
// Output queue holding completed bgzf_jobs
hts_tpool_process *out_queue;
// I/O thread.
pthread_t io_task;
pthread_mutex_t job_pool_m;
int jobs_pending; // number of jobs waiting
int flush_pending;
void *free_block;
int hit_eof; // r/w entirely within main thread
// Message passing to the reader thread; eg seek requests
int errcode;
uint64_t block_address;
int eof;
pthread_mutex_t command_m; // Set whenever fp is being updated
pthread_cond_t command_c;
enum mtaux_cmd command;
// For multi-threaded on-the-fly indexing. See bgzf_idx_push below.
pthread_mutex_t idx_m;
hts_idx_t *hts_idx;
uint64_t block_number, block_written;
hts_idx_cache_t idx_cache;
} mtaux_t;
#endif
typedef struct
{
uint64_t uaddr; // offset w.r.t. uncompressed data
uint64_t caddr; // offset w.r.t. compressed data
}
bgzidx1_t;
struct bgzidx_t
{
int noffs, moffs; // the size of the index, n:used, m:allocated
bgzidx1_t *offs; // offsets
uint64_t ublock_addr; // offset of the current block (uncompressed data)
};
/*
* Buffers up arguments to hts_idx_push for later use, once we've written all bar
* this block. This is necessary when multiple blocks are in flight (threading)
* and fp->block_address isn't known at the time of call as we have in-flight
* blocks that haven't yet been compressed.
*
* NB: this only matters when we're indexing on the fly (writing).
* Normal indexing is threaded reads, but we already know block sizes
* so it's a simpler process
*
* Returns 0 on success,
* -1 on failure
*/
int bgzf_idx_push(BGZF *fp, hts_idx_t *hidx, int tid, hts_pos_t beg, hts_pos_t end, uint64_t offset, int is_mapped) {
hts_idx_cache_entry *e;
mtaux_t *mt = fp->mt;
if (!mt)
return hts_idx_push(hidx, tid, beg, end, offset, is_mapped);
// Early check for out of range positions which would fail in hts_idx_push()
if (hts_idx_check_range(hidx, tid, beg, end) < 0)
return -1;
pthread_mutex_lock(&mt->idx_m);
mt->hts_idx = hidx;
hts_idx_cache_t *ic = &mt->idx_cache;
if (ic->nentries >= ic->mentries) {
int new_sz = ic->mentries ? ic->mentries*2 : 1024;
if (!(e = realloc(ic->e, new_sz * sizeof(*ic->e)))) {
pthread_mutex_unlock(&mt->idx_m);
return -1;
}
ic->e = e;
ic->mentries = new_sz;
}
e = &ic->e[ic->nentries++];
e->tid = tid;
e->beg = beg;
e->end = end;
e->is_mapped = is_mapped;
e->offset = offset & 0xffff;
e->block_number = mt->block_number;
pthread_mutex_unlock(&mt->idx_m);
return 0;
}
/*
* bgzf analogue to hts_idx_amend_last.
*
* This is needed when multi-threading and writing indices on the fly.
* At the point of writing a record we know the virtual offset for start
* and end, but that end virtual offset may be the end of the current
* block. In standard indexing our end virtual offset becomes the start
* of the next block. Thus to ensure bit for bit compatibility we
* detect this boundary case and fix it up here.
*
* In theory this has no behavioural change, but it also works around
* a bug elsewhere which causes bgzf_read to return 0 when our offset
* is the end of a block rather than the start of the next.
*/
void bgzf_idx_amend_last(BGZF *fp, hts_idx_t *hidx, uint64_t offset) {
mtaux_t *mt = fp->mt;
if (!mt) {
hts_idx_amend_last(hidx, offset);
return;
}
pthread_mutex_lock(&mt->idx_m);
hts_idx_cache_t *ic = &mt->idx_cache;
if (ic->nentries > 0) {
hts_idx_cache_entry *e = &ic->e[ic->nentries-1];
if ((offset & 0xffff) == 0 && e->offset != 0) {
// bumped to next block number
e->offset = 0;
e->block_number++;
}
}
pthread_mutex_unlock(&mt->idx_m);
}
static int bgzf_idx_flush(BGZF *fp) {
mtaux_t *mt = fp->mt;
if (!mt->idx_cache.e) {
mt->block_written++;
return 0;
}
pthread_mutex_lock(&mt->idx_m);
hts_idx_cache_entry *e = mt->idx_cache.e;
int i;
assert(mt->idx_cache.nentries == 0 || mt->block_written <= e[0].block_number);
for (i = 0; i < mt->idx_cache.nentries && e[i].block_number == mt->block_written; i++) {
if (hts_idx_push(mt->hts_idx, e[i].tid, e[i].beg, e[i].end,
(mt->block_address << 16) + e[i].offset,
e[i].is_mapped) < 0) {
pthread_mutex_unlock(&mt->idx_m);
return -1;
}
}
memmove(&e[0], &e[i], (mt->idx_cache.nentries - i) * sizeof(*e));
mt->idx_cache.nentries -= i;
mt->block_written++;
pthread_mutex_unlock(&mt->idx_m);
return 0;
}
void bgzf_index_destroy(BGZF *fp);
int bgzf_index_add_block(BGZF *fp);
static int mt_destroy(mtaux_t *mt);
static inline void packInt16(uint8_t *buffer, uint16_t value)
{
buffer[0] = value;
buffer[1] = value >> 8;
}
static inline int unpackInt16(const uint8_t *buffer)
{
return buffer[0] | buffer[1] << 8;
}
static inline void packInt32(uint8_t *buffer, uint32_t value)
{
buffer[0] = value;
buffer[1] = value >> 8;
buffer[2] = value >> 16;
buffer[3] = value >> 24;
}
static void razf_info(hFILE *hfp, const char *filename)
{
uint64_t usize, csize;
off_t sizes_pos;
if (filename == NULL || strcmp(filename, "-") == 0) filename = "FILE";
// RAZF files end with USIZE,CSIZE stored as big-endian uint64_t
if ((sizes_pos = hseek(hfp, -16, SEEK_END)) < 0) goto no_sizes;
if (hread(hfp, &usize, 8) != 8 || hread(hfp, &csize, 8) != 8) goto no_sizes;
if (!ed_is_big()) ed_swap_8p(&usize), ed_swap_8p(&csize);
if (csize >= sizes_pos) goto no_sizes; // Very basic validity check
hts_log_error(
"To decompress this file, use the following commands:\n"
" truncate -s %" PRIu64 " %s\n"
" gunzip %s\n"
"The resulting uncompressed file should be %" PRIu64 " bytes in length.\n"
"If you do not have a truncate command, skip that step (though gunzip will\n"
"likely produce a \"trailing garbage ignored\" message, which can be ignored).",
csize, filename, filename, usize);
return;
no_sizes:
hts_log_error(
"To decompress this file, use the following command:\n"
" gunzip %s\n"
"This will likely produce a \"trailing garbage ignored\" message, which can\n"
"usually be safely ignored.", filename);
}
static const char *bgzf_zerr(int errnum, z_stream *zs)
{
static char buffer[32];
/* Return zs->msg if available.
zlib doesn't set this very reliably. Looking at the source suggests
that it may get set to a useful message for deflateInit2, inflateInit2
and inflate when it returns Z_DATA_ERROR. For inflate with other
return codes, deflate, deflateEnd and inflateEnd it doesn't appear
to be useful. For the likely non-useful cases, the caller should
pass NULL into zs. */
if (zs && zs->msg) return zs->msg;
// gzerror OF((gzFile file, int *errnum)
switch (errnum) {
case Z_ERRNO:
return strerror(errno);
case Z_STREAM_ERROR:
return "invalid parameter/compression level, or inconsistent stream state";
case Z_DATA_ERROR:
return "invalid or incomplete IO";
case Z_MEM_ERROR:
return "out of memory";
case Z_BUF_ERROR:
return "progress temporarily not possible, or in() / out() returned an error";
case Z_VERSION_ERROR:
return "zlib version mismatch";
case Z_NEED_DICT:
return "data was compressed using a dictionary";
case Z_OK: // 0: maybe gzgets error Z_NULL
default:
snprintf(buffer, sizeof(buffer), "[%d] unknown", errnum);
return buffer; // FIXME: Not thread-safe.
}
}
static BGZF *bgzf_read_init(hFILE *hfpr, const char *filename)
{
BGZF *fp;
uint8_t magic[18];
ssize_t n = hpeek(hfpr, magic, 18);
if (n < 0) return NULL;
fp = (BGZF*)calloc(1, sizeof(BGZF));
if (fp == NULL) return NULL;
fp->is_write = 0;
fp->uncompressed_block = malloc(2 * BGZF_MAX_BLOCK_SIZE);
if (fp->uncompressed_block == NULL) { free(fp); return NULL; }
fp->compressed_block = (char *)fp->uncompressed_block + BGZF_MAX_BLOCK_SIZE;
fp->is_compressed = (n==18 && magic[0]==0x1f && magic[1]==0x8b);
fp->is_gzip = ( !fp->is_compressed || ((magic[3]&4) && memcmp(&magic[12], "BC\2\0",4)==0) ) ? 0 : 1;
if (fp->is_compressed && (magic[3]&4) && memcmp(&magic[12], "RAZF", 4)==0) {
hts_log_error("Cannot decompress legacy RAZF format");
razf_info(hfpr, filename);
free(fp->uncompressed_block);
free(fp);
errno = EFTYPE;
return NULL;
}
#ifdef BGZF_CACHE
if (!(fp->cache = malloc(sizeof(*fp->cache)))) {
free(fp->uncompressed_block);
free(fp);
return NULL;
}
if (!(fp->cache->h = kh_init(cache))) {
free(fp->uncompressed_block);
free(fp->cache);
free(fp);
return NULL;
}
fp->cache->last_pos = 0;
#endif
return fp;
}
// get the compress level from the mode string: compress_level==-1 for the default level, -2 plain uncompressed
static int mode2level(const char *mode)
{
int i, compress_level = -1;
for (i = 0; mode[i]; ++i)
if (mode[i] >= '0' && mode[i] <= '9') break;
if (mode[i]) compress_level = (int)mode[i] - '0';
if (strchr(mode, 'u')) compress_level = -2;
return compress_level;
}
static BGZF *bgzf_write_init(const char *mode)
{
BGZF *fp;
fp = (BGZF*)calloc(1, sizeof(BGZF));
if (fp == NULL) goto mem_fail;
fp->is_write = 1;
int compress_level = mode2level(mode);
if ( compress_level==-2 )
{
fp->is_compressed = 0;
return fp;
}
fp->is_compressed = 1;
fp->uncompressed_block = malloc(2 * BGZF_MAX_BLOCK_SIZE);
if (fp->uncompressed_block == NULL) goto mem_fail;
fp->compressed_block = (char *)fp->uncompressed_block + BGZF_MAX_BLOCK_SIZE;
fp->compress_level = compress_level < 0? Z_DEFAULT_COMPRESSION : compress_level; // Z_DEFAULT_COMPRESSION==-1
if (fp->compress_level > 9) fp->compress_level = Z_DEFAULT_COMPRESSION;
if ( strchr(mode,'g') )
{
// gzip output
fp->is_gzip = 1;
fp->gz_stream = (z_stream*)calloc(1,sizeof(z_stream));
if (fp->gz_stream == NULL) goto mem_fail;
fp->gz_stream->zalloc = NULL;
fp->gz_stream->zfree = NULL;
fp->gz_stream->msg = NULL;
int ret = deflateInit2(fp->gz_stream, fp->compress_level, Z_DEFLATED, 15|16, 8, Z_DEFAULT_STRATEGY);
if (ret!=Z_OK) {
hts_log_error("Call to deflateInit2 failed: %s", bgzf_zerr(ret, fp->gz_stream));
goto fail;
}
}
return fp;
mem_fail:
hts_log_error("%s", strerror(errno));
fail:
if (fp != NULL) {
free(fp->uncompressed_block);
free(fp->gz_stream);
free(fp);
}
return NULL;
}
BGZF *bgzf_open(const char *path, const char *mode)
{
BGZF *fp = 0;
if (strchr(mode, 'r')) {
hFILE *fpr;
if ((fpr = hopen(path, mode)) == 0) return 0;
fp = bgzf_read_init(fpr, path);
if (fp == 0) { hclose_abruptly(fpr); return NULL; }
fp->fp = fpr;
} else if (strchr(mode, 'w') || strchr(mode, 'a')) {
hFILE *fpw;
if ((fpw = hopen(path, mode)) == 0) return 0;
fp = bgzf_write_init(mode);
if (fp == NULL) return NULL;
fp->fp = fpw;
}
else { errno = EINVAL; return 0; }
fp->is_be = ed_is_big();
return fp;
}
BGZF *bgzf_dopen(int fd, const char *mode)
{
BGZF *fp = 0;
if (strchr(mode, 'r')) {
hFILE *fpr;
if ((fpr = hdopen(fd, mode)) == 0) return 0;
fp = bgzf_read_init(fpr, NULL);
if (fp == 0) { hclose_abruptly(fpr); return NULL; } // FIXME this closes fd
fp->fp = fpr;
} else if (strchr(mode, 'w') || strchr(mode, 'a')) {
hFILE *fpw;
if ((fpw = hdopen(fd, mode)) == 0) return 0;
fp = bgzf_write_init(mode);
if (fp == NULL) return NULL;
fp->fp = fpw;
}
else { errno = EINVAL; return 0; }
fp->is_be = ed_is_big();
return fp;
}
BGZF *bgzf_hopen(hFILE *hfp, const char *mode)
{
BGZF *fp = NULL;
if (strchr(mode, 'r')) {
fp = bgzf_read_init(hfp, NULL);
if (fp == NULL) return NULL;
} else if (strchr(mode, 'w') || strchr(mode, 'a')) {
fp = bgzf_write_init(mode);
if (fp == NULL) return NULL;
}
else { errno = EINVAL; return 0; }
fp->fp = hfp;
fp->is_be = ed_is_big();
return fp;
}
#ifdef HAVE_LIBDEFLATE
int bgzf_compress(void *_dst, size_t *dlen, const void *src, size_t slen, int level)
{
if (slen == 0) {
// EOF block
if (*dlen < 28) return -1;
memcpy(_dst, "\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", 28);
*dlen = 28;
return 0;
}
uint8_t *dst = (uint8_t*)_dst;
if (level == 0) {
// Uncompressed data
if (*dlen < slen+5 + BLOCK_HEADER_LENGTH + BLOCK_FOOTER_LENGTH) return -1;
dst[BLOCK_HEADER_LENGTH] = 1; // BFINAL=1, BTYPE=00; see RFC1951
u16_to_le(slen, &dst[BLOCK_HEADER_LENGTH+1]); // length
u16_to_le(~slen, &dst[BLOCK_HEADER_LENGTH+3]); // ones-complement length
memcpy(dst + BLOCK_HEADER_LENGTH+5, src, slen);
*dlen = slen+5 + BLOCK_HEADER_LENGTH + BLOCK_FOOTER_LENGTH;
} else {
level = level > 0 ? level : 6; // libdeflate doesn't honour -1 as default
// NB levels go up to 12 here.
int lvl_map[] = {0,1,2,3,5,6,7,8,10,12};
level = lvl_map[level>9 ?9 :level];
struct libdeflate_compressor *z = libdeflate_alloc_compressor(level);
if (!z) return -1;
// Raw deflate
size_t clen =
libdeflate_deflate_compress(z, src, slen,
dst + BLOCK_HEADER_LENGTH,
*dlen - BLOCK_HEADER_LENGTH - BLOCK_FOOTER_LENGTH);
if (clen <= 0) {
hts_log_error("Call to libdeflate_deflate_compress failed");
libdeflate_free_compressor(z);
return -1;
}
*dlen = clen + BLOCK_HEADER_LENGTH + BLOCK_FOOTER_LENGTH;
libdeflate_free_compressor(z);
}
// write the header
memcpy(dst, g_magic, BLOCK_HEADER_LENGTH); // the last two bytes are a place holder for the length of the block
packInt16(&dst[16], *dlen - 1); // write the compressed length; -1 to fit 2 bytes
// write the footer
uint32_t crc = libdeflate_crc32(0, src, slen);
packInt32((uint8_t*)&dst[*dlen - 8], crc);
packInt32((uint8_t*)&dst[*dlen - 4], slen);
return 0;
}
#else
int bgzf_compress(void *_dst, size_t *dlen, const void *src, size_t slen, int level)
{
uint32_t crc;
z_stream zs;
uint8_t *dst = (uint8_t*)_dst;
if (level == 0) {
uncomp:
// Uncompressed data
if (*dlen < slen+5 + BLOCK_HEADER_LENGTH + BLOCK_FOOTER_LENGTH) return -1;
dst[BLOCK_HEADER_LENGTH] = 1; // BFINAL=1, BTYPE=00; see RFC1951
u16_to_le(slen, &dst[BLOCK_HEADER_LENGTH+1]); // length
u16_to_le(~slen, &dst[BLOCK_HEADER_LENGTH+3]); // ones-complement length
memcpy(dst + BLOCK_HEADER_LENGTH+5, src, slen);
*dlen = slen+5 + BLOCK_HEADER_LENGTH + BLOCK_FOOTER_LENGTH;
} else {
// compress the body
zs.zalloc = NULL; zs.zfree = NULL;
zs.msg = NULL;
zs.next_in = (Bytef*)src;
zs.avail_in = slen;
zs.next_out = dst + BLOCK_HEADER_LENGTH;
zs.avail_out = *dlen - BLOCK_HEADER_LENGTH - BLOCK_FOOTER_LENGTH;
int ret = deflateInit2(&zs, level, Z_DEFLATED, -15, 8, Z_DEFAULT_STRATEGY); // -15 to disable zlib header/footer
if (ret!=Z_OK) {
hts_log_error("Call to deflateInit2 failed: %s", bgzf_zerr(ret, &zs));
return -1;
}
if ((ret = deflate(&zs, Z_FINISH)) != Z_STREAM_END) {
if (ret == Z_OK && zs.avail_out == 0) {
deflateEnd(&zs);
goto uncomp;
} else {
hts_log_error("Deflate operation failed: %s", bgzf_zerr(ret, ret == Z_DATA_ERROR ? &zs : NULL));
}
return -1;
}
// If we used up the entire output buffer, then we either ran out of
// room or we *just* fitted, but either way we may as well store
// uncompressed for faster decode.
if (zs.avail_out == 0) {
deflateEnd(&zs);
goto uncomp;
}
if ((ret = deflateEnd(&zs)) != Z_OK) {
hts_log_error("Call to deflateEnd failed: %s", bgzf_zerr(ret, NULL));
return -1;
}
*dlen = zs.total_out + BLOCK_HEADER_LENGTH + BLOCK_FOOTER_LENGTH;
}
// write the header
memcpy(dst, g_magic, BLOCK_HEADER_LENGTH); // the last two bytes are a place holder for the length of the block
packInt16(&dst[16], *dlen - 1); // write the compressed length; -1 to fit 2 bytes
// write the footer
crc = crc32(crc32(0L, NULL, 0L), (Bytef*)src, slen);
packInt32((uint8_t*)&dst[*dlen - 8], crc);
packInt32((uint8_t*)&dst[*dlen - 4], slen);
return 0;
}
#endif // HAVE_LIBDEFLATE
static int bgzf_gzip_compress(BGZF *fp, void *_dst, size_t *dlen, const void *src, size_t slen, int level)
{
uint8_t *dst = (uint8_t*)_dst;
z_stream *zs = fp->gz_stream;
int flush = slen ? Z_PARTIAL_FLUSH : Z_FINISH;
zs->next_in = (Bytef*)src;
zs->avail_in = slen;
zs->next_out = dst;
zs->avail_out = *dlen;
int ret = deflate(zs, flush);
if (ret == Z_STREAM_ERROR) {
hts_log_error("Deflate operation failed: %s", bgzf_zerr(ret, NULL));
return -1;
}
if (zs->avail_in != 0) {
hts_log_error("Deflate block too large for output buffer");
return -1;
}
*dlen = *dlen - zs->avail_out;
return 0;
}
// Deflate the block in fp->uncompressed_block into fp->compressed_block. Also adds an extra field that stores the compressed block length.
static int deflate_block(BGZF *fp, int block_length)
{
size_t comp_size = BGZF_MAX_BLOCK_SIZE;
int ret;
if ( !fp->is_gzip )
ret = bgzf_compress(fp->compressed_block, &comp_size, fp->uncompressed_block, block_length, fp->compress_level);
else
ret = bgzf_gzip_compress(fp, fp->compressed_block, &comp_size, fp->uncompressed_block, block_length, fp->compress_level);
if ( ret != 0 )
{
hts_log_debug("Compression error %d", ret);
fp->errcode |= BGZF_ERR_ZLIB;
return -1;
}
fp->block_offset = 0;
return comp_size;
}
#ifdef HAVE_LIBDEFLATE
static int bgzf_uncompress(uint8_t *dst, size_t *dlen,
const uint8_t *src, size_t slen,
uint32_t expected_crc) {
struct libdeflate_decompressor *z = libdeflate_alloc_decompressor();
if (!z) {
hts_log_error("Call to libdeflate_alloc_decompressor failed");
return -1;
}
int ret = libdeflate_deflate_decompress(z, src, slen, dst, *dlen, dlen);
libdeflate_free_decompressor(z);
if (ret != LIBDEFLATE_SUCCESS) {
hts_log_error("Inflate operation failed: %d", ret);
return -1;
}
uint32_t crc = libdeflate_crc32(0, (unsigned char *)dst, *dlen);
if (crc != expected_crc) {
hts_log_error("CRC32 checksum mismatch");
return -2;
}
return 0;
}
#else
static int bgzf_uncompress(uint8_t *dst, size_t *dlen,
const uint8_t *src, size_t slen,
uint32_t expected_crc) {
z_stream zs = {
.zalloc = NULL,
.zfree = NULL,
.msg = NULL,
.next_in = (Bytef*)src,
.avail_in = slen,
.next_out = (Bytef*)dst,
.avail_out = *dlen
};
int ret = inflateInit2(&zs, -15);
if (ret != Z_OK) {
hts_log_error("Call to inflateInit2 failed: %s", bgzf_zerr(ret, &zs));
return -1;
}
if ((ret = inflate(&zs, Z_FINISH)) != Z_STREAM_END) {
hts_log_error("Inflate operation failed: %s", bgzf_zerr(ret, ret == Z_DATA_ERROR ? &zs : NULL));
if ((ret = inflateEnd(&zs)) != Z_OK) {
hts_log_warning("Call to inflateEnd failed: %s", bgzf_zerr(ret, NULL));
}
return -1;
}
if ((ret = inflateEnd(&zs)) != Z_OK) {
hts_log_error("Call to inflateEnd failed: %s", bgzf_zerr(ret, NULL));
return -1;
}
*dlen = *dlen - zs.avail_out;
uint32_t crc = crc32(crc32(0L, NULL, 0L), (unsigned char *)dst, *dlen);
if (crc != expected_crc) {
hts_log_error("CRC32 checksum mismatch");
return -2;
}
return 0;
}
#endif // HAVE_LIBDEFLATE
// Inflate the block in fp->compressed_block into fp->uncompressed_block
static int inflate_block(BGZF* fp, int block_length)
{
size_t dlen = BGZF_MAX_BLOCK_SIZE;
uint32_t crc = le_to_u32((uint8_t *)fp->compressed_block + block_length-8);
int ret = bgzf_uncompress(fp->uncompressed_block, &dlen,
(Bytef*)fp->compressed_block + 18,
block_length - 18, crc);
if (ret < 0) {
if (ret == -2)
fp->errcode |= BGZF_ERR_CRC;
else
fp->errcode |= BGZF_ERR_ZLIB;
return -1;
}
return dlen;
}
// Decompress the next part of a non-blocked GZIP file.
// Return the number of uncompressed bytes read, 0 on EOF, or a negative number on error.
// Will fill the output buffer unless the end of the GZIP file is reached.
static int inflate_gzip_block(BGZF *fp)
{
// we will set this to true when we detect EOF, so we don't bang against the EOF more than once per call
int input_eof = 0;
// write to the part of the output buffer after block_offset
fp->gz_stream->next_out = (Bytef*)fp->uncompressed_block + fp->block_offset;
fp->gz_stream->avail_out = BGZF_MAX_BLOCK_SIZE - fp->block_offset;
while ( fp->gz_stream->avail_out != 0 ) {
// until we fill the output buffer (or hit EOF)
if ( !input_eof && fp->gz_stream->avail_in == 0 ) {
// we are out of input data in the buffer. Get more.
fp->gz_stream->next_in = fp->compressed_block;
int ret = hread(fp->fp, fp->compressed_block, BGZF_BLOCK_SIZE);
if ( ret < 0 ) {
// hread had an error. Pass it on.
return ret;
}
fp->gz_stream->avail_in = ret;
if ( fp->gz_stream->avail_in < BGZF_BLOCK_SIZE ) {
// we have reached EOF but the decompressor hasn't necessarily
input_eof = 1;
}
}
fp->gz_stream->msg = NULL;
// decompress as much data as we can
int ret = inflate(fp->gz_stream, Z_SYNC_FLUSH);
if ( (ret < 0 && ret != Z_BUF_ERROR) || ret == Z_NEED_DICT ) {
// an error occurred, other than running out of space
hts_log_error("Inflate operation failed: %s", bgzf_zerr(ret, ret == Z_DATA_ERROR ? fp->gz_stream : NULL));
fp->errcode |= BGZF_ERR_ZLIB;
return -1;
} else if ( ret == Z_STREAM_END ) {
// we finished a GZIP member
// scratch for peeking to see if the file is over
char c;
if (fp->gz_stream->avail_in > 0 || hpeek(fp->fp, &c, 1) == 1) {
// there is more data; try and read another GZIP member in the remaining data
int reset_ret = inflateReset(fp->gz_stream);
if (reset_ret != Z_OK) {
hts_log_error("Call to inflateReset failed: %s", bgzf_zerr(reset_ret, NULL));
fp->errcode |= BGZF_ERR_ZLIB;
return -1;
}
} else {
// we consumed all the input data and hit Z_STREAM_END
// so stop looping, even if we never fill the output buffer
break;
}
} else if ( ret == Z_BUF_ERROR && input_eof && fp->gz_stream->avail_out > 0 ) {
// the gzip file has ended prematurely
hts_log_error("Gzip file truncated");
fp->errcode |= BGZF_ERR_IO;
return -1;
}
}
// when we get here, the buffer is full or there is an EOF after a complete gzip member
return BGZF_MAX_BLOCK_SIZE - fp->gz_stream->avail_out;
}
// Returns: 0 on success (BGZF header); -1 on non-BGZF GZIP header; -2 on error
static int check_header(const uint8_t *header)
{
if ( header[0] != 31 || header[1] != 139 || header[2] != 8 ) return -2;
return ((header[3] & 4) != 0
&& unpackInt16((uint8_t*)&header[10]) == 6
&& header[12] == 'B' && header[13] == 'C'
&& unpackInt16((uint8_t*)&header[14]) == 2) ? 0 : -1;
}
#ifdef BGZF_CACHE
static void free_cache(BGZF *fp)
{
khint_t k;
if (fp->is_write) return;
khash_t(cache) *h = fp->cache->h;
for (k = kh_begin(h); k < kh_end(h); ++k)
if (kh_exist(h, k)) free(kh_val(h, k).block);
kh_destroy(cache, h);
free(fp->cache);
}
static int load_block_from_cache(BGZF *fp, int64_t block_address)
{
khint_t k;
cache_t *p;
khash_t(cache) *h = fp->cache->h;
k = kh_get(cache, h, block_address);
if (k == kh_end(h)) return 0;
p = &kh_val(h, k);
if (fp->block_length != 0) fp->block_offset = 0;
fp->block_address = block_address;
fp->block_length = p->size;
memcpy(fp->uncompressed_block, p->block, p->size);
if ( hseek(fp->fp, p->end_offset, SEEK_SET) < 0 )
{
// todo: move the error up
hts_log_error("Could not hseek to %" PRId64, p->end_offset);
exit(1);
}
return p->size;
}
static void cache_block(BGZF *fp, int size)
{
int ret;
khint_t k, k_orig;
uint8_t *block = NULL;
cache_t *p;
//fprintf(stderr, "Cache block at %llx\n", (int)fp->block_address);
khash_t(cache) *h = fp->cache->h;
if (BGZF_MAX_BLOCK_SIZE >= fp->cache_size) return;
if (fp->block_length < 0 || fp->block_length > BGZF_MAX_BLOCK_SIZE) return;
if ((kh_size(h) + 1) * BGZF_MAX_BLOCK_SIZE > (uint32_t)fp->cache_size) {
/* Remove uniformly from any position in the hash by a simple
* round-robin approach. An alternative strategy would be to
* remove the least recently accessed block, but the round-robin
* removal is simpler and is not expected to have a big impact
* on performance */
if (fp->cache->last_pos >= kh_end(h)) fp->cache->last_pos = kh_begin(h);
k_orig = k = fp->cache->last_pos;
if (++k >= kh_end(h)) k = kh_begin(h);
while (k != k_orig) {
if (kh_exist(h, k))
break;
if (++k == kh_end(h))
k = kh_begin(h);
}
fp->cache->last_pos = k;
if (k != k_orig) {
block = kh_val(h, k).block;
kh_del(cache, h, k);
}
} else {
block = (uint8_t*)malloc(BGZF_MAX_BLOCK_SIZE);
}
if (!block) return;
k = kh_put(cache, h, fp->block_address, &ret);
if (ret <= 0) { // kh_put failed, or in there already (shouldn't happen)
free(block);
return;
}
p = &kh_val(h, k);
p->size = fp->block_length;
p->end_offset = fp->block_address + size;
p->block = block;
memcpy(p->block, fp->uncompressed_block, p->size);
}
#else
static void free_cache(BGZF *fp) {}
static int load_block_from_cache(BGZF *fp, int64_t block_address) {return 0;}
static void cache_block(BGZF *fp, int size) {}
#endif
/*
* Absolute htell in this compressed file.
*
* Do not confuse with the external bgzf_tell macro which returns the virtual
* offset.
*/
static off_t bgzf_htell(BGZF *fp) {
if (fp->mt) {
pthread_mutex_lock(&fp->mt->job_pool_m);
off_t pos = fp->block_address + fp->block_clength;
pthread_mutex_unlock(&fp->mt->job_pool_m);
return pos;
} else {
return htell(fp->fp);
}
}
int bgzf_read_block(BGZF *fp)
{
hts_tpool_result *r;
if (fp->mt) {
again:
if (fp->mt->hit_eof) {
// Further reading at EOF will always return 0
fp->block_length = 0;
return 0;
}
r = hts_tpool_next_result_wait(fp->mt->out_queue);
bgzf_job *j = r ? (bgzf_job *)hts_tpool_result_data(r) : NULL;