forked from samtools/htslib
-
Notifications
You must be signed in to change notification settings - Fork 1
/
sam.c
2685 lines (2422 loc) · 87.3 KB
/
sam.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
/* sam.c -- SAM and BAM file I/O and manipulation.
Copyright (C) 2008-2010, 2012-2018 Genome Research Ltd.
Copyright (C) 2010, 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. */
#include <config.h>
#include <strings.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <zlib.h>
#include <assert.h>
#include "htslib/sam.h"
#include "htslib/bgzf.h"
#include "cram/cram.h"
#include "hts_internal.h"
#include "htslib/hfile.h"
#include "htslib/hts_endian.h"
#include "htslib/khash.h"
KHASH_DECLARE(s2i, kh_cstr_t, int64_t)
typedef khash_t(s2i) sdict_t;
#ifndef EOVERFLOW
#define EOVERFLOW ERANGE
#endif
/**********************
*** BAM header I/O ***
**********************/
bam_hdr_t *bam_hdr_init()
{
return (bam_hdr_t*)calloc(1, sizeof(bam_hdr_t));
}
void bam_hdr_destroy(bam_hdr_t *h)
{
int32_t i;
if (h == NULL) return;
if (h->target_name) {
for (i = 0; i < h->n_targets; ++i)
free(h->target_name[i]);
free(h->target_name);
free(h->target_len);
}
free(h->text); free(h->cigar_tab);
if (h->sdict) kh_destroy(s2i, (sdict_t*)h->sdict);
free(h);
}
bam_hdr_t *bam_hdr_dup(const bam_hdr_t *h0)
{
if (h0 == NULL) return NULL;
bam_hdr_t *h;
if ((h = bam_hdr_init()) == NULL) return NULL;
// copy the simple data
h->n_targets = h0->n_targets;
h->ignore_sam_err = h0->ignore_sam_err;
h->l_text = h0->l_text;
// Then the pointery stuff
h->cigar_tab = NULL;
h->sdict = NULL;
// TODO Check for memory allocation failures
h->text = (char*)calloc(h->l_text + 1, 1);
memcpy(h->text, h0->text, h->l_text);
h->target_len = (uint32_t*)calloc(h->n_targets, sizeof(uint32_t));
h->target_name = (char**)calloc(h->n_targets, sizeof(char*));
int i;
for (i = 0; i < h->n_targets; ++i) {
h->target_len[i] = h0->target_len[i];
h->target_name[i] = strdup(h0->target_name[i]);
}
return h;
}
static bam_hdr_t *hdr_from_dict(sdict_t *d)
{
bam_hdr_t *h;
khint_t k;
h = bam_hdr_init();
h->sdict = d;
h->n_targets = kh_size(d);
// TODO Check for memory allocation failures
h->target_len = (uint32_t*)malloc(sizeof(uint32_t) * h->n_targets);
h->target_name = (char**)malloc(sizeof(char*) * h->n_targets);
for (k = kh_begin(d); k != kh_end(d); ++k) {
if (!kh_exist(d, k)) continue;
h->target_name[kh_val(d, k)>>32] = (char*)kh_key(d, k);
h->target_len[kh_val(d, k)>>32] = kh_val(d, k) & 0xffffffffUL;
kh_val(d, k) >>= 32;
}
return h;
}
bam_hdr_t *bam_hdr_read(BGZF *fp)
{
bam_hdr_t *h;
char buf[4];
int magic_len, has_EOF;
int32_t i, name_len, num_names = 0;
size_t bufsize;
ssize_t bytes;
// check EOF
has_EOF = bgzf_check_EOF(fp);
if (has_EOF < 0) {
perror("[W::bam_hdr_read] bgzf_check_EOF");
} else if (has_EOF == 0) {
hts_log_warning("EOF marker is absent. The input is probably truncated");
}
// read "BAM1"
magic_len = bgzf_read(fp, buf, 4);
if (magic_len != 4 || strncmp(buf, "BAM\1", 4)) {
hts_log_error("Invalid BAM binary header");
return 0;
}
h = bam_hdr_init();
if (!h) goto nomem;
// read plain text and the number of reference sequences
bytes = bgzf_read(fp, &h->l_text, 4);
if (bytes != 4) goto read_err;
if (fp->is_be) ed_swap_4p(&h->l_text);
bufsize = ((size_t) h->l_text) + 1;
if (bufsize < h->l_text) goto nomem; // so large that adding 1 overflowed
h->text = (char*)malloc(bufsize);
if (!h->text) goto nomem;
h->text[h->l_text] = 0; // make sure it is NULL terminated
bytes = bgzf_read(fp, h->text, h->l_text);
if (bytes != h->l_text) goto read_err;
bytes = bgzf_read(fp, &h->n_targets, 4);
if (bytes != 4) goto read_err;
if (fp->is_be) ed_swap_4p(&h->n_targets);
if (h->n_targets < 0) goto invalid;
// read reference sequence names and lengths
if (h->n_targets > 0) {
h->target_name = (char**)calloc(h->n_targets, sizeof(char*));
if (!h->target_name) goto nomem;
h->target_len = (uint32_t*)calloc(h->n_targets, sizeof(uint32_t));
if (!h->target_len) goto nomem;
}
else {
h->target_name = NULL;
h->target_len = NULL;
}
for (i = 0; i != h->n_targets; ++i) {
bytes = bgzf_read(fp, &name_len, 4);
if (bytes != 4) goto read_err;
if (fp->is_be) ed_swap_4p(&name_len);
if (name_len <= 0) goto invalid;
h->target_name[i] = (char*)malloc(name_len);
if (!h->target_name[i]) goto nomem;
num_names++;
bytes = bgzf_read(fp, h->target_name[i], name_len);
if (bytes != name_len) goto read_err;
if (h->target_name[i][name_len - 1] != '\0') {
/* Fix missing NUL-termination. Is this being too nice?
We could alternatively bail out with an error. */
char *new_name;
if (name_len == INT32_MAX) goto invalid;
new_name = realloc(h->target_name[i], name_len + 1);
if (new_name == NULL) goto nomem;
h->target_name[i] = new_name;
h->target_name[i][name_len] = '\0';
}
bytes = bgzf_read(fp, &h->target_len[i], 4);
if (bytes != 4) goto read_err;
if (fp->is_be) ed_swap_4p(&h->target_len[i]);
}
return h;
nomem:
hts_log_error("Out of memory");
goto clean;
read_err:
if (bytes < 0) {
hts_log_error("Error reading BGZF stream");
} else {
hts_log_error("Truncated BAM header");
}
goto clean;
invalid:
hts_log_error("Invalid BAM binary header");
clean:
if (h != NULL) {
h->n_targets = num_names; // ensure we free only allocated target_names
bam_hdr_destroy(h);
}
return NULL;
}
int bam_hdr_write(BGZF *fp, const bam_hdr_t *h)
{
char buf[4];
int32_t i, name_len, x;
// write "BAM1"
strncpy(buf, "BAM\1", 4);
if (bgzf_write(fp, buf, 4) < 0) return -1;
// write plain text and the number of reference sequences
if (fp->is_be) {
x = ed_swap_4(h->l_text);
if (bgzf_write(fp, &x, 4) < 0) return -1;
if (h->l_text) {
if (bgzf_write(fp, h->text, h->l_text) < 0) return -1;
}
x = ed_swap_4(h->n_targets);
if (bgzf_write(fp, &x, 4) < 0) return -1;
} else {
if (bgzf_write(fp, &h->l_text, 4) < 0) return -1;
if (h->l_text) {
if (bgzf_write(fp, h->text, h->l_text) < 0) return -1;
}
if (bgzf_write(fp, &h->n_targets, 4) < 0) return -1;
}
// write sequence names and lengths
for (i = 0; i != h->n_targets; ++i) {
char *p = h->target_name[i];
name_len = strlen(p) + 1;
if (fp->is_be) {
x = ed_swap_4(name_len);
if (bgzf_write(fp, &x, 4) < 0) return -1;
} else {
if (bgzf_write(fp, &name_len, 4) < 0) return -1;
}
if (bgzf_write(fp, p, name_len) < 0) return -1;
if (fp->is_be) {
x = ed_swap_4(h->target_len[i]);
if (bgzf_write(fp, &x, 4) < 0) return -1;
} else {
if (bgzf_write(fp, &h->target_len[i], 4) < 0) return -1;
}
}
if (bgzf_flush(fp) < 0) return -1;
return 0;
}
int bam_name2id(bam_hdr_t *h, const char *ref)
{
sdict_t *d = (sdict_t*)h->sdict;
khint_t k;
if (h->sdict == 0) {
int i, absent;
d = kh_init(s2i);
for (i = 0; i < h->n_targets; ++i) {
k = kh_put(s2i, d, h->target_name[i], &absent);
kh_val(d, k) = i;
}
h->sdict = d;
}
k = kh_get(s2i, d, ref);
return k == kh_end(d)? -1 : kh_val(d, k);
}
/*************************
*** BAM alignment I/O ***
*************************/
bam1_t *bam_init1()
{
return (bam1_t*)calloc(1, sizeof(bam1_t));
}
void bam_destroy1(bam1_t *b)
{
if (b == 0) return;
free(b->data); free(b);
}
bam1_t *bam_copy1(bam1_t *bdst, const bam1_t *bsrc)
{
uint8_t *data = bdst->data;
int m_data = bdst->m_data; // backup data and m_data
if (m_data < bsrc->l_data) { // double the capacity
m_data = bsrc->l_data; kroundup32(m_data);
data = (uint8_t*)realloc(data, m_data);
}
memcpy(data, bsrc->data, bsrc->l_data); // copy var-len data
*bdst = *bsrc; // copy the rest
// restore the backup
bdst->m_data = m_data;
bdst->data = data;
return bdst;
}
bam1_t *bam_dup1(const bam1_t *bsrc)
{
if (bsrc == NULL) return NULL;
bam1_t *bdst = bam_init1();
if (bdst == NULL) return NULL;
return bam_copy1(bdst, bsrc);
}
void bam_cigar2rqlens(int n_cigar, const uint32_t *cigar, int *rlen, int *qlen)
{
int k;
*rlen = *qlen = 0;
for (k = 0; k < n_cigar; ++k) {
int type = bam_cigar_type(bam_cigar_op(cigar[k]));
int len = bam_cigar_oplen(cigar[k]);
if (type & 1) *qlen += len;
if (type & 2) *rlen += len;
}
}
int bam_cigar2qlen(int n_cigar, const uint32_t *cigar)
{
int k, l;
for (k = l = 0; k < n_cigar; ++k)
if (bam_cigar_type(bam_cigar_op(cigar[k]))&1)
l += bam_cigar_oplen(cigar[k]);
return l;
}
int bam_cigar2rlen(int n_cigar, const uint32_t *cigar)
{
int k, l;
for (k = l = 0; k < n_cigar; ++k)
if (bam_cigar_type(bam_cigar_op(cigar[k]))&2)
l += bam_cigar_oplen(cigar[k]);
return l;
}
int32_t bam_endpos(const bam1_t *b)
{
if (!(b->core.flag & BAM_FUNMAP) && b->core.n_cigar > 0)
return b->core.pos + bam_cigar2rlen(b->core.n_cigar, bam_get_cigar(b));
else
return b->core.pos + 1;
}
static int bam_tag2cigar(bam1_t *b, int recal_bin, int give_warning) // return 0 if CIGAR is untouched; 1 if CIGAR is updated with CG
{
bam1_core_t *c = &b->core;
uint32_t cigar_st, n_cigar4, CG_st, CG_en, ori_len = b->l_data, *cigar0, CG_len, fake_bytes;
uint8_t *CG;
// test where there is a real CIGAR in the CG tag to move
if (c->n_cigar == 0 || c->tid < 0 || c->pos < 0) return 0;
cigar0 = bam_get_cigar(b);
if (bam_cigar_op(cigar0[0]) != BAM_CSOFT_CLIP || bam_cigar_oplen(cigar0[0]) != c->l_qseq) return 0;
fake_bytes = c->n_cigar * 4;
if ((CG = bam_aux_get(b, "CG")) == 0) return 0; // no CG tag
if (CG[0] != 'B' || CG[1] != 'I') return 0; // not of type B,I
CG_len = le_to_u32(CG + 2);
if (CG_len < c->n_cigar || CG_len >= 1U<<29) return 0; // don't move if the real CIGAR length is shorter than the fake cigar length
// move from the CG tag to the right position
cigar_st = (uint8_t*)cigar0 - b->data;
c->n_cigar = CG_len;
n_cigar4 = c->n_cigar * 4;
CG_st = CG - b->data - 2;
CG_en = CG_st + 8 + n_cigar4;
b->l_data = b->l_data - fake_bytes + n_cigar4; // we need c->n_cigar-fake_bytes bytes to swap CIGAR to the right place
if (b->m_data < b->l_data) {
uint8_t *new_data;
uint32_t new_max = b->l_data;
kroundup32(new_max);
new_data = (uint8_t*)realloc(b->data, new_max);
if (new_data == 0) return -1;
b->m_data = new_max, b->data = new_data;
}
memmove(b->data + cigar_st + n_cigar4, b->data + cigar_st + fake_bytes, ori_len - (cigar_st + fake_bytes)); // insert c->n_cigar-fake_bytes empty space to make room
memcpy(b->data + cigar_st, b->data + (n_cigar4 - fake_bytes) + CG_st + 8, n_cigar4); // copy the real CIGAR to the right place; -fake_bytes for the fake CIGAR
if (ori_len > CG_en) // move data after the CG tag
memmove(b->data + CG_st + n_cigar4 - fake_bytes, b->data + CG_en + n_cigar4 - fake_bytes, ori_len - CG_en);
b->l_data -= n_cigar4 + 8; // 8: CGBI (4 bytes) and CGBI length (4)
if (recal_bin)
b->core.bin = hts_reg2bin(b->core.pos, b->core.pos + bam_cigar2rlen(b->core.n_cigar, bam_get_cigar(b)), 14, 5);
if (give_warning)
hts_log_error("%s encodes a CIGAR with %d operators at the CG tag", bam_get_qname(b), c->n_cigar);
return 1;
}
static inline int aux_type2size(uint8_t type)
{
switch (type) {
case 'A': case 'c': case 'C':
return 1;
case 's': case 'S':
return 2;
case 'i': case 'I': case 'f':
return 4;
case 'd':
return 8;
case 'Z': case 'H': case 'B':
return type;
default:
return 0;
}
}
static void swap_data(const bam1_core_t *c, int l_data, uint8_t *data, int is_host)
{
uint32_t *cigar = (uint32_t*)(data + c->l_qname);
uint32_t i;
for (i = 0; i < c->n_cigar; ++i) ed_swap_4p(&cigar[i]);
}
int bam_read1(BGZF *fp, bam1_t *b)
{
bam1_core_t *c = &b->core;
int32_t block_len, ret, i;
uint32_t x[8];
if ((ret = bgzf_read(fp, &block_len, 4)) != 4) {
if (ret == 0) return -1; // normal end-of-file
else return -2; // truncated
}
if (fp->is_be)
ed_swap_4p(&block_len);
if (block_len < 32) return -4; // block_len includes core data
if (bgzf_read(fp, x, 32) != 32) return -3;
if (fp->is_be) {
for (i = 0; i < 8; ++i) ed_swap_4p(x + i);
}
c->tid = x[0]; c->pos = x[1];
c->bin = x[2]>>16; c->qual = x[2]>>8&0xff; c->l_qname = x[2]&0xff;
c->l_extranul = (c->l_qname%4 != 0)? (4 - c->l_qname%4) : 0;
if ((uint32_t) c->l_qname + c->l_extranul > 255) // l_qname would overflow
return -4;
c->flag = x[3]>>16; c->n_cigar = x[3]&0xffff;
c->l_qseq = x[4];
c->mtid = x[5]; c->mpos = x[6]; c->isize = x[7];
b->l_data = block_len - 32 + c->l_extranul;
if (b->l_data < 0 || c->l_qseq < 0 || c->l_qname < 1) return -4;
if (((uint64_t) c->n_cigar << 2) + c->l_qname + c->l_extranul
+ (((uint64_t) c->l_qseq + 1) >> 1) + c->l_qseq > (uint64_t) b->l_data)
return -4;
if (b->m_data < b->l_data) {
uint8_t *new_data;
uint32_t new_m = b->l_data;
kroundup32(new_m);
new_data = (uint8_t*)realloc(b->data, new_m);
if (!new_data)
return -4;
b->data = new_data;
b->m_data = new_m;
}
if (bgzf_read(fp, b->data, c->l_qname) != c->l_qname) return -4;
for (i = 0; i < c->l_extranul; ++i) b->data[c->l_qname+i] = '\0';
c->l_qname += c->l_extranul;
if (b->l_data < c->l_qname ||
bgzf_read(fp, b->data + c->l_qname, b->l_data - c->l_qname) != b->l_data - c->l_qname)
return -4;
if (fp->is_be) swap_data(c, b->l_data, b->data, 0);
if (bam_tag2cigar(b, 0, 0) < 0)
return -4;
if (c->n_cigar > 0) { // recompute "bin" and check CIGAR-qlen consistency
int rlen, qlen;
bam_cigar2rqlens(c->n_cigar, bam_get_cigar(b), &rlen, &qlen);
if ((b->core.flag & BAM_FUNMAP)) rlen=1;
b->core.bin = hts_reg2bin(b->core.pos, b->core.pos + rlen, 14, 5);
// Sanity check for broken CIGAR alignments
if (c->l_qseq > 0 && !(c->flag & BAM_FUNMAP) && qlen != c->l_qseq) {
hts_log_error("CIGAR and query sequence lengths differ for %s",
bam_get_qname(b));
return -4;
}
}
return 4 + block_len;
}
int bam_write1(BGZF *fp, const bam1_t *b)
{
const bam1_core_t *c = &b->core;
uint32_t x[8], block_len = b->l_data - c->l_extranul + 32, y;
int i, ok;
if (c->n_cigar > 0xffff) block_len += 16; // "16" for "CGBI", 4-byte tag length and 8-byte fake CIGAR
x[0] = c->tid;
x[1] = c->pos;
x[2] = (uint32_t)c->bin<<16 | c->qual<<8 | (c->l_qname - c->l_extranul);
if (c->n_cigar > 0xffff) x[3] = (uint32_t)c->flag << 16 | 2;
else x[3] = (uint32_t)c->flag << 16 | (c->n_cigar & 0xffff);
x[4] = c->l_qseq;
x[5] = c->mtid;
x[6] = c->mpos;
x[7] = c->isize;
ok = (bgzf_flush_try(fp, 4 + block_len) >= 0);
if (fp->is_be) {
for (i = 0; i < 8; ++i) ed_swap_4p(x + i);
y = block_len;
if (ok) ok = (bgzf_write(fp, ed_swap_4p(&y), 4) >= 0);
swap_data(c, b->l_data, b->data, 1);
} else {
if (ok) ok = (bgzf_write(fp, &block_len, 4) >= 0);
}
if (ok) ok = (bgzf_write(fp, x, 32) >= 0);
if (ok) ok = (bgzf_write(fp, b->data, c->l_qname - c->l_extranul) >= 0);
if (c->n_cigar <= 0xffff) { // no long CIGAR; write normally
if (ok) ok = (bgzf_write(fp, b->data + c->l_qname, b->l_data - c->l_qname) >= 0);
} else { // with long CIGAR, insert a fake CIGAR record and move the real CIGAR to the CG:B,I tag
uint8_t buf[8];
uint32_t cigar_st, cigar_en, cigar[2];
cigar_st = (uint8_t*)bam_get_cigar(b) - b->data;
cigar_en = cigar_st + c->n_cigar * 4;
cigar[0] = (uint32_t)c->l_qseq << 4 | BAM_CSOFT_CLIP;
cigar[1] = (uint32_t)bam_cigar2rlen(c->n_cigar, bam_get_cigar(b)) << 4 | BAM_CREF_SKIP;
u32_to_le(cigar[0], buf);
u32_to_le(cigar[1], buf + 4);
if (ok) ok = (bgzf_write(fp, buf, 8) >= 0); // write cigar: <read_length>S<ref_length>N
if (ok) ok = (bgzf_write(fp, &b->data[cigar_en], b->l_data - cigar_en) >= 0); // write data after CIGAR
if (ok) ok = (bgzf_write(fp, "CGBI", 4) >= 0); // write CG:B,I
u32_to_le(c->n_cigar, buf);
if (ok) ok = (bgzf_write(fp, buf, 4) >= 0); // write the true CIGAR length
if (ok) ok = (bgzf_write(fp, &b->data[cigar_st], c->n_cigar * 4) >= 0); // write the real CIGAR
}
if (fp->is_be) swap_data(c, b->l_data, b->data, 0);
return ok? 4 + block_len : -1;
}
/********************
*** BAM indexing ***
********************/
static hts_idx_t *bam_index(BGZF *fp, int min_shift)
{
int n_lvls, i, fmt, ret;
bam1_t *b;
hts_idx_t *idx;
bam_hdr_t *h;
h = bam_hdr_read(fp);
if (h == NULL) return NULL;
if (min_shift > 0) {
int64_t max_len = 0, s;
for (i = 0; i < h->n_targets; ++i)
if (max_len < h->target_len[i]) max_len = h->target_len[i];
max_len += 256;
for (n_lvls = 0, s = 1<<min_shift; max_len > s; ++n_lvls, s <<= 3);
fmt = HTS_FMT_CSI;
} else min_shift = 14, n_lvls = 5, fmt = HTS_FMT_BAI;
idx = hts_idx_init(h->n_targets, fmt, bgzf_tell(fp), min_shift, n_lvls);
bam_hdr_destroy(h);
b = bam_init1();
while ((ret = bam_read1(fp, b)) >= 0) {
ret = hts_idx_push(idx, b->core.tid, b->core.pos, bam_endpos(b), bgzf_tell(fp), !(b->core.flag&BAM_FUNMAP));
if (ret < 0) goto err; // unsorted
}
if (ret < -1) goto err; // corrupted BAM file
hts_idx_finish(idx, bgzf_tell(fp));
bam_destroy1(b);
return idx;
err:
bam_destroy1(b);
hts_idx_destroy(idx);
return NULL;
}
int sam_index_build3(const char *fn, const char *fnidx, int min_shift, int nthreads)
{
hts_idx_t *idx;
htsFile *fp;
int ret = 0;
if ((fp = hts_open(fn, "r")) == 0) return -2;
if (nthreads)
hts_set_threads(fp, nthreads);
switch (fp->format.format) {
case cram:
ret = cram_index_build(fp->fp.cram, fn, fnidx);
break;
case bam:
idx = bam_index(fp->fp.bgzf, min_shift);
if (idx) {
ret = hts_idx_save_as(idx, fn, fnidx, (min_shift > 0)? HTS_FMT_CSI : HTS_FMT_BAI);
if (ret < 0) ret = -4;
hts_idx_destroy(idx);
}
else ret = -1;
break;
default:
ret = -3;
break;
}
hts_close(fp);
return ret;
}
int sam_index_build2(const char *fn, const char *fnidx, int min_shift)
{
return sam_index_build3(fn, fnidx, min_shift, 0);
}
int sam_index_build(const char *fn, int min_shift)
{
return sam_index_build3(fn, NULL, min_shift, 0);
}
// Provide bam_index_build() symbol for binary compability with earlier HTSlib
#undef bam_index_build
int bam_index_build(const char *fn, int min_shift)
{
return sam_index_build2(fn, NULL, min_shift);
}
static int bam_readrec(BGZF *fp, void *ignored, void *bv, int *tid, int *beg, int *end)
{
bam1_t *b = bv;
int ret;
if ((ret = bam_read1(fp, b)) >= 0) {
*tid = b->core.tid;
*beg = b->core.pos;
*end = bam_endpos(b);
}
return ret;
}
// This is used only with read_rest=1 iterators, so need not set tid/beg/end.
static int cram_readrec(BGZF *ignored, void *fpv, void *bv, int *tid, int *beg, int *end)
{
htsFile *fp = fpv;
bam1_t *b = bv;
int ret = cram_get_bam_seq(fp->fp.cram, &b);
if (ret < 0)
return cram_eof(fp->fp.cram) ? -1 : -2;
if (bam_tag2cigar(b, 1, 1) < 0)
return -2;
*tid = b->core.tid;
*beg = b->core.pos;
*end = bam_endpos(b);
return ret;
}
static int cram_pseek(void *fp, int64_t offset, int whence)
{
cram_fd *fd = (cram_fd *)fp;
if ((0 != cram_seek(fd, offset, SEEK_SET))
&& (0 != cram_seek(fd, offset - fd->first_container, SEEK_CUR)))
return -1;
if (fd->ctr) {
cram_free_container(fd->ctr);
fd->ctr = NULL;
fd->ooc = 0;
}
return 0;
}
/*
* cram_ptell is a pseudo-tell function, because it matches the position of the disk cursor only
* after a fresh seek call. Otherwise it indicates that the read takes place inside the buffered
* container previously fetched. It was designed like this to integrate with the functionality
* of the iterator stepping logic.
*/
static int64_t cram_ptell(void *fp)
{
cram_fd *fd = (cram_fd *)fp;
cram_container *c;
int64_t ret = -1L;
if (fd && fd->fp) {
ret = htell(fd->fp);
if ((c = fd->ctr) != NULL) {
ret -= ((c->curr_slice != c->max_slice || c->curr_rec != c->max_rec) ? c->offset + 1 : 0);
}
}
return ret;
}
static int bam_pseek(void *fp, int64_t offset, int whence)
{
BGZF *fd = (BGZF *)fp;
return bgzf_seek(fd, offset, whence);
}
static int64_t bam_ptell(void *fp)
{
BGZF *fd = (BGZF *)fp;
if (!fd)
return -1L;
return bgzf_tell(fd);
}
// This is used only with read_rest=1 iterators, so need not set tid/beg/end.
static int sam_bam_cram_readrec(BGZF *bgzfp, void *fpv, void *bv, int *tid, int *beg, int *end)
{
htsFile *fp = fpv;
bam1_t *b = bv;
switch (fp->format.format) {
case bam: return bam_read1(bgzfp, b);
case cram: {
int ret = cram_get_bam_seq(fp->fp.cram, &b);
if (ret < 0)
return cram_eof(fp->fp.cram) ? -1 : -2;
if (bam_tag2cigar(b, 1, 1) < 0)
return -2;
return ret;
}
default:
// TODO Need headers available to implement this for SAM files
hts_log_error("Not implemented for SAM files");
abort();
}
}
hts_idx_t *sam_index_load2(htsFile *fp, const char *fn, const char *fnidx)
{
switch (fp->format.format) {
case bam:
return fnidx? hts_idx_load2(fn, fnidx) : hts_idx_load(fn, HTS_FMT_BAI);
case cram: {
if (cram_index_load(fp->fp.cram, fn, fnidx) < 0) return NULL;
// Cons up a fake "index" just pointing at the associated cram_fd:
hts_cram_idx_t *idx = malloc(sizeof (hts_cram_idx_t));
if (idx == NULL) return NULL;
idx->fmt = HTS_FMT_CRAI;
idx->cram = fp->fp.cram;
return (hts_idx_t *) idx;
}
default:
return NULL; // TODO Would use tbx_index_load if it returned hts_idx_t
}
}
hts_idx_t *sam_index_load(htsFile *fp, const char *fn)
{
return sam_index_load2(fp, fn, NULL);
}
static hts_itr_t *cram_itr_query(const hts_idx_t *idx, int tid, int beg, int end, hts_readrec_func *readrec)
{
const hts_cram_idx_t *cidx = (const hts_cram_idx_t *) idx;
hts_itr_t *iter = (hts_itr_t *) calloc(1, sizeof(hts_itr_t));
if (iter == NULL) return NULL;
// Cons up a dummy iterator for which hts_itr_next() will simply invoke
// the readrec function:
iter->is_cram = 1;
iter->read_rest = 1;
iter->off = NULL;
iter->bins.a = NULL;
iter->readrec = readrec;
if (tid >= 0 || tid == HTS_IDX_NOCOOR || tid == HTS_IDX_START) {
cram_range r = { tid, beg+1, end };
int ret = cram_set_option(cidx->cram, CRAM_OPT_RANGE, &r);
iter->curr_off = 0;
// The following fields are not required by hts_itr_next(), but are
// filled in in case user code wants to look at them.
iter->tid = tid;
iter->beg = beg;
iter->end = end;
switch (ret) {
case 0:
break;
case -2:
// No data vs this ref, so mark iterator as completed.
// Same as HTS_IDX_NONE.
iter->finished = 1;
break;
default:
free(iter);
return NULL;
}
}
else switch (tid) {
case HTS_IDX_REST:
iter->curr_off = 0;
break;
case HTS_IDX_NONE:
iter->curr_off = 0;
iter->finished = 1;
break;
default:
hts_log_error("Query with tid=%d not implemented for CRAM files", tid);
abort();
break;
}
return iter;
}
hts_itr_t *sam_itr_queryi(const hts_idx_t *idx, int tid, int beg, int end)
{
const hts_cram_idx_t *cidx = (const hts_cram_idx_t *) idx;
if (idx == NULL)
return hts_itr_query(NULL, tid, beg, end, sam_bam_cram_readrec);
else if (cidx->fmt == HTS_FMT_CRAI)
return cram_itr_query(idx, tid, beg, end, cram_readrec);
else
return hts_itr_query(idx, tid, beg, end, bam_readrec);
}
static int cram_name2id(void *fdv, const char *ref)
{
cram_fd *fd = (cram_fd *) fdv;
return sam_hdr_name2ref(fd->header, ref);
}
hts_itr_t *sam_itr_querys(const hts_idx_t *idx, bam_hdr_t *hdr, const char *region)
{
const hts_cram_idx_t *cidx = (const hts_cram_idx_t *) idx;
if (cidx->fmt == HTS_FMT_CRAI)
return hts_itr_querys(idx, region, cram_name2id, cidx->cram, cram_itr_query, cram_readrec);
else
return hts_itr_querys(idx, region, (hts_name2id_f)(bam_name2id), hdr, hts_itr_query, bam_readrec);
}
hts_itr_multi_t *sam_itr_regions(const hts_idx_t *idx, bam_hdr_t *hdr, hts_reglist_t *reglist, unsigned int regcount)
{
const hts_cram_idx_t *cidx = (const hts_cram_idx_t *) idx;
if (cidx->fmt == HTS_FMT_CRAI)
return hts_itr_regions(idx, reglist, regcount, cram_name2id, cidx->cram,
hts_itr_multi_cram, cram_readrec, cram_pseek, cram_ptell);
else
return hts_itr_regions(idx, reglist, regcount, (hts_name2id_f)(bam_name2id), hdr,
hts_itr_multi_bam, bam_readrec, bam_pseek, bam_ptell);
}
/**********************
*** SAM header I/O ***
**********************/
#include "htslib/kseq.h"
#include "htslib/kstring.h"
bam_hdr_t *sam_hdr_parse(int l_text, const char *text)
{
const char *q, *r, *p;
khash_t(s2i) *d;
d = kh_init(s2i);
for (p = text; *p; ++p) {
if (strncmp(p, "@SQ\t", 4) == 0) {
char *sn = 0;
int ln = -1;
for (q = p + 4;; ++q) {
if (strncmp(q, "SN:", 3) == 0) {
q += 3;
for (r = q; *r != '\t' && *r != '\n' && *r != '\0'; ++r);
sn = (char*)calloc(r - q + 1, 1);
strncpy(sn, q, r - q);
q = r;
} else if (strncmp(q, "LN:", 3) == 0)
ln = strtol(q + 3, (char**)&q, 10);
while (*q != '\t' && *q != '\n' && *q != '\0') ++q;
if (*q == '\0' || *q == '\n') break;
}
p = q;
if (sn && ln >= 0) {
khint_t k;
int absent;
k = kh_put(s2i, d, sn, &absent);
if (!absent) {
hts_log_warning("Duplicated sequence '%s'", sn);
free(sn);
} else kh_val(d, k) = (int64_t)(kh_size(d) - 1)<<32 | ln;
}
}
while (*p != '\0' && *p != '\n') ++p;
}
return hdr_from_dict(d);
}
// Minimal sanitisation of a header to ensure.
// - null terminated string.
// - all lines start with @ (also implies no blank lines).
//
// Much more could be done, but currently is not, including:
// - checking header types are known (HD, SQ, etc).
// - syntax (eg checking tab separated fields).
// - validating n_targets matches @SQ records.
// - validating target lengths against @SQ records.
static bam_hdr_t *sam_hdr_sanitise(bam_hdr_t *h) {
if (!h)
return NULL;
// Special case for empty headers.
if (h->l_text == 0)
return h;
uint32_t i, lnum = 0;
char *cp = h->text, last = '\n';
for (i = 0; i < h->l_text; i++) {
// NB: l_text excludes terminating nul. This finds early ones.
if (cp[i] == 0)
break;
// Error on \n[^@], including duplicate newlines
if (last == '\n') {
lnum++;
if (cp[i] != '@') {
hts_log_error("Malformed SAM header at line %u", lnum);
bam_hdr_destroy(h);
return NULL;
}
}
last = cp[i];
}
if (i < h->l_text) { // Early nul found. Complain if not just padding.
uint32_t j = i;
while (j < h->l_text && cp[j] == '\0') j++;
if (j < h->l_text)
hts_log_warning("Unexpected NUL character in header. Possibly truncated");
}
// Add trailing newline and/or trailing nul if required.
if (last != '\n') {
hts_log_warning("Missing trailing newline on SAM header. Possibly truncated");
if (h->l_text == UINT32_MAX) {
hts_log_error("No room for extra newline");
bam_hdr_destroy(h);
return NULL;
}
if (i >= h->l_text - 1) {
cp = realloc(h->text, (size_t) h->l_text+2);
if (!cp) {
bam_hdr_destroy(h);
return NULL;
}
h->text = cp;
}
cp[i++] = '\n';
// l_text may be larger already due to multiple nul padding
if (h->l_text < i)
h->l_text = i;
cp[h->l_text] = '\0';
}
return h;
}
bam_hdr_t *sam_hdr_read(htsFile *fp)
{
switch (fp->format.format) {
case bam:
return sam_hdr_sanitise(bam_hdr_read(fp->fp.bgzf));
case cram:
return sam_hdr_sanitise(cram_header_to_bam(fp->fp.cram->header));
case sam: {
kstring_t str = { 0, 0, NULL };
bam_hdr_t *h = NULL;
int ret, has_SQ = 0;
while ((ret = hts_getline(fp, KS_SEP_LINE, &fp->line)) >= 0) {
if (fp->line.s[0] != '@') break;
if (fp->line.l > 3 && strncmp(fp->line.s,"@SQ",3) == 0) has_SQ = 1;