-
Notifications
You must be signed in to change notification settings - Fork 446
/
hts.c
5155 lines (4547 loc) · 165 KB
/
hts.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
/* hts.c -- format-neutral I/O, indexing, and iterator API functions.
Copyright (C) 2008, 2009, 2012-2024 Genome Research Ltd.
Copyright (C) 2012, 2013 Broad Institute.
Author: Heng Li <[email protected]>
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 <zlib.h>
#include <stdio.h>
#include <string.h>
#include <strings.h>
#include <stdlib.h>
#include <unistd.h>
#include <inttypes.h>
#include <limits.h>
#include <stdint.h>
#include <fcntl.h>
#include <errno.h>
#include <time.h>
#include <sys/stat.h>
#include <assert.h>
#ifdef HAVE_LIBLZMA
#ifdef HAVE_LZMA_H
#include <lzma.h>
#else
#include "os/lzma_stub.h"
#endif
#endif
#include "htslib/hts.h"
#include "htslib/bgzf.h"
#include "cram/cram.h"
#include "htslib/hfile.h"
#include "htslib/hts_endian.h"
#include "version.h"
#include "config_vars.h"
#include "hts_internal.h"
#include "hfile_internal.h"
#include "sam_internal.h"
#include "htslib/hts_expr.h"
#include "htslib/hts_os.h" // drand48
#include "htslib/khash.h"
#include "htslib/kseq.h"
#include "htslib/ksort.h"
#include "htslib/tbx.h"
#if defined(HAVE_EXTERNAL_LIBHTSCODECS)
#include <htscodecs/htscodecs.h>
#else
#include "htscodecs/htscodecs/htscodecs.h"
#endif
#ifndef EFTYPE
#define EFTYPE ENOEXEC
#endif
KHASH_INIT2(s2i,, kh_cstr_t, int64_t, 1, kh_str_hash_func, kh_str_hash_equal)
HTSLIB_EXPORT
int hts_verbose = HTS_LOG_WARNING;
const char *hts_version(void)
{
return HTS_VERSION_TEXT;
}
unsigned int hts_features(void) {
unsigned int feat = HTS_FEATURE_HTSCODECS; // Always present
#ifdef PACKAGE_URL
feat |= HTS_FEATURE_CONFIGURE;
#endif
#ifdef ENABLE_PLUGINS
feat |= HTS_FEATURE_PLUGINS;
#endif
#ifdef HAVE_LIBCURL
feat |= HTS_FEATURE_LIBCURL;
#endif
#ifdef ENABLE_S3
feat |= HTS_FEATURE_S3;
#endif
#ifdef ENABLE_GCS
feat |= HTS_FEATURE_GCS;
#endif
#ifdef HAVE_LIBDEFLATE
feat |= HTS_FEATURE_LIBDEFLATE;
#endif
#ifdef HAVE_LIBLZMA
feat |= HTS_FEATURE_LZMA;
#endif
#ifdef HAVE_LIBBZ2
feat |= HTS_FEATURE_BZIP2;
#endif
return feat;
}
const char *hts_test_feature(unsigned int id) {
unsigned int feat = hts_features();
switch (id) {
case HTS_FEATURE_CONFIGURE:
return feat & HTS_FEATURE_CONFIGURE ? "yes" : NULL;
case HTS_FEATURE_PLUGINS:
return feat & HTS_FEATURE_PLUGINS ? "yes" : NULL;
case HTS_FEATURE_LIBCURL:
return feat & HTS_FEATURE_LIBCURL ? "yes" : NULL;
case HTS_FEATURE_S3:
return feat & HTS_FEATURE_S3 ? "yes" : NULL;
case HTS_FEATURE_GCS:
return feat & HTS_FEATURE_GCS ? "yes" : NULL;
case HTS_FEATURE_LIBDEFLATE:
return feat & HTS_FEATURE_LIBDEFLATE ? "yes" : NULL;
case HTS_FEATURE_BZIP2:
return feat & HTS_FEATURE_BZIP2 ? "yes" : NULL;
case HTS_FEATURE_LZMA:
return feat & HTS_FEATURE_LZMA ? "yes" : NULL;
case HTS_FEATURE_HTSCODECS:
return htscodecs_version();
case HTS_FEATURE_CC:
return HTS_CC;
case HTS_FEATURE_CFLAGS:
return HTS_CFLAGS;
case HTS_FEATURE_LDFLAGS:
return HTS_LDFLAGS;
case HTS_FEATURE_CPPFLAGS:
return HTS_CPPFLAGS;
default:
fprintf(stderr, "Unknown feature code: %u\n", id);
}
return NULL;
}
// Note this implementation also means we can just "strings" the library
// to find the configuration parameters.
const char *hts_feature_string(void) {
static char config[1200];
const char *flags=
#ifdef PACKAGE_URL
"build=configure "
#else
"build=Makefile "
#endif
#ifdef HAVE_LIBCURL
"libcurl=yes "
#else
"libcurl=no "
#endif
#ifdef ENABLE_S3
"S3=yes "
#else
"S3=no "
#endif
#ifdef ENABLE_GCS
"GCS=yes "
#else
"GCS=no "
#endif
#ifdef HAVE_LIBDEFLATE
"libdeflate=yes "
#else
"libdeflate=no "
#endif
#ifdef HAVE_LIBLZMA
"lzma=yes "
#else
"lzma=no "
#endif
#ifdef HAVE_LIBBZ2
"bzip2=yes "
#else
"bzip2=no "
#endif
// "plugins=" must stay at the end as it is followed by "plugin-path="
#ifdef ENABLE_PLUGINS
"plugins=yes";
#else
"plugins=no";
#endif
#ifdef ENABLE_PLUGINS
snprintf(config, sizeof(config),
"%s plugin-path=%.1000s htscodecs=%.40s",
flags, hts_plugin_path(), htscodecs_version());
#else
snprintf(config, sizeof(config),
"%s htscodecs=%.40s",
flags, htscodecs_version());
#endif
return config;
}
// Converts ASCII to BAM nibble encoding.
// Note 0123 is treated as ACGT (ABI colourspace encoding) and
// U is treated as T.
HTSLIB_EXPORT
const unsigned char seq_nt16_table[256] = {
15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
1, 2, 4, 8, 15,15,15,15, 15,15,15,15, 15, 0 /*=*/,15,15,
15, 1,14, 2, 13,15,15, 4, 11,15,15,12, 15, 3,15,15,
15,15, 5, 6, 8, 8, 7, 9, 15,10,15,15, 15,15,15,15,
15, 1,14, 2, 13,15,15, 4, 11,15,15,12, 15, 3,15,15,
15,15, 5, 6, 8, 8, 7, 9, 15,10,15,15, 15,15,15,15,
15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15
};
HTSLIB_EXPORT
const char seq_nt16_str[] = "=ACMGRSVTWYHKDBN";
HTSLIB_EXPORT
const int seq_nt16_int[] = { 4, 0, 1, 4, 2, 4, 4, 4, 3, 4, 4, 4, 4, 4, 4, 4 };
/**********************
*** Basic file I/O ***
**********************/
static enum htsFormatCategory format_category(enum htsExactFormat fmt)
{
switch (fmt) {
case bam:
case sam:
case cram:
case fastq_format:
case fasta_format:
return sequence_data;
case vcf:
case bcf:
return variant_data;
case bai:
case crai:
case csi:
case fai_format:
case fqi_format:
case gzi:
case tbi:
return index_file;
case bed:
case d4_format:
return region_list;
case htsget:
case hts_crypt4gh_format:
return unknown_category;
case unknown_format:
case binary_format:
case text_format:
case empty_format:
case format_maximum:
break;
}
return unknown_category;
}
// Decompress several hundred bytes by peeking at the file, which must be
// positioned at the start of a GZIP block.
static ssize_t
decompress_peek_gz(hFILE *fp, unsigned char *dest, size_t destsize)
{
unsigned char buffer[2048];
z_stream zs;
ssize_t npeek = hpeek(fp, buffer, sizeof buffer);
if (npeek < 0) return -1;
zs.zalloc = NULL;
zs.zfree = NULL;
zs.next_in = buffer;
zs.avail_in = npeek;
zs.next_out = dest;
zs.avail_out = destsize;
if (inflateInit2(&zs, 31) != Z_OK) return -1;
int ret;
const unsigned char *last_in = buffer;
while (zs.avail_out > 0) {
ret = inflate(&zs, Z_SYNC_FLUSH);
if (ret == Z_STREAM_END) {
if (last_in == zs.next_in)
break; // Paranoia to avoid potential looping. Shouldn't happen
else
last_in = zs.next_in;
inflateReset(&zs);
} else if (ret != Z_OK) {
// eg Z_BUF_ERROR due to avail_in/out becoming zero
break;
}
}
// NB: zs.total_out is changed by inflateReset, so use pointer diff instead
destsize = zs.next_out - dest;
inflateEnd(&zs);
return destsize;
}
#ifdef HAVE_LIBLZMA
// Similarly decompress a portion by peeking at the file, which must be
// positioned at the start of the file.
static ssize_t
decompress_peek_xz(hFILE *fp, unsigned char *dest, size_t destsize)
{
unsigned char buffer[2048];
ssize_t npeek = hpeek(fp, buffer, sizeof buffer);
if (npeek < 0) return -1;
lzma_stream ls = LZMA_STREAM_INIT;
if (lzma_stream_decoder(&ls, lzma_easy_decoder_memusage(9), 0) != LZMA_OK)
return -1;
ls.next_in = buffer;
ls.avail_in = npeek;
ls.next_out = dest;
ls.avail_out = destsize;
int r = lzma_code(&ls, LZMA_RUN);
if (! (r == LZMA_OK || r == LZMA_STREAM_END)) {
lzma_end(&ls);
return -1;
}
destsize = ls.total_out;
lzma_end(&ls);
return destsize;
}
#endif
// Parse "x.y" text, taking care because the string is not NUL-terminated
// and filling in major/minor only when the digits are followed by a delimiter,
// so we don't misread "1.10" as "1.1" due to reaching the end of the buffer.
static void
parse_version(htsFormat *fmt, const unsigned char *u, const unsigned char *ulim)
{
const char *s = (const char *) u;
const char *slim = (const char *) ulim;
short v;
fmt->version.major = fmt->version.minor = -1;
for (v = 0; s < slim && isdigit_c(*s); s++)
v = 10 * v + *s - '0';
if (s < slim) {
fmt->version.major = v;
if (*s == '.') {
s++;
for (v = 0; s < slim && isdigit_c(*s); s++)
v = 10 * v + *s - '0';
if (s < slim)
fmt->version.minor = v;
}
else
fmt->version.minor = 0;
}
}
static int
cmp_nonblank(const char *key, const unsigned char *u, const unsigned char *ulim)
{
const unsigned char *ukey = (const unsigned char *) key;
while (*ukey)
if (u >= ulim) return +1;
else if (isspace_c(*u)) u++;
else if (*u != *ukey) return (*ukey < *u)? -1 : +1;
else u++, ukey++;
return 0;
}
static int is_text_only(const unsigned char *u, const unsigned char *ulim)
{
for (; u < ulim; u++)
if (! (*u >= ' ' || *u == '\t' || *u == '\r' || *u == '\n'))
return 0;
return 1;
}
static inline int
alternate_zeros(const unsigned char *u, const unsigned char *ulim)
{
for (; u < ulim; u += 2)
if (*u != '\0') return 0;
return 1;
}
static int is_utf16_text(const unsigned char *u, const unsigned char *ulim)
{
if (ulim - u >= 6 &&
((u[0] == 0xfe && u[1] == 0xff && alternate_zeros(u+2, ulim)) ||
(u[0] == 0xff && u[1] == 0xfe && alternate_zeros(u+3, ulim))))
return 2;
else if (ulim - u >= 8 &&
(alternate_zeros(u, ulim) || alternate_zeros(u+1, ulim)))
return 1;
else
return 0;
}
static int is_fastaq(const unsigned char *u, const unsigned char *ulim)
{
const unsigned char *eol = memchr(u, '\n', ulim - u);
// Check that the first line is entirely textual
if (! is_text_only(u, eol? eol : ulim)) return 0;
// If the first line is very long, consider the file to indeed be FASTA/Q
if (eol == NULL) return 1;
u = eol+1; // Now points to the first character of the second line
// Scan over all base-encoding letters (including 'N' but not SEQ's '=')
while (u < ulim && (seq_nt16_table[*u] != 15 || toupper(*u) == 'N')) {
if (*u == '=') return 0;
u++;
}
return (u == ulim || *u == '\r' || *u == '\n')? 1 : 0;
}
// Parse tab-delimited text, filling in a string of column types and returning
// the number of columns spotted (within [u,ulim), and up to column_len) or -1
// if non-printable characters were seen. Column types:
// i: integer, s: strand sign, C: CIGAR, O: SAM optional field, Z: anything
static int
parse_tabbed_text(char *columns, int column_len,
const unsigned char *u, const unsigned char *ulim,
int *complete)
{
const char *str = (const char *) u;
const char *slim = (const char *) ulim;
const char *s;
int ncolumns = 0;
enum { digit = 1, leading_sign = 2, cigar_operator = 4, other = 8 };
unsigned seen = 0;
*complete = 0;
for (s = str; s < slim; s++)
if (*s >= ' ') {
if (isdigit_c(*s))
seen |= digit;
else if ((*s == '+' || *s == '-') && s == str)
seen |= leading_sign;
else if (strchr(BAM_CIGAR_STR, *s) && s > str && isdigit_c(s[-1]))
seen |= cigar_operator;
else
seen |= other;
}
else if (*s == '\t' || *s == '\r' || *s == '\n') {
size_t len = s - str;
char type;
if (seen == digit || seen == (leading_sign|digit)) type = 'i';
else if (seen == (digit|cigar_operator)) type = 'C';
else if (len == 1)
switch (str[0]) {
case '*': type = 'C'; break;
case '+': case '-': case '.': type = 's'; break;
default: type = 'Z'; break;
}
else if (len >= 5 && str[2] == ':' && str[4] == ':') type = 'O';
else type = 'Z';
columns[ncolumns++] = type;
if (*s != '\t' || ncolumns >= column_len - 1) {
*complete = 1; // finished the line or more columns than needed
break;
}
str = s + 1;
seen = 0;
}
else return -1;
columns[ncolumns] = '\0';
return ncolumns;
}
// Match COLUMNS as a prefix against PATTERN (so COLUMNS may run out first).
// Returns len(COLUMNS) (modulo '+'), or 0 if there is a mismatched entry.
static int colmatch(const char *columns, const char *pattern)
{
int i;
for (i = 0; columns[i] != '\0'; i++) {
if (pattern[i] == '+') return i;
if (! (columns[i] == pattern[i] || pattern[i] == 'Z')) return 0;
}
return i;
}
int hts_detect_format(hFILE *hfile, htsFormat *fmt)
{
return hts_detect_format2(hfile, NULL, fmt);
}
int hts_detect_format2(hFILE *hfile, const char *fname, htsFormat *fmt)
{
char extension[HTS_MAX_EXT_LEN], columns[24];
unsigned char s[1024];
int complete = 0;
ssize_t len = hpeek(hfile, s, 18);
if (len < 0) return -1;
fmt->category = unknown_category;
fmt->format = unknown_format;
fmt->version.major = fmt->version.minor = -1;
fmt->compression = no_compression;
fmt->compression_level = -1;
fmt->specific = NULL;
if (len >= 2 && s[0] == 0x1f && s[1] == 0x8b) {
// The stream is either gzip-compressed or BGZF-compressed.
// Determine which, and decompress the first few records or lines.
fmt->compression = gzip;
if (len >= 18 && (s[3] & 4)) {
if (memcmp(&s[12], "BC\2\0", 4) == 0)
fmt->compression = bgzf;
else if (memcmp(&s[12], "RAZF", 4) == 0)
fmt->compression = razf_compression;
}
if (len >= 9 && s[2] == 8)
fmt->compression_level = (s[8] == 2)? 9 : (s[8] == 4)? 1 : -1;
len = decompress_peek_gz(hfile, s, sizeof s);
}
else if (len >= 10 && memcmp(s, "BZh", 3) == 0 &&
(memcmp(&s[4], "\x31\x41\x59\x26\x53\x59", 6) == 0 ||
memcmp(&s[4], "\x17\x72\x45\x38\x50\x90", 6) == 0)) {
fmt->compression = bzip2_compression;
fmt->compression_level = s[3] - '0';
// Decompressing via libbz2 produces no output until it has a whole
// block (of size 100Kb x level), which is too large for peeking.
// So unfortunately we can recognise bzip2 but not the contents,
// except that \x1772... magic indicates the stream is empty.
if (s[4] == '\x31') return 0;
else len = 0;
}
else if (len >= 6 && memcmp(s, "\xfd""7zXZ\0", 6) == 0) {
fmt->compression = xz_compression;
#ifdef HAVE_LIBLZMA
len = decompress_peek_xz(hfile, s, sizeof s);
#else
// Without liblzma, we can't recognise the decompressed contents.
return 0;
#endif
}
else if (len >= 4 && memcmp(s, "\x28\xb5\x2f\xfd", 4) == 0) {
fmt->compression = zstd_compression;
return 0;
}
else {
len = hpeek(hfile, s, sizeof s);
}
if (len < 0) return -1;
if (len == 0) {
fmt->format = empty_format;
return 0;
}
// We avoid using filename extensions wherever possible (as filenames are
// not always available), but in a few cases they must be considered:
// - FASTA/Q indexes are simply tab-separated text; files that match these
// patterns but not the fai/fqi extension are usually generic BED files
// - GZI indexes have no magic numbers so can only be detected by filename
if (fname && strcmp(fname, "-") != 0) {
char *s;
if (find_file_extension(fname, extension) < 0) extension[0] = '\0';
for (s = extension; *s; s++) *s = tolower_c(*s);
}
else extension[0] = '\0';
if (len >= 6 && memcmp(s,"CRAM",4) == 0 && s[4]>=1 && s[4]<=7 && s[5]<=7) {
fmt->category = sequence_data;
fmt->format = cram;
fmt->version.major = s[4], fmt->version.minor = s[5];
fmt->compression = custom;
return 0;
}
else if (len >= 4 && s[3] <= '\4') {
if (memcmp(s, "BAM\1", 4) == 0) {
fmt->category = sequence_data;
fmt->format = bam;
// TODO Decompress enough to pick version from @HD-VN header
fmt->version.major = 1, fmt->version.minor = -1;
return 0;
}
else if (memcmp(s, "BAI\1", 4) == 0) {
fmt->category = index_file;
fmt->format = bai;
fmt->version.major = -1, fmt->version.minor = -1;
return 0;
}
else if (memcmp(s, "BCF\4", 4) == 0) {
fmt->category = variant_data;
fmt->format = bcf;
fmt->version.major = 1, fmt->version.minor = -1;
return 0;
}
else if (memcmp(s, "BCF\2", 4) == 0) {
fmt->category = variant_data;
fmt->format = bcf;
fmt->version.major = s[3];
fmt->version.minor = (len >= 5 && s[4] <= 2)? s[4] : 0;
return 0;
}
else if (memcmp(s, "CSI\1", 4) == 0) {
fmt->category = index_file;
fmt->format = csi;
fmt->version.major = 1, fmt->version.minor = -1;
return 0;
}
else if (memcmp(s, "TBI\1", 4) == 0) {
fmt->category = index_file;
fmt->format = tbi;
return 0;
}
// GZI indexes have no magic numbers, so must be recognised solely by
// filename extension.
else if (strcmp(extension, "gzi") == 0) {
fmt->category = index_file;
fmt->format = gzi;
return 0;
}
}
else if (len >= 16 && memcmp(s, "##fileformat=VCF", 16) == 0) {
fmt->category = variant_data;
fmt->format = vcf;
if (len >= 21 && s[16] == 'v')
parse_version(fmt, &s[17], &s[len]);
return 0;
}
else if (len >= 4 && s[0] == '@' &&
(memcmp(s, "@HD\t", 4) == 0 || memcmp(s, "@SQ\t", 4) == 0 ||
memcmp(s, "@RG\t", 4) == 0 || memcmp(s, "@PG\t", 4) == 0 ||
memcmp(s, "@CO\t", 4) == 0)) {
fmt->category = sequence_data;
fmt->format = sam;
// @HD-VN is not guaranteed to be the first tag, but then @HD is
// not guaranteed to be present at all...
if (len >= 9 && memcmp(s, "@HD\tVN:", 7) == 0)
parse_version(fmt, &s[7], &s[len]);
else
fmt->version.major = 1, fmt->version.minor = -1;
return 0;
}
else if (len >= 8 && memcmp(s, "d4\xdd\xdd", 4) == 0) {
fmt->category = region_list;
fmt->format = d4_format;
// How to decode the D4 Format Version bytes is not yet specified
// so we don't try to set fmt->version.{major,minor}.
return 0;
}
else if (cmp_nonblank("{\"htsget\":", s, &s[len]) == 0) {
fmt->category = unknown_category;
fmt->format = htsget;
return 0;
}
else if (len > 8 && memcmp(s, "crypt4gh", 8) == 0) {
fmt->category = unknown_category;
fmt->format = hts_crypt4gh_format;
return 0;
}
else if (len >= 1 && s[0] == '>' && is_fastaq(s, &s[len])) {
fmt->category = sequence_data;
fmt->format = fasta_format;
return 0;
}
else if (len >= 1 && s[0] == '@' && is_fastaq(s, &s[len])) {
fmt->category = sequence_data;
fmt->format = fastq_format;
return 0;
}
else if (parse_tabbed_text(columns, sizeof columns, s,
&s[len], &complete) > 0) {
// A complete SAM line is at least 11 columns. On unmapped long reads may
// be missing two. (On mapped long reads we must have an @ header so long
// CIGAR is irrelevant.)
if (colmatch(columns, "ZiZiiCZiiZZOOOOOOOOOOOOOOOOOOOO+")
>= 9 + 2*complete) {
fmt->category = sequence_data;
fmt->format = sam;
fmt->version.major = 1, fmt->version.minor = -1;
return 0;
}
else if (fmt->compression == gzip && colmatch(columns, "iiiiii") == 6) {
fmt->category = index_file;
fmt->format = crai;
return 0;
}
else if (strstr(extension, "fqi") && colmatch(columns, "Ziiiii") == 6) {
fmt->category = index_file;
fmt->format = fqi_format;
return 0;
}
else if (strstr(extension, "fai") && colmatch(columns, "Ziiii") == 5) {
fmt->category = index_file;
fmt->format = fai_format;
return 0;
}
else if (colmatch(columns, "Zii+") >= 3) {
fmt->category = region_list;
fmt->format = bed;
return 0;
}
}
// Arbitrary text files can be read using hts_getline().
if (is_text_only(s, &s[len])) fmt->format = text_format;
// Nothing recognised: leave unset fmt-> fields as unknown.
return 0;
}
char *hts_format_description(const htsFormat *format)
{
kstring_t str = { 0, 0, NULL };
switch (format->format) {
case sam: kputs("SAM", &str); break;
case bam: kputs("BAM", &str); break;
case cram: kputs("CRAM", &str); break;
case fasta_format: kputs("FASTA", &str); break;
case fastq_format: kputs("FASTQ", &str); break;
case vcf: kputs("VCF", &str); break;
case bcf:
if (format->version.major == 1) kputs("Legacy BCF", &str);
else kputs("BCF", &str);
break;
case bai: kputs("BAI", &str); break;
case crai: kputs("CRAI", &str); break;
case csi: kputs("CSI", &str); break;
case fai_format: kputs("FASTA-IDX", &str); break;
case fqi_format: kputs("FASTQ-IDX", &str); break;
case gzi: kputs("GZI", &str); break;
case tbi: kputs("Tabix", &str); break;
case bed: kputs("BED", &str); break;
case d4_format: kputs("D4", &str); break;
case htsget: kputs("htsget", &str); break;
case hts_crypt4gh_format: kputs("crypt4gh", &str); break;
case empty_format: kputs("empty", &str); break;
default: kputs("unknown", &str); break;
}
if (format->version.major >= 0) {
kputs(" version ", &str);
kputw(format->version.major, &str);
if (format->version.minor >= 0) {
kputc('.', &str);
kputw(format->version.minor, &str);
}
}
switch (format->compression) {
case bzip2_compression: kputs(" bzip2-compressed", &str); break;
case razf_compression: kputs(" legacy-RAZF-compressed", &str); break;
case xz_compression: kputs(" XZ-compressed", &str); break;
case zstd_compression: kputs(" Zstandard-compressed", &str); break;
case custom: kputs(" compressed", &str); break;
case gzip: kputs(" gzip-compressed", &str); break;
case bgzf:
switch (format->format) {
case bam:
case bcf:
case csi:
case tbi:
// These are by definition BGZF, so just use the generic term
kputs(" compressed", &str);
break;
default:
kputs(" BGZF-compressed", &str);
break;
}
break;
case no_compression:
switch (format->format) {
case bam:
case bcf:
case cram:
case csi:
case tbi:
// These are normally compressed, so emphasise that this one isn't
kputs(" uncompressed", &str);
break;
default:
break;
}
break;
default: break;
}
switch (format->category) {
case sequence_data: kputs(" sequence", &str); break;
case variant_data: kputs(" variant calling", &str); break;
case index_file: kputs(" index", &str); break;
case region_list: kputs(" genomic region", &str); break;
default: break;
}
if (format->compression == no_compression)
switch (format->format) {
case text_format:
case sam:
case crai:
case vcf:
case bed:
case fai_format:
case fqi_format:
case fasta_format:
case fastq_format:
case htsget:
kputs(" text", &str);
break;
case empty_format:
break;
default:
kputs(" data", &str);
break;
}
else
kputs(" data", &str);
return ks_release(&str);
}
htsFile *hts_open_format(const char *fn, const char *mode, const htsFormat *fmt)
{
char smode[101], *cp, *cp2, *mode_c, *uncomp = NULL;
htsFile *fp = NULL;
hFILE *hfile = NULL;
char fmt_code = '\0';
// see enum htsExactFormat in htslib/hts.h
const char format_to_mode[] = "\0g\0\0b\0c\0\0b\0g\0\0\0\0\0Ff\0\0";
strncpy(smode, mode, 99);
smode[99]=0;
if ((cp = strchr(smode, ',')))
*cp = '\0';
// Migrate format code (b or c) to the end of the smode buffer.
for (cp2 = cp = smode; *cp; cp++) {
if (*cp == 'b')
fmt_code = 'b';
else if (*cp == 'c')
fmt_code = 'c';
else {
*cp2++ = *cp;
// Cache the uncompress flag 'u' pos if present
if (!uncomp && (*cp == 'u')) {
uncomp = cp2 - 1;
}
}
}
mode_c = cp2;
*cp2++ = fmt_code;
*cp2++ = 0;
// Set or reset the format code if opts->format is used
if (fmt && fmt->format > unknown_format
&& fmt->format < sizeof(format_to_mode)) {
*mode_c = format_to_mode[fmt->format];
}
// Uncompressed bam/bcf is not supported, change 'u' to '0' on write
if (uncomp && *mode_c == 'b' && (strchr(smode, 'w') || strchr(smode, 'a'))) {
*uncomp = '0';
}
// If we really asked for a compressed text format then mode_c above will
// point to nul. We set to 'z' to enable bgzf.
if (strchr(mode, 'w') && fmt && fmt->compression == bgzf) {
if (fmt->format == sam || fmt->format == vcf || fmt->format == text_format)
*mode_c = 'z';
}
char *rmme = NULL, *fnidx = strstr(fn, HTS_IDX_DELIM);
if ( fnidx ) {
rmme = strdup(fn);
if ( !rmme ) goto error;
rmme[fnidx-fn] = 0;
fn = rmme;
}
hfile = hopen(fn, smode);
if (hfile == NULL) goto error;
fp = hts_hopen(hfile, fn, smode);
if (fp == NULL) goto error;
// Compensate for the loss of exactness in htsExactFormat.
// hts_hopen returns generics such as binary or text, but we
// have been given something explicit here so use that instead.
if (fp->is_write && fmt &&
(fmt->format == bam || fmt->format == sam ||
fmt->format == vcf || fmt->format == bcf ||
fmt->format == bed || fmt->format == fasta_format ||
fmt->format == fastq_format))
fp->format.format = fmt->format;
if (fmt && fmt->specific) {
if (hts_opt_apply(fp, fmt->specific) != 0) {
if (((hts_opt*)fmt->specific)->opt == CRAM_OPT_REFERENCE &&
(errno == ENOENT || errno == EIO || errno == EBADF ||
errno == EACCES || errno == EISDIR)) {
/* error during reference file operation
for these specific errors, set the error as EINVAL */
errno = EINVAL;
}
goto error;
}
}
if ( rmme ) free(rmme);
return fp;
error:
hts_log_error("Failed to open file \"%s\"%s%s", fn,
errno ? " : " : "", errno ? strerror(errno) : "");
if ( rmme ) free(rmme);
if (hfile)
hclose_abruptly(hfile);
return NULL;
}
htsFile *hts_open(const char *fn, const char *mode) {
return hts_open_format(fn, mode, NULL);
}
/*
* Splits str into a prefix, delimiter ('\0' or delim), and suffix, writing
* the prefix in lowercase into buf and returning a pointer to the suffix.
* On return, buf is always NUL-terminated; thus assumes that the "keyword"
* prefix should be one of several known values of maximum length buflen-2.
* (If delim is not found, returns a pointer to the '\0'.)